@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,265 @@
|
|
|
1
|
+
/** Shared Codex execution and plan tool registration (decoupled from Host preset editor). */
|
|
2
|
+
import { ESCALATION_TARGETS, sandboxPermissionsDescription } from '@deepseek-ai/dsh-sandbox';
|
|
3
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
4
|
+
import { disposeAgentExecSessions, renderExecResult, runExecCommand, runWriteStdin } from "./exec-runner.js";
|
|
5
|
+
import { registerPatchTool } from "./patch-tool.js";
|
|
6
|
+
import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE, readHostSettings } from "../contracts/settings.js";
|
|
7
|
+
import { assertCapabilityEnabled, codexToolEnabled, markCodexTool } from "../policy/tool-capabilities.js";
|
|
8
|
+
export const DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024;
|
|
9
|
+
const EXEC_COMMAND_DESCRIPTION = 'Runs a command in the host-configured shell. By default it uses pipes: a running session can be polled for output but does not accept stdin. Set tty=true before starting a command that needs interactive input; background jobs use pipes.';
|
|
10
|
+
const WRITE_STDIN_DESCRIPTION = 'Polls output from an existing unified exec session. Non-empty chars can be sent to a session created with tty=true; pipe-backed sessions accept empty chars for polling or "\\u0003" to interrupt.';
|
|
11
|
+
const UPDATE_PLAN_DESCRIPTION = 'Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.';
|
|
12
|
+
const PLAN_STATUSES = ['pending', 'in_progress', 'completed'];
|
|
13
|
+
function planTodos(args) {
|
|
14
|
+
const seen = new Set();
|
|
15
|
+
let active = 0;
|
|
16
|
+
const todos = [];
|
|
17
|
+
for (const item of args.plan) {
|
|
18
|
+
const content = item.step.trim();
|
|
19
|
+
if (content.length === 0)
|
|
20
|
+
throw new Error('update_plan: every step must be non-empty');
|
|
21
|
+
if (seen.has(content))
|
|
22
|
+
throw new Error(`update_plan: duplicate step ${JSON.stringify(content)}`);
|
|
23
|
+
seen.add(content);
|
|
24
|
+
if (item.status === 'in_progress')
|
|
25
|
+
active++;
|
|
26
|
+
todos.push({ content, status: item.status });
|
|
27
|
+
}
|
|
28
|
+
if (active > 1)
|
|
29
|
+
throw new Error('update_plan: at most one step may be in_progress');
|
|
30
|
+
return todos;
|
|
31
|
+
}
|
|
32
|
+
/** Release every registration once, even when one release fails. */
|
|
33
|
+
export function composeToolDisposers(disposers) {
|
|
34
|
+
return () => {
|
|
35
|
+
const errors = [];
|
|
36
|
+
for (const dispose of disposers.splice(0).reverse()) {
|
|
37
|
+
try {
|
|
38
|
+
dispose();
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
errors.push(error);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (errors.length > 0)
|
|
45
|
+
throw new AggregateError(errors, 'Could not unregister Codex tools');
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function terminalResultView(result) {
|
|
49
|
+
if (result.isError)
|
|
50
|
+
return undefined;
|
|
51
|
+
const meta = typeof result.meta === 'object' && result.meta !== null && !Array.isArray(result.meta)
|
|
52
|
+
? result.meta
|
|
53
|
+
: undefined;
|
|
54
|
+
if (typeof meta?.output !== 'string')
|
|
55
|
+
return undefined;
|
|
56
|
+
return {
|
|
57
|
+
card: 'terminal',
|
|
58
|
+
output: meta.output,
|
|
59
|
+
...typeof meta.exitCode === 'number' ? { exitCode: meta.exitCode } : {},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
export function registerExecTools(ctx, config) {
|
|
63
|
+
const tools = ctx.get('tools');
|
|
64
|
+
if (tools === undefined)
|
|
65
|
+
throw new Error('Codex execution tools require ctx.tools');
|
|
66
|
+
const shell = ctx.get('shell');
|
|
67
|
+
if (shell === undefined)
|
|
68
|
+
throw new Error('Codex execution tools require ctx.shell');
|
|
69
|
+
const confines = shell.sandboxMode !== undefined;
|
|
70
|
+
if (confines && ctx.get('sandboxPolicy') === undefined)
|
|
71
|
+
throw new Error('Codex execution tools: a sandboxing shell requires ctx.sandboxPolicy');
|
|
72
|
+
const metadata = {
|
|
73
|
+
capability: 'terminalToolsEnabled',
|
|
74
|
+
presetEnabled: config.presetEnabled !== false,
|
|
75
|
+
...(config.presetOverridesLegacy ? { presetOverridesLegacy: true } : {}),
|
|
76
|
+
};
|
|
77
|
+
const ownedAgents = new Set();
|
|
78
|
+
const offDisposed = typeof ctx.on === 'function'
|
|
79
|
+
? ctx.on('agent/disposed', ({ agent }) => {
|
|
80
|
+
ownedAgents.delete(agent);
|
|
81
|
+
disposeAgentExecSessions(agent);
|
|
82
|
+
})
|
|
83
|
+
: () => { };
|
|
84
|
+
const cleanupOwned = () => {
|
|
85
|
+
offDisposed();
|
|
86
|
+
for (const agent of [...ownedAgents]) {
|
|
87
|
+
ownedAgents.delete(agent);
|
|
88
|
+
disposeAgentExecSessions(agent);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
let unregisterExec;
|
|
92
|
+
try {
|
|
93
|
+
unregisterExec = tools.register(markCodexTool(defineTool({
|
|
94
|
+
name: 'exec_command',
|
|
95
|
+
description: EXEC_COMMAND_DESCRIPTION,
|
|
96
|
+
parameters: {
|
|
97
|
+
cmd: { type: 'string', required: true, description: 'Shell command to execute.' },
|
|
98
|
+
workdir: { type: 'string', description: 'Working directory for the command. Defaults to the turn cwd.' },
|
|
99
|
+
tty: { type: 'boolean', description: confines ? 'This host cannot carry sandbox policy into a PTY; omit tty or use false.' : 'True allocates a PTY for the command; false or omitted uses plain pipes.' },
|
|
100
|
+
run_in_background: { type: 'boolean', description: 'Run as a DSH background job and return its job id immediately; collect output with job_output and stop it with job_kill. Only supported for pipe-backed commands.' },
|
|
101
|
+
yield_time_ms: { type: 'number', description: 'Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.' },
|
|
102
|
+
max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
|
|
103
|
+
...confines ? {
|
|
104
|
+
sandbox_permissions: { type: 'string', enum: [...ESCALATION_TARGETS], description: sandboxPermissionsDescription('command') },
|
|
105
|
+
justification: { type: 'string', description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request.' },
|
|
106
|
+
} : {},
|
|
107
|
+
},
|
|
108
|
+
output: {
|
|
109
|
+
schema: {
|
|
110
|
+
type: 'object',
|
|
111
|
+
additionalProperties: false,
|
|
112
|
+
properties: {
|
|
113
|
+
chunk_id: { type: 'string' },
|
|
114
|
+
wall_time_seconds: { type: 'number', required: true },
|
|
115
|
+
exit_code: { type: 'number' },
|
|
116
|
+
session_id: { type: 'number' },
|
|
117
|
+
job_id: { type: 'string' },
|
|
118
|
+
original_token_count: { type: 'number' },
|
|
119
|
+
output: { type: 'string', required: true },
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
|
|
123
|
+
presentationMeta: (_args, value) => ({
|
|
124
|
+
output: value.output,
|
|
125
|
+
...value.exit_code === undefined ? {} : { exitCode: value.exit_code },
|
|
126
|
+
...value.job_id === undefined ? {} : { jobId: value.job_id },
|
|
127
|
+
}),
|
|
128
|
+
},
|
|
129
|
+
async execute(args, exec) {
|
|
130
|
+
assertCapabilityEnabled(ctx, config.currentSettings, 'exec_command', exec.agent, metadata, config.authority);
|
|
131
|
+
const result = await runExecCommand(ctx, args, exec, config);
|
|
132
|
+
if (result.session_id !== undefined && exec.agent !== undefined)
|
|
133
|
+
ownedAgents.add(exec.agent);
|
|
134
|
+
return result;
|
|
135
|
+
},
|
|
136
|
+
presentCall: args => args.run_in_background === true
|
|
137
|
+
? { card: 'generic', title: args.cmd, kind: 'execute', rawInput: args.cmd }
|
|
138
|
+
: { card: 'terminal', title: args.cmd, ...args.workdir === undefined ? {} : { cwd: args.workdir } },
|
|
139
|
+
presentResult: (args, result) => args.run_in_background === true ? undefined : terminalResultView(result),
|
|
140
|
+
}), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'exec_command', metadata, config.currentSettings, config.authority) });
|
|
141
|
+
const unregisterStdin = tools.register(markCodexTool(defineTool({
|
|
142
|
+
name: 'write_stdin',
|
|
143
|
+
description: WRITE_STDIN_DESCRIPTION,
|
|
144
|
+
parameters: {
|
|
145
|
+
session_id: { type: 'number', required: true, description: 'Identifier of the running unified exec session.' },
|
|
146
|
+
chars: { type: 'string', description: 'Characters to send to a PTY session created with tty=true. Leave empty to poll output without writing; pipe-backed sessions accept empty chars to poll or "\\u0003" to interrupt.' },
|
|
147
|
+
yield_time_ms: { type: 'number', description: 'Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default.' },
|
|
148
|
+
max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
|
|
149
|
+
},
|
|
150
|
+
output: {
|
|
151
|
+
schema: {
|
|
152
|
+
type: 'object',
|
|
153
|
+
additionalProperties: false,
|
|
154
|
+
properties: {
|
|
155
|
+
chunk_id: { type: 'string' },
|
|
156
|
+
wall_time_seconds: { type: 'number', required: true },
|
|
157
|
+
exit_code: { type: 'number' },
|
|
158
|
+
session_id: { type: 'number' },
|
|
159
|
+
original_token_count: { type: 'number' },
|
|
160
|
+
output: { type: 'string', required: true },
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
|
|
164
|
+
presentationMeta: (_args, value) => ({
|
|
165
|
+
output: value.output,
|
|
166
|
+
...value.exit_code === undefined ? {} : { exitCode: value.exit_code },
|
|
167
|
+
}),
|
|
168
|
+
},
|
|
169
|
+
async execute(args, exec) {
|
|
170
|
+
assertCapabilityEnabled(ctx, config.currentSettings, 'write_stdin', exec.agent, metadata, config.authority);
|
|
171
|
+
return runWriteStdin(ctx, args, exec, config);
|
|
172
|
+
},
|
|
173
|
+
presentCall: args => ({ card: 'terminal', title: `write_stdin #${args.session_id}` }),
|
|
174
|
+
presentResult: (_args, result) => terminalResultView(result),
|
|
175
|
+
}), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'write_stdin', metadata, config.currentSettings, config.authority) });
|
|
176
|
+
return composeToolDisposers([cleanupOwned, unregisterExec, unregisterStdin]);
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
cleanupOwned();
|
|
180
|
+
unregisterExec?.();
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
export function registerPlanTool(ctx, currentSettings, presetEnabled = true, authority, presetOverridesLegacy = false) {
|
|
185
|
+
const tools = ctx.get('tools');
|
|
186
|
+
if (tools === undefined)
|
|
187
|
+
throw new Error('Codex plan tools require ctx.tools');
|
|
188
|
+
const metadata = {
|
|
189
|
+
capability: 'planToolEnabled',
|
|
190
|
+
presetEnabled,
|
|
191
|
+
...(presetOverridesLegacy ? { presetOverridesLegacy: true } : {}),
|
|
192
|
+
};
|
|
193
|
+
return tools.register(markCodexTool(defineTool({
|
|
194
|
+
name: 'update_plan',
|
|
195
|
+
description: UPDATE_PLAN_DESCRIPTION,
|
|
196
|
+
parameters: {
|
|
197
|
+
explanation: { type: 'string', description: 'Optional explanation for this plan update.' },
|
|
198
|
+
plan: {
|
|
199
|
+
type: 'array',
|
|
200
|
+
required: true,
|
|
201
|
+
description: 'The list of steps',
|
|
202
|
+
items: {
|
|
203
|
+
type: 'object',
|
|
204
|
+
additionalProperties: false,
|
|
205
|
+
properties: {
|
|
206
|
+
step: { type: 'string', required: true, description: 'Task step text.' },
|
|
207
|
+
status: { type: 'string', required: true, enum: [...PLAN_STATUSES], description: 'Step status.' },
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
},
|
|
211
|
+
},
|
|
212
|
+
output: {
|
|
213
|
+
schema: { type: 'object', additionalProperties: false, properties: {} },
|
|
214
|
+
render: () => [{ type: 'text', text: 'Plan updated' }],
|
|
215
|
+
},
|
|
216
|
+
execute(args, exec) {
|
|
217
|
+
assertCapabilityEnabled(ctx, currentSettings, 'update_plan', exec.agent, metadata, authority);
|
|
218
|
+
const agent = exec.agent;
|
|
219
|
+
if (agent === undefined)
|
|
220
|
+
throw new Error('update_plan requires an owning agent session');
|
|
221
|
+
const events = typeof agent.session.snapshotEvents === 'function'
|
|
222
|
+
? agent.session.snapshotEvents()
|
|
223
|
+
: undefined;
|
|
224
|
+
const planEvent = events?.findLast(event => event.type === 'plan/mode');
|
|
225
|
+
if (planEvent?.data?.active === true) {
|
|
226
|
+
throw new Error('update_plan is a task-execution checklist tool and is not allowed in plan mode; submit your plan via exit_plan_mode');
|
|
227
|
+
}
|
|
228
|
+
agent.session.append('todo/write', { todos: planTodos(args) });
|
|
229
|
+
return Promise.resolve({});
|
|
230
|
+
},
|
|
231
|
+
}), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'update_plan', metadata, currentSettings, authority) });
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Register selected Codex tools through the existing pipeline, without prompt hooks.
|
|
235
|
+
* Compiled adapters receive authority once; the disposer supports an additional owner.
|
|
236
|
+
*/
|
|
237
|
+
export function registerCodexExecAndPlan(ctx, options = {}) {
|
|
238
|
+
const currentSettings = () => ({
|
|
239
|
+
...CODEX_SETTINGS_ENTRY,
|
|
240
|
+
...readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE),
|
|
241
|
+
});
|
|
242
|
+
const disposers = [];
|
|
243
|
+
const dispose = composeToolDisposers(disposers);
|
|
244
|
+
try {
|
|
245
|
+
if (options.terminal !== false)
|
|
246
|
+
disposers.push(registerExecTools(ctx, {
|
|
247
|
+
defaultYieldTimeMs: options.defaultYieldTimeMs ?? 10_000,
|
|
248
|
+
pollYieldTimeMs: options.pollYieldTimeMs ?? 5_000,
|
|
249
|
+
writeYieldTimeMs: options.writeYieldTimeMs ?? 250,
|
|
250
|
+
maxOutputBytes: options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
|
|
251
|
+
currentSettings,
|
|
252
|
+
...(options.capabilityAuthority?.terminalToolsEnabled === undefined ? {} : { authority: options.capabilityAuthority.terminalToolsEnabled }),
|
|
253
|
+
}));
|
|
254
|
+
if (options.plan !== false)
|
|
255
|
+
disposers.push(registerPlanTool(ctx, currentSettings, true, options.capabilityAuthority?.planToolEnabled));
|
|
256
|
+
if (options.patch === true)
|
|
257
|
+
disposers.push(registerPatchTool(ctx, currentSettings, true, options.capabilityAuthority?.patchToolEnabled));
|
|
258
|
+
return dispose;
|
|
259
|
+
}
|
|
260
|
+
catch (error) {
|
|
261
|
+
dispose();
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
//# sourceMappingURL=exec-plan-tools.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Codex `exec_command` and `write_stdin` execution over DSH 0.2.2+ capability seams. */
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
3
|
+
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
4
|
+
import type { ToolExecution } from '@deepseek-ai/dsh-tools';
|
|
5
|
+
import type { ExecCommandArgs, ExecResult, WriteStdinArgs } from './exec-output.ts';
|
|
6
|
+
export { normalizeWaitMs, renderExecResult, sanitizePipeOutput } from './exec-output.ts';
|
|
7
|
+
export type { ExecCommandArgs, ExecResult, WriteStdinArgs } from './exec-output.ts';
|
|
8
|
+
/** Kill any yielded pipe-backed shell processes retained by a disposed Agent. */
|
|
9
|
+
export declare function disposeAgentExecSessions(agent: Agent): void;
|
|
10
|
+
/** Execute one Codex command through the configured pipe or PTY capability. */
|
|
11
|
+
export declare function runExecCommand(ctx: Context, args: ExecCommandArgs, exec: ToolExecution, config: {
|
|
12
|
+
defaultYieldTimeMs: number;
|
|
13
|
+
maxOutputBytes: number;
|
|
14
|
+
}): Promise<ExecResult>;
|
|
15
|
+
/** Poll or write to one session returned by {@link runExecCommand}. */
|
|
16
|
+
export declare function runWriteStdin(ctx: Context, args: WriteStdinArgs, exec: ToolExecution, config: {
|
|
17
|
+
pollYieldTimeMs: number;
|
|
18
|
+
writeYieldTimeMs: number;
|
|
19
|
+
maxOutputBytes: number;
|
|
20
|
+
}): Promise<ExecResult>;
|
|
21
|
+
//# sourceMappingURL=exec-runner.d.ts.map
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/** Codex `exec_command` and `write_stdin` execution over DSH 0.2.2+ capability seams. */
|
|
2
|
+
import { resolve as resolvePath } from 'node:path';
|
|
3
|
+
import { approveEscalation, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox';
|
|
4
|
+
import { assertShellCompleted, backgroundOutcome, hasInteractivePrompt, normalizeWaitMs, outputLimit, positiveFinite, readShellOutput, sandboxNotes, terminalResult, withChunkId, } from "./exec-output.js";
|
|
5
|
+
export { normalizeWaitMs, renderExecResult, sanitizePipeOutput } from "./exec-output.js";
|
|
6
|
+
const STATES = new WeakMap();
|
|
7
|
+
const MAX_UNIFIED_EXEC_SESSIONS = 64;
|
|
8
|
+
const PROTECTED_RECENT_SESSIONS = 8;
|
|
9
|
+
function stateFor(agent) {
|
|
10
|
+
const current = STATES.get(agent);
|
|
11
|
+
if (current !== undefined)
|
|
12
|
+
return current;
|
|
13
|
+
const created = { nextId: 0, clock: 0, sessions: new Map() };
|
|
14
|
+
STATES.set(agent, created);
|
|
15
|
+
return created;
|
|
16
|
+
}
|
|
17
|
+
function sessionCwd(ctx, exec, workdir) {
|
|
18
|
+
const directories = ctx.get('workingDirectory');
|
|
19
|
+
const cwd = exec.agent === undefined
|
|
20
|
+
? undefined
|
|
21
|
+
: directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd;
|
|
22
|
+
return workdir === undefined ? cwd : resolvePath(cwd ?? process.cwd(), workdir);
|
|
23
|
+
}
|
|
24
|
+
async function startShell(ctx, request) {
|
|
25
|
+
const shell = ctx.get('shell');
|
|
26
|
+
if (shell === undefined)
|
|
27
|
+
throw new Error('exec_command requires ctx.shell');
|
|
28
|
+
return shell.execute(shell.resolve(request));
|
|
29
|
+
}
|
|
30
|
+
async function waitForShell(process, ms, signal) {
|
|
31
|
+
let timer;
|
|
32
|
+
let onAbort = () => { };
|
|
33
|
+
const elapsed = new Promise(resolve => {
|
|
34
|
+
onAbort = () => resolve(false);
|
|
35
|
+
if (signal.aborted) {
|
|
36
|
+
onAbort();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
40
|
+
timer = setTimeout(() => resolve(undefined), ms);
|
|
41
|
+
});
|
|
42
|
+
try {
|
|
43
|
+
const completed = await Promise.race([process.done.then(() => true), elapsed]);
|
|
44
|
+
if (signal.aborted)
|
|
45
|
+
signal.throwIfAborted();
|
|
46
|
+
return completed === true || process.status !== 'running';
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
if (timer !== undefined)
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
signal.removeEventListener('abort', onAbort);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Stop a pipe-backed session when the current Codex tool is cancelled. */
|
|
55
|
+
async function stopShellOnAbort(process, signal) {
|
|
56
|
+
if (!signal.aborted || process.status !== 'running')
|
|
57
|
+
return;
|
|
58
|
+
process.kill();
|
|
59
|
+
await process.done;
|
|
60
|
+
}
|
|
61
|
+
function allocateSession(ctx, agent, session) {
|
|
62
|
+
const state = stateFor(agent);
|
|
63
|
+
while (state.sessions.size >= MAX_UNIFIED_EXEC_SESSIONS) {
|
|
64
|
+
const byRecency = [...state.sessions.entries()].sort((a, b) => b[1].lastUsed - a[1].lastUsed);
|
|
65
|
+
const protectedIds = new Set(byRecency.slice(0, PROTECTED_RECENT_SESSIONS).map(([id]) => id));
|
|
66
|
+
const unprotected = byRecency.filter(([id]) => !protectedIds.has(id));
|
|
67
|
+
const exited = [...unprotected].reverse().find(([, entry]) => entry.kind === 'shell' && entry.process.status !== 'running');
|
|
68
|
+
const victim = exited ?? unprotected.at(-1);
|
|
69
|
+
if (victim === undefined)
|
|
70
|
+
break;
|
|
71
|
+
const [victimId, evicted] = victim;
|
|
72
|
+
state.sessions.delete(victimId);
|
|
73
|
+
if (evicted.kind === 'shell') {
|
|
74
|
+
if (evicted.process.status === 'running')
|
|
75
|
+
evicted.process.kill();
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
void ctx.get('terminals')?.kill(evicted.owner, evicted.id, 'Codex session cap reached')?.catch(() => { });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const id = ++state.nextId;
|
|
82
|
+
state.sessions.set(id, { ...session, lastUsed: ++state.clock });
|
|
83
|
+
return id;
|
|
84
|
+
}
|
|
85
|
+
function storedSession(agent, id) {
|
|
86
|
+
const state = stateFor(agent);
|
|
87
|
+
const session = state.sessions.get(id);
|
|
88
|
+
if (session === undefined)
|
|
89
|
+
throw new Error(`unknown unified exec session ${id}`);
|
|
90
|
+
session.lastUsed = ++state.clock;
|
|
91
|
+
return session;
|
|
92
|
+
}
|
|
93
|
+
function forgetSession(agent, id) {
|
|
94
|
+
const state = STATES.get(agent);
|
|
95
|
+
if (state === undefined)
|
|
96
|
+
return;
|
|
97
|
+
state.sessions.delete(id);
|
|
98
|
+
if (state.sessions.size === 0)
|
|
99
|
+
STATES.delete(agent);
|
|
100
|
+
}
|
|
101
|
+
/** Kill any yielded pipe-backed shell processes retained by a disposed Agent. */
|
|
102
|
+
export function disposeAgentExecSessions(agent) {
|
|
103
|
+
const state = STATES.get(agent);
|
|
104
|
+
if (state === undefined)
|
|
105
|
+
return;
|
|
106
|
+
STATES.delete(agent);
|
|
107
|
+
for (const session of state.sessions.values()) {
|
|
108
|
+
if (session.kind === 'shell' && session.process.status === 'running') {
|
|
109
|
+
session.process.kill();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
state.sessions.clear();
|
|
113
|
+
}
|
|
114
|
+
async function runTtyCommand(ctx, args, exec, workdir, maxBytes, startedAt) {
|
|
115
|
+
const agent = exec.agent;
|
|
116
|
+
const terminals = ctx.get('terminals');
|
|
117
|
+
if (agent === undefined || terminals === undefined) {
|
|
118
|
+
throw new Error('exec_command with tty=true requires the dsh terminal capability and an owning agent session');
|
|
119
|
+
}
|
|
120
|
+
const spawnRequest = {
|
|
121
|
+
type: 'shell',
|
|
122
|
+
...workdir === undefined ? {} : { cwd: workdir },
|
|
123
|
+
};
|
|
124
|
+
const spawned = await terminals.spawn(agent, spawnRequest, exec.signal);
|
|
125
|
+
let retained = false;
|
|
126
|
+
let closeReason = 'Codex command failed';
|
|
127
|
+
try {
|
|
128
|
+
const sendRequest = { text: args.cmd, submit: true, signal: exec.signal };
|
|
129
|
+
const result = await terminals.startSend(agent, spawned.sessionId, sendRequest).done;
|
|
130
|
+
const output = terminalResult(result, maxBytes, startedAt);
|
|
131
|
+
if (result.sessionStatus.kind === 'running') {
|
|
132
|
+
output.session_id = allocateSession(ctx, agent, { kind: 'terminal', owner: agent, id: spawned.sessionId });
|
|
133
|
+
retained = true;
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
closeReason = 'Codex command exited';
|
|
137
|
+
}
|
|
138
|
+
return output;
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
// A PTY is published by spawn before the first send starts. Do not leave
|
|
142
|
+
// that session behind when send setup or its foreground operation fails.
|
|
143
|
+
if (!retained)
|
|
144
|
+
await terminals.kill(agent, spawned.sessionId, closeReason);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function startBackgroundJob(ctx, args, exec, shellRequest, confines, maxBytes, startedAt) {
|
|
148
|
+
const owner = exec.agent;
|
|
149
|
+
if (owner === undefined)
|
|
150
|
+
throw new Error('run_in_background requires an owning agent session');
|
|
151
|
+
const jobs = ctx.get('jobs');
|
|
152
|
+
if (jobs === undefined) {
|
|
153
|
+
throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs');
|
|
154
|
+
}
|
|
155
|
+
if (exec.signal.aborted) {
|
|
156
|
+
exec.signal.throwIfAborted();
|
|
157
|
+
throw new Error('tool call aborted');
|
|
158
|
+
}
|
|
159
|
+
let process;
|
|
160
|
+
let cancelled = false;
|
|
161
|
+
const lifetime = new AbortController();
|
|
162
|
+
const jobSpec = {
|
|
163
|
+
kind: 'bash',
|
|
164
|
+
label: args.cmd,
|
|
165
|
+
owner: owner.id,
|
|
166
|
+
outputLimitBytes: maxBytes,
|
|
167
|
+
output: ['stdout', 'stderr'].map(channel => ({
|
|
168
|
+
channel,
|
|
169
|
+
read: (fromByte) => process?.observed?.[channel].readFrom(fromByte)
|
|
170
|
+
?? { text: '', nextOffset: fromByte, lossy: false },
|
|
171
|
+
})),
|
|
172
|
+
run: () => {
|
|
173
|
+
const prepared = startShell(ctx, { ...shellRequest, signal: lifetime.signal });
|
|
174
|
+
const done = (async () => {
|
|
175
|
+
try {
|
|
176
|
+
process = await prepared;
|
|
177
|
+
if (cancelled)
|
|
178
|
+
process.kill();
|
|
179
|
+
await process.done;
|
|
180
|
+
const completed = await assertShellCompleted(process, confines);
|
|
181
|
+
return backgroundOutcome(process, confines, completed?.sandbox ?? process.sandbox);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
if (cancelled)
|
|
185
|
+
return { status: 'killed', detail: 'cancelled during shell preparation' };
|
|
186
|
+
return {
|
|
187
|
+
status: 'failed',
|
|
188
|
+
detail: [error instanceof Error ? error.message : String(error), ...sandboxNotes(process?.sandbox, confines)].join('; '),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
})();
|
|
192
|
+
return {
|
|
193
|
+
cancel: () => {
|
|
194
|
+
cancelled = true;
|
|
195
|
+
lifetime.abort();
|
|
196
|
+
process?.kill();
|
|
197
|
+
},
|
|
198
|
+
done,
|
|
199
|
+
};
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
const id = jobs.start(jobSpec);
|
|
203
|
+
return withChunkId({
|
|
204
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
205
|
+
job_id: id,
|
|
206
|
+
output: `Started background job ${id}. Use job_output with job_id "${id}" to read output.`,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
/** Execute one Codex command through the configured pipe or PTY capability. */
|
|
210
|
+
export async function runExecCommand(ctx, args, exec, config) {
|
|
211
|
+
if (args.cmd.trim().length === 0)
|
|
212
|
+
throw new Error('cmd must be a non-empty string');
|
|
213
|
+
positiveFinite('yield_time_ms', args.yield_time_ms);
|
|
214
|
+
const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens);
|
|
215
|
+
validateEscalationArgs(args.sandbox_permissions, args.justification);
|
|
216
|
+
const confines = ctx.get('shell')?.sandboxMode !== undefined;
|
|
217
|
+
const policyService = ctx.get('sandboxPolicy');
|
|
218
|
+
if (confines && policyService === undefined)
|
|
219
|
+
throw new Error('exec_command: a sandboxing shell requires ctx.sandboxPolicy');
|
|
220
|
+
if (confines && args.tty === true)
|
|
221
|
+
throw new Error('exec_command: tty=true cannot carry the sandbox policy; use pipe-backed execution on this host');
|
|
222
|
+
let policy = policyService?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session });
|
|
223
|
+
if (args.sandbox_permissions !== undefined) {
|
|
224
|
+
if (!confines)
|
|
225
|
+
throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)');
|
|
226
|
+
const approvedMode = await approveEscalation({
|
|
227
|
+
requestedMode: args.sandbox_permissions,
|
|
228
|
+
justification: args.justification,
|
|
229
|
+
effectiveMode: policy.mode,
|
|
230
|
+
subject: 'command',
|
|
231
|
+
}, {
|
|
232
|
+
approver: ctx.get('approval'),
|
|
233
|
+
agent: exec.agent,
|
|
234
|
+
callId: exec.callId,
|
|
235
|
+
toolName: 'exec_command',
|
|
236
|
+
signal: exec.signal,
|
|
237
|
+
});
|
|
238
|
+
exec.signal.throwIfAborted();
|
|
239
|
+
policy = { ...policy, mode: approvedMode };
|
|
240
|
+
}
|
|
241
|
+
const workdir = sessionCwd(ctx, exec, args.workdir);
|
|
242
|
+
const startedAt = performance.now();
|
|
243
|
+
if (args.run_in_background === true && args.tty === true) {
|
|
244
|
+
throw new Error('run_in_background is only supported for pipe-backed commands; omit tty');
|
|
245
|
+
}
|
|
246
|
+
if (args.tty === true)
|
|
247
|
+
return runTtyCommand(ctx, args, exec, workdir, maxBytes, startedAt);
|
|
248
|
+
const dshEnv = ctx.get('shellEnv')?.collect(exec);
|
|
249
|
+
const shellRequest = {
|
|
250
|
+
command: args.cmd,
|
|
251
|
+
onExpiry: 'none',
|
|
252
|
+
...workdir === undefined ? {} : { workdir },
|
|
253
|
+
stdoutMaxBytes: maxBytes,
|
|
254
|
+
...dshEnv === undefined ? {} : { dshEnv },
|
|
255
|
+
...policy === undefined ? {} : { sandboxPolicy: policy },
|
|
256
|
+
};
|
|
257
|
+
if (args.run_in_background === true) {
|
|
258
|
+
return startBackgroundJob(ctx, args, exec, shellRequest, confines, maxBytes, startedAt);
|
|
259
|
+
}
|
|
260
|
+
const process = await startShell(ctx, { ...shellRequest, signal: exec.signal });
|
|
261
|
+
try {
|
|
262
|
+
await waitForShell(process, normalizeWaitMs(args.yield_time_ms, config.defaultYieldTimeMs, false, true), exec.signal);
|
|
263
|
+
const read = process.readOutput();
|
|
264
|
+
if (process.status === 'running') {
|
|
265
|
+
if (exec.agent === undefined) {
|
|
266
|
+
process.kill();
|
|
267
|
+
await process.done;
|
|
268
|
+
const completed = await assertShellCompleted(process, confines);
|
|
269
|
+
const formatted = readShellOutput({ ...read, delta: read.delta + process.readOutput().delta }, maxBytes, completed?.sandbox ?? process.sandbox, confines);
|
|
270
|
+
return withChunkId({
|
|
271
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
272
|
+
output: formatted.output,
|
|
273
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
const formatted = readShellOutput(read, maxBytes, process.sandbox, confines);
|
|
277
|
+
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]';
|
|
278
|
+
const output = hasInteractivePrompt(formatted.output)
|
|
279
|
+
? `${formatted.output}${formatted.output.length > 0 && !formatted.output.endsWith('\n') ? '\n' : ''}${interactiveHint}`
|
|
280
|
+
: formatted.output;
|
|
281
|
+
return withChunkId({
|
|
282
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
283
|
+
output,
|
|
284
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
285
|
+
session_id: allocateSession(ctx, exec.agent, { kind: 'shell', process, escalationAvailable: confines }),
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
const completed = await assertShellCompleted(process, confines);
|
|
289
|
+
const formatted = readShellOutput(read, maxBytes, completed?.sandbox ?? process.sandbox, confines);
|
|
290
|
+
return withChunkId({
|
|
291
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
292
|
+
output: formatted.output,
|
|
293
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
294
|
+
...process.exitCode === null ? {} : { exit_code: process.exitCode },
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
await stopShellOnAbort(process, exec.signal);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/** Poll or write to one session returned by {@link runExecCommand}. */
|
|
302
|
+
export async function runWriteStdin(ctx, args, exec, config) {
|
|
303
|
+
const escalation = args;
|
|
304
|
+
if (escalation.sandbox_permissions !== undefined || escalation.justification !== undefined) {
|
|
305
|
+
throw new Error('write_stdin cannot change an existing command sandbox; use exec_command for an approved one-shot retry');
|
|
306
|
+
}
|
|
307
|
+
positiveFinite('yield_time_ms', args.yield_time_ms);
|
|
308
|
+
if (!Number.isSafeInteger(args.session_id) || args.session_id <= 0) {
|
|
309
|
+
throw new Error('session_id must be a positive integer');
|
|
310
|
+
}
|
|
311
|
+
const agent = exec.agent;
|
|
312
|
+
if (agent === undefined)
|
|
313
|
+
throw new Error('write_stdin requires an owning agent session');
|
|
314
|
+
const session = storedSession(agent, args.session_id);
|
|
315
|
+
const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens);
|
|
316
|
+
const startedAt = performance.now();
|
|
317
|
+
const chars = args.chars ?? '';
|
|
318
|
+
if (session.kind === 'shell') {
|
|
319
|
+
if (chars === '\u0003') {
|
|
320
|
+
session.process.kill();
|
|
321
|
+
}
|
|
322
|
+
else if (chars.length > 0) {
|
|
323
|
+
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');
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
const waitMs = normalizeWaitMs(args.yield_time_ms, chars === '\u0003' ? config.writeYieldTimeMs : config.pollYieldTimeMs, chars.length === 0);
|
|
327
|
+
await waitForShell(session.process, waitMs, exec.signal);
|
|
328
|
+
const read = session.process.readOutput();
|
|
329
|
+
if (session.process.status !== 'running') {
|
|
330
|
+
forgetSession(agent, args.session_id);
|
|
331
|
+
const completed = await assertShellCompleted(session.process, session.escalationAvailable);
|
|
332
|
+
const formatted = readShellOutput(read, maxBytes, completed?.sandbox ?? session.process.sandbox, session.escalationAvailable);
|
|
333
|
+
return withChunkId({
|
|
334
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
335
|
+
output: formatted.output,
|
|
336
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
337
|
+
...session.process.exitCode === null ? {} : { exit_code: session.process.exitCode },
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
const formatted = readShellOutput(read, maxBytes, session.process.sandbox, session.escalationAvailable);
|
|
341
|
+
return withChunkId({
|
|
342
|
+
wall_time_seconds: (performance.now() - startedAt) / 1000,
|
|
343
|
+
output: formatted.output,
|
|
344
|
+
...formatted.originalTokenCount === undefined ? {} : { original_token_count: formatted.originalTokenCount },
|
|
345
|
+
session_id: args.session_id,
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
finally {
|
|
349
|
+
if (exec.signal.aborted) {
|
|
350
|
+
try {
|
|
351
|
+
await stopShellOnAbort(session.process, exec.signal);
|
|
352
|
+
}
|
|
353
|
+
finally {
|
|
354
|
+
forgetSession(agent, args.session_id);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const terminals = ctx.get('terminals');
|
|
360
|
+
if (terminals === undefined)
|
|
361
|
+
throw new Error('the dsh terminal capability is no longer available');
|
|
362
|
+
const sendRequest = { text: chars, submit: false, signal: exec.signal };
|
|
363
|
+
let retained = false;
|
|
364
|
+
let closeReason = 'Codex command failed';
|
|
365
|
+
try {
|
|
366
|
+
const result = await terminals.startSend(agent, session.id, sendRequest).done;
|
|
367
|
+
const output = terminalResult(result, maxBytes, startedAt);
|
|
368
|
+
if (result.sessionStatus.kind === 'running') {
|
|
369
|
+
output.session_id = args.session_id;
|
|
370
|
+
retained = true;
|
|
371
|
+
}
|
|
372
|
+
else {
|
|
373
|
+
closeReason = 'Codex command exited';
|
|
374
|
+
forgetSession(agent, args.session_id);
|
|
375
|
+
}
|
|
376
|
+
return output;
|
|
377
|
+
}
|
|
378
|
+
finally {
|
|
379
|
+
if (!retained) {
|
|
380
|
+
forgetSession(agent, args.session_id);
|
|
381
|
+
await terminals.kill(agent, session.id, closeReason);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
//# sourceMappingURL=exec-runner.js.map
|