@shuind/dsh-codex-harness 0.2.21 → 0.2.32-dsh-v0.2.2-rc.1
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 +121 -0
- package/README.md +48 -38
- package/RELEASE.md +61 -0
- package/assets/codex.svg +5 -0
- package/cordis.patch.yml +150 -6
- package/docs/preset-library.md +39 -23
- package/docs/tool-policy-benchmark.json +310 -0
- package/docs/tool-policy.md +144 -0
- package/lib/client.js +1639 -111
- package/lib/compaction.js +17 -2
- package/lib/index.js +799 -188
- package/lib/installer.js +50 -6
- package/lib/preferences.js +111 -0
- package/lib/tool-policy.js +2235 -0
- package/lib/typert.js +57 -10
- package/lib/types/activity.d.ts +1 -1
- package/lib/types/activity.js +50 -14
- package/lib/types/client/activity.d.ts +33 -9
- package/lib/types/client/desktop.d.ts +43 -0
- package/lib/types/client/desktop.js +121 -0
- package/lib/types/client/entry.d.ts +10 -0
- package/lib/types/client/entry.js +12 -0
- package/lib/types/client/index.d.ts +109 -19
- package/lib/types/client/index.js +21 -40
- package/lib/types/client/policy-drafts.d.ts +25 -0
- package/lib/types/client/policy-drafts.js +47 -0
- package/lib/types/client/preset-copy.d.ts +1 -0
- package/lib/types/client/preset-copy.js +2 -0
- package/lib/types/client/preset-manager.d.ts +12 -2
- package/lib/types/client/preset-manager.js +70 -25
- package/lib/types/client/preset-requests.d.ts +12 -0
- package/lib/types/client/preset-requests.js +101 -0
- package/lib/types/client/session.d.ts +6 -0
- package/lib/types/client/session.js +9 -0
- package/lib/types/client/tool-policy.d.ts +120 -0
- package/lib/types/client/tool-policy.js +394 -0
- package/lib/types/compaction.d.ts +3 -3
- package/lib/types/compaction.js +6 -2
- package/lib/types/desktop-preset.d.ts +20 -0
- package/lib/types/desktop-preset.js +39 -0
- package/lib/types/exec.d.ts +4 -0
- package/lib/types/exec.js +192 -66
- package/lib/types/host-settings.d.ts +4 -0
- package/lib/types/host-settings.js +13 -0
- package/lib/types/index.d.ts +20 -2
- package/lib/types/index.js +181 -68
- package/lib/types/installer.js +11 -2
- package/lib/types/preferences.d.ts +11 -0
- package/lib/types/preferences.js +16 -0
- package/lib/types/preset-editor-remote.d.ts +2 -0
- package/lib/types/preset-editor-remote.js +6 -2
- package/lib/types/preset-editor.d.ts +12 -7
- package/lib/types/preset-editor.js +43 -13
- package/lib/types/preset-prompt-catalog-schema.d.ts +16 -0
- package/lib/types/preset-prompt-catalog-schema.js +11 -0
- package/lib/types/preset-prompt-catalog.d.ts +21 -0
- package/lib/types/preset-prompt-catalog.js +192 -0
- package/lib/types/preset-prompt-contract.d.ts +22 -0
- package/lib/types/preset-prompt-contract.js +3 -0
- package/lib/types/preset-tool-catalog-schema.d.ts +38 -0
- package/lib/types/preset-tool-catalog-schema.js +28 -0
- package/lib/types/preset-tool-catalog.d.ts +5 -0
- package/lib/types/preset-tool-catalog.js +51 -0
- package/lib/types/prompt-sections.d.ts +1 -1
- package/lib/types/prompt-sections.js +9 -3
- package/lib/types/prompt.js +4 -2
- package/lib/types/remote.js +23 -8
- package/lib/types/settings.d.ts +3 -3
- package/lib/types/settings.js +3 -3
- package/lib/types/tool-capabilities.d.ts +32 -0
- package/lib/types/tool-capabilities.js +42 -0
- package/lib/types/tool-policy-contract.d.ts +60 -0
- package/lib/types/tool-policy-contract.js +26 -0
- package/lib/types/tool-policy.d.ts +171 -0
- package/lib/types/tool-policy.js +367 -0
- package/lib/types/typert.host.d.ts +2 -2
- package/lib/types/typert.host.js +12 -2
- package/locale/en.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 +375 -299
- package/scripts/benchmark-tool-policy.mjs +186 -0
- package/scripts/build-preset.mjs +19 -0
- package/scripts/clean-build.mjs +11 -0
- package/src/activity-types.ts +7 -0
- package/src/activity.ts +158 -0
- package/src/client/activity.ts +82 -0
- package/src/client/desktop.tsx +162 -0
- package/src/client/entry.tsx +16 -0
- package/src/client/index.tsx +972 -0
- package/src/client/policy-drafts.ts +56 -0
- package/src/client/preset-copy.ts +83 -0
- package/src/client/preset-manager.tsx +281 -0
- package/src/client/preset-requests.ts +113 -0
- package/src/client/session.ts +11 -0
- package/src/client/tool-policy.tsx +380 -0
- package/src/compact-command.ts +112 -0
- package/src/compaction.ts +190 -0
- package/src/context.ts +15 -0
- package/src/desktop-preset.ts +55 -0
- package/src/exec.ts +570 -0
- package/src/host-settings.ts +17 -0
- package/src/index.ts +1097 -0
- package/src/installer.ts +172 -0
- package/src/invariant.ts +34 -0
- package/src/patch.ts +258 -0
- package/src/preferences.ts +17 -0
- package/src/preset-contract.ts +85 -0
- package/src/preset-editor-remote.ts +41 -0
- package/src/preset-editor.ts +502 -0
- package/src/preset-prompt-catalog-schema.ts +10 -0
- package/src/preset-prompt-catalog.ts +191 -0
- package/src/preset-prompt-contract.ts +21 -0
- package/src/preset-tool-catalog-schema.ts +28 -0
- package/src/preset-tool-catalog.ts +51 -0
- package/src/prompt-sections.ts +33 -0
- package/src/prompt.ts +62 -0
- package/src/remote.ts +748 -0
- package/src/settings.ts +79 -0
- package/src/tool-capabilities.ts +76 -0
- package/src/tool-policy-contract.ts +76 -0
- package/src/tool-policy.ts +388 -0
- package/src/typert.host.ts +119 -0
- package/tsconfig.json +29 -0
- package/tsdown.config.ts +110 -0
- package/lib/types/preset-templates.d.ts +0 -36
- package/lib/types/preset-templates.js +0 -12
package/src/exec.ts
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
/** Codex `exec_command` and `write_stdin` execution over dsh capability seams. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import { randomBytes } from 'node:crypto'
|
|
5
|
+
import { resolve as resolvePath } from 'node:path'
|
|
6
|
+
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
7
|
+
import { HarnessError } from '@deepseek-ai/dsh-llm'
|
|
8
|
+
import type { JobOutcome } from '@deepseek-ai/dsh-jobs'
|
|
9
|
+
import type { ToolExecution } from '@deepseek-ai/dsh-tools'
|
|
10
|
+
import type { ShellExecRequest, ShellProcess, ShellProcessRead, ShellRunResult } from '@deepseek-ai/dsh-shell'
|
|
11
|
+
import { approveEscalation, escalationHintMarker, sandboxDenialMarker, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
|
|
12
|
+
import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
|
13
|
+
import type {} from '@deepseek-ai/dsh-user-approval'
|
|
14
|
+
import type {
|
|
15
|
+
TerminalSendRequest,
|
|
16
|
+
TerminalSendResult,
|
|
17
|
+
TerminalSessionId,
|
|
18
|
+
TerminalSpawnRequest,
|
|
19
|
+
} from '@deepseek-ai/dsh-terminal'
|
|
20
|
+
import type {} from '@deepseek-ai/dsh-fs'
|
|
21
|
+
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
|
22
|
+
import type {} from '@deepseek-ai/dsh-shell-env'
|
|
23
|
+
import type {} from '@deepseek-ai/dsh-terminal'
|
|
24
|
+
|
|
25
|
+
/** The exact model-facing argument vocabulary of Codex's unified exec tool. */
|
|
26
|
+
export interface ExecCommandArgs {
|
|
27
|
+
cmd: string
|
|
28
|
+
workdir?: string
|
|
29
|
+
tty?: boolean
|
|
30
|
+
run_in_background?: boolean
|
|
31
|
+
yield_time_ms?: number
|
|
32
|
+
max_output_tokens?: number
|
|
33
|
+
shell?: string
|
|
34
|
+
login?: boolean
|
|
35
|
+
sandbox_permissions?: string
|
|
36
|
+
justification?: string
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The exact model-facing argument vocabulary of Codex's stdin poll tool. */
|
|
40
|
+
export interface WriteStdinArgs {
|
|
41
|
+
session_id: number
|
|
42
|
+
chars?: string
|
|
43
|
+
yield_time_ms?: number
|
|
44
|
+
max_output_tokens?: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Canonical result fields shared by both unified exec tools. */
|
|
48
|
+
export interface ExecResult {
|
|
49
|
+
chunk_id?: string
|
|
50
|
+
wall_time_seconds: number
|
|
51
|
+
output: string
|
|
52
|
+
session_id?: number
|
|
53
|
+
job_id?: string
|
|
54
|
+
exit_code?: number
|
|
55
|
+
original_token_count?: number
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type StoredSession =
|
|
59
|
+
| { kind: 'shell'; process: ShellProcess; escalationAvailable: boolean }
|
|
60
|
+
| { kind: 'terminal'; owner: Agent; id: TerminalSessionId }
|
|
61
|
+
|
|
62
|
+
// rc.5 exposed these optional controls; rc.6 moved them into the mounted
|
|
63
|
+
// providers. Keep passing them when an older provider accepts them while
|
|
64
|
+
// allowing the rc.6 service definitions to type-check.
|
|
65
|
+
type CodexShellExecRequest = ShellExecRequest & { shell?: string; login?: boolean }
|
|
66
|
+
type CodexTerminalSpawnRequest = TerminalSpawnRequest & { shell?: string; login?: boolean }
|
|
67
|
+
type CodexTerminalSendRequest = TerminalSendRequest & { waitMs?: number }
|
|
68
|
+
|
|
69
|
+
interface AgentExecState {
|
|
70
|
+
nextId: number
|
|
71
|
+
sessions: Map<number, StoredSession>
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const STATES = new WeakMap<Agent, AgentExecState>()
|
|
75
|
+
const MIN_YIELD_TIME_MS = 250
|
|
76
|
+
const WINDOWS_INITIAL_EXEC_YIELD_TIME_MS = 10_000
|
|
77
|
+
const MIN_EMPTY_YIELD_TIME_MS = 5_000
|
|
78
|
+
const MAX_YIELD_TIME_MS = 30_000
|
|
79
|
+
const MAX_EMPTY_YIELD_TIME_MS = 300_000
|
|
80
|
+
const DEFAULT_OUTPUT_TOKENS = 10_000
|
|
81
|
+
const APPROX_BYTES_PER_TOKEN = 4
|
|
82
|
+
|
|
83
|
+
function stateFor(agent: Agent): AgentExecState {
|
|
84
|
+
const current = STATES.get(agent)
|
|
85
|
+
if (current !== undefined) return current
|
|
86
|
+
const created: AgentExecState = { nextId: 0, sessions: new Map() }
|
|
87
|
+
STATES.set(agent, created)
|
|
88
|
+
return created
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function positiveFinite(name: string, value: number | undefined): void {
|
|
92
|
+
if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
|
|
93
|
+
throw new Error(`${name} must be a non-negative finite number`)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function normalizeWaitMs(
|
|
98
|
+
value: number | undefined,
|
|
99
|
+
fallback: number,
|
|
100
|
+
empty = false,
|
|
101
|
+
initialExec = false,
|
|
102
|
+
): number {
|
|
103
|
+
const lower = empty
|
|
104
|
+
? MIN_EMPTY_YIELD_TIME_MS
|
|
105
|
+
: initialExec && process.platform === 'win32'
|
|
106
|
+
? WINDOWS_INITIAL_EXEC_YIELD_TIME_MS
|
|
107
|
+
: MIN_YIELD_TIME_MS
|
|
108
|
+
const upper = empty ? MAX_EMPTY_YIELD_TIME_MS : MAX_YIELD_TIME_MS
|
|
109
|
+
return Math.max(lower, Math.min(upper, Math.trunc(value ?? fallback)))
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function outputLimit(maxOutputBytes: number, maxOutputTokens: number | undefined): number {
|
|
113
|
+
const tokens = maxOutputTokens ?? DEFAULT_OUTPUT_TOKENS
|
|
114
|
+
if (maxOutputTokens !== undefined) positiveFinite('max_output_tokens', maxOutputTokens)
|
|
115
|
+
return Math.max(1, Math.min(maxOutputBytes, Math.trunc(tokens * APPROX_BYTES_PER_TOKEN)))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function limitOutput(text: string, maxBytes: number): string {
|
|
119
|
+
if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text
|
|
120
|
+
let end = Math.min(text.length, maxBytes)
|
|
121
|
+
while (end > 0 && Buffer.byteLength(text.slice(0, end), 'utf8') > maxBytes) end--
|
|
122
|
+
return `${text.slice(0, end)}\n[output truncated]`
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function newChunkId(): string {
|
|
126
|
+
return randomBytes(3).toString('hex')
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function withChunkId(result: Omit<ExecResult, 'chunk_id'>): ExecResult {
|
|
130
|
+
return { chunk_id: newChunkId(), ...result }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Render the ordinary Responses tool result text used by Codex's unified exec tools. */
|
|
134
|
+
export function renderExecResult(result: ExecResult): string {
|
|
135
|
+
const sections: string[] = []
|
|
136
|
+
if (result.chunk_id !== undefined) sections.push(`Chunk ID: ${result.chunk_id}`)
|
|
137
|
+
sections.push(`Wall time: ${result.wall_time_seconds.toFixed(4)} seconds`)
|
|
138
|
+
if (result.exit_code !== undefined) sections.push(`Process exited with code ${result.exit_code}`)
|
|
139
|
+
if (result.session_id !== undefined) sections.push(`Process running with session ID ${result.session_id}`)
|
|
140
|
+
if (result.job_id !== undefined) sections.push(`Background job ID: ${result.job_id}`)
|
|
141
|
+
if (result.original_token_count !== undefined) sections.push(`Original token count: ${result.original_token_count}`)
|
|
142
|
+
sections.push('Output:', result.output)
|
|
143
|
+
return sections.join('\n')
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function sessionCwd(ctx: Context, exec: ToolExecution, workdir: string | undefined): string | undefined {
|
|
147
|
+
const directories = ctx.get('workingDirectory') as { get(session: Agent['session']): string } | undefined
|
|
148
|
+
const cwd = exec.agent === undefined
|
|
149
|
+
? undefined
|
|
150
|
+
: directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd
|
|
151
|
+
return workdir === undefined ? cwd : resolvePath(cwd ?? process.cwd(), workdir)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Per-call shell selection belonged to legacy providers, not the current shell seam. */
|
|
155
|
+
export function supportsLegacyShellOptions(ctx: Context): boolean {
|
|
156
|
+
const shell = ctx.get('shell')
|
|
157
|
+
if (shell === undefined) throw new Error('exec_command requires ctx.shell')
|
|
158
|
+
return typeof (shell as unknown as { execute?: unknown }).execute !== 'function'
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Surface infrastructure failures from the current execution handle without reclassifying nonzero exits. */
|
|
162
|
+
async function assertShellCompleted(process: ShellProcess, escalationAvailable = false): Promise<ShellRunResult | undefined> {
|
|
163
|
+
const result = (process as ShellProcess & { result?: () => Promise<ShellRunResult> }).result
|
|
164
|
+
if (typeof result !== 'function') return undefined
|
|
165
|
+
try { return await result.call(process) } catch (error) {
|
|
166
|
+
const notes = sandboxNotes(process.sandbox, escalationAvailable)
|
|
167
|
+
if (notes.length === 0) throw error
|
|
168
|
+
const message = [error instanceof Error ? error.message : String(error), ...notes].join('\n')
|
|
169
|
+
const failure = error instanceof HarnessError
|
|
170
|
+
? new HarnessError(message, error.code, { cause: error })
|
|
171
|
+
: new Error(message, { cause: error })
|
|
172
|
+
if (error instanceof Error) failure.name = error.name
|
|
173
|
+
throw failure
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Preserve policy/runner facts after bounding command output; never truncate these markers. */
|
|
178
|
+
function sandboxNotes(sandbox: ShellProcess['sandbox'], escalationAvailable: boolean): string[] {
|
|
179
|
+
if (sandbox?.runnerFailed) return [`[sandbox: the sandbox runner itself failed under ${sandbox.mode} mode — the command did not run; this is a sandbox problem, not a command failure]`]
|
|
180
|
+
if (!sandbox?.denied) return []
|
|
181
|
+
return [sandboxDenialMarker(sandbox.mode), ...escalationAvailable ? [escalationHintMarker('command')] : []]
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Current executors prepare asynchronously; old providers published a handle synchronously. */
|
|
185
|
+
function startShell(ctx: Context, request: CodexShellExecRequest): ShellProcess | Promise<ShellProcess> {
|
|
186
|
+
const provider = ctx.get('shell')
|
|
187
|
+
if (provider === undefined) throw new Error('exec_command requires ctx.shell')
|
|
188
|
+
const shell = provider as unknown as {
|
|
189
|
+
resolve(request: CodexShellExecRequest): unknown
|
|
190
|
+
execute?: (spec: unknown) => Promise<ShellProcess>
|
|
191
|
+
start?: (spec: unknown) => ShellProcess
|
|
192
|
+
}
|
|
193
|
+
const spec = shell.resolve(request)
|
|
194
|
+
if (typeof shell.execute === 'function') return shell.execute(spec)
|
|
195
|
+
if (typeof shell.start === 'function') return shell.start(spec)
|
|
196
|
+
throw new Error('exec_command: the configured shell has no execution capability')
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function readShellOutput(
|
|
200
|
+
read: ShellProcessRead,
|
|
201
|
+
maxBytes: number,
|
|
202
|
+
sandbox?: ShellProcess['sandbox'],
|
|
203
|
+
escalationAvailable = false,
|
|
204
|
+
): string {
|
|
205
|
+
const output = limitOutput(read.delta, maxBytes)
|
|
206
|
+
const notes = sandboxNotes(sandbox, escalationAvailable)
|
|
207
|
+
return notes.length === 0 ? output : `${output}${output.length > 0 && !output.endsWith('\n') ? '\n' : ''}${notes.join('\n')}`
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function terminalResult(result: TerminalSendResult, maxBytes: number, startedAt: number): ExecResult {
|
|
211
|
+
const output = limitOutput(result.viewport, maxBytes)
|
|
212
|
+
return withChunkId({
|
|
213
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
214
|
+
output,
|
|
215
|
+
...result.sessionStatus.kind === 'exited' ? {
|
|
216
|
+
...result.sessionStatus.exitCode === null ? {} : { exit_code: result.sessionStatus.exitCode },
|
|
217
|
+
} : {},
|
|
218
|
+
})
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Map a detached shell process onto the generic DSH job outcome contract. */
|
|
222
|
+
function backgroundOutcome(process: ShellProcess, escalationAvailable: boolean, sandbox = process.sandbox): JobOutcome {
|
|
223
|
+
const base: JobOutcome = process.status === 'killed'
|
|
224
|
+
? { status: 'killed', detail: process.signal !== null ? `signal: ${process.signal}` : 'killed before exit' }
|
|
225
|
+
: { status: 'completed', detail: `exit code: ${process.exitCode ?? 0}` }
|
|
226
|
+
const notes = sandboxNotes(sandbox, escalationAvailable)
|
|
227
|
+
return notes.length === 0 ? base : { ...base, detail: `${base.detail}; ${notes.join(' ')}` }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function waitForShell(process: ShellProcess, ms: number, signal: AbortSignal): Promise<boolean> {
|
|
231
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
232
|
+
let onAbort: () => void = () => {}
|
|
233
|
+
const elapsed = new Promise<boolean | undefined>(resolve => {
|
|
234
|
+
onAbort = () => resolve(false)
|
|
235
|
+
if (signal.aborted) {
|
|
236
|
+
onAbort()
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
240
|
+
timer = setTimeout(() => resolve(undefined), ms)
|
|
241
|
+
})
|
|
242
|
+
try {
|
|
243
|
+
const completed = await Promise.race([process.done.then(() => true), elapsed])
|
|
244
|
+
if (signal.aborted) signal.throwIfAborted()
|
|
245
|
+
return completed === true || process.status !== 'running'
|
|
246
|
+
} finally {
|
|
247
|
+
// Retire the losing wait even when the process completes before its deadline.
|
|
248
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
249
|
+
signal.removeEventListener('abort', onAbort)
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Stop a pipe-backed session when the current Codex tool is cancelled. */
|
|
254
|
+
async function stopShellOnAbort(process: ShellProcess, signal: AbortSignal): Promise<void> {
|
|
255
|
+
if (!signal.aborted || process.status !== 'running') return
|
|
256
|
+
process.kill()
|
|
257
|
+
await process.done
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function allocateSession(agent: Agent, session: StoredSession): number {
|
|
261
|
+
const state = stateFor(agent)
|
|
262
|
+
const id = ++state.nextId
|
|
263
|
+
state.sessions.set(id, session)
|
|
264
|
+
return id
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function storedSession(agent: Agent, id: number): StoredSession {
|
|
268
|
+
const session = stateFor(agent).sessions.get(id)
|
|
269
|
+
if (session === undefined) throw new Error(`unknown unified exec session ${id}`)
|
|
270
|
+
return session
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function forgetSession(agent: Agent, id: number): void {
|
|
274
|
+
stateFor(agent).sessions.delete(id)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function commandFor(args: ExecCommandArgs): string {
|
|
278
|
+
// Pass the command verbatim; executable/startup selection belongs to the
|
|
279
|
+
// mounted provider. Legacy shell controls are handled before this seam.
|
|
280
|
+
return args.cmd
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Execute one Codex command through the configured pipe or PTY capability. */
|
|
284
|
+
export async function runExecCommand(
|
|
285
|
+
ctx: Context,
|
|
286
|
+
args: ExecCommandArgs,
|
|
287
|
+
exec: ToolExecution,
|
|
288
|
+
config: { defaultYieldTimeMs: number; maxOutputBytes: number },
|
|
289
|
+
): Promise<ExecResult> {
|
|
290
|
+
if (args.cmd.trim().length === 0) throw new Error('cmd must be a non-empty string')
|
|
291
|
+
positiveFinite('yield_time_ms', args.yield_time_ms)
|
|
292
|
+
const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens)
|
|
293
|
+
const legacyShellOptions = supportsLegacyShellOptions(ctx)
|
|
294
|
+
if (!legacyShellOptions && (args.shell !== undefined || args.login !== undefined)) {
|
|
295
|
+
throw new Error('exec_command: this host selects the shell and startup mode in its configuration; per-call shell/login options are unavailable')
|
|
296
|
+
}
|
|
297
|
+
validateEscalationArgs(args.sandbox_permissions, args.justification)
|
|
298
|
+
const confines = ctx.get('shell')?.sandboxMode !== undefined
|
|
299
|
+
const policyService = ctx.get('sandboxPolicy')
|
|
300
|
+
if (confines && policyService === undefined) throw new Error('exec_command: a sandboxing shell requires ctx.sandboxPolicy')
|
|
301
|
+
if (confines && args.tty === true) throw new Error('exec_command: tty=true cannot carry the sandbox policy; use pipe-backed execution on this host')
|
|
302
|
+
let policy: SandboxExecutionPolicy | undefined = policyService?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
|
|
303
|
+
if (args.sandbox_permissions !== undefined) {
|
|
304
|
+
if (!confines) throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
|
|
305
|
+
const approvedMode = await approveEscalation({
|
|
306
|
+
requestedMode: args.sandbox_permissions,
|
|
307
|
+
justification: args.justification!,
|
|
308
|
+
effectiveMode: policy!.mode,
|
|
309
|
+
subject: 'command',
|
|
310
|
+
}, {
|
|
311
|
+
approver: ctx.get('approval'),
|
|
312
|
+
agent: exec.agent,
|
|
313
|
+
callId: exec.callId,
|
|
314
|
+
toolName: 'exec_command',
|
|
315
|
+
signal: exec.signal,
|
|
316
|
+
})
|
|
317
|
+
exec.signal.throwIfAborted()
|
|
318
|
+
policy = { ...policy!, mode: approvedMode }
|
|
319
|
+
}
|
|
320
|
+
const workdir = sessionCwd(ctx, exec, args.workdir)
|
|
321
|
+
const startedAt = performance.now()
|
|
322
|
+
if (args.run_in_background === true && args.tty === true) {
|
|
323
|
+
throw new Error('run_in_background is only supported for pipe-backed commands; omit tty')
|
|
324
|
+
}
|
|
325
|
+
if (args.tty === true) {
|
|
326
|
+
const agent = exec.agent
|
|
327
|
+
const terminals = ctx.get('terminals')
|
|
328
|
+
if (agent === undefined || terminals === undefined) {
|
|
329
|
+
throw new Error('exec_command with tty=true requires the dsh terminal capability and an owning agent session')
|
|
330
|
+
}
|
|
331
|
+
const spawnRequest: CodexTerminalSpawnRequest = {
|
|
332
|
+
type: 'shell',
|
|
333
|
+
...legacyShellOptions ? {
|
|
334
|
+
...args.shell === undefined ? {} : { shell: args.shell },
|
|
335
|
+
login: args.login ?? true,
|
|
336
|
+
} : {},
|
|
337
|
+
...workdir === undefined ? {} : { cwd: workdir },
|
|
338
|
+
}
|
|
339
|
+
const spawned = await terminals.spawn(agent, spawnRequest, exec.signal)
|
|
340
|
+
let retained = false
|
|
341
|
+
let closeReason = 'Codex command failed'
|
|
342
|
+
try {
|
|
343
|
+
const sendRequest: CodexTerminalSendRequest = {
|
|
344
|
+
text: commandFor(args),
|
|
345
|
+
submit: true,
|
|
346
|
+
waitMs: normalizeWaitMs(args.yield_time_ms, config.defaultYieldTimeMs, false, true),
|
|
347
|
+
signal: exec.signal,
|
|
348
|
+
}
|
|
349
|
+
const operation = terminals.startSend(agent, spawned.sessionId, sendRequest)
|
|
350
|
+
const result = await operation.done
|
|
351
|
+
const output = terminalResult(result, maxBytes, startedAt)
|
|
352
|
+
if (result.sessionStatus.kind === 'running') {
|
|
353
|
+
output.session_id = allocateSession(agent, { kind: 'terminal', owner: agent, id: spawned.sessionId })
|
|
354
|
+
retained = true
|
|
355
|
+
} else {
|
|
356
|
+
closeReason = 'Codex command exited'
|
|
357
|
+
}
|
|
358
|
+
return output
|
|
359
|
+
} finally {
|
|
360
|
+
// A PTY is published by spawn before the first send starts. Do not leave
|
|
361
|
+
// that session behind when send setup or its foreground operation fails.
|
|
362
|
+
if (!retained) await terminals.kill(agent, spawned.sessionId, closeReason)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const dshEnv = ctx.get('shellEnv')?.collect(exec)
|
|
367
|
+
// Background jobs intentionally omit the tool-call signal. Once this call
|
|
368
|
+
// returns, the job lifetime belongs to the jobs registry, not the request.
|
|
369
|
+
const shellRequest: CodexShellExecRequest = {
|
|
370
|
+
command: commandFor(args),
|
|
371
|
+
// Unified exec bounds its own wait; yielding must not arm the provider's kill deadline.
|
|
372
|
+
onExpiry: 'none',
|
|
373
|
+
...legacyShellOptions ? {
|
|
374
|
+
...args.shell === undefined ? {} : { shell: args.shell },
|
|
375
|
+
login: args.login ?? true,
|
|
376
|
+
} : {},
|
|
377
|
+
...workdir === undefined ? {} : { workdir },
|
|
378
|
+
stdoutMaxBytes: maxBytes,
|
|
379
|
+
...dshEnv === undefined ? {} : { dshEnv },
|
|
380
|
+
...policy === undefined ? {} : { sandboxPolicy: policy },
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (args.run_in_background === true) {
|
|
384
|
+
const owner = exec.agent
|
|
385
|
+
if (owner === undefined) throw new Error('run_in_background requires an owning agent session')
|
|
386
|
+
const jobs = ctx.get('jobs')
|
|
387
|
+
if (jobs === undefined) {
|
|
388
|
+
throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs')
|
|
389
|
+
}
|
|
390
|
+
if (exec.signal.aborted) {
|
|
391
|
+
exec.signal.throwIfAborted()
|
|
392
|
+
throw new Error('tool call aborted')
|
|
393
|
+
}
|
|
394
|
+
// The ring-backed jobs API owns output cursors and identifies owners by SessionId.
|
|
395
|
+
// Legacy registries instead accept the exact Agent and a consuming readOutput hook.
|
|
396
|
+
const ringBacked = typeof (jobs as unknown as { readAt?: unknown }).readAt === 'function'
|
|
397
|
+
let process: ShellProcess | undefined
|
|
398
|
+
let cancelled = false
|
|
399
|
+
const lifetime = new AbortController()
|
|
400
|
+
const start = () => {
|
|
401
|
+
const prepared = startShell(ctx, {
|
|
402
|
+
...shellRequest,
|
|
403
|
+
...ringBacked ? { signal: lifetime.signal } : {},
|
|
404
|
+
})
|
|
405
|
+
const done = (async (): Promise<JobOutcome> => {
|
|
406
|
+
try {
|
|
407
|
+
process = 'then' in prepared ? await prepared : prepared
|
|
408
|
+
if (cancelled) process.kill()
|
|
409
|
+
await process.done
|
|
410
|
+
const completed = await assertShellCompleted(process, confines)
|
|
411
|
+
return backgroundOutcome(process, confines, completed?.sandbox ?? process.sandbox)
|
|
412
|
+
} catch (error) {
|
|
413
|
+
if (cancelled) return { status: 'killed', detail: 'cancelled during shell preparation' }
|
|
414
|
+
return { status: 'failed', detail: [error instanceof Error ? error.message : String(error), ...sandboxNotes(process?.sandbox, confines)].join('; ') }
|
|
415
|
+
}
|
|
416
|
+
})()
|
|
417
|
+
return {
|
|
418
|
+
cancel: () => {
|
|
419
|
+
cancelled = true
|
|
420
|
+
lifetime.abort()
|
|
421
|
+
process?.kill()
|
|
422
|
+
},
|
|
423
|
+
done,
|
|
424
|
+
...ringBacked ? {} : {
|
|
425
|
+
readOutput: () => process === undefined ? '' : readShellOutput(process.readOutput(), maxBytes, process.sandbox, confines),
|
|
426
|
+
},
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const output = (['stdout', 'stderr'] as const).map(channel => ({
|
|
430
|
+
channel,
|
|
431
|
+
read: (fromByte: number) => process?.observed?.[channel].readFrom(fromByte)
|
|
432
|
+
?? { text: '', nextOffset: fromByte, lossy: false },
|
|
433
|
+
}))
|
|
434
|
+
const id = jobs.start({
|
|
435
|
+
kind: 'bash',
|
|
436
|
+
label: args.cmd,
|
|
437
|
+
owner: ringBacked ? owner.id : owner,
|
|
438
|
+
outputLimitBytes: maxBytes,
|
|
439
|
+
...ringBacked ? { output } : {},
|
|
440
|
+
run: start,
|
|
441
|
+
} as unknown as Parameters<typeof jobs.start>[0])
|
|
442
|
+
return withChunkId({
|
|
443
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
444
|
+
job_id: id,
|
|
445
|
+
output: `Started background job ${id}. Use job_output with job_id "${id}" to read output.`,
|
|
446
|
+
})
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const prepared = startShell(ctx, { ...shellRequest, signal: exec.signal })
|
|
450
|
+
const process = 'then' in prepared ? await prepared : prepared
|
|
451
|
+
try {
|
|
452
|
+
await waitForShell(process, normalizeWaitMs(args.yield_time_ms, config.defaultYieldTimeMs, false, true), exec.signal)
|
|
453
|
+
const read = process.readOutput()
|
|
454
|
+
if (process.status === 'running') {
|
|
455
|
+
const output = readShellOutput(read, maxBytes, process.sandbox, confines)
|
|
456
|
+
if (exec.agent === undefined) {
|
|
457
|
+
process.kill()
|
|
458
|
+
await process.done
|
|
459
|
+
const completed = await assertShellCompleted(process, confines)
|
|
460
|
+
return withChunkId({
|
|
461
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
462
|
+
output: readShellOutput({ ...read, delta: read.delta + process.readOutput().delta }, maxBytes, completed?.sandbox ?? process.sandbox, confines),
|
|
463
|
+
})
|
|
464
|
+
}
|
|
465
|
+
return withChunkId({
|
|
466
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
467
|
+
output,
|
|
468
|
+
session_id: allocateSession(exec.agent, { kind: 'shell', process, escalationAvailable: confines }),
|
|
469
|
+
})
|
|
470
|
+
}
|
|
471
|
+
const completed = await assertShellCompleted(process, confines)
|
|
472
|
+
return withChunkId({
|
|
473
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
474
|
+
output: readShellOutput(read, maxBytes, completed?.sandbox ?? process.sandbox, confines),
|
|
475
|
+
...process.exitCode === null ? {} : { exit_code: process.exitCode },
|
|
476
|
+
})
|
|
477
|
+
} finally {
|
|
478
|
+
await stopShellOnAbort(process, exec.signal)
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** Poll or write to one session returned by {@link runExecCommand}. */
|
|
483
|
+
export async function runWriteStdin(
|
|
484
|
+
ctx: Context,
|
|
485
|
+
args: WriteStdinArgs,
|
|
486
|
+
exec: ToolExecution,
|
|
487
|
+
config: { pollYieldTimeMs: number; writeYieldTimeMs: number; maxOutputBytes: number },
|
|
488
|
+
): Promise<ExecResult> {
|
|
489
|
+
const escalation = args as WriteStdinArgs & { sandbox_permissions?: unknown; justification?: unknown }
|
|
490
|
+
if (escalation.sandbox_permissions !== undefined || escalation.justification !== undefined) {
|
|
491
|
+
throw new Error('write_stdin cannot change an existing command sandbox; use exec_command for an approved one-shot retry')
|
|
492
|
+
}
|
|
493
|
+
positiveFinite('yield_time_ms', args.yield_time_ms)
|
|
494
|
+
if (!Number.isSafeInteger(args.session_id) || args.session_id <= 0) {
|
|
495
|
+
throw new Error('session_id must be a positive integer')
|
|
496
|
+
}
|
|
497
|
+
const agent = exec.agent
|
|
498
|
+
if (agent === undefined) throw new Error('write_stdin requires an owning agent session')
|
|
499
|
+
const session = storedSession(agent, args.session_id)
|
|
500
|
+
const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens)
|
|
501
|
+
const startedAt = performance.now()
|
|
502
|
+
const chars = args.chars ?? ''
|
|
503
|
+
if (session.kind === 'shell') {
|
|
504
|
+
if (chars.length > 0) {
|
|
505
|
+
throw new Error('this unified exec session uses pipes and does not accept stdin; rerun exec_command with tty=true')
|
|
506
|
+
}
|
|
507
|
+
try {
|
|
508
|
+
await waitForShell(session.process, normalizeWaitMs(args.yield_time_ms, config.pollYieldTimeMs, true), exec.signal)
|
|
509
|
+
const read = session.process.readOutput()
|
|
510
|
+
if (session.process.status !== 'running') {
|
|
511
|
+
forgetSession(agent, args.session_id)
|
|
512
|
+
const completed = await assertShellCompleted(session.process, session.escalationAvailable)
|
|
513
|
+
return withChunkId({
|
|
514
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
515
|
+
output: readShellOutput(read, maxBytes, completed?.sandbox ?? session.process.sandbox, session.escalationAvailable),
|
|
516
|
+
...session.process.exitCode === null ? {} : { exit_code: session.process.exitCode },
|
|
517
|
+
})
|
|
518
|
+
}
|
|
519
|
+
return withChunkId({
|
|
520
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
521
|
+
output: readShellOutput(read, maxBytes, session.process.sandbox, session.escalationAvailable),
|
|
522
|
+
session_id: args.session_id,
|
|
523
|
+
})
|
|
524
|
+
} finally {
|
|
525
|
+
if (exec.signal.aborted) {
|
|
526
|
+
try {
|
|
527
|
+
await stopShellOnAbort(session.process, exec.signal)
|
|
528
|
+
} finally {
|
|
529
|
+
forgetSession(agent, args.session_id)
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const terminals = ctx.get('terminals')
|
|
536
|
+
if (terminals === undefined) throw new Error('the dsh terminal capability is no longer available')
|
|
537
|
+
const sendRequest: CodexTerminalSendRequest = {
|
|
538
|
+
text: chars,
|
|
539
|
+
submit: false,
|
|
540
|
+
waitMs: normalizeWaitMs(
|
|
541
|
+
args.yield_time_ms,
|
|
542
|
+
chars.length > 0 ? config.writeYieldTimeMs : config.pollYieldTimeMs,
|
|
543
|
+
chars.length === 0,
|
|
544
|
+
),
|
|
545
|
+
signal: exec.signal,
|
|
546
|
+
}
|
|
547
|
+
let retained = false
|
|
548
|
+
let closeReason = 'Codex command failed'
|
|
549
|
+
try {
|
|
550
|
+
const operation = terminals.startSend(agent, session.id, sendRequest)
|
|
551
|
+
const result = await operation.done
|
|
552
|
+
const output = terminalResult(result, maxBytes, startedAt)
|
|
553
|
+
if (result.sessionStatus.kind === 'running') {
|
|
554
|
+
output.session_id = args.session_id
|
|
555
|
+
retained = true
|
|
556
|
+
} else {
|
|
557
|
+
closeReason = 'Codex command exited'
|
|
558
|
+
forgetSession(agent, args.session_id)
|
|
559
|
+
}
|
|
560
|
+
return output
|
|
561
|
+
} finally {
|
|
562
|
+
// A failed send must not strand either side of the two-level session
|
|
563
|
+
// registry: the local numeric id and the underlying PTY must be retired
|
|
564
|
+
// together. A successful running result is the only retained case.
|
|
565
|
+
if (!retained) {
|
|
566
|
+
forgetSession(agent, args.session_id)
|
|
567
|
+
await terminals.kill(agent, session.id, closeReason)
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
+
|
|
3
|
+
interface SettingsReader {
|
|
4
|
+
get?: (namespace: string) => unknown
|
|
5
|
+
describe?: () => Array<{ ns: string; value: unknown }>
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Host-only reads: never expose the unredacted provider configuration to clients. */
|
|
9
|
+
export function readHostSettings<T>(ctx: Context, namespace: string): T | undefined {
|
|
10
|
+
const settings = ctx.get('settings') as SettingsReader | undefined
|
|
11
|
+
if (typeof settings?.get === 'function') return settings.get(namespace) as T | undefined
|
|
12
|
+
if (namespace === 'codex') {
|
|
13
|
+
const preferences = ctx.get('codexPreferences') as { current(): T } | undefined
|
|
14
|
+
if (preferences !== undefined) return preferences.current()
|
|
15
|
+
}
|
|
16
|
+
return settings?.describe?.().find(row => row.ns === namespace)?.value as T | undefined
|
|
17
|
+
}
|