3672cd25b4
Review direction (tianyicui, PR #660): in a stacked PR, change all other process-running places to use the new service. - lsp-local: LspConnection spawns through ctx.subprocess (piped protocol streams + a no-spill collected stderr tail); its private process-tree helpers (POSIX group signalling, Windows taskkill, liveness polling) are deleted in favor of the seam's handle verbs, and its buildChildEnv now rides scrubbedParentEnv (LSP children also stop inheriting stale DSH_*). The plugin injects 'subprocess'; compositions/tests mount dsh-subprocess-local. - subagent-acp: the ACP child spawns through the seam (piped ndjson streams, inherited stderr); spawn failure surfaces through done-rejection into the same startup race; disposal is handle.dispose with the plugin's configured graces. dsh-subagent-subprocess is DELETED — its dispose ladder and scrub are the seam's, and the isolated-config-dir helper had no consumer. - mcp-client, pty-local, sdk-helper: adopt scrubbedParentEnv as the one scrub definition (their spawns stay put by ownership: the MCP SDK and node-pty own those calls; the SDK wizard runs outside any composition). - Coverage: per-file 100% over every touched src file, with each v8 ignore carrying a platform or contract reason; new suites cover stdio dispositions, the dispose ladder tiers, injected-win32 tree semantics, waitForExit, settled-kill/terminate no-ops, and spawn-failure disposal. - Docs: consumer-migration Agent Note (en; zh follows in this PR), seam note updated in place, subprocess.md rewritten for the reshaped vocabulary (type-equiv re-registered), READMEs and SERVICE_ROLES updated, taskkill added to knip ignoreBinaries.
137 lines
5.2 KiB
TypeScript
137 lines
5.2 KiB
TypeScript
/**
|
|
* Local persistent PTY backend using public `node-pty` APIs, shared sandbox
|
|
* policy, bounded output, platform readiness probes, and process-session cleanup.
|
|
* @module @deepseek-ai/dsh-pty-local
|
|
*/
|
|
|
|
import { Context } from 'cordis'
|
|
import * as nodePty from 'node-pty'
|
|
import type { IPtyForkOptions } from 'node-pty'
|
|
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
|
import { PtyBackendCleanupError } from '@deepseek-ai/dsh-pty'
|
|
import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
|
|
import type { PtyBackend, PtyBackendSpawnSpec } from '@deepseek-ai/dsh-pty'
|
|
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
|
|
import { effectiveSandboxMode } from '@deepseek-ai/dsh-sandbox-policy'
|
|
import { type Config, type ResolvedConfig, validateConfig } from './config.ts'
|
|
import { createProcessInspector } from './process-inspector.ts'
|
|
import type { ProcessInspector } from './process-inspector.ts'
|
|
import { LocalPtySession } from './session.ts'
|
|
|
|
export { Config } from './config.ts'
|
|
export type { Config as PtyLocalConfig } from './config.ts'
|
|
|
|
/** Cordis plugin name. */
|
|
export const name = 'pty-local'
|
|
/** Required services: PTY registry plus the one shared confinement policy. */
|
|
export const inject = ['pty', 'sandbox', 'sandboxPolicy']
|
|
|
|
interface SandboxModeFenceState {
|
|
pty: Context['pty']
|
|
sandboxPolicy: Context['sandboxPolicy']
|
|
}
|
|
|
|
const sandboxModeFences = new WeakMap<Agent, SandboxModeFenceState>()
|
|
|
|
function ensureSandboxModeFence(ctx: Context, owner: Agent): void {
|
|
const existing = sandboxModeFences.get(owner)
|
|
if (existing !== undefined) {
|
|
existing.pty = ctx.pty
|
|
existing.sandboxPolicy = ctx.sandboxPolicy
|
|
return
|
|
}
|
|
const state: SandboxModeFenceState = { pty: ctx.pty, sandboxPolicy: ctx.sandboxPolicy }
|
|
sandboxModeFences.set(owner, state)
|
|
owner.ctx.on('internal/dispatch', (_mode, eventName, args) => {
|
|
if (eventName !== 'session/event') return
|
|
const [session, event] = args as [Session, SessionEvent]
|
|
if (session !== owner.session || event.type !== 'sandbox/mode') return
|
|
const currentMode = effectiveSandboxMode(session.events) ?? state.sandboxPolicy.defaultMode
|
|
if (event.data.mode === currentMode || !state.pty.hasOwnerActivity(owner)) return
|
|
throw new Error(
|
|
`cannot change sandbox mode from "${currentMode}" to "${event.data.mode}" while persistent terminal sessions are open or being created; wait for creation to settle and close them first`,
|
|
)
|
|
}, { global: true })
|
|
}
|
|
|
|
function childEnvironment(spec: PtyBackendSpawnSpec): NodeJS.ProcessEnv {
|
|
// node-pty owns the spawn; the base env shares the subprocess seam's scrub.
|
|
return {
|
|
...scrubbedParentEnv(),
|
|
TERM: 'dumb',
|
|
PAGER: 'cat',
|
|
GIT_PAGER: 'cat',
|
|
PS1: 'dsh> ',
|
|
PROMPT_COMMAND: 'printf "\\033]133;D;%s\\007" "$?"',
|
|
BASH_SILENCE_DEPRECATION_WARNING: '1',
|
|
DSH_SHELL: '1',
|
|
DSH_SESSION_ID: spec.owner.id,
|
|
DSH_PTY_SESSION_ID: spec.sessionId,
|
|
}
|
|
}
|
|
|
|
function spawnArgv(ctx: Context, config: ResolvedConfig, spec: PtyBackendSpawnSpec): string[] {
|
|
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, {
|
|
mode: mode,
|
|
workspaceRoot: ctx.sandboxPolicy.workspaceRoot,
|
|
}).argv
|
|
}
|
|
|
|
/** Local shell backend registered under the configured type. */
|
|
export class LocalPtyBackend implements PtyBackend {
|
|
readonly type: string
|
|
|
|
constructor(
|
|
private readonly ctx: Context,
|
|
private readonly config: ResolvedConfig,
|
|
private readonly inspector: ProcessInspector,
|
|
private readonly spawnTerminal: typeof nodePty.spawn = nodePty.spawn,
|
|
private readonly createSession: (
|
|
terminal: ReturnType<typeof nodePty.spawn>,
|
|
inspector: ProcessInspector,
|
|
config: ResolvedConfig,
|
|
) => LocalPtySession = (terminal, inspector, config) => new LocalPtySession(terminal, inspector, config),
|
|
) {
|
|
this.type = config.backendType
|
|
}
|
|
|
|
async spawn(spec: PtyBackendSpawnSpec): Promise<LocalPtySession> {
|
|
spec.signal?.throwIfAborted()
|
|
ensureSandboxModeFence(this.ctx, spec.owner)
|
|
const argv = spawnArgv(this.ctx, this.config, spec)
|
|
const file = argv[0]
|
|
if (file === undefined) throw new Error('pty-local: sandbox returned empty argv')
|
|
const options: IPtyForkOptions = {
|
|
name: 'dumb',
|
|
cols: this.config.cols,
|
|
rows: this.config.rows,
|
|
cwd: spec.cwd ?? this.ctx.sandboxPolicy.workspaceRoot,
|
|
env: childEnvironment(spec),
|
|
}
|
|
const terminal = this.spawnTerminal(file, argv.slice(1), options)
|
|
const session = this.createSession(terminal, this.inspector, this.config)
|
|
try {
|
|
await session.initialize(spec.signal)
|
|
return session
|
|
} catch (error) {
|
|
try {
|
|
await session.close('PTY startup failed')
|
|
} catch (closeError: unknown) {
|
|
throw new PtyBackendCleanupError(error, closeError)
|
|
}
|
|
throw error
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Register the local PTY backend. */
|
|
export function apply(ctx: Context, config: Config): void {
|
|
validateConfig(config)
|
|
const inspector = createProcessInspector()
|
|
ctx.pty.registerBackend(new LocalPtyBackend(ctx, config, inspector))
|
|
}
|