Machine-produced by `pnpm run rescope-vendor --apply` plus the regeneration it prints: `pnpm install` for the lockfile, `pnpm run gen-third-party-notices`, `verify-translation-pairing --write` for the touched bilingual pairs, `gen-doc-graphs`, and one typert snapshot whose ids embed character offsets. `pnpm run rescope-vendor --check` verifies the result. Renames nine vendored packages (cordis, cosmokit, schemastery and the six @cordisjs plugins) and every reference that resolves them: manifest names and dependency keys, module specifiers including declare-module merges, cordis.yml plugin names, tsconfig paths, every Markdown fence, and `docs/` prose. Directory names, upstream versions, and dependency ranges are unchanged, so vendor/README.md still reads as an upstream snapshot; its manifest table gains an upstream-name column so THIRD_PARTY_NOTICES keeps MIT attribution pointed at each fork's origin. The tutorial tier follows the rename end to end: its yaml fences named plugins the Loader can no longer resolve, its `ts ignore-check` fences disagreed with the compiled fences beside them, and its prose quoted both. The contracts that told readers to keep upstream names — the root convention and the vendoring cookbook's tree comment and manifest invariant — now say to rescope instead. Two rules read `@deepseek-ai/` as "another workspace plugin": the client bundle purity gate now names the vendored libraries a browser bundle inlines, and the files where a bare `cordis` is an agent-preset id keep that product data.
154 lines
6.0 KiB
TypeScript
154 lines
6.0 KiB
TypeScript
/**
|
|
* Persistent shell PTY backend over the subprocess terminal primitive, shared
|
|
* sandbox policy, bounded output, and provider-owned session cleanup.
|
|
* @module @deepseek-ai/dsh-pty-local
|
|
*/
|
|
|
|
import { Context } from '@deepseek-ai/cordis'
|
|
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 type { PtyBackend, PtyBackendSpawnSpec } from '@deepseek-ai/dsh-pty'
|
|
import type { SubprocessTerminalHandle, SubprocessTerminalSpawnSpec } from '@deepseek-ai/dsh-subprocess'
|
|
import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
|
import { effectiveSandboxMode } from '@deepseek-ai/dsh-sandbox-policy'
|
|
import { type Config, type ResolvedConfig, validateConfig } from './config.ts'
|
|
import { LocalPtySession } from './session.ts'
|
|
import { CONTROLLED_PROMPT } from './sanitize.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, shared confinement policy, and process substrate. */
|
|
export const inject = ['pty', 'sandboxPolicy', 'subprocess']
|
|
|
|
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): Record<string, string> {
|
|
// The subprocess provider supplies its own scrubbed ambient base; these are
|
|
// deliberate terminal-specific overrides layered after it.
|
|
return {
|
|
TERM: 'dumb',
|
|
PAGER: 'cat',
|
|
GIT_PAGER: 'cat',
|
|
PS1: CONTROLLED_PROMPT,
|
|
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, policy: SandboxExecutionPolicy): string[] {
|
|
const argv = [config.shellPath, ...config.shellArgs]
|
|
if (policy.mode === 'danger-full-access') return argv
|
|
const sandbox = ctx.get('sandbox')
|
|
if (sandbox === undefined) {
|
|
throw new Error(`pty-local: sandbox mode "${policy.mode}" requires a ctx.sandbox provider in the execution world`)
|
|
}
|
|
// Re-state the discriminant because object spread does not preserve its narrowed type.
|
|
return sandbox.confine(argv, { ...policy, mode: policy.mode }).argv
|
|
}
|
|
|
|
// TODO(pty-initialize-race-home): Fold this outer abort race into
|
|
// LocalPtySession.initialize when the send-state consolidation lands; the
|
|
// session already owns the send lifecycle the race protects.
|
|
async function initializeSession(session: LocalPtySession, signal?: AbortSignal): Promise<void> {
|
|
if (signal === undefined) {
|
|
await session.initialize(signal)
|
|
return
|
|
}
|
|
const aborted = Promise.withResolvers<never>()
|
|
const onAbort = (): void => { aborted.reject(signal.reason) }
|
|
signal.addEventListener('abort', onAbort, { once: true })
|
|
try {
|
|
signal.throwIfAborted()
|
|
await Promise.race([session.initialize(signal), aborted.promise])
|
|
} finally {
|
|
signal.removeEventListener('abort', onAbort)
|
|
}
|
|
}
|
|
|
|
/** 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 spawnTerminal: (
|
|
spec: SubprocessTerminalSpawnSpec,
|
|
) => Promise<SubprocessTerminalHandle> = spec => ctx.subprocess.spawnTerminal(spec),
|
|
private readonly createSession: (
|
|
terminal: SubprocessTerminalHandle,
|
|
config: ResolvedConfig,
|
|
) => LocalPtySession = (terminal, config) => new LocalPtySession(terminal, config),
|
|
) {
|
|
this.type = config.backendType
|
|
}
|
|
|
|
async spawn(spec: PtyBackendSpawnSpec): Promise<LocalPtySession> {
|
|
spec.signal?.throwIfAborted()
|
|
ensureSandboxModeFence(this.ctx, spec.owner)
|
|
const policy = this.ctx.sandboxPolicy.resolve({ session: spec.owner.session })
|
|
const argv = spawnArgv(this.ctx, this.config, policy)
|
|
if (argv[0] === undefined) throw new Error('pty-local: sandbox returned empty argv')
|
|
const terminal = await this.spawnTerminal({
|
|
argv,
|
|
cwd: spec.cwd ?? policy.workspaceRoot,
|
|
env: childEnvironment(spec),
|
|
rows: this.config.rows,
|
|
cols: this.config.cols,
|
|
graceMs: this.config.disposeGraceMs,
|
|
signal: spec.signal,
|
|
})
|
|
const session = this.createSession(terminal, this.config)
|
|
try {
|
|
await initializeSession(session, 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)
|
|
ctx.pty.registerBackend(new LocalPtyBackend(ctx, config))
|
|
}
|