Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/dsh-loopx-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ 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.
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,
keep your installed version or use the source-build instructions below:
Expand Down
151 changes: 130 additions & 21 deletions packages/dsh-loopx-plugin/src/cli.ts
Original file line number Diff line number Diff line change
@@ -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, 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.
Expand Down Expand Up @@ -99,6 +100,17 @@ export interface LoopXCommand {
readonly prefix: readonly string[]
readonly skillCommand: string
readonly version: string
/**
* 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']
}

Expand Down Expand Up @@ -474,12 +486,81 @@ 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("'", `'"'"'`)}'`
}

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]
// 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(resolve(directory), spelling)
try {
if (statSync(candidate, { throwIfNoEntry: false })?.isFile() !== true) continue
accessSync(candidate, constants.X_OK)
} catch {
continue
}
return candidate
}
return undefined
}

/**
* 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 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 resolve(name)
const searchPath = env.PATH ?? env.Path
for (const directory of searchPath?.split(delimiter) ?? []) {
const discovered = probeExecutableFile(directory, name)
if (discovered !== undefined) return discovered
}
return undefined
}

/**
* 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
}
return route
}

/** Resolve the console script first, then the stable Python module fallback. */
export async function resolveLoopXCommand(
options: ResolveLoopXCommandOptions = {},
Expand All @@ -494,34 +575,62 @@ export async function resolveLoopXCommand(
? ['python3', 'python']
: [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
? discoverExecutablePath(configured, probeEnv)
: undefined
const pathLoopxRoute = configured ? undefined : discoverExecutablePath('loopx', probeEnv)
const managedCandidates: Array<Omit<LoopXCommand, 'version'>> = configured
|| managedLauncher === undefined
? []
: [...new Set(managedLauncher.pythonBins)].map(pythonBin => ({
file: pythonBin,
prefix: [managedLauncher.path],
skillCommand: [
shellWord(pythonBin),
shellWord(managedLauncher.path),
].join(' '),
}))
const candidates: Array<Omit<LoopXCommand, 'version'>> = configured
? [{ file: configured, prefix: [], skillCommand: '"$LOOPX_BIN"' }]
: [...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<LoopXCommand, 'version'>
readonly label: LoopXCliDiagnostics['candidate']
}> = configured
? [{
spec: {
file: configuredRoute ?? configured,
prefix: [],
skillCommand: '"$LOOPX_BIN"',
...(configuredRoute === undefined ? {} : { cliBin: configuredRoute }),
},
label: 'configured-command',
}]
: [
...managedCandidates,
{ file: 'loopx', prefix: [], skillCommand: 'loopx' },
...managedCandidates.map(spec => ({ spec, label: 'managed-launcher' as const })),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 插件自管运行时仍会把续跑交给另一套 Core。 未配置 LOOPX_BIN 时,存在自管 launcher 的真实 DSH resolver 优先选中它。用准确头的 Core 渲染真实 heartbeat 正文后,首个续跑 guard 仍以裸 loopx 开头,实际运行它命中了独立 PATH 替身。当前描述的 Fixes #9300 会一并关闭这个仍存在的安装路径问题。

让插件自管入口提供可直接执行、指向原隔离 runtime 的 launcher,向现有单可执行文件接口传它的绝对路径。用另一套 PATH 做反事实,核对 guard 和结算均命中同一 Core。若本 PR 先落单文件修复,保留 #9300 待后续解决自管路径,移除自动关闭声明。 用插件自管 runtime 和另一套 PATH CLI 运行已有公开发现和真实 heartbeat 渲染,再执行生成的 guard 与结算命令,核对所有边界选中同一 Core。

{
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(
Expand Down
28 changes: 27 additions & 1 deletion packages/dsh-loopx-plugin/src/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { SessionEvent, UserMessage } from '@deepseek-ai/dsh-session'
import {
LoopXCliError,
cliErrorFields,
coreRouteBin,
resolveLoopXCommand,
runJsonCommand,
supportedLoopXVersion,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1529,7 +1540,16 @@ export class LoopXContinuationDriver {
private async loopXCommand(signal: AbortSignal): Promise<LoopXCommand> {
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) {
// 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',
)
}
}
return resolved
}

Expand Down Expand Up @@ -1584,6 +1604,7 @@ export class LoopXContinuationDriver {
[
'--registry', '.loopx/registry.json',
'--format', 'json',
...coreRouteArgs(command),
'quota', 'should-run',
'--goal-id', binding.goalId,
'--agent-id', binding.agentId,
Expand Down Expand Up @@ -1644,7 +1665,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',
Expand Down
47 changes: 41 additions & 6 deletions packages/dsh-loopx-plugin/src/managed-runtime.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -70,24 +71,58 @@ export function pluginRuntimeDir(options: LoopXRuntimeOptions): string {
)
}

async function managedExecutable(
runtimeDir: string,
python: string,
launcher: string,
): Promise<string> {
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<LoopXCommand> {
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 }
const hasManagedLauncher = await stat(launcherPath).then(
value => value.isFile(),
() => false,
)
return resolveLoopXCommand({
const command = await resolveLoopXCommand({
...options,
runner: options.runner ?? runFile,
env,
managedLauncher: hasManagedLauncher
? { 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 }
}
Loading
Loading