@shuind/dsh-codex-harness 0.2.21 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +185 -0
- package/README.md +38 -50
- package/RELEASE.md +61 -0
- package/assets/codex.svg +5 -0
- package/cordis.patch.yml +181 -6
- package/docs/preset-library.md +33 -23
- package/docs/tool-policy-benchmark.json +310 -0
- package/docs/tool-policy.md +148 -0
- package/lib/client.js +4774 -2416
- package/lib/compact-command.js +416 -0
- package/lib/compaction.js +141 -12
- package/lib/hybrid-executor.js +1196 -0
- package/lib/index.js +3658 -2334
- package/lib/preferences.js +117 -0
- package/lib/tool-policy.js +2422 -0
- package/lib/typert.js +86 -79
- package/lib/types/client/activity.d.ts +33 -9
- package/lib/types/client/activity.js +4 -3
- package/lib/types/client/desktop.d.ts +67 -0
- package/lib/types/client/desktop.js +229 -0
- package/lib/types/client/index.d.ts +207 -110
- package/lib/types/client/index.js +99 -492
- package/lib/types/client/policy-drafts.d.ts +25 -0
- package/lib/types/client/policy-drafts.js +47 -0
- package/lib/types/client/policy-locale.d.ts +260 -0
- package/lib/types/client/policy-locale.js +357 -0
- package/lib/types/client/preset-manager.d.ts +38 -10
- package/lib/types/client/preset-manager.js +235 -185
- package/lib/types/client/preset-requests.d.ts +12 -0
- package/lib/types/client/preset-requests.js +101 -0
- package/lib/types/client/tool-policy.d.ts +33 -0
- package/lib/types/client/tool-policy.js +336 -0
- package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
- package/lib/types/contracts/preset-editor-schema.js +95 -0
- package/lib/types/{prompt.js → contracts/prompt.js} +13 -7
- package/lib/types/{settings.d.ts → contracts/settings.d.ts} +11 -4
- package/lib/types/{settings.js → contracts/settings.js} +22 -6
- package/lib/types/contracts/tool-policy-contract.d.ts +63 -0
- package/lib/types/contracts/tool-policy-contract.js +33 -0
- package/lib/types/contracts/ui-contracts.d.ts +92 -0
- package/lib/types/contracts/ui-contracts.js +83 -0
- package/lib/types/entries/client.d.ts +10 -0
- package/lib/types/entries/client.js +10 -0
- package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
- package/lib/types/entries/compact-command.js +176 -0
- package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +15 -3
- package/lib/types/{compaction.js → entries/compaction.js} +47 -11
- package/lib/types/entries/hybrid-executor.d.ts +19 -0
- package/lib/types/entries/hybrid-executor.js +57 -0
- package/lib/types/entries/index.d.ts +66 -0
- package/lib/types/entries/index.js +192 -0
- package/lib/types/entries/preferences.d.ts +11 -0
- package/lib/types/entries/preferences.js +16 -0
- package/lib/types/entries/tool-policy.d.ts +97 -0
- package/lib/types/entries/tool-policy.js +158 -0
- package/lib/types/entries/typert.host.d.ts +23 -0
- package/lib/types/entries/typert.host.js +24 -0
- package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
- package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
- package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
- package/lib/types/hybrid/hybrid-sdk.js +196 -0
- package/lib/types/hybrid/program-calls.d.ts +28 -0
- package/lib/types/hybrid/program-calls.js +193 -0
- package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
- package/lib/types/hybrid/subcall-scheduler.js +343 -0
- package/lib/types/policy/deferred-tools.d.ts +42 -0
- package/lib/types/policy/deferred-tools.js +264 -0
- package/lib/types/policy/overlay-installer.d.ts +12 -0
- package/lib/types/policy/overlay-installer.js +179 -0
- package/lib/types/policy/rule-resolver.d.ts +94 -0
- package/lib/types/policy/rule-resolver.js +114 -0
- package/lib/types/policy/tool-capabilities.d.ts +33 -0
- package/lib/types/policy/tool-capabilities.js +46 -0
- package/lib/types/{activity.d.ts → presets/activity.d.ts} +3 -5
- package/lib/types/{activity.js → presets/activity.js} +51 -27
- package/lib/types/presets/desktop-preset.d.ts +22 -0
- package/lib/types/presets/desktop-preset.js +43 -0
- package/lib/types/presets/preset-editor.d.ts +47 -0
- package/lib/types/presets/preset-editor.js +81 -0
- package/lib/types/presets/preset-prompt-catalog.d.ts +23 -0
- package/lib/types/presets/preset-prompt-catalog.js +215 -0
- package/lib/types/presets/preset-tool-catalog.d.ts +5 -0
- package/lib/types/presets/preset-tool-catalog.js +58 -0
- package/lib/types/presets/runtime-enhancements.d.ts +45 -0
- package/lib/types/presets/runtime-enhancements.js +349 -0
- package/lib/types/presets/small-window-compaction.d.ts +15 -0
- package/lib/types/presets/small-window-compaction.js +121 -0
- package/lib/types/responses/compact-checkpoint.d.ts +27 -0
- package/lib/types/responses/compact-checkpoint.js +257 -0
- package/lib/types/responses/fetch-transport.d.ts +16 -0
- package/lib/types/responses/fetch-transport.js +257 -0
- package/lib/types/responses/remote-compact.d.ts +13 -0
- package/lib/types/responses/remote-compact.js +319 -0
- package/lib/types/responses/sse-diagnostics.d.ts +9 -0
- package/lib/types/responses/sse-diagnostics.js +157 -0
- package/lib/types/responses/wire-rewrite.d.ts +35 -0
- package/lib/types/responses/wire-rewrite.js +237 -0
- package/lib/types/tools/exec-output.d.ts +58 -0
- package/lib/types/tools/exec-output.js +173 -0
- package/lib/types/tools/exec-plan-tools.d.ts +37 -0
- package/lib/types/tools/exec-plan-tools.js +265 -0
- package/lib/types/tools/exec-runner.d.ts +21 -0
- package/lib/types/tools/exec-runner.js +385 -0
- package/lib/types/tools/patch-tool.d.ts +16 -0
- package/lib/types/tools/patch-tool.js +258 -0
- package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
- package/lib/types/{patch.js → tools/patch.js} +96 -21
- package/locale/en.json +6 -0
- package/locale/hybrid-executor/en.json +6 -0
- package/locale/hybrid-executor/zh.json +6 -0
- package/locale/tool-policy/en.json +6 -0
- package/locale/tool-policy/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +297 -299
- package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
- package/presets/codex-hybrid/preset.yml +3 -0
- package/scripts/benchmark-tool-policy.mjs +186 -0
- package/scripts/build-preset.mjs +19 -0
- package/scripts/clean-build.mjs +11 -0
- package/src/client/activity.ts +83 -0
- package/src/client/desktop.tsx +276 -0
- package/src/client/index.tsx +391 -0
- package/src/client/policy-drafts.ts +56 -0
- package/src/client/policy-locale.ts +362 -0
- package/src/client/preset-manager.tsx +376 -0
- package/src/client/preset-requests.ts +113 -0
- package/src/client/tool-policy.tsx +402 -0
- package/src/contracts/preset-editor-schema.ts +110 -0
- package/src/contracts/prompt.ts +66 -0
- package/src/contracts/settings.ts +103 -0
- package/src/contracts/tool-policy-contract.ts +93 -0
- package/src/contracts/ui-contracts.ts +173 -0
- package/src/entries/client.tsx +14 -0
- package/src/entries/compact-command.ts +256 -0
- package/src/entries/compaction.ts +218 -0
- package/src/entries/hybrid-executor.ts +76 -0
- package/src/entries/index.ts +298 -0
- package/src/entries/preferences.ts +17 -0
- package/src/entries/tool-policy.ts +162 -0
- package/src/entries/typert.host.ts +29 -0
- package/src/hybrid/codex-hybrid-executor.ts +310 -0
- package/src/hybrid/hybrid-sdk.ts +217 -0
- package/src/hybrid/program-calls.ts +202 -0
- package/src/hybrid/subcall-scheduler.ts +446 -0
- package/src/policy/deferred-tools.ts +331 -0
- package/src/policy/overlay-installer.ts +191 -0
- package/src/policy/rule-resolver.ts +128 -0
- package/src/policy/tool-capabilities.ts +88 -0
- package/src/presets/activity.ts +146 -0
- package/src/presets/desktop-preset.ts +60 -0
- package/src/presets/preset-editor.ts +101 -0
- package/src/presets/preset-prompt-catalog.ts +221 -0
- package/src/presets/preset-tool-catalog.ts +58 -0
- package/src/presets/runtime-enhancements.ts +415 -0
- package/src/presets/small-window-compaction.ts +166 -0
- package/src/responses/compact-checkpoint.ts +264 -0
- package/src/responses/fetch-transport.ts +290 -0
- package/src/responses/remote-compact.ts +393 -0
- package/src/responses/sse-diagnostics.ts +156 -0
- package/src/responses/wire-rewrite.ts +261 -0
- package/src/tools/exec-output.ts +211 -0
- package/src/tools/exec-plan-tools.ts +307 -0
- package/src/tools/exec-runner.ts +445 -0
- package/src/tools/patch-tool.ts +331 -0
- package/src/tools/patch.ts +328 -0
- package/tsconfig.json +29 -0
- package/tsdown.config.ts +110 -0
- package/lib/installer.js +0 -237
- package/lib/invariant.js +0 -23
- package/lib/types/activity-types.d.ts +0 -6
- package/lib/types/activity-types.js +0 -3
- package/lib/types/client/preset-copy.d.ts +0 -42
- package/lib/types/client/preset-copy.js +0 -81
- package/lib/types/compact-command.js +0 -79
- package/lib/types/context.d.ts +0 -8
- package/lib/types/context.js +0 -14
- package/lib/types/exec.d.ts +0 -46
- package/lib/types/exec.js +0 -365
- package/lib/types/index.d.ts +0 -95
- package/lib/types/index.js +0 -738
- package/lib/types/installer.d.ts +0 -27
- package/lib/types/installer.js +0 -146
- package/lib/types/invariant.d.ts +0 -16
- package/lib/types/invariant.js +0 -22
- package/lib/types/preset-contract.d.ts +0 -69
- package/lib/types/preset-contract.js +0 -22
- package/lib/types/preset-editor-remote.d.ts +0 -30
- package/lib/types/preset-editor-remote.js +0 -37
- package/lib/types/preset-editor.d.ts +0 -69
- package/lib/types/preset-editor.js +0 -557
- package/lib/types/preset-templates.d.ts +0 -36
- package/lib/types/preset-templates.js +0 -12
- package/lib/types/prompt-sections.d.ts +0 -15
- package/lib/types/prompt-sections.js +0 -23
- package/lib/types/remote.d.ts +0 -40
- package/lib/types/remote.js +0 -683
- package/lib/types/typert.host.d.ts +0 -47
- package/lib/types/typert.host.js +0 -99
- package/presets/codex-collaboration/preset.yml +0 -3
- /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
/** Codex `exec_command` and `write_stdin` execution over DSH 0.2.2+ capability seams. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import { resolve as resolvePath } from 'node:path'
|
|
5
|
+
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
6
|
+
import type { JobOutcome, JobSpec } from '@deepseek-ai/dsh-jobs'
|
|
7
|
+
import type { ToolExecution } from '@deepseek-ai/dsh-tools'
|
|
8
|
+
import type { ShellExecRequest, ShellExecution, ShellProcess } from '@deepseek-ai/dsh-shell'
|
|
9
|
+
import { approveEscalation, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
|
|
10
|
+
import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
|
11
|
+
import type {} from '@deepseek-ai/dsh-user-approval'
|
|
12
|
+
import type {
|
|
13
|
+
TerminalSendRequest,
|
|
14
|
+
TerminalSessionId,
|
|
15
|
+
TerminalSpawnRequest,
|
|
16
|
+
} from '@deepseek-ai/dsh-terminal'
|
|
17
|
+
import type {} from '@deepseek-ai/dsh-fs'
|
|
18
|
+
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
|
19
|
+
import type {} from '@deepseek-ai/dsh-shell-env'
|
|
20
|
+
import type {} from '@deepseek-ai/dsh-terminal'
|
|
21
|
+
import {
|
|
22
|
+
assertShellCompleted,
|
|
23
|
+
backgroundOutcome,
|
|
24
|
+
hasInteractivePrompt,
|
|
25
|
+
normalizeWaitMs,
|
|
26
|
+
outputLimit,
|
|
27
|
+
positiveFinite,
|
|
28
|
+
readShellOutput,
|
|
29
|
+
sandboxNotes,
|
|
30
|
+
terminalResult,
|
|
31
|
+
withChunkId,
|
|
32
|
+
} from './exec-output.ts'
|
|
33
|
+
import type { ExecCommandArgs, ExecResult, WriteStdinArgs } from './exec-output.ts'
|
|
34
|
+
|
|
35
|
+
export { normalizeWaitMs, renderExecResult, sanitizePipeOutput } from './exec-output.ts'
|
|
36
|
+
export type { ExecCommandArgs, ExecResult, WriteStdinArgs } from './exec-output.ts'
|
|
37
|
+
|
|
38
|
+
type StoredSessionData =
|
|
39
|
+
| { kind: 'shell'; process: ShellProcess; escalationAvailable: boolean }
|
|
40
|
+
| { kind: 'terminal'; owner: Agent; id: TerminalSessionId }
|
|
41
|
+
|
|
42
|
+
type StoredSession = StoredSessionData & { lastUsed: number }
|
|
43
|
+
|
|
44
|
+
interface AgentExecState {
|
|
45
|
+
nextId: number
|
|
46
|
+
clock: number
|
|
47
|
+
sessions: Map<number, StoredSession>
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const STATES = new WeakMap<Agent, AgentExecState>()
|
|
51
|
+
const MAX_UNIFIED_EXEC_SESSIONS = 64
|
|
52
|
+
const PROTECTED_RECENT_SESSIONS = 8
|
|
53
|
+
|
|
54
|
+
function stateFor(agent: Agent): AgentExecState {
|
|
55
|
+
const current = STATES.get(agent)
|
|
56
|
+
if (current !== undefined) return current
|
|
57
|
+
const created: AgentExecState = { nextId: 0, clock: 0, sessions: new Map() }
|
|
58
|
+
STATES.set(agent, created)
|
|
59
|
+
return created
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function sessionCwd(ctx: Context, exec: ToolExecution, workdir: string | undefined): string | undefined {
|
|
63
|
+
const directories = ctx.get('workingDirectory') as { get(session: Agent['session']): string } | undefined
|
|
64
|
+
const cwd = exec.agent === undefined
|
|
65
|
+
? undefined
|
|
66
|
+
: directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd
|
|
67
|
+
return workdir === undefined ? cwd : resolvePath(cwd ?? process.cwd(), workdir)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function startShell(ctx: Context, request: ShellExecRequest): Promise<ShellExecution> {
|
|
71
|
+
const shell = ctx.get('shell')
|
|
72
|
+
if (shell === undefined) throw new Error('exec_command requires ctx.shell')
|
|
73
|
+
return shell.execute(shell.resolve(request))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function waitForShell(process: ShellProcess, ms: number, signal: AbortSignal): Promise<boolean> {
|
|
77
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
78
|
+
let onAbort: () => void = () => {}
|
|
79
|
+
const elapsed = new Promise<boolean | undefined>(resolve => {
|
|
80
|
+
onAbort = () => resolve(false)
|
|
81
|
+
if (signal.aborted) {
|
|
82
|
+
onAbort()
|
|
83
|
+
return
|
|
84
|
+
}
|
|
85
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
86
|
+
timer = setTimeout(() => resolve(undefined), ms)
|
|
87
|
+
})
|
|
88
|
+
try {
|
|
89
|
+
const completed = await Promise.race([process.done.then(() => true), elapsed])
|
|
90
|
+
if (signal.aborted) signal.throwIfAborted()
|
|
91
|
+
return completed === true || process.status !== 'running'
|
|
92
|
+
} finally {
|
|
93
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
94
|
+
signal.removeEventListener('abort', onAbort)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Stop a pipe-backed session when the current Codex tool is cancelled. */
|
|
99
|
+
async function stopShellOnAbort(process: ShellProcess, signal: AbortSignal): Promise<void> {
|
|
100
|
+
if (!signal.aborted || process.status !== 'running') return
|
|
101
|
+
process.kill()
|
|
102
|
+
await process.done
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function allocateSession(ctx: Context, agent: Agent, session: StoredSessionData): number {
|
|
106
|
+
const state = stateFor(agent)
|
|
107
|
+
while (state.sessions.size >= MAX_UNIFIED_EXEC_SESSIONS) {
|
|
108
|
+
const byRecency = [...state.sessions.entries()].sort((a, b) => b[1].lastUsed - a[1].lastUsed)
|
|
109
|
+
const protectedIds = new Set(byRecency.slice(0, PROTECTED_RECENT_SESSIONS).map(([id]) => id))
|
|
110
|
+
const unprotected = byRecency.filter(([id]) => !protectedIds.has(id))
|
|
111
|
+
const exited = [...unprotected].reverse().find(([, entry]) => entry.kind === 'shell' && entry.process.status !== 'running')
|
|
112
|
+
const victim = exited ?? unprotected.at(-1)
|
|
113
|
+
if (victim === undefined) break
|
|
114
|
+
const [victimId, evicted] = victim
|
|
115
|
+
state.sessions.delete(victimId)
|
|
116
|
+
if (evicted.kind === 'shell') {
|
|
117
|
+
if (evicted.process.status === 'running') evicted.process.kill()
|
|
118
|
+
} else {
|
|
119
|
+
void ctx.get('terminals')?.kill(evicted.owner, evicted.id, 'Codex session cap reached')?.catch(() => {})
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const id = ++state.nextId
|
|
123
|
+
state.sessions.set(id, { ...session, lastUsed: ++state.clock })
|
|
124
|
+
return id
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function storedSession(agent: Agent, id: number): StoredSession {
|
|
128
|
+
const state = stateFor(agent)
|
|
129
|
+
const session = state.sessions.get(id)
|
|
130
|
+
if (session === undefined) throw new Error(`unknown unified exec session ${id}`)
|
|
131
|
+
session.lastUsed = ++state.clock
|
|
132
|
+
return session
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function forgetSession(agent: Agent, id: number): void {
|
|
136
|
+
const state = STATES.get(agent)
|
|
137
|
+
if (state === undefined) return
|
|
138
|
+
state.sessions.delete(id)
|
|
139
|
+
if (state.sessions.size === 0) STATES.delete(agent)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Kill any yielded pipe-backed shell processes retained by a disposed Agent. */
|
|
143
|
+
export function disposeAgentExecSessions(agent: Agent): void {
|
|
144
|
+
const state = STATES.get(agent)
|
|
145
|
+
if (state === undefined) return
|
|
146
|
+
STATES.delete(agent)
|
|
147
|
+
for (const session of state.sessions.values()) {
|
|
148
|
+
if (session.kind === 'shell' && session.process.status === 'running') {
|
|
149
|
+
session.process.kill()
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
state.sessions.clear()
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function runTtyCommand(
|
|
156
|
+
ctx: Context,
|
|
157
|
+
args: ExecCommandArgs,
|
|
158
|
+
exec: ToolExecution,
|
|
159
|
+
workdir: string | undefined,
|
|
160
|
+
maxBytes: number,
|
|
161
|
+
startedAt: number,
|
|
162
|
+
): Promise<ExecResult> {
|
|
163
|
+
const agent = exec.agent
|
|
164
|
+
const terminals = ctx.get('terminals')
|
|
165
|
+
if (agent === undefined || terminals === undefined) {
|
|
166
|
+
throw new Error('exec_command with tty=true requires the dsh terminal capability and an owning agent session')
|
|
167
|
+
}
|
|
168
|
+
const spawnRequest: TerminalSpawnRequest = {
|
|
169
|
+
type: 'shell',
|
|
170
|
+
...workdir === undefined ? {} : { cwd: workdir },
|
|
171
|
+
}
|
|
172
|
+
const spawned = await terminals.spawn(agent, spawnRequest, exec.signal)
|
|
173
|
+
let retained = false
|
|
174
|
+
let closeReason = 'Codex command failed'
|
|
175
|
+
try {
|
|
176
|
+
const sendRequest: TerminalSendRequest = { text: args.cmd, submit: true, signal: exec.signal }
|
|
177
|
+
const result = await terminals.startSend(agent, spawned.sessionId, sendRequest).done
|
|
178
|
+
const output = terminalResult(result, maxBytes, startedAt)
|
|
179
|
+
if (result.sessionStatus.kind === 'running') {
|
|
180
|
+
output.session_id = allocateSession(ctx, agent, { kind: 'terminal', owner: agent, id: spawned.sessionId })
|
|
181
|
+
retained = true
|
|
182
|
+
} else {
|
|
183
|
+
closeReason = 'Codex command exited'
|
|
184
|
+
}
|
|
185
|
+
return output
|
|
186
|
+
} finally {
|
|
187
|
+
// A PTY is published by spawn before the first send starts. Do not leave
|
|
188
|
+
// that session behind when send setup or its foreground operation fails.
|
|
189
|
+
if (!retained) await terminals.kill(agent, spawned.sessionId, closeReason)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function startBackgroundJob(
|
|
194
|
+
ctx: Context,
|
|
195
|
+
args: ExecCommandArgs,
|
|
196
|
+
exec: ToolExecution,
|
|
197
|
+
shellRequest: ShellExecRequest,
|
|
198
|
+
confines: boolean,
|
|
199
|
+
maxBytes: number,
|
|
200
|
+
startedAt: number,
|
|
201
|
+
): ExecResult {
|
|
202
|
+
const owner = exec.agent
|
|
203
|
+
if (owner === undefined) throw new Error('run_in_background requires an owning agent session')
|
|
204
|
+
const jobs = ctx.get('jobs')
|
|
205
|
+
if (jobs === undefined) {
|
|
206
|
+
throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs')
|
|
207
|
+
}
|
|
208
|
+
if (exec.signal.aborted) {
|
|
209
|
+
exec.signal.throwIfAborted()
|
|
210
|
+
throw new Error('tool call aborted')
|
|
211
|
+
}
|
|
212
|
+
let process: ShellProcess | undefined
|
|
213
|
+
let cancelled = false
|
|
214
|
+
const lifetime = new AbortController()
|
|
215
|
+
const jobSpec: JobSpec = {
|
|
216
|
+
kind: 'bash',
|
|
217
|
+
label: args.cmd,
|
|
218
|
+
owner: owner.id,
|
|
219
|
+
outputLimitBytes: maxBytes,
|
|
220
|
+
output: (['stdout', 'stderr'] as const).map(channel => ({
|
|
221
|
+
channel,
|
|
222
|
+
read: (fromByte: number) => process?.observed?.[channel].readFrom(fromByte)
|
|
223
|
+
?? { text: '', nextOffset: fromByte, lossy: false },
|
|
224
|
+
})),
|
|
225
|
+
run: () => {
|
|
226
|
+
const prepared = startShell(ctx, { ...shellRequest, signal: lifetime.signal })
|
|
227
|
+
const done = (async (): Promise<JobOutcome> => {
|
|
228
|
+
try {
|
|
229
|
+
process = await prepared
|
|
230
|
+
if (cancelled) process.kill()
|
|
231
|
+
await process.done
|
|
232
|
+
const completed = await assertShellCompleted(process, confines)
|
|
233
|
+
return backgroundOutcome(process, confines, completed?.sandbox ?? process.sandbox)
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (cancelled) return { status: 'killed', detail: 'cancelled during shell preparation' }
|
|
236
|
+
return {
|
|
237
|
+
status: 'failed',
|
|
238
|
+
detail: [error instanceof Error ? error.message : String(error), ...sandboxNotes(process?.sandbox, confines)].join('; '),
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
})()
|
|
242
|
+
return {
|
|
243
|
+
cancel: () => {
|
|
244
|
+
cancelled = true
|
|
245
|
+
lifetime.abort()
|
|
246
|
+
process?.kill()
|
|
247
|
+
},
|
|
248
|
+
done,
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
}
|
|
252
|
+
const id = jobs.start(jobSpec)
|
|
253
|
+
return withChunkId({
|
|
254
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
255
|
+
job_id: id,
|
|
256
|
+
output: `Started background job ${id}. Use job_output with job_id "${id}" to read output.`,
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Execute one Codex command through the configured pipe or PTY capability. */
|
|
261
|
+
export async function runExecCommand(
|
|
262
|
+
ctx: Context,
|
|
263
|
+
args: ExecCommandArgs,
|
|
264
|
+
exec: ToolExecution,
|
|
265
|
+
config: { defaultYieldTimeMs: number; maxOutputBytes: number },
|
|
266
|
+
): Promise<ExecResult> {
|
|
267
|
+
if (args.cmd.trim().length === 0) throw new Error('cmd must be a non-empty string')
|
|
268
|
+
positiveFinite('yield_time_ms', args.yield_time_ms)
|
|
269
|
+
const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens)
|
|
270
|
+
validateEscalationArgs(args.sandbox_permissions, args.justification)
|
|
271
|
+
const confines = ctx.get('shell')?.sandboxMode !== undefined
|
|
272
|
+
const policyService = ctx.get('sandboxPolicy')
|
|
273
|
+
if (confines && policyService === undefined) throw new Error('exec_command: a sandboxing shell requires ctx.sandboxPolicy')
|
|
274
|
+
if (confines && args.tty === true) throw new Error('exec_command: tty=true cannot carry the sandbox policy; use pipe-backed execution on this host')
|
|
275
|
+
let policy: SandboxExecutionPolicy | undefined = policyService?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
|
|
276
|
+
if (args.sandbox_permissions !== undefined) {
|
|
277
|
+
if (!confines) throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
|
|
278
|
+
const approvedMode = await approveEscalation({
|
|
279
|
+
requestedMode: args.sandbox_permissions,
|
|
280
|
+
justification: args.justification!,
|
|
281
|
+
effectiveMode: policy!.mode,
|
|
282
|
+
subject: 'command',
|
|
283
|
+
}, {
|
|
284
|
+
approver: ctx.get('approval'),
|
|
285
|
+
agent: exec.agent,
|
|
286
|
+
callId: exec.callId,
|
|
287
|
+
toolName: 'exec_command',
|
|
288
|
+
signal: exec.signal,
|
|
289
|
+
})
|
|
290
|
+
exec.signal.throwIfAborted()
|
|
291
|
+
policy = { ...policy!, mode: approvedMode }
|
|
292
|
+
}
|
|
293
|
+
const workdir = sessionCwd(ctx, exec, args.workdir)
|
|
294
|
+
const startedAt = performance.now()
|
|
295
|
+
if (args.run_in_background === true && args.tty === true) {
|
|
296
|
+
throw new Error('run_in_background is only supported for pipe-backed commands; omit tty')
|
|
297
|
+
}
|
|
298
|
+
if (args.tty === true) return runTtyCommand(ctx, args, exec, workdir, maxBytes, startedAt)
|
|
299
|
+
|
|
300
|
+
const dshEnv = ctx.get('shellEnv')?.collect(exec)
|
|
301
|
+
const shellRequest: ShellExecRequest = {
|
|
302
|
+
command: args.cmd,
|
|
303
|
+
onExpiry: 'none',
|
|
304
|
+
...workdir === undefined ? {} : { workdir },
|
|
305
|
+
stdoutMaxBytes: maxBytes,
|
|
306
|
+
...dshEnv === undefined ? {} : { dshEnv },
|
|
307
|
+
...policy === undefined ? {} : { sandboxPolicy: policy },
|
|
308
|
+
}
|
|
309
|
+
if (args.run_in_background === true) {
|
|
310
|
+
return startBackgroundJob(ctx, args, exec, shellRequest, confines, maxBytes, startedAt)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const process = await startShell(ctx, { ...shellRequest, signal: exec.signal })
|
|
314
|
+
try {
|
|
315
|
+
await waitForShell(process, normalizeWaitMs(args.yield_time_ms, config.defaultYieldTimeMs, false, true), exec.signal)
|
|
316
|
+
const read = process.readOutput()
|
|
317
|
+
if (process.status === 'running') {
|
|
318
|
+
if (exec.agent === undefined) {
|
|
319
|
+
process.kill()
|
|
320
|
+
await process.done
|
|
321
|
+
const completed = await assertShellCompleted(process, confines)
|
|
322
|
+
const formatted = readShellOutput(
|
|
323
|
+
{ ...read, delta: read.delta + process.readOutput().delta },
|
|
324
|
+
maxBytes,
|
|
325
|
+
completed?.sandbox ?? process.sandbox,
|
|
326
|
+
confines,
|
|
327
|
+
)
|
|
328
|
+
return withChunkId({
|
|
329
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
330
|
+
output: formatted.output,
|
|
331
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
332
|
+
})
|
|
333
|
+
}
|
|
334
|
+
const formatted = readShellOutput(read, maxBytes, process.sandbox, confines)
|
|
335
|
+
const interactiveHint = '[exec: command appears waiting on interactive stdin over pipes; interrupt with write_stdin chars="\\u0003" and rerun with a non-interactive flag or tty=true]'
|
|
336
|
+
const output = hasInteractivePrompt(formatted.output)
|
|
337
|
+
? `${formatted.output}${formatted.output.length > 0 && !formatted.output.endsWith('\n') ? '\n' : ''}${interactiveHint}`
|
|
338
|
+
: formatted.output
|
|
339
|
+
return withChunkId({
|
|
340
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
341
|
+
output,
|
|
342
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
343
|
+
session_id: allocateSession(ctx, exec.agent, { kind: 'shell', process, escalationAvailable: confines }),
|
|
344
|
+
})
|
|
345
|
+
}
|
|
346
|
+
const completed = await assertShellCompleted(process, confines)
|
|
347
|
+
const formatted = readShellOutput(read, maxBytes, completed?.sandbox ?? process.sandbox, confines)
|
|
348
|
+
return withChunkId({
|
|
349
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
350
|
+
output: formatted.output,
|
|
351
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
352
|
+
...process.exitCode === null ? {} : { exit_code: process.exitCode },
|
|
353
|
+
})
|
|
354
|
+
} finally {
|
|
355
|
+
await stopShellOnAbort(process, exec.signal)
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Poll or write to one session returned by {@link runExecCommand}. */
|
|
360
|
+
export async function runWriteStdin(
|
|
361
|
+
ctx: Context,
|
|
362
|
+
args: WriteStdinArgs,
|
|
363
|
+
exec: ToolExecution,
|
|
364
|
+
config: { pollYieldTimeMs: number; writeYieldTimeMs: number; maxOutputBytes: number },
|
|
365
|
+
): Promise<ExecResult> {
|
|
366
|
+
const escalation = args as WriteStdinArgs & { sandbox_permissions?: unknown; justification?: unknown }
|
|
367
|
+
if (escalation.sandbox_permissions !== undefined || escalation.justification !== undefined) {
|
|
368
|
+
throw new Error('write_stdin cannot change an existing command sandbox; use exec_command for an approved one-shot retry')
|
|
369
|
+
}
|
|
370
|
+
positiveFinite('yield_time_ms', args.yield_time_ms)
|
|
371
|
+
if (!Number.isSafeInteger(args.session_id) || args.session_id <= 0) {
|
|
372
|
+
throw new Error('session_id must be a positive integer')
|
|
373
|
+
}
|
|
374
|
+
const agent = exec.agent
|
|
375
|
+
if (agent === undefined) throw new Error('write_stdin requires an owning agent session')
|
|
376
|
+
const session = storedSession(agent, args.session_id)
|
|
377
|
+
const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens)
|
|
378
|
+
const startedAt = performance.now()
|
|
379
|
+
const chars = args.chars ?? ''
|
|
380
|
+
if (session.kind === 'shell') {
|
|
381
|
+
if (chars === '\u0003') {
|
|
382
|
+
session.process.kill()
|
|
383
|
+
} else if (chars.length > 0) {
|
|
384
|
+
throw new Error('this unified exec session uses pipes and does not accept stdin; send "\\u0003" to interrupt or rerun exec_command with tty=true')
|
|
385
|
+
}
|
|
386
|
+
try {
|
|
387
|
+
const waitMs = normalizeWaitMs(
|
|
388
|
+
args.yield_time_ms,
|
|
389
|
+
chars === '\u0003' ? config.writeYieldTimeMs : config.pollYieldTimeMs,
|
|
390
|
+
chars.length === 0,
|
|
391
|
+
)
|
|
392
|
+
await waitForShell(session.process, waitMs, exec.signal)
|
|
393
|
+
const read = session.process.readOutput()
|
|
394
|
+
if (session.process.status !== 'running') {
|
|
395
|
+
forgetSession(agent, args.session_id)
|
|
396
|
+
const completed = await assertShellCompleted(session.process, session.escalationAvailable)
|
|
397
|
+
const formatted = readShellOutput(read, maxBytes, completed?.sandbox ?? session.process.sandbox, session.escalationAvailable)
|
|
398
|
+
return withChunkId({
|
|
399
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
400
|
+
output: formatted.output,
|
|
401
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
402
|
+
...session.process.exitCode === null ? {} : { exit_code: session.process.exitCode },
|
|
403
|
+
})
|
|
404
|
+
}
|
|
405
|
+
const formatted = readShellOutput(read, maxBytes, session.process.sandbox, session.escalationAvailable)
|
|
406
|
+
return withChunkId({
|
|
407
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
408
|
+
output: formatted.output,
|
|
409
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
410
|
+
session_id: args.session_id,
|
|
411
|
+
})
|
|
412
|
+
} finally {
|
|
413
|
+
if (exec.signal.aborted) {
|
|
414
|
+
try {
|
|
415
|
+
await stopShellOnAbort(session.process, exec.signal)
|
|
416
|
+
} finally {
|
|
417
|
+
forgetSession(agent, args.session_id)
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const terminals = ctx.get('terminals')
|
|
424
|
+
if (terminals === undefined) throw new Error('the dsh terminal capability is no longer available')
|
|
425
|
+
const sendRequest: TerminalSendRequest = { text: chars, submit: false, signal: exec.signal }
|
|
426
|
+
let retained = false
|
|
427
|
+
let closeReason = 'Codex command failed'
|
|
428
|
+
try {
|
|
429
|
+
const result = await terminals.startSend(agent, session.id, sendRequest).done
|
|
430
|
+
const output = terminalResult(result, maxBytes, startedAt)
|
|
431
|
+
if (result.sessionStatus.kind === 'running') {
|
|
432
|
+
output.session_id = args.session_id
|
|
433
|
+
retained = true
|
|
434
|
+
} else {
|
|
435
|
+
closeReason = 'Codex command exited'
|
|
436
|
+
forgetSession(agent, args.session_id)
|
|
437
|
+
}
|
|
438
|
+
return output
|
|
439
|
+
} finally {
|
|
440
|
+
if (!retained) {
|
|
441
|
+
forgetSession(agent, args.session_id)
|
|
442
|
+
await terminals.kill(agent, session.id, closeReason)
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|