From 94292f3098e6b77611f67ce195f3dc7028a1ab24 Mon Sep 17 00:00:00 2001 From: Lihua <1017343802@qq.com> Date: Sun, 22 Nov 2026 23:35:52 -0800 Subject: [PATCH 1/4] fix(dsh): pin continuation Core commands to the resolved CLI executable The DSH continuation Driver rendered automatic-Turn text through Core without --cli-bin, so thin heartbeat task bodies and quota settlement command templates always prefixed bare loopx: when the agent shell's PATH names a different LoopX install than the plugin-probed command, guard, writeback and settlement ran a different Core binary than admission used (#9300). resolveLoopXCommand now derives the one-executable Core --cli-bin route for single-executable candidates, resolving bare names against the probe PATH to that absolute file, and the Driver passes it as the global route on quota should-run and as both the global and heartbeat-prompt options so rendered task bodies embed the pinned executable. Host-injected commands without the new field keep their plain file route. Interpreter-prefixed routes (managed launcher, python -m loopx.cli) cannot be expressed as one --cli-bin executable; their continuation text keeps Core's bare loopx route and the Driver discloses that once in its warning log, with LOOPX_BIN pointing at one absolute executable as the pinning remedy. Signed-off-by: Lihua <1017343802@qq.com> --- packages/dsh-loopx-plugin/README.md | 8 ++ packages/dsh-loopx-plugin/src/cli.ts | 89 +++++++++++- packages/dsh-loopx-plugin/src/driver.ts | 30 +++- packages/dsh-loopx-plugin/tests/cli.spec.ts | 117 +++++++++++++++- .../dsh-loopx-plugin/tests/driver.spec.ts | 131 +++++++++++++++++- 5 files changed, 367 insertions(+), 8 deletions(-) diff --git a/packages/dsh-loopx-plugin/README.md b/packages/dsh-loopx-plugin/README.md index 64e04fe886..6c34351dc8 100644 --- a/packages/dsh-loopx-plugin/README.md +++ b/packages/dsh-loopx-plugin/README.md @@ -72,6 +72,14 @@ owner. Older plugin releases retain their original CLI requirements. The continuation driver follows LoopX's context delivery setting. When the guard returns a capture reference, the driver reads the admission fields from that same capture. +Continuation Turns run Core-rendered commands (thin heartbeat bodies, quota +settlement templates) against the same executable the plugin probed: the +Driver passes its resolved route as Core's `--cli-bin`, resolving a bare name +to that absolute `PATH` file first. Interpreter-prefixed routes (the managed +launcher, `python -m loopx.cli`) cannot be expressed as one executable; their +continuation text keeps Core's bare `loopx` route, and the Driver discloses +that once in its warning log. Point `LOOPX_BIN` at one absolute loopx +executable to pin those sessions. Install the prebuilt `0.1.1-beta.7` release into the web profile: ```bash diff --git a/packages/dsh-loopx-plugin/src/cli.ts b/packages/dsh-loopx-plugin/src/cli.ts index a770626c29..3084f2e7d3 100644 --- a/packages/dsh-loopx-plugin/src/cli.ts +++ b/packages/dsh-loopx-plugin/src/cli.ts @@ -1,5 +1,6 @@ import { execFile, spawn } from 'node:child_process' -import { statSync } from 'node:fs' +import { accessSync, constants, statSync } from 'node:fs' +import { delimiter, join } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' // 2.4.0 adds the original-Turn receipt reader used by selection recovery. @@ -99,6 +100,15 @@ export interface LoopXCommand { readonly prefix: readonly string[] readonly skillCommand: string readonly version: string + /** + * One executable Core accepts as `--cli-bin`, pinning its rendered + * continuation text (heartbeat task bodies, settlement command templates) to + * the same binary this adapter probed. Bare names are resolved against the + * probe PATH to an absolute path when possible. Undefined when the resolved + * invocation cannot be expressed as one executable (interpreter plus module + * or managed-launcher prefix), leaving Core's default bare `loopx` route. + */ + readonly cliBin?: string | undefined readonly candidate?: LoopXCliDiagnostics['candidate'] } @@ -480,6 +490,64 @@ function shellWord(value: string): string { : `'${value.replaceAll("'", `'"'"'`)}'` } +function probeExecutableFile(directory: string, name: string): string | undefined { + // Mirror the spawn adapter's bare-name discovery: CreateProcess appends + // `.exe` on Windows, while POSIX keeps one exact executable spelling. + const spellings = process.platform === 'win32' && !/\.(exe|com)$/iu.test(name) + ? [name, `${name}.exe`] + : [name] + for (const spelling of spellings) { + const candidate = join(directory, spelling) + try { + if (statSync(candidate, { throwIfNoEntry: false })?.isFile() !== true) continue + accessSync(candidate, constants.X_OK) + } catch { + continue + } + return candidate + } + return undefined +} + +/** + * Derive the one-executable Core `--cli-bin` route for a probeable command + * name. Bare names resolve to the exact PATH file the spawn environment would + * execute, so continuation text Core renders cannot drift to another PATH + * installation. Names Core's validator rejects (empty, option-like, control + * characters) return undefined; a bare name the probe PATH cannot resolve is + * returned unchanged so Core still pins the probed name instead of an + * invented path. + */ +function coreCliBinRoute( + name: string, + env: NodeJS.ProcessEnv, +): string | undefined { + if (name === '' || name.startsWith('-') || /[\u0000-\u001f]/u.test(name)) { + return undefined + } + if (name.includes('/') || name.includes('\\')) return name + const searchPath = env.PATH ?? env.Path + for (const directory of searchPath?.split(delimiter) ?? []) { + const resolved = probeExecutableFile(directory, name) + if (resolved !== undefined) return resolved + } + return name +} + +/** The one executable Core may embed as `--cli-bin` for this command, if any. */ +export function coreRouteBin(command: LoopXCommand): string | undefined { + if (command.cliBin !== undefined) return command.cliBin + // Host-injected commands may predate the resolved route field. Pass their + // plain executable file through without re-resolving it: the driver cannot + // know which PATH the injecting resolver probed, so it must not invent one. + const file = command.file + if (command.prefix.length > 0 || file === '' || file.startsWith('-') + || /[\u0000-\u001f]/u.test(file)) { + return undefined + } + return file +} + /** Resolve the console script first, then the stable Python module fallback. */ export async function resolveLoopXCommand( options: ResolveLoopXCommandOptions = {}, @@ -494,6 +562,11 @@ export async function resolveLoopXCommand( ? ['python3', 'python'] : [configuredPython] const managedLauncher = options.managedLauncher + const probeEnv = options.env ?? process.env + const configuredRoute = configured + ? coreCliBinRoute(configured, probeEnv) + : undefined + const pathLoopxRoute = configured ? undefined : coreCliBinRoute('loopx', probeEnv) const managedCandidates: Array> = configured || managedLauncher === undefined ? [] @@ -506,10 +579,20 @@ export async function resolveLoopXCommand( ].join(' '), })) const candidates: Array> = configured - ? [{ file: configured, prefix: [], skillCommand: '"$LOOPX_BIN"' }] + ? [{ + file: configured, + prefix: [], + skillCommand: '"$LOOPX_BIN"', + ...(configuredRoute === undefined ? {} : { cliBin: configuredRoute }), + }] : [ ...managedCandidates, - { file: 'loopx', prefix: [], skillCommand: 'loopx' }, + { + file: 'loopx', + prefix: [], + skillCommand: 'loopx', + ...(pathLoopxRoute === undefined ? {} : { cliBin: pathLoopxRoute }), + }, ...pythonNames.map(pythonName => ({ file: pythonName, prefix: ['-m', 'loopx.cli'], diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts index e6a4b9a17a..50c74c939f 100644 --- a/packages/dsh-loopx-plugin/src/driver.ts +++ b/packages/dsh-loopx-plugin/src/driver.ts @@ -10,6 +10,7 @@ import type { SessionEvent, UserMessage } from '@deepseek-ai/dsh-session' import { LoopXCliError, cliErrorFields, + coreRouteBin, resolveLoopXCommand, runJsonCommand, supportedLoopXVersion, @@ -175,6 +176,16 @@ function preStepRejection( return `pre_step_rejected stage=pre-step-recheck reason=${reason} other_kinds=${kinds.join(',') || 'none'} elapsed_ms=${Math.round(performance.now() - startedAt)}` } +/** + * Global Core route options that pin Core-rendered continuation text (task + * bodies, settlement command templates) to the same executable this adapter + * probed, instead of whatever bare `loopx` resolves to on the agent's PATH. + */ +function coreRouteArgs(command: LoopXCommand): string[] { + const route = coreRouteBin(command) + return route === undefined ? [] : ['--cli-bin', route] +} + export interface LoopXDriverOptions { readonly isLiveAgent: (agent: Agent) => boolean readonly runner?: FileRunner | undefined @@ -1507,7 +1518,18 @@ export class LoopXContinuationDriver { private async loopXCommand(signal: AbortSignal): Promise { if (this.command !== undefined) return this.command const resolved = await this.commandResolver(signal) - if (!signal.aborted) this.command = resolved + if (!signal.aborted) { + this.command = resolved + if (coreRouteBin(resolved) === undefined) { + // Interpreter-prefixed routes (managed launcher, python -m) cannot be + // one Core `--cli-bin` executable; continuation text keeps Core's bare + // `loopx`. Disclose once instead of pinning a wrong binary. + this.warn( + `dsh-loopx-driver: cli_route_unpinned candidate=${resolved.candidate ?? 'unknown'}` + + ' hint=point LOOPX_BIN at one absolute loopx executable to pin continuation commands', + ) + } + } return resolved } @@ -1562,6 +1584,7 @@ export class LoopXContinuationDriver { [ '--registry', '.loopx/registry.json', '--format', 'json', + ...coreRouteArgs(command), 'quota', 'should-run', '--goal-id', binding.goalId, '--agent-id', binding.agentId, @@ -1622,7 +1645,12 @@ export class LoopXContinuationDriver { [ '--registry', '.loopx/registry.json', '--format', 'json', + // The global option binds Core's command-route context for this + // invocation; the heartbeat-prompt option names the executable its + // rendered task-body commands embed. + ...coreRouteArgs(command), 'heartbeat-prompt', '--thin', + ...coreRouteArgs(command), '--goal-id', binding.goalId, '--agent-id', binding.agentId, '--runtime-profile', 'generic_cli', diff --git a/packages/dsh-loopx-plugin/tests/cli.spec.ts b/packages/dsh-loopx-plugin/tests/cli.spec.ts index 76f35239d3..8baa690538 100644 --- a/packages/dsh-loopx-plugin/tests/cli.spec.ts +++ b/packages/dsh-loopx-plugin/tests/cli.spec.ts @@ -1,7 +1,7 @@ import { execFileSync } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { delimiter, join } from 'node:path' import { describe, expect, it } from 'vitest' import { LoopXCliError, @@ -318,6 +318,119 @@ describe('reap-aware mutation execution', () => { }) }) +describe('Core --cli-bin route derivation', () => { + it('keeps an absolute configured executable as the route', async () => { + const configured = '/opt/Loop X/loopx' + const resolved = await resolveLoopXCommand({ + env: { LOOPX_BIN: configured }, + runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), + }) + expect(resolved.cliBin).toBe(configured) + }) + + it('falls back to the configured name when the probe PATH cannot resolve it', async () => { + const resolved = await resolveLoopXCommand({ + env: { LOOPX_BIN: 'nowhere-loopx', PATH: '/nonexistent-loopx-route' }, + runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), + }) + expect(resolved.cliBin).toBe('nowhere-loopx') + }) + + it('leaves interpreter-prefixed routes unpinned', async () => { + const launcher = await resolveLoopXCommand({ + managedLauncher: { path: '/opt/DSH/runtime/loopx_cli.py', pythonBins: ['/opt/bin/python3'] }, + runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), + }) + expect(launcher.candidate).toBe('managed-launcher') + expect(launcher.cliBin).toBeUndefined() + + const module = await resolveLoopXCommand({ + env: { LOOPX_BIN: '', PYTHON_BIN: 'fixture-python', PATH: '/nonexistent-loopx-route' }, + runner: async file => ({ + exitCode: file === 'fixture-python' ? 0 : 1, + stdout: file === 'fixture-python' ? 'loopx 2.4.0\n' : '', + stderr: '', + }), + }) + expect(module.candidate).toBe('python-module') + expect(module.cliBin).toBeUndefined() + }) +}) + +describe.skipIf(process.platform === 'win32')('Core --cli-bin PATH resolution', () => { + it('resolves the probed path-loopx name to its PATH entry', async () => { + const dir = mkdtempSync(join(tmpdir(), 'loopx-route-')) + try { + const pinned = join(dir, 'loopx') + writeFileSync(pinned, '#!/bin/sh\nexit 0\n', { mode: 0o755 }) + const resolved = await resolveLoopXCommand({ + env: { PATH: dir }, + runner: async file => ({ + exitCode: file === 'loopx' ? 0 : 1, + stdout: file === 'loopx' ? 'loopx 2.4.0\n' : '', + stderr: '', + }), + }) + expect(resolved.candidate).toBe('path-loopx') + expect(resolved.cliBin).toBe(pinned) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('resolves a bare configured name against the probe PATH', async () => { + const dir = mkdtempSync(join(tmpdir(), 'loopx-route-')) + try { + const pinned = join(dir, 'loopx-canary') + writeFileSync(pinned, '#!/bin/sh\nexit 0\n', { mode: 0o755 }) + const resolved = await resolveLoopXCommand({ + env: { LOOPX_BIN: 'loopx-canary', PATH: dir }, + runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), + }) + expect(resolved.candidate).toBe('configured-command') + expect(resolved.cliBin).toBe(pinned) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('prefers the first PATH entry and skips non-executable files', async () => { + const root = mkdtempSync(join(tmpdir(), 'loopx-route-')) + try { + const first = join(root, 'first') + const second = join(root, 'second') + mkdirSync(first) + mkdirSync(second) + const executable = join(first, 'loopx') + writeFileSync(executable, '#!/bin/sh\nexit 0\n', { mode: 0o755 }) + const plain = join(second, 'loopx') + writeFileSync(plain, 'not executable\n', { mode: 0o644 }) + const resolved = await resolveLoopXCommand({ + env: { PATH: [first, second].join(delimiter) }, + runner: async file => ({ + exitCode: file === 'loopx' ? 0 : 1, + stdout: file === 'loopx' ? 'loopx 2.4.0\n' : '', + stderr: '', + }), + }) + expect(resolved.cliBin).toBe(executable) + + chmodSync(plain, 0o755) + const flipped = await resolveLoopXCommand({ + env: { PATH: [second, first].join(delimiter) }, + runner: async file => ({ + exitCode: file === 'loopx' ? 0 : 1, + stdout: file === 'loopx' ? 'loopx 2.4.0\n' : '', + stderr: '', + }), + }) + expect(flipped.cliBin).toBe(plain) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +}) + describe.skipIf(process.platform === 'win32')('owned CLI process group', () => { it.each(['timeout', 'abort', 'mutation', 'escaped pipe'] as const)( 'retires a descendant holding an inherited pipe on %s before returning or retrying', diff --git a/packages/dsh-loopx-plugin/tests/driver.spec.ts b/packages/dsh-loopx-plugin/tests/driver.spec.ts index 6b73250dcf..8e5274d022 100644 --- a/packages/dsh-loopx-plugin/tests/driver.spec.ts +++ b/packages/dsh-loopx-plugin/tests/driver.spec.ts @@ -1,11 +1,14 @@ import { randomUUID } from 'node:crypto' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { Context, Logger, LoggerService } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import { SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent, UserMessage } from '@deepseek-ai/dsh-session' -import type { FileRunner } from '../src/cli.ts' -import { LoopXCliError } from '../src/cli.ts' +import type { FileRunner, LoopXCommand } from '../src/cli.ts' +import { LoopXCliError, resolveLoopXCommand } from '../src/cli.ts' import { apply as applyDriver, LoopXContinuationDriver, @@ -3300,3 +3303,127 @@ describe('plugin unload cause classification', () => { } }) }) + +describe('continuation Core command route parity', () => { + function pinnedRouteDriver( + fixture: ReturnType, + resolved: LoopXCommand, + warnings: string[], + ): LoopXContinuationDriver { + return new LoopXContinuationDriver({ + runner: fixture.runner, + isLiveAgent: () => true, + makeTurnInstanceId: () => 'turn-stable', + retryDelaysMs: [0, 0], + resolveCommand: async () => resolved, + warn: message => { warnings.push(message) }, + }) + } + + async function admittedQuotaAndHeartbeat( + driver: LoopXContinuationDriver, + host: FakeAgent, + ): Promise { + observeActivated(driver, host) + await waitFor(() => host.nextTurn.length === 1) + await driver.dispose() + } + + it('pins quota and heartbeat commands to the resolved single executable', async () => { + const fixture = runnerFixture() + const host = fakeAgent() + const warnings: string[] = [] + const driver = pinnedRouteDriver(fixture, { + file: '/opt/pinned/loopx', + prefix: [], + skillCommand: '"$LOOPX_BIN"', + version: 'loopx 2.4.0', + candidate: 'configured-command', + cliBin: '/opt/pinned/loopx', + }, warnings) + await admittedQuotaAndHeartbeat(driver, host) + + expect(fixture.quotaCalls.length).toBeGreaterThan(0) + for (const argv of fixture.quotaCalls) { + const flag = argv.indexOf('--cli-bin') + expect(flag).toBeGreaterThanOrEqual(0) + expect(argv[flag + 1]).toBe('/opt/pinned/loopx') + // Core binds the global route only before the subcommand token. + expect(flag).toBeLessThan(argv.indexOf('quota')) + } + expect(fixture.heartbeatArgv.length).toBeGreaterThan(0) + for (const argv of fixture.heartbeatArgv) { + const flags = argv + .map((value, index) => (value === '--cli-bin' ? index : -1)) + .filter(index => index >= 0) + // One global route binding plus the heartbeat-prompt option that feeds + // the rendered task-body command prefixes. + expect(flags).toHaveLength(2) + expect(argv[flags[0]! + 1]).toBe('/opt/pinned/loopx') + expect(flags[0]!).toBeLessThan(argv.indexOf('heartbeat-prompt')) + expect(argv[flags[1]! + 1]).toBe('/opt/pinned/loopx') + expect(flags[1]!).toBeGreaterThan(argv.indexOf('heartbeat-prompt')) + } + expect(warnings).toEqual([]) + }) + + it('keeps bare loopx text and discloses once for a non-executable route', async () => { + const fixture = runnerFixture() + const host = fakeAgent() + const warnings: string[] = [] + const driver = pinnedRouteDriver(fixture, { + file: '/opt/managed/python3', + prefix: ['/opt/managed/loopx_cli.py'], + skillCommand: "/opt/managed/python3 '/opt/managed/loopx_cli.py'", + version: 'loopx 2.4.0', + candidate: 'managed-launcher', + }, warnings) + await admittedQuotaAndHeartbeat(driver, host) + + for (const argv of [...fixture.quotaCalls, ...fixture.heartbeatArgv]) { + expect(argv).not.toContain('--cli-bin') + } + const unpinned = warnings.filter(value => value.includes('cli_route_unpinned')) + expect(unpinned).toHaveLength(1) + expect(unpinned[0]).toContain('candidate=managed-launcher') + }) +}) + +describe.skipIf(process.platform === 'win32')( + 'continuation Core command route parity through the real resolver', + () => { + it('pins the PATH-resolved executable the resolver probed', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-cli-parity-')) + const pinned = join(dir, 'loopx') + writeFileSync(pinned, '#!/bin/sh\nexit 0\n', { mode: 0o755 }) + try { + const fixture = runnerFixture() + const host = fakeAgent() + const driver = new LoopXContinuationDriver({ + runner: fixture.runner, + isLiveAgent: () => true, + makeTurnInstanceId: () => 'turn-stable', + retryDelaysMs: [0, 0], + resolveCommand: signal => resolveLoopXCommand({ + runner: fixture.runner, + signal, + env: { PATH: dir }, + }), + }) + observeActivated(driver, host) + await waitFor(() => host.nextTurn.length === 1) + await driver.dispose() + + const quotaArgv = fixture.quotaCalls[0] as string[] + const quotaFlag = quotaArgv.indexOf('--cli-bin') + expect(quotaFlag).toBeGreaterThanOrEqual(0) + expect(quotaArgv[quotaFlag + 1]).toBe(pinned) + const heartbeatArgv = fixture.heartbeatArgv[0] as string[] + expect(heartbeatArgv.filter(value => value === '--cli-bin')).toHaveLength(2) + expect(heartbeatArgv[heartbeatArgv.indexOf('--cli-bin') + 1]).toBe(pinned) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }, 15_000) + }, +) From 920700c8a58901bd4ab50ed7147c17c041fd9a58 Mon Sep 17 00:00:00 2001 From: Lihua <1017343802@qq.com> Date: Mon, 23 Nov 2026 01:23:21 -0800 Subject: [PATCH 2/4] fix(dsh): bind relative PATH routes to one absolute Core executable Review P2 on #9309: a relative PATH entry (PATH=bin:/usr/bin:/bin) let coreCliBinRoute store a relative route (bin/loopx), so the version probe (host cwd), driver admission spawns (Session cwd), and the rendered Core route execution (agent cwd) could each select a different loopx install; the continuation prefix could still change the Core source. The resolver now binds one absolute executable before probing: explicit paths normalize against the discovery working directory, bare names resolve to the exact PATH file, and relative PATH entries are made absolute at discovery. The bound path becomes the candidate file, so the version probe, every business spawn, and the Core-rendered --cli-bin text run the same file. When no single executable can be bound (unlocatable name, illegal --cli-bin value), the candidate keeps bare probe semantics, Core keeps its bare loopx fallback route, and the driver's existing typed warning discloses the unbound state; coreRouteBin now only validates the resolver-bound route. Adds a real-subprocess three-cwd regression matrix (probe, driver admission from the Session cwd, and sh -c execution of the rendered route in the agent cwd) with per-directory decoy installs, plus the absolute-PATH control group; the relative case is red on 94292f309 and green now, the control holds in both. Signed-off-by: Lihua <1017343802@qq.com> --- packages/dsh-loopx-plugin/README.md | 14 +- packages/dsh-loopx-plugin/src/cli.ts | 115 +++++++++------- packages/dsh-loopx-plugin/src/driver.ts | 6 +- .../admission-closeout.integration.spec.ts | 3 + packages/dsh-loopx-plugin/tests/cli.spec.ts | 53 ++++--- .../dsh-loopx-plugin/tests/driver.spec.ts | 129 +++++++++++++++++- 6 files changed, 240 insertions(+), 80 deletions(-) diff --git a/packages/dsh-loopx-plugin/README.md b/packages/dsh-loopx-plugin/README.md index 6c34351dc8..4aec09dfc7 100644 --- a/packages/dsh-loopx-plugin/README.md +++ b/packages/dsh-loopx-plugin/README.md @@ -74,12 +74,14 @@ When the guard returns a capture reference, the driver reads the admission fields from that same capture. Continuation Turns run Core-rendered commands (thin heartbeat bodies, quota settlement templates) against the same executable the plugin probed: the -Driver passes its resolved route as Core's `--cli-bin`, resolving a bare name -to that absolute `PATH` file first. Interpreter-prefixed routes (the managed -launcher, `python -m loopx.cli`) cannot be expressed as one executable; their -continuation text keeps Core's bare `loopx` route, and the Driver discloses -that once in its warning log. Point `LOOPX_BIN` at one absolute loopx -executable to pin those sessions. +resolver binds one absolute file — normalizing relative `PATH` entries against +its discovery directory — and the Driver passes that route as Core's +`--cli-bin`, so the version probe, admission spawns, and rendered commands +share one executable. Interpreter-prefixed routes (the managed launcher, +`python -m loopx.cli`) and names the probe environment cannot locate cannot +be bound to one executable; their continuation text keeps Core's bare +`loopx` route, and the Driver discloses that once in its warning log. Point +`LOOPX_BIN` at one absolute loopx executable to pin those sessions. Install the prebuilt `0.1.1-beta.7` release into the web profile: ```bash diff --git a/packages/dsh-loopx-plugin/src/cli.ts b/packages/dsh-loopx-plugin/src/cli.ts index 3084f2e7d3..f5d0d52b70 100644 --- a/packages/dsh-loopx-plugin/src/cli.ts +++ b/packages/dsh-loopx-plugin/src/cli.ts @@ -1,6 +1,6 @@ import { execFile, spawn } from 'node:child_process' import { accessSync, constants, statSync } from 'node:fs' -import { delimiter, join } from 'node:path' +import { delimiter, join, resolve } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' // 2.4.0 adds the original-Turn receipt reader used by selection recovery. @@ -101,12 +101,14 @@ export interface LoopXCommand { readonly skillCommand: string readonly version: string /** - * One executable Core accepts as `--cli-bin`, pinning its rendered - * continuation text (heartbeat task bodies, settlement command templates) to - * the same binary this adapter probed. Bare names are resolved against the - * probe PATH to an absolute path when possible. Undefined when the resolved - * invocation cannot be expressed as one executable (interpreter plus module - * or managed-launcher prefix), leaving Core's default bare `loopx` route. + * The absolute executable bound at discovery and passed to Core as + * `--cli-bin`, pinning rendered continuation text (heartbeat task bodies, + * settlement command templates) to the same binary this adapter probes and + * spawns. Relative PATH entries are normalized against the discovery + * working directory. Undefined when no one executable can be bound — an + * interpreter plus module or managed-launcher prefix, or a name the probe + * environment cannot locate — leaving Core's bare `loopx` fallback route + * and the driver's unbound disclosure. */ readonly cliBin?: string | undefined readonly candidate?: LoopXCliDiagnostics['candidate'] @@ -496,8 +498,12 @@ function probeExecutableFile(directory: string, name: string): string | undefine const spellings = process.platform === 'win32' && !/\.(exe|com)$/iu.test(name) ? [name, `${name}.exe`] : [name] + // Normalize relative PATH entries against this process's working directory + // at discovery time. A relative route would re-resolve on every later + // spawn's cwd, letting the version probe, driver admission, and rendered + // Core commands select different installations of the same name. for (const spelling of spellings) { - const candidate = join(directory, spelling) + const candidate = join(resolve(directory), spelling) try { if (statSync(candidate, { throwIfNoEntry: false })?.isFile() !== true) continue accessSync(candidate, constants.X_OK) @@ -510,42 +516,42 @@ function probeExecutableFile(directory: string, name: string): string | undefine } /** - * Derive the one-executable Core `--cli-bin` route for a probeable command - * name. Bare names resolve to the exact PATH file the spawn environment would - * execute, so continuation text Core renders cannot drift to another PATH - * installation. Names Core's validator rejects (empty, option-like, control - * characters) return undefined; a bare name the probe PATH cannot resolve is - * returned unchanged so Core still pins the probed name instead of an - * invented path. + * Bind one probeable command name to the absolute executable the spawn + * environment would run: explicit paths normalize against the current working + * directory, and bare names resolve to the exact PATH file, with relative PATH + * entries made absolute at discovery. Returns undefined when no single + * executable can be bound — an illegal `--cli-bin` value, or a name the probe + * environment cannot locate — so callers keep the bare fallback route and + * disclose the unbound state instead of pinning a wrong or relative path. */ -function coreCliBinRoute( +function discoverExecutablePath( name: string, env: NodeJS.ProcessEnv, ): string | undefined { if (name === '' || name.startsWith('-') || /[\u0000-\u001f]/u.test(name)) { return undefined } - if (name.includes('/') || name.includes('\\')) return name + if (name.includes('/') || name.includes('\\')) return resolve(name) const searchPath = env.PATH ?? env.Path for (const directory of searchPath?.split(delimiter) ?? []) { - const resolved = probeExecutableFile(directory, name) - if (resolved !== undefined) return resolved + const discovered = probeExecutableFile(directory, name) + if (discovered !== undefined) return discovered } - return name + return undefined } -/** The one executable Core may embed as `--cli-bin` for this command, if any. */ +/** + * The one executable Core may embed as `--cli-bin` for this command, if any. + * Resolver-produced commands bind `cliBin` at discovery; a value Core's + * parser would reject is reported as unbound instead of breaking invocation. + */ export function coreRouteBin(command: LoopXCommand): string | undefined { - if (command.cliBin !== undefined) return command.cliBin - // Host-injected commands may predate the resolved route field. Pass their - // plain executable file through without re-resolving it: the driver cannot - // know which PATH the injecting resolver probed, so it must not invent one. - const file = command.file - if (command.prefix.length > 0 || file === '' || file.startsWith('-') - || /[\u0000-\u001f]/u.test(file)) { + const route = command.cliBin + if (route === undefined || route === '' || route.startsWith('-') + || /[\u0000-\u001f]/u.test(route)) { return undefined } - return file + return route } /** Resolve the console script first, then the stable Python module fallback. */ @@ -563,10 +569,14 @@ export async function resolveLoopXCommand( : [configuredPython] const managedLauncher = options.managedLauncher const probeEnv = options.env ?? process.env + // Bind single-executable routes before probing so the version probe, every + // later business spawn, and Core's rendered `--cli-bin` text all run one + // absolute file. Unbound candidates keep bare probe semantics and surface + // the unbound state through the driver's typed warning. const configuredRoute = configured - ? coreCliBinRoute(configured, probeEnv) + ? discoverExecutablePath(configured, probeEnv) : undefined - const pathLoopxRoute = configured ? undefined : coreCliBinRoute('loopx', probeEnv) + const pathLoopxRoute = configured ? undefined : discoverExecutablePath('loopx', probeEnv) const managedCandidates: Array> = configured || managedLauncher === undefined ? [] @@ -578,33 +588,42 @@ export async function resolveLoopXCommand( shellWord(managedLauncher.path), ].join(' '), })) - const candidates: Array> = configured + const candidates: Array<{ + readonly spec: Omit + readonly label: LoopXCliDiagnostics['candidate'] + }> = configured ? [{ - file: configured, - prefix: [], - skillCommand: '"$LOOPX_BIN"', - ...(configuredRoute === undefined ? {} : { cliBin: configuredRoute }), + spec: { + file: configuredRoute ?? configured, + prefix: [], + skillCommand: '"$LOOPX_BIN"', + ...(configuredRoute === undefined ? {} : { cliBin: configuredRoute }), + }, + label: 'configured-command', }] : [ - ...managedCandidates, + ...managedCandidates.map(spec => ({ spec, label: 'managed-launcher' as const })), { - file: 'loopx', - prefix: [], - skillCommand: 'loopx', - ...(pathLoopxRoute === undefined ? {} : { cliBin: pathLoopxRoute }), + spec: { + file: pathLoopxRoute ?? 'loopx', + prefix: [], + skillCommand: 'loopx', + ...(pathLoopxRoute === undefined ? {} : { cliBin: pathLoopxRoute }), + }, + label: 'path-loopx', }, ...pythonNames.map(pythonName => ({ - file: pythonName, - prefix: ['-m', 'loopx.cli'], - skillCommand: `${shellWord(pythonName)} -m loopx.cli`, + spec: { + file: pythonName, + prefix: ['-m', 'loopx.cli'], + skillCommand: `${shellWord(pythonName)} -m loopx.cli`, + }, + label: 'python-module' as const, })), ] const probes: LoopXCliError[] = [] - for (const candidate of candidates) { - const label = configured ? 'configured-command' - : managedCandidates.includes(candidate) ? 'managed-launcher' - : candidate.file === 'loopx' ? 'path-loopx' : 'python-module' + for (const { spec: candidate, label } of candidates) { const cwdExists = spawnCwdExists() try { const result = await runner( diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts index 50c74c939f..4bf79a2a4f 100644 --- a/packages/dsh-loopx-plugin/src/driver.ts +++ b/packages/dsh-loopx-plugin/src/driver.ts @@ -1522,8 +1522,10 @@ export class LoopXContinuationDriver { this.command = resolved if (coreRouteBin(resolved) === undefined) { // Interpreter-prefixed routes (managed launcher, python -m) cannot be - // one Core `--cli-bin` executable; continuation text keeps Core's bare - // `loopx`. Disclose once instead of pinning a wrong binary. + // one Core `--cli-bin` executable, and a name the resolver could not + // bind has no safe absolute route; continuation text keeps Core's + // bare `loopx` fallback. Disclose once instead of pinning a wrong + // or relative binary. this.warn( `dsh-loopx-driver: cli_route_unpinned candidate=${resolved.candidate ?? 'unknown'}` + ' hint=point LOOPX_BIN at one absolute loopx executable to pin continuation commands', diff --git a/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts b/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts index c999adf9de..9275ef216c 100644 --- a/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts +++ b/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts @@ -434,6 +434,7 @@ describe('DSH admission-to-closeout integration', () => { prefix: [], skillCommand: 'loopx', version, + cliBin: 'loopx', }), makeTurnInstanceId: () => turnInstanceId, retryDelaysMs: [0, 0], @@ -636,6 +637,7 @@ describe('DSH admission-to-closeout integration', () => { isLiveAgent: () => true, runner, retryDelaysMs: [0, 0], resolveCommand: async () => ({ file: 'loopx', prefix: [], skillCommand: 'loopx', version: 'loopx 2.3.0', + cliBin: 'loopx', }), makeTurnInstanceId: () => turnInstanceId, warn: message => { warnings.push(message) }, @@ -726,6 +728,7 @@ describe('DSH admission-to-closeout integration', () => { isLiveAgent: () => true, runner, retryDelaysMs: [0, 0], resolveCommand: async () => ({ file: 'loopx', prefix: [], skillCommand: 'loopx', version: 'loopx 2.3.0', + cliBin: 'loopx', }), makeTurnInstanceId: () => turnInstanceId, runDetached: async operation => { diff --git a/packages/dsh-loopx-plugin/tests/cli.spec.ts b/packages/dsh-loopx-plugin/tests/cli.spec.ts index 8baa690538..a7196d03eb 100644 --- a/packages/dsh-loopx-plugin/tests/cli.spec.ts +++ b/packages/dsh-loopx-plugin/tests/cli.spec.ts @@ -1,7 +1,7 @@ import { execFileSync } from 'node:child_process' -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { delimiter, join } from 'node:path' +import { delimiter, isAbsolute, join } from 'node:path' import { describe, expect, it } from 'vitest' import { LoopXCliError, @@ -328,12 +328,13 @@ describe('Core --cli-bin route derivation', () => { expect(resolved.cliBin).toBe(configured) }) - it('falls back to the configured name when the probe PATH cannot resolve it', async () => { + it('leaves an unlocatable configured name unpinned on the bare fallback', async () => { const resolved = await resolveLoopXCommand({ env: { LOOPX_BIN: 'nowhere-loopx', PATH: '/nonexistent-loopx-route' }, runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), }) - expect(resolved.cliBin).toBe('nowhere-loopx') + expect(resolved.file).toBe('nowhere-loopx') + expect(resolved.cliBin).toBeUndefined() }) it('leaves interpreter-prefixed routes unpinned', async () => { @@ -365,13 +366,11 @@ describe.skipIf(process.platform === 'win32')('Core --cli-bin PATH resolution', writeFileSync(pinned, '#!/bin/sh\nexit 0\n', { mode: 0o755 }) const resolved = await resolveLoopXCommand({ env: { PATH: dir }, - runner: async file => ({ - exitCode: file === 'loopx' ? 0 : 1, - stdout: file === 'loopx' ? 'loopx 2.4.0\n' : '', - stderr: '', - }), + runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), }) expect(resolved.candidate).toBe('path-loopx') + // The bound route is also the file the adapter probes and spawns. + expect(resolved.file).toBe(pinned) expect(resolved.cliBin).toBe(pinned) } finally { rmSync(dir, { recursive: true, force: true }) @@ -388,12 +387,36 @@ describe.skipIf(process.platform === 'win32')('Core --cli-bin PATH resolution', runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), }) expect(resolved.candidate).toBe('configured-command') + expect(resolved.file).toBe(pinned) expect(resolved.cliBin).toBe(pinned) } finally { rmSync(dir, { recursive: true, force: true }) } }) + it('normalizes a relative PATH entry against the discovery directory', async () => { + const root = mkdtempSync(join(tmpdir(), 'loopx-route-')) + const originalCwd = process.cwd() + try { + const written = join(root, 'bin', 'loopx') + mkdirSync(join(root, 'bin')) + writeFileSync(written, '#!/bin/sh\nexit 0\n', { mode: 0o755 }) + process.chdir(root) + const resolved = await resolveLoopXCommand({ + env: { PATH: ['bin', '/nonexistent-loopx-route'].join(delimiter) }, + runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), + }) + // resolve() binds through the physical working directory. + const pinned = realpathSync(written) + expect(isAbsolute(resolved.cliBin as string)).toBe(true) + expect(resolved.file).toBe(pinned) + expect(resolved.cliBin).toBe(pinned) + } finally { + process.chdir(originalCwd) + rmSync(root, { recursive: true, force: true }) + } + }) + it('prefers the first PATH entry and skips non-executable files', async () => { const root = mkdtempSync(join(tmpdir(), 'loopx-route-')) try { @@ -407,22 +430,14 @@ describe.skipIf(process.platform === 'win32')('Core --cli-bin PATH resolution', writeFileSync(plain, 'not executable\n', { mode: 0o644 }) const resolved = await resolveLoopXCommand({ env: { PATH: [first, second].join(delimiter) }, - runner: async file => ({ - exitCode: file === 'loopx' ? 0 : 1, - stdout: file === 'loopx' ? 'loopx 2.4.0\n' : '', - stderr: '', - }), + runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), }) expect(resolved.cliBin).toBe(executable) chmodSync(plain, 0o755) const flipped = await resolveLoopXCommand({ env: { PATH: [second, first].join(delimiter) }, - runner: async file => ({ - exitCode: file === 'loopx' ? 0 : 1, - stdout: file === 'loopx' ? 'loopx 2.4.0\n' : '', - stderr: '', - }), + runner: async () => ({ exitCode: 0, stdout: 'loopx 2.4.0\n', stderr: '' }), }) expect(flipped.cliBin).toBe(plain) } finally { diff --git a/packages/dsh-loopx-plugin/tests/driver.spec.ts b/packages/dsh-loopx-plugin/tests/driver.spec.ts index 8e5274d022..804b54ade4 100644 --- a/packages/dsh-loopx-plugin/tests/driver.spec.ts +++ b/packages/dsh-loopx-plugin/tests/driver.spec.ts @@ -1,14 +1,14 @@ import { randomUUID } from 'node:crypto' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { delimiter, isAbsolute, join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { Context, Logger, LoggerService } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import { SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent, UserMessage } from '@deepseek-ai/dsh-session' import type { FileRunner, LoopXCommand } from '../src/cli.ts' -import { LoopXCliError, resolveLoopXCommand } from '../src/cli.ts' +import { LoopXCliError, resolveLoopXCommand, runFile } from '../src/cli.ts' import { apply as applyDriver, LoopXContinuationDriver, @@ -44,7 +44,7 @@ function userMessage(text: string): UserMessage { } } -function fakeAgent(id = sessionId): FakeAgent { +function fakeAgent(id = sessionId, sessionCwd = '/fixture/project'): FakeAgent { const nextTurn: UserMessage[] = [] const nextStep: UserMessage[] = [] let status: 'idle' | 'running' = 'idle' @@ -90,7 +90,7 @@ function fakeAgent(id = sessionId): FakeAgent { version: 0, id, createdAt: 1, - cwd: '/fixture/project', + cwd: sessionCwd, seedLength: 0, }) const agent = { @@ -3427,3 +3427,122 @@ describe.skipIf(process.platform === 'win32')( }, 15_000) }, ) + +describe.skipIf(process.platform === 'win32')('route binding across working directories', () => { + // One LoopX-shaped script per working directory; each reports its own + // absolute path on stderr so every stage records the executable that ran. + function writeLoopxFixture(directory: string): string { + const binDirectory = join(directory, 'bin') + mkdirSync(binDirectory, { recursive: true }) + const file = join(binDirectory, 'loopx') + writeFileSync(file, [ + '#!/bin/sh', + 'self=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")', + 'echo "SELF=$self" >&2', + 'case "$*" in', + " *'--version'*) echo 'loopx 2.4.0';;", + " *'resolve-agent-thread'*) echo '{\"ok\":true,\"schema_version\":\"loopx_thread_agent_binding_resolution_v0\",\"host_surface\":\"deepseek-harness-native\",\"thread_id\":\"session-fixture\",\"status\":\"bound\",\"goal_id\":\"goal-fixture\",\"agent_id\":\"agent-fixture\",\"matches\":[{\"goal_id\":\"goal-fixture\",\"agent_id\":\"agent-fixture\"}]}';;", + " *'should-run'*) echo '{\"ok\":true,\"mode\":\"should-run\",\"goal_id\":\"goal-fixture\",\"should_run\":true,\"agent_identity\":{\"agent_id\":\"agent-fixture\",\"registered\":true},\"heartbeat_receipt\":{\"schema_version\":\"heartbeat_quota_receipt_v0\",\"turn_instance_id\":\"turn-stable\",\"status\":\"committed\"},\"scheduler_hint\":{\"action\":\"run_now\"}}';;", + " *'heartbeat-prompt'*) echo '{\"ok\":true,\"schema_version\":\"heartbeat_agent_input_v1\",\"goal_id\":\"goal-fixture\",\"agent_id\":\"agent-fixture\",\"turn_instance_id\":\"turn-stable\",\"task_body\":\"LOOPX_TURN=turn-stable Continue through the authoritative LoopX workflow.\"}';;", + 'esac', + '', + ].join('\n'), { mode: 0o755 }) + return file + } + + function selfPaths(stderr: string): string[] { + return stderr + .split('\n') + .filter(line => line.startsWith('SELF=')) + .map(line => line.slice('SELF='.length)) + } + + async function runRouteMatrix( + pathEntries: string[], + expectedLoopx: string, + resolveCwd: string, + ): Promise { + const root = mkdtempSync(join(tmpdir(), 'dsh-route-matrix-')) + const projectDir = join(root, 'project') + const agentDir = join(root, 'agent') + for (const directory of [projectDir, agentDir]) { + // Decoy installs the PATH must never select once the route is bound. + writeLoopxFixture(directory) + } + const searchEnv = { PATH: pathEntries.join(delimiter) } + const originalCwd = process.cwd() + const spawned: string[] = [] + const runner: FileRunner = (file, args, options) => runFile(file, args, { + ...options, + env: { ...options.env, ...searchEnv }, + }).then(result => { + spawned.push(...selfPaths(result.stderr)) + return result + }) + try { + process.chdir(resolveCwd) + // Stage 1: the version probe runs from the host working directory. + const resolved = await resolveLoopXCommand({ runner, env: searchEnv }) + expect(resolved.candidate).toBe('path-loopx') + expect(resolved.cliBin).toBeDefined() + expect(isAbsolute(resolved.cliBin as string)).toBe(true) + expect(resolved.cliBin).toBe(expectedLoopx) + + // Stage 2: driver admission spawns from the Session working directory. + const host = fakeAgent(sessionId, projectDir) + const admissionWarnings: string[] = [] + const driver = new LoopXContinuationDriver({ + runner, + isLiveAgent: () => true, + makeTurnInstanceId: () => 'turn-stable', + retryDelaysMs: [0, 0], + resolveCommand: async () => resolved, + warn: message => { admissionWarnings.push(message) }, + }) + observeActivated(driver, host) + // Real subprocess admission needs a wall-clock budget, not microtask polls. + for (let attempt = 0; attempt < 400 && host.nextTurn.length === 0; attempt += 1) { + await new Promise(resolve => setTimeout(resolve, 10)) + } + expect([...admissionWarnings, `spawned=${spawned.length}`]).toEqual([`spawned=${spawned.length}`]) + expect(host.nextTurn).toHaveLength(1) + await driver.dispose() + expect(spawned.length).toBeGreaterThan(3) + expect(new Set(spawned)).toEqual(new Set([expectedLoopx])) + + // Stage 3: the Core-rendered route executes in the agent directory. + const route = resolved.cliBin as string + const rendered = `${route} --cli-bin ${route} --format json quota should-run --goal-id goal-fixture` + const executed = await runFile('/bin/sh', ['-c', rendered], { + cwd: agentDir, + env: searchEnv, + }) + expect(selfPaths(executed.stderr)).toEqual([expectedLoopx]) + } finally { + process.chdir(originalCwd) + rmSync(root, { recursive: true, force: true }) + } + } + + it('binds probe, admission, and rendered execution to one executable through relative PATH entries', async () => { + const hostDir = mkdtempSync(join(tmpdir(), 'dsh-route-host-')) + try { + const hostLoopx = realpathSync(writeLoopxFixture(hostDir)) + await runRouteMatrix(['bin', '/usr/bin', '/bin'], hostLoopx, hostDir) + } finally { + rmSync(hostDir, { recursive: true, force: true }) + } + }, 20_000) + + it('keeps the same single executable when PATH entries are absolute', async () => { + // Control group: absolute PATH entries resist the per-cwd decoy installs, + // and an explicit absolute entry stays bound exactly as written. + const hostDir = mkdtempSync(join(tmpdir(), 'dsh-route-host-')) + try { + const hostLoopx = writeLoopxFixture(hostDir) + await runRouteMatrix([join(hostDir, 'bin'), '/usr/bin', '/bin'], hostLoopx, tmpdir()) + } finally { + rmSync(hostDir, { recursive: true, force: true }) + } + }, 20_000) +}) From 373a6e31d3b3f5a0341263922d847842f537a285 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:04:55 +0800 Subject: [PATCH 3/4] fix(dsh): pin managed continuation to the probed Python runtime Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- packages/dsh-loopx-plugin/README.md | 18 ++--- packages/dsh-loopx-plugin/src/cli.ts | 18 ++--- packages/dsh-loopx-plugin/src/driver.ts | 6 +- .../dsh-loopx-plugin/src/managed-runtime.ts | 47 +++++++++-- .../admission-closeout.integration.spec.ts | 77 ++++++++++++++++++- .../tests/init-command.spec.ts | 7 +- 6 files changed, 139 insertions(+), 34 deletions(-) diff --git a/packages/dsh-loopx-plugin/README.md b/packages/dsh-loopx-plugin/README.md index 7135651161..bb8baa8f16 100644 --- a/packages/dsh-loopx-plugin/README.md +++ b/packages/dsh-loopx-plugin/README.md @@ -71,16 +71,14 @@ owner. Older plugin releases retain their original CLI requirements. The continuation driver follows LoopX's context delivery setting. When the guard returns a capture reference, the driver reads the admission fields from that same capture. -Continuation Turns run Core-rendered commands (thin heartbeat bodies, quota -settlement templates) against the same executable the plugin probed: the -resolver binds one absolute file — normalizing relative `PATH` entries against -its discovery directory — and the Driver passes that route as Core's -`--cli-bin`, so the version probe, admission spawns, and rendered commands -share one executable. Interpreter-prefixed routes (the managed launcher, -`python -m loopx.cli`) and names the probe environment cannot locate cannot -be bound to one executable; their continuation text keeps Core's bare -`loopx` route, and the Driver discloses that once in its warning log. Point -`LOOPX_BIN` at one absolute loopx executable to pin those sessions. +The Driver uses Core's `--cli-bin` to keep thin heartbeat and quota settlement +commands on the same LoopX installation as admission. The resolver normalizes +relative `PATH` entries at discovery. On POSIX, the plugin-managed runtime +provides a launcher that runs the selected Python interpreter and managed +script by absolute path. If the plugin cannot bind a launcher (including on +Windows), or uses the `python -m loopx.cli` fallback, the Driver logs +`cli_route_unpinned` and Core renders bare `loopx` commands. Set `LOOPX_BIN` +to an absolute LoopX executable to pin those sessions. After the beta.8 GitHub release lists its tarball, install the pinned `0.1.1-beta.8` asset into the web profile. If the asset is not yet listed, diff --git a/packages/dsh-loopx-plugin/src/cli.ts b/packages/dsh-loopx-plugin/src/cli.ts index f5d0d52b70..c0653b50ac 100644 --- a/packages/dsh-loopx-plugin/src/cli.ts +++ b/packages/dsh-loopx-plugin/src/cli.ts @@ -486,7 +486,7 @@ export function supportedLoopXVersion( return !parsed[4] && (!parsed[6] || parsed[5]) ? value : undefined } -function shellWord(value: string): string { +export function shellWord(value: string): string { return /^[A-Za-z0-9_./:-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'` @@ -580,14 +580,14 @@ export async function resolveLoopXCommand( const managedCandidates: Array> = configured || managedLauncher === undefined ? [] - : [...new Set(managedLauncher.pythonBins)].map(pythonBin => ({ - file: pythonBin, - prefix: [managedLauncher.path], - skillCommand: [ - shellWord(pythonBin), - shellWord(managedLauncher.path), - ].join(' '), - })) + : [...new Set(managedLauncher.pythonBins)].map(pythonBin => { + const file = discoverExecutablePath(pythonBin, probeEnv) ?? pythonBin + return { + file, + prefix: [managedLauncher.path], + skillCommand: [shellWord(file), shellWord(managedLauncher.path)].join(' '), + } + }) const candidates: Array<{ readonly spec: Omit readonly label: LoopXCliDiagnostics['candidate'] diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts index 7b36f073ba..17b2d8d32a 100644 --- a/packages/dsh-loopx-plugin/src/driver.ts +++ b/packages/dsh-loopx-plugin/src/driver.ts @@ -1543,11 +1543,7 @@ export class LoopXContinuationDriver { if (!signal.aborted) { this.command = resolved if (coreRouteBin(resolved) === undefined) { - // Interpreter-prefixed routes (managed launcher, python -m) cannot be - // one Core `--cli-bin` executable, and a name the resolver could not - // bind has no safe absolute route; continuation text keeps Core's - // bare `loopx` fallback. Disclose once instead of pinning a wrong - // or relative binary. + // Without a bound executable, Core renders the bare `loopx` fallback. this.warn( `dsh-loopx-driver: cli_route_unpinned candidate=${resolved.candidate ?? 'unknown'}` + ' hint=point LOOPX_BIN at one absolute loopx executable to pin continuation commands', diff --git a/packages/dsh-loopx-plugin/src/managed-runtime.ts b/packages/dsh-loopx-plugin/src/managed-runtime.ts index df92e0610b..b43f8ec096 100644 --- a/packages/dsh-loopx-plugin/src/managed-runtime.ts +++ b/packages/dsh-loopx-plugin/src/managed-runtime.ts @@ -1,8 +1,9 @@ -import { stat } from 'node:fs/promises' -import { readdirSync } from 'node:fs' +import { createHash, randomUUID } from 'node:crypto' +import { access, readFile, rename, rm, stat, writeFile } from 'node:fs/promises' +import { constants, readdirSync } from 'node:fs' import { homedir } from 'node:os' -import { delimiter, join, resolve } from 'node:path' -import { resolveLoopXCommand, runFile } from './cli.ts' +import { delimiter, isAbsolute, join, resolve } from 'node:path' +import { resolveLoopXCommand, runFile, shellWord } from './cli.ts' import type { FileRunner, LoopXCommand } from './cli.ts' export const MANAGED_LAUNCHER_NAME = 'loopx_cli.py' @@ -70,11 +71,36 @@ export function pluginRuntimeDir(options: LoopXRuntimeOptions): string { ) } +async function managedExecutable( + runtimeDir: string, + python: string, + launcher: string, +): Promise { + const source = `#!/bin/sh\nexec ${shellWord(python)} ${shellWord(launcher)} "$@"\n` + // Keep queued commands pinned when a later resolver selects another Python. + const digest = createHash('sha256').update(source).digest('hex') + const executable = join(runtimeDir, `loopx-${digest}`) + const existing = await readFile(executable, 'utf8').catch(() => undefined) + if (existing === source && await access(executable, constants.X_OK).then(() => true, () => false)) { + return executable + } + const pending = join(runtimeDir, `.loopx-${randomUUID()}.tmp`) + try { + await writeFile(pending, source, { flag: 'wx', mode: 0o700 }) + await rename(pending, executable) + await access(executable, constants.X_OK) + } finally { + await rm(pending, { force: true }) + } + return executable +} + /** Resolve the exact CLI surface shared by bootstrap, Driver, and GoalBar. */ export async function resolvePluginLoopXCommand( options: LoopXRuntimeOptions = {}, ): Promise { - const launcherPath = join(pluginRuntimeDir(options), MANAGED_LAUNCHER_NAME) + const runtimeDir = pluginRuntimeDir(options) + const launcherPath = join(runtimeDir, MANAGED_LAUNCHER_NAME) const env = options.pythonBin === undefined ? options.env : { ...(options.env ?? process.env), PYTHON_BIN: options.pythonBin } @@ -82,7 +108,7 @@ export async function resolvePluginLoopXCommand( value => value.isFile(), () => false, ) - return resolveLoopXCommand({ + const command = await resolveLoopXCommand({ ...options, runner: options.runner ?? runFile, env, @@ -90,4 +116,13 @@ export async function resolvePluginLoopXCommand( ? { path: launcherPath, pythonBins: pluginPythonCandidates(options) } : undefined, }) + if (command.candidate !== 'managed-launcher' || process.platform === 'win32' + || !isAbsolute(command.file)) { + return command + } + // The Python invocation still works on a read-only runtime. Let the + // existing Driver warning explain why Core could not pin its commands. + const cliBin = await managedExecutable(runtimeDir, command.file, launcherPath) + .catch(() => undefined) + return cliBin === undefined ? command : { ...command, cliBin } } diff --git a/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts b/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts index 9275ef216c..063c965841 100644 --- a/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts +++ b/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts @@ -8,10 +8,12 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type { SessionEvent, UserMessage } from '@deepseek-ai/dsh-session' import { describe, expect, it, onTestFinished } from 'vitest' -import { LoopXCliError, runFile } from '../src/cli.ts' +import { coreRouteBin, LoopXCliError, runFile, runJsonCommand } from '../src/cli.ts' import type { FileRunner } from '../src/cli.ts' import { LoopXContinuationDriver } from '../src/driver.ts' -import { pluginPythonCandidates } from '../src/managed-runtime.ts' +import { + MANAGED_LAUNCHER_NAME, pluginPythonCandidates, resolvePluginLoopXCommand, +} from '../src/managed-runtime.ts' import { GoalBarCoordinator } from '../src/goalbar/events.ts' import { createGoalBarService } from '../src/goalbar/service.ts' @@ -298,6 +300,77 @@ function executablePlanArgs( } describe('DSH admission-to-closeout integration', () => { + it.skipIf(process.platform === 'win32')('keeps managed Core across a different agent PATH', async () => { + const f = await fixture() + const managed = join(f.runtime, "managed 'runtime") + const otherPath = join(f.runtime, 'other-bin') + const invocations = join(f.runtime, 'managed-invocations') + await mkdir(managed, { recursive: true }) + await mkdir(otherPath) + await writeFile(join(otherPath, 'loopx'), '#!/bin/sh\nexit 73\n', { mode: 0o700 }) + await writeFile(join(managed, MANAGED_LAUNCHER_NAME), [ + 'import sys', + `sys.path.insert(0, ${JSON.stringify(repoRoot)})`, + `with open(${JSON.stringify(invocations)}, "a") as log:`, + ' print(" ".join(sys.argv[1:]), file=log)', + 'if sys.argv[1:] == ["--version"]:', + ' from loopx import __version__', + ' print("loopx", __version__)', + ' raise SystemExit(0)', + 'from loopx.cli import main', + 'raise SystemExit(main(sys.argv[1:]))', + ].join('\n')) + const env = { + ...process.env, + LOOPX_BIN: '', + LOOPX_USAGE_PING: '0', + LOOPX_CONTEXT_DELIVERY: 'off', + LOOPX_TURN: turnInstanceId, + PATH: `${otherPath}:${process.env.PATH ?? ''}`, + } + expect((await runFile('loopx', ['--version'], { env })).exitCode).toBe(73) + const options = { env, runtimeDir: managed, pythonBin: await integrationPython } + const command = await resolvePluginLoopXCommand(options) + expect(command.candidate).toBe('managed-launcher') + const cliBin = coreRouteBin(command) + if (cliBin === undefined) throw new Error('The managed command has no continuation launcher') + expect(coreRouteBin(await resolvePluginLoopXCommand(options))).toBe(cliBin) + + const claimed = await runCli(f, [ + 'todo', 'claim', '--goal-id', goalId, '--todo-id', todoId, + '--agent-id', agentId, '--claimed-by', agentId, + ]) + expect(claimed.payload.ok).toBe(true) + const route = ['--cli-bin', cliBin] + const heartbeat = await runJsonCommand(command, [ + '--registry', f.registry, '--runtime-root', f.runtime, '--format', 'json', ...route, + 'heartbeat-prompt', '--thin', ...route, '--goal-id', goalId, '--agent-id', agentId, + '--runtime-profile', 'generic_cli', '--turn-instance-id', turnInstanceId, + ], { cwd: f.project, env }) + const guardCommand = String(heartbeat.task_body).split('\n') + .find(line => line.includes(' quota should-run ')) + if (guardCommand === undefined) throw new Error('The heartbeat has no quota guard') + const guard = await runFile('/bin/sh', ['-c', `${guardCommand} --todo-id ${todoId}`], { + cwd: otherPath, env, + }) + expect(guard.exitCode, guard.stderr || guard.stdout).toBe(0) + const channel = record(record(JSON.parse(guard.stdout).interaction_contract).cli_channel) + const steps = array(record(channel.settlement_plan).ordered_steps).map(record) + const template = String(steps.find(step => step.kind === 'durable_writeback')?.command_template) + const writebackCommand = template + .replace('', 'managed_route_validated') + .replace('', 'single_surface') + .replace('', 'outcome_progress') + const writeback = await runFile('/bin/sh', [ + '-c', `${writebackCommand} --no-global-sync --suppress-external-sinks`, + ], { cwd: f.project, env }) + expect(writeback.exitCode, writeback.stderr || writeback.stdout).toBe(0) + expect(receiptEffectIds(record(JSON.parse(writeback.stdout)))).toHaveLength(3) + expect(await readFile(invocations, 'utf8')).toMatch( + /heartbeat-prompt[\s\S]+quota should-run[\s\S]+refresh-state/u, + ) + }, 30_000) + it.skipIf(process.platform === 'win32').each(['file', 'sqlite'] as const)( 'fences an escaped old Pause after a newer Start on real %s authority', async provider => { const f = await fixture(provider) diff --git a/packages/dsh-loopx-plugin/tests/init-command.spec.ts b/packages/dsh-loopx-plugin/tests/init-command.spec.ts index 55ccd3e640..88010a9c55 100644 --- a/packages/dsh-loopx-plugin/tests/init-command.spec.ts +++ b/packages/dsh-loopx-plugin/tests/init-command.spec.ts @@ -600,6 +600,7 @@ describe('/loopx-init implementation', () => { const root = await mkdtemp(join(tmpdir(), 'dsh-loopx-managed-runtime-')) const runtimeDir = join(root, 'runtime') const launcherPath = join(runtimeDir, 'loopx_cli.py') + const pythonBin = join(root, 'bin', 'python3') await mkdir(runtimeDir, { recursive: true }) await writeFile(launcherPath, '# fixture launcher\n', 'utf8') const calls: Array<{ readonly file: string; readonly args: readonly string[] }> = [] @@ -621,11 +622,13 @@ describe('/loopx-init implementation', () => { } try { - const command = await resolvePluginLoopXCommand({ runner, runtimeDir }) + const command = await resolvePluginLoopXCommand({ runner, runtimeDir, pythonBin }) + expect(command.file).toBe(pythonBin) expect(command.prefix).toEqual([launcherPath]) const result = await initializeLoopX({ runner, runtimeDir, + pythonBin, skillsDir: join(root, 'skills'), }) expect(result.cliInstalled).toBe(false) @@ -634,7 +637,7 @@ describe('/loopx-init implementation', () => { ))).toBe(false) expect(calls.filter(call => call.args.includes('workflow-skills')).every(call => ( call.args[call.args.indexOf('--cli-bin') + 1] - === `python3 ${launcherPath}` + === command.skillCommand ))).toBe(true) } finally { await rm(root, { recursive: true, force: true }) From be2bd0b38163960c3560d0ebfcd225330e8c06b4 Mon Sep 17 00:00:00 2001 From: Lihua <1017343802@qq.com> Date: Tue, 24 Nov 2026 07:28:28 -0800 Subject: [PATCH 4/4] fix(dsh): pin host-injected absolute commands without the resolver field Round-2 review side note on #9309: a host-injected command with an explicit absolute file but no resolver-bound cliBin fell to the disclosed unpinned branch even though that file is exactly what the Driver spawns. coreRouteBin now passes one absolute, prefix-free injected file through unchanged (never re-resolved), while bare or relative names, interpreter-prefixed routes, and values Core's parser would reject stay unbound with the existing cli_route_unpinned disclosure. Adds unit coverage for the route handed to Core across injected shapes and driver-level red/green tests for the absolute pass-through and the bare/relative unpinned disclosure. Signed-off-by: Lihua <1017343802@qq.com> --- packages/dsh-loopx-plugin/src/cli.ts | 15 ++++-- packages/dsh-loopx-plugin/tests/cli.spec.ts | 26 +++++++++++ .../dsh-loopx-plugin/tests/driver.spec.ts | 46 +++++++++++++++++++ 3 files changed, 83 insertions(+), 4 deletions(-) diff --git a/packages/dsh-loopx-plugin/src/cli.ts b/packages/dsh-loopx-plugin/src/cli.ts index c0653b50ac..9abc5049e6 100644 --- a/packages/dsh-loopx-plugin/src/cli.ts +++ b/packages/dsh-loopx-plugin/src/cli.ts @@ -1,6 +1,6 @@ import { execFile, spawn } from 'node:child_process' import { accessSync, constants, statSync } from 'node:fs' -import { delimiter, join, resolve } from 'node:path' +import { delimiter, isAbsolute, join, resolve } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' // 2.4.0 adds the original-Turn receipt reader used by selection recovery. @@ -541,12 +541,19 @@ function discoverExecutablePath( } /** - * The one executable Core may embed as `--cli-bin` for this command, if any. - * Resolver-produced commands bind `cliBin` at discovery; a value Core's - * parser would reject is reported as unbound instead of breaking invocation. + * The one absolute executable Core may embed as `--cli-bin`, if any. + * + * Resolver-produced commands bind `cliBin` at discovery. A host-injected + * command may predate that field: when it names one absolute executable with + * no interpreter prefix, that file is exactly what the Driver spawns, so it + * passes through unchanged and is never re-resolved. Anything else — a bare + * or relative name, which depends on the caller's PATH or working directory, + * an interpreter-prefixed route, or a value Core's parser would reject — is + * unbound, so Core keeps its bare `loopx` fallback and the Driver discloses it. */ export function coreRouteBin(command: LoopXCommand): string | undefined { const route = command.cliBin + ?? (command.prefix.length === 0 && isAbsolute(command.file) ? command.file : undefined) if (route === undefined || route === '' || route.startsWith('-') || /[\u0000-\u001f]/u.test(route)) { return undefined diff --git a/packages/dsh-loopx-plugin/tests/cli.spec.ts b/packages/dsh-loopx-plugin/tests/cli.spec.ts index a7196d03eb..8ef42c4109 100644 --- a/packages/dsh-loopx-plugin/tests/cli.spec.ts +++ b/packages/dsh-loopx-plugin/tests/cli.spec.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest' import { LoopXCliError, cliErrorFields, + coreRouteBin, resolveLoopXCommand, runFile, runJsonCommand, @@ -446,6 +447,31 @@ describe.skipIf(process.platform === 'win32')('Core --cli-bin PATH resolution', }) }) +describe('route handed to Core for rendering', () => { + const shape = { skillCommand: 'loopx', version: 'loopx 2.4.0' } + const absolute = join(tmpdir(), 'injected', 'loopx') + + it('embeds the resolver-bound route over the spawned file', () => { + expect(coreRouteBin({ + ...shape, file: join(tmpdir(), 'other', 'loopx'), prefix: [], cliBin: absolute, + })).toBe(absolute) + }) + + it('passes a host-injected absolute executable through without re-resolving it', () => { + expect(coreRouteBin({ ...shape, file: absolute, prefix: [] })).toBe(absolute) + }) + + it.each([ + ['a bare name', { file: 'loopx', prefix: [] }], + ['a relative path', { file: join('bin', 'loopx'), prefix: [] }], + ['an interpreter prefix', { file: join(tmpdir(), 'python3'), prefix: [join(tmpdir(), 'loopx_cli.py')] }], + ['an option-like value', { file: absolute, prefix: [], cliBin: '--cli-bin' }], + ['a control character', { file: absolute, prefix: [], cliBin: 'loop\nx' }], + ])('reports %s as unbound', (_label, command) => { + expect(coreRouteBin({ ...shape, ...command })).toBeUndefined() + }) +}) + describe.skipIf(process.platform === 'win32')('owned CLI process group', () => { it.each(['timeout', 'abort', 'mutation', 'escaped pipe'] as const)( 'retires a descendant holding an inherited pipe on %s before returning or retrying', diff --git a/packages/dsh-loopx-plugin/tests/driver.spec.ts b/packages/dsh-loopx-plugin/tests/driver.spec.ts index 465de9715d..52412994e8 100644 --- a/packages/dsh-loopx-plugin/tests/driver.spec.ts +++ b/packages/dsh-loopx-plugin/tests/driver.spec.ts @@ -3585,6 +3585,52 @@ describe('continuation Core command route parity', () => { expect(unpinned).toHaveLength(1) expect(unpinned[0]).toContain('candidate=managed-launcher') }) + + it('keeps a host-injected absolute executable pinned without the resolver field', async () => { + const fixture = runnerFixture() + const host = fakeAgent() + const warnings: string[] = [] + const injected = join(tmpdir(), 'injected', 'loopx') + const driver = pinnedRouteDriver(fixture, { + file: injected, + prefix: [], + skillCommand: 'loopx', + version: 'loopx 2.4.0', + }, warnings) + await admittedQuotaAndHeartbeat(driver, host) + + // The injected file is exactly what the Driver spawns, so Core embeds it. + expect(fixture.quotaCalls.length).toBeGreaterThan(0) + for (const argv of fixture.quotaCalls) { + expect(argv[argv.indexOf('--cli-bin') + 1]).toBe(injected) + } + expect(fixture.heartbeatArgv.length).toBeGreaterThan(0) + for (const argv of fixture.heartbeatArgv) { + expect(argv.filter(value => value === '--cli-bin')).toHaveLength(2) + expect(argv[argv.indexOf('--cli-bin') + 1]).toBe(injected) + } + expect(warnings).toEqual([]) + }) + + it.each([ + ['bare', 'loopx'], + ['relative', join('bin', 'loopx')], + ])('leaves a host-injected %s name unbound and discloses it once', async (_kind, file) => { + // A name that depends on the caller's PATH or working directory is not a + // file the Driver can hand to Core; it keeps Core's default route. + const fixture = runnerFixture() + const host = fakeAgent() + const warnings: string[] = [] + const driver = pinnedRouteDriver(fixture, { + file, prefix: [], skillCommand: file, version: 'loopx 2.4.0', + }, warnings) + await admittedQuotaAndHeartbeat(driver, host) + + for (const argv of [...fixture.quotaCalls, ...fixture.heartbeatArgv]) { + expect(argv).not.toContain('--cli-bin') + } + expect(warnings.filter(value => value.includes('cli_route_unpinned'))).toHaveLength(1) + }) }) describe.skipIf(process.platform === 'win32')(