fix(runtime): close review lifecycle and bound gaps

This commit is contained in:
Tianyi Cui
2026-07-29 21:19:27 +08:00
parent 674d23118b
commit b71dbbe766
15 changed files with 130 additions and 29 deletions

View File

@@ -223,4 +223,5 @@ export class RuntimeOutputLedger {
}
export { decodeWorkerJson, encodeWorkerJson, snapshotCodeJsonValue } from './worker-json.ts'
export { jsonValueBytesUpTo } from './output-json.ts'
export type { WorkerJsonWire } from './worker-json.ts'

View File

@@ -106,6 +106,16 @@ export const Config: z<Config> = z.object({
servers: z.dict(LspLocalServerConfig).required(),
})
/** Propagate teardown failures only after every sibling has settled. */
function throwTeardownFailures(results: readonly PromiseSettledResult<void>[], message: string): void {
const failures: unknown[] = []
for (const result of results) {
if (result.status === 'rejected') failures.push(result.reason)
}
if (failures.length === 1) throw failures[0]
if (failures.length > 1) throw new AggregateError(failures, message)
}
/**
* Register the configured stdio LSP providers. Resolves every executable at load (after credential
* scrubbing) before publishing any provider; each process launches lazily on its first matching
@@ -169,7 +179,8 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
return async () => {
// Remove every route before process teardown so no new query can enter a draining provider.
for (const dispose of disposers.reverse()) dispose()
await Promise.all(providers.map(provider => provider.disposeAll()))
const results = await Promise.allSettled(providers.map(provider => provider.disposeAll()))
throwTeardownFailures(results, 'lsp-local provider teardown failed')
}
}, 'lsp-local.registerProviders')
}
@@ -346,12 +357,13 @@ class LocalLspProvider implements LspProvider {
const draining = [...this.queues.values()]
const resolving = [...this.workspaceLookups]
this.instances.clear()
await Promise.all([
const results = await Promise.allSettled([
...live.map(instance => instance.dispose()),
...draining,
...resolving,
])
this.queues.clear()
this.workspaceLookups.clear()
throwTeardownFailures(results, 'lsp-local instance teardown failed')
}
}

View File

@@ -350,6 +350,78 @@ describe('lsp-local end to end over a fake server', () => {
expect(signal.aborted).toBe(true)
})
it('waits for every owned teardown before aggregating instance failures', async () => {
let provider: LspProvider | undefined
const ctx = await mount({ LSP_FAKE_DEF: 'null' }, {}, (registered) => { provider = registered })
if (provider === undefined) throw new Error('expected lsp-local to register a provider')
const internals = provider as unknown as {
readonly instances: Map<string, { dispose(): Promise<void> }>
readonly queues: Map<string, Promise<void>>
readonly workspaceLookups: Set<Promise<void>>
disposeAll(): Promise<void>
}
const firstFailure = new Error('first instance cleanup failed')
const secondFailure = new Error('second instance cleanup failed')
const release = Promise.withResolvers<undefined>()
internals.instances.set('first', { dispose: async () => { throw firstFailure } })
internals.instances.set('second', { dispose: async () => { throw secondFailure } })
internals.queues.set('pending', release.promise)
internals.workspaceLookups.add(Promise.resolve())
let settled = false
const disposing = internals.disposeAll().finally(() => { settled = true })
await new Promise<void>(resolve => setImmediate(resolve))
expect(settled).toBe(false)
release.resolve(undefined)
await expect(disposing).rejects.toMatchObject({
errors: [firstFailure, secondFailure],
message: 'lsp-local instance teardown failed',
})
expect(internals.instances.size).toBe(0)
expect(internals.queues.size).toBe(0)
expect(internals.workspaceLookups.size).toBe(0)
await ctx.fiber.dispose()
})
it('waits for every provider before reporting plugin teardown failure', async () => {
const ctx = new Context()
const disposalErrors: unknown[] = []
ctx.logger.error = ((error: unknown) => { disposalErrors.push(error) }) as typeof ctx.logger.error
await ctx.plugin(Lsp)
await ctx.plugin(LocalSubprocessService)
await ctx.plugin(LocalFileSystem, { cwd: process.cwd() })
const providers: LspProvider[] = []
const register = ctx.lsp.registerProvider.bind(ctx.lsp)
const registrationSpy = vi.spyOn(ctx.lsp, 'registerProvider').mockImplementation((provider) => {
providers.push(provider)
return register(provider)
})
const fiber = await ctx.plugin(LspLocal, {
servers: {
first: fakeServer(),
second: fakeServer({}, { extensionToLanguage: { '.js': 'javascript' } }),
},
})
registrationSpy.mockRestore()
expect(providers).toHaveLength(2)
const failure = new Error('provider cleanup failed')
const release = Promise.withResolvers<undefined>()
const first = providers[0] as LspProvider & { disposeAll(): Promise<void> }
const second = providers[1] as LspProvider & { disposeAll(): Promise<void> }
first.disposeAll = async () => { throw failure }
second.disposeAll = async () => { await release.promise }
let disposed = false
const disposing = fiber.dispose().then(() => { disposed = true })
await new Promise<void>(resolve => setImmediate(resolve))
expect(disposed).toBe(false)
expect(disposalErrors).toEqual([])
release.resolve(undefined)
await disposing
expect(disposalErrors).toEqual([failure])
await ctx.fiber.dispose()
})
it('runs distinct workspaces in parallel instances', async () => {
const ws2 = join(root, 'ws2')
await mkdir(ws2)

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/pty/pty-local/README.md
README.md: c4af7bc8293689d64c58eebab2606d4f9b52fd2f
README.zh.md: 21075ccbf53d173a54220b58b384f01cfe50ced1
README.md: 92a3d7be68ada6f38ab3c4ca5bdd2622ebefc8ee
README.zh.md: 016043f7842df8bb963cdc5eea015666c9ce6941

View File

@@ -6,7 +6,7 @@ Persistent shell backend for `ctx.pty` over `ctx.subprocess.spawnTerminal`. It s
## Plugin (`pty-local`)
The plugin injects `pty`, `sandbox`, `sandboxPolicy`, and `subprocess`, then registers the configured backend type (`shell`). `danger-full-access` starts the shell directly; confined modes wrap the exact shell argv through `ctx.sandbox`. The effective session mode is resolved at spawn. A change to a different effective mode is rejected before its `sandbox/mode` event commits while that owner has an open PTY or a spawn in progress; the fence is attached to the exact owner and therefore outlives a provider reload that retains existing sessions. Wait for creation to settle and close the sessions before changing modes, so a terminal opened with wider access cannot survive a downgrade.
The plugin injects `pty`, `sandboxPolicy`, and `subprocess`, then registers the configured backend type (`shell`). `danger-full-access` starts the shell directly without requiring a sandbox provider; confined modes require a same-world `ctx.sandbox` and wrap the exact shell argv through it, failing before spawn when none is mounted. The effective session mode is resolved at spawn. A change to a different effective mode is rejected before its `sandbox/mode` event commits while that owner has an open PTY or a spawn in progress; the fence is attached to the exact owner and therefore outlives a provider reload that retains existing sessions. Wait for creation to settle and close the sessions before changing modes, so a terminal opened with wider access cannot survive a downgrade.
Readiness combines a foreground-verified private bash prompt marker, provider-reported foreground stdin-wait facts, silence fallback, and absolute timeout. A marker is not ready until the printable tail after the latest owned marker exactly equals the controlled `PS1`, including when the OSC marker and prompt are split across data callbacks; echoed input or output following an earlier prompt therefore cannot settle the current send. Prompt and silence evidence collected before the provider write, including while pre-write foreground inspection is pending, is discarded at the write boundary. When bash prints the marker before the terminal provider publishes its return to the foreground process group, polling retains the candidate for `handoffGraceMs` past the ordinary silence bound so a coincident handoff can win. An interactive child that inherits `PROMPT_COMMAND` therefore cannot suppress inferred-idle readiness until the absolute timeout. Unknown foreground state is never a positive exact-idle signal. A foreground group's stdin wait that existed before a send is likewise not post-write readiness: the same group must be observed outside that wait before a later wait can settle the send, while a changed foreground group is new evidence. During unpublished startup, a fallback requires observed output; zero-output silence cannot publish an empty session, and timeout rejects the spawn. Cancellation closes the unpublished shell and rejects with the caller's exact abort reason; `PtyBackendCleanupError` separately preserves a cleanup failure. The caller's signal is forwarded for terminal allocation and readiness initialization; after publication the handle owns its lifetime. Incomplete terminal-control sequences are bounded by `maxReadBytes` and discarded through their terminator after crossing that limit; malformed UTF-8 terminal output uses replacement characters, and a trailing carriage return is carried across callbacks so split CRLF becomes one newline.

View File

@@ -2,15 +2,15 @@
[English](README.md) | 中文
这是基于 `ctx.subprocess.spawnTerminal` `ctx.pty` 持久 shell 后端。它在共享 `ctx.sandboxPolicy` 下启动交互式 shell保留有界的逐行输出并检测就绪状态进程管理提供方负责 PTY 分配、环境清理、前台进程组、信号发送和完整终端会话清理。因此,同一个 PTY 后端可以与本地或远程执行世界提供方组合。
这是一个基于 `ctx.subprocess.spawnTerminal`、为 `ctx.pty` 提供的持久 shell 后端。它在共享 `ctx.sandboxPolicy` 下启动交互式 shell保留有界的逐行输出并检测就绪状态进程管理提供方负责 PTY 分配、环境清理、前台进程组、信号发送和完整终端会话清理。因此,同一个 PTY 后端可以与本地或远程执行世界提供方组合。
## 插件(`pty-local`
该插件注入 `pty``sandbox``sandboxPolicy``subprocess`,然后注册所配置的后端类型(`shell`)。`danger-full-access` 直接启动 shell受限模式则通过 `ctx.sandbox` 包装确切的 shell argv。系统在 spawn 时解析会话的实际模式。当某个所有者存在开放的 PTY 或正在进行 spawn 时,如果配置变更会得到不同的实际模式,系统会在对应 `sandbox/mode` 事件提交前拒绝该变更。该限制绑定到确切所有者,因此即使提供方重新加载并保留现有会话,它仍然有效。更改模式前,请等待创建结算并关闭会话,避免以更宽权限打开的终端在权限降级后继续存在。
该插件注入 `pty``sandboxPolicy``subprocess`,然后注册所配置的后端类型(`shell`)。`danger-full-access` 无需沙箱提供方即可直接启动 shell受限模式要求同一执行世界中存在 `ctx.sandbox`,并通过它包装确切的 shell argv,未挂载时会在 spawn 前失败。系统在 spawn 时解析会话的实际模式。当某个所有者存在开放的 PTY 或正在进行 spawn 时,如果配置变更会得到不同的实际模式,系统会在对应 `sandbox/mode` 事件提交前拒绝该变更。该限制绑定到确切所有者,因此即使提供方重新加载并保留现有会话,它仍然有效。更改模式前,请等待创建完成并关闭会话,避免以更宽权限打开的终端在权限降级后继续存在。
就绪检测结合以下机制:由前台状态验证的私有 bash 提示符标记、提供方报告的前台 stdin 等待事实、静默回退和绝对超时。只有最近一个自有标记之后的可打印尾部与受控 `PS1` 完全相等时,系统才会把标记视为就绪;即使 OSC 标记和提示符被拆到多个数据回调中也是如此。因此,如果回显输入或输出跟在先前提示符之后,该提示符无法使当前 send 完成。系统会在写入边界丢弃提供方写入前收集的提示符与静默证据,包括写入前前台检查尚未完成时收集的证据。如果 bash 在终端提供方发布其重新取得前台进程组的状态前打印标记,轮询会在普通静默上限之后再保留该候选状态 `handoffGraceMs`,使恰好同时发生的前台交接有机会胜出。因此,继承 `PROMPT_COMMAND` 的交互式子进程无法持续压制推断空闲就绪,最多只能延续到绝对超时。未知的前台状态绝不会作为精确空闲的正向信号。同样,一次 send 之前就已存在的前台进程组 stdin 等待并不代表写入后就绪:必须先观察到同一进程组脱离该等待,之后再次进入等待才能使该次 send 完成;前台进程组发生变化则构成新的证据。尚未发布的启动过程中,回退路径要求已经观察到输出;零输出静默不能发布空会话,超时则拒绝 spawn。取消操作会关闭尚未发布的 shell并以调用方提供的确切中止原因拒绝`PtyBackendCleanupError` 会单独保留清理失败。调用方信号会转发给终端分配就绪初始化;句柄一经发布,便负责自身生命周期。未完成的终端控制序列受 `maxReadBytes` 限制;超过上限后,系统会丢弃内容直到其终止符。格式错误的 UTF-8 终端输出使用替换字符;末尾的回车会跨回调保留,使拆分的 CRLF 合并为一个换行。
就绪检测结合以下机制:由前台状态验证的私有 bash 提示符标记、提供方报告的前台 stdin 等待事实、静默回退和绝对超时。只有最自有标记之后的可打印尾部与受控 `PS1` 完全相等,标记才算就绪;即使 OSC 标记和提示符被拆到多个数据回调中也一样。因此,较早提示符之后的回显输入或输出无法使当前 send 完成。提供方写入前收集的提示符与静默证据,包括写入前前台检查仍在等待时收集的证据,都会在写入边界丢弃。如果 bash 在终端提供方发布其重新取得前台进程组的状态前打印标记,轮询会在普通静默上限之后再保留该候选状态 `handoffGraceMs`,使恰好同时发生的前台交接有机会胜出。因此,继承 `PROMPT_COMMAND` 的交互式子进程无法一直抑制推断空闲就绪直至绝对超时。未知的前台状态绝不会作为精确空闲的正向信号。同样,一次 send 之前就已存在的前台进程组 stdin 等待并不代表写入后就绪:必须先观察到同一进程组脱离该等待,之后再次进入等待才能使该次 send 完成;前台进程组发生变化则构成新的证据。尚未发布的启动过程中,回退路径要求已经观察到输出;零输出静默不能发布空会话,超时则拒绝 spawn。取消操作会关闭尚未发布的 shell并以调用方提供的确切中止原因拒绝`PtyBackendCleanupError` 会单独保留清理失败。调用方的 signal 会转发给终端分配就绪初始化;发布后,句柄负责其生命周期。未完成的终端控制序列受 `maxReadBytes` 限制;超过上限后,系统会丢弃内容直到其终止符。格式错误的 UTF-8 终端输出使用替换字符;末尾的回车会跨回调保留,使拆分的 CRLF 合并为一个换行。
取消发送会先把排队输入标记为已取消,再求终端句柄向当前前台进程组发送真正的 `SIGINT`如果异步写入前检查随后结算,也无法执行该输入。如果提供方写入已在途,信号发送会等待写入结算;写入被拒绝时不会发送信号。取消的发送会保留其位,直写入前台信号发送都结算,因此后续发送既不会收到延迟字节,也不会成为该信号的目标。取消等待期间,绝对截止时间仍保持启用。信号发送失败属于终结性传输失败,并会使当前发送被拒绝。取消绝不会通过写入 `\x03` 模拟中断,因此原始模式程序仍可取消。关闭操作会拒绝新的公开信号、停止就绪轮询,并等待句柄执行由提供方负责的完整会话终止,后才将当前发送以 `session_exit` 结算
取消发送时,系统会先把排队输入标记为已取消,再求终端句柄向当前前台进程组发送真正的 `SIGINT`;异步写入前检查即使随后结算,也无法执行该输入。如果提供方写入已在途,信号发送会等待结算;写入被拒绝时不会发送信号。取消的 send 会保留其位,直写入前台信号发送都结算,因此后继 send 不会收到延迟字节或该信号。取消等待期间,绝对 deadline 仍保持启用。信号发送失败是终端传输失败,会拒绝活跃 send。取消绝不会通过写入 `\x03` 模拟中断,因此,即使程序运行在 raw 模式下,也仍可取消。关闭操作会拒绝新的公开信号、停止就绪轮询,并等待句柄提供方负责的完整会话终止,后才把活跃 send 结算为 `session_exit`
## 模型体验
@@ -22,15 +22,15 @@
#### Token 影响
消费方返回有界的后端输出前没有影响。此包不会把保留的 PTY scrollback 放入模型历史。
消费方返回有界的后端输出前没有影响。此包package不会把保留的 PTY scrollback 放入模型历史。
#### KV Cache 影响
不会直接失效提示词、schema 与追加结果由消费方负责。
不会直接使 KV Cache 失效提示词、schema 与追加结果由消费方负责。
## 已知限制与暂缓工作
## 已知限制与暂缓事项
- 输出按行规范化;不支持全屏备用缓冲区交互。
- 精确 stdin 等待检测取决于挂载的进程管理提供方;无法证明该事实的提供方使用提示符标记和静默/超时就绪机制。
- 清理保证遵循 `SubprocessTerminalHandle`;提供方特缺口属于该实现的契约,而非 PTY 消费方。
- 会话无法跨 harness 进程退出保留
- 精确 stdin 等待检测取决于挂载的进程管理提供方;无法证明该状态的提供方使用提示符标记和静默/超时就绪机制。
- 清理保证 `SubprocessTerminalHandle` 的保证为准;提供方特定的缺口属于该实现的契约,而非这个 PTY 消费方。
- harness 进程退出后,会话无法继续存在

View File

@@ -22,7 +22,7 @@ export type { Config as PtyLocalConfig } from './config.ts'
/** Cordis plugin name. */
export const name = 'pty-local'
/** Required services: PTY registry, shared confinement policy, and process substrate. */
export const inject = ['pty', 'sandbox', 'sandboxPolicy', 'subprocess']
export const inject = ['pty', 'sandboxPolicy', 'subprocess']
interface SandboxModeFenceState {
pty: Context['pty']
@@ -72,7 +72,11 @@ function spawnArgv(ctx: Context, config: ResolvedConfig, spec: PtyBackendSpawnSp
const argv = [config.shellPath, ...config.shellArgs]
const mode: SandboxMode = effectiveSandboxMode(spec.owner.session.events) ?? ctx.sandboxPolicy.defaultMode
if (mode === 'danger-full-access') return argv
return ctx.sandbox.confine(argv, {
const sandbox = ctx.get('sandbox')
if (sandbox === undefined) {
throw new Error(`pty-local: sandbox mode "${mode}" requires a ctx.sandbox provider in the execution world`)
}
return sandbox.confine(argv, {
mode: mode,
workspaceRoot: ctx.sandboxPolicy.workspaceRoot,
}).argv

View File

@@ -120,7 +120,6 @@ describe('LocalPtyBackend startup rollback', () => {
it('closes failed startup and aggregates cleanup failure', async () => {
const ctx = new Context()
await ctx.plugin(EmptySandbox)
await ctx.plugin(SandboxPolicyService, { mode: 'danger-full-access', workspaceRoot: '/tmp' })
const spawnTerminal = async (): Promise<SubprocessTerminalHandle> => terminalHandle()
@@ -186,6 +185,20 @@ describe('LocalPtyBackend startup rollback', () => {
expect(initialized).toHaveBeenCalledWith(undefined)
})
it('rejects a confined spawn without a sandbox provider', async () => {
const confinedCtx = new Context()
await confinedCtx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: '/workspace' })
const confined = new LocalPtyBackend(
confinedCtx,
config(),
async () => { throw new Error('terminal spawn must not run') },
() => stubLocalSession(),
)
await expect(confined.spawn(spec(agent(confinedCtx)))).rejects.toThrow(
'sandbox mode "workspace-write" requires a ctx.sandbox provider in the execution world',
)
})
it('forwards terminal allocation cancellation directly', async () => {
const ctx = new Context()
await ctx.plugin(EmptySandbox)
@@ -266,7 +279,7 @@ describe('pty-local plugin shape', () => {
const loader = Object.create(Loader.prototype) as Loader
const unwrapped = loader.unwrapExports(ptyLocal) as Record<string, unknown>
expect(unwrapped.name).toBe('pty-local')
expect(unwrapped.inject).toEqual(['pty', 'sandbox', 'sandboxPolicy', 'subprocess'])
expect(unwrapped.inject).toEqual(['pty', 'sandboxPolicy', 'subprocess'])
expect(unwrapped.Config).toBeDefined()
})
@@ -274,7 +287,6 @@ describe('pty-local plugin shape', () => {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
await ctx.plugin(PtyService)
await ctx.plugin(EmptySandbox)
await ctx.plugin(SandboxPolicyService, { mode: 'danger-full-access', workspaceRoot: '/tmp' })
await ctx.plugin(StubSubprocessService)
const fiber = await ctx.plugin(ptyLocal, config())