@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
|
@@ -0,0 +1,2235 @@
|
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { createScope, scopeOf, scopeParentOf } from "@deepseek-ai/dsh-scope";
|
|
3
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
4
|
+
import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from "@deepseek-ai/dsh-sandbox";
|
|
5
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
6
|
+
import { dirname, isAbsolute, relative, resolve } from "node:path";
|
|
7
|
+
import { HarnessError } from "@deepseek-ai/dsh-llm";
|
|
8
|
+
import "@deepseek-ai/dsh-credentials";
|
|
9
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
10
|
+
import { z as z$1 } from "zod";
|
|
11
|
+
import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
|
|
12
|
+
import { readFile, realpath, stat, unlink } from "node:fs/promises";
|
|
13
|
+
import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
14
|
+
import { Scalar, YAMLMap, isMap, isScalar, isSeq, parseDocument } from "yaml";
|
|
15
|
+
import { PERSONA_PREFIX_SECTION, PERSONA_SUFFIX_SECTION } from "@deepseek-ai/dsh-system-prompt";
|
|
16
|
+
String.raw`start: begin_patch hunk+ end_patch
|
|
17
|
+
begin_patch: "*** Begin Patch" LF
|
|
18
|
+
end_patch: "*** End Patch" LF?
|
|
19
|
+
hunk: add_hunk | delete_hunk | update_hunk
|
|
20
|
+
add_hunk: "*** Add File: " filename LF add_line+
|
|
21
|
+
delete_hunk: "*** Delete File: " filename LF
|
|
22
|
+
update_hunk: "*** Update File: " filename LF change_move? change?
|
|
23
|
+
filename: /(.+)/
|
|
24
|
+
add_line: "+" /(.*)/ LF -> line
|
|
25
|
+
change_move: "*** Move to: " filename LF
|
|
26
|
+
change: (change_context | change_line)+ eof_line?
|
|
27
|
+
change_context: ("@@" | "@@ " /(.+)/) LF
|
|
28
|
+
change_line: ("+" | "-" | " ") /(.*)/ LF
|
|
29
|
+
eof_line: "*** End of File" LF
|
|
30
|
+
%import common.LF
|
|
31
|
+
`;
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region lib/types/exec.js
|
|
34
|
+
/** Codex `exec_command` and `write_stdin` execution over dsh capability seams. */
|
|
35
|
+
const STATES = /* @__PURE__ */ new WeakMap();
|
|
36
|
+
const MIN_YIELD_TIME_MS = 250;
|
|
37
|
+
const WINDOWS_INITIAL_EXEC_YIELD_TIME_MS = 1e4;
|
|
38
|
+
const MIN_EMPTY_YIELD_TIME_MS = 5e3;
|
|
39
|
+
const MAX_YIELD_TIME_MS = 3e4;
|
|
40
|
+
const MAX_EMPTY_YIELD_TIME_MS = 3e5;
|
|
41
|
+
const DEFAULT_OUTPUT_TOKENS = 1e4;
|
|
42
|
+
const APPROX_BYTES_PER_TOKEN = 4;
|
|
43
|
+
function stateFor(agent) {
|
|
44
|
+
const current = STATES.get(agent);
|
|
45
|
+
if (current !== void 0) return current;
|
|
46
|
+
const created = {
|
|
47
|
+
nextId: 0,
|
|
48
|
+
sessions: /* @__PURE__ */ new Map()
|
|
49
|
+
};
|
|
50
|
+
STATES.set(agent, created);
|
|
51
|
+
return created;
|
|
52
|
+
}
|
|
53
|
+
function positiveFinite(name, value) {
|
|
54
|
+
if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new Error(`${name} must be a non-negative finite number`);
|
|
55
|
+
}
|
|
56
|
+
function normalizeWaitMs(value, fallback, empty = false, initialExec = false) {
|
|
57
|
+
const lower = empty ? MIN_EMPTY_YIELD_TIME_MS : initialExec && process.platform === "win32" ? WINDOWS_INITIAL_EXEC_YIELD_TIME_MS : MIN_YIELD_TIME_MS;
|
|
58
|
+
return Math.max(lower, Math.min(empty ? MAX_EMPTY_YIELD_TIME_MS : MAX_YIELD_TIME_MS, Math.trunc(value ?? fallback)));
|
|
59
|
+
}
|
|
60
|
+
function outputLimit(maxOutputBytes, maxOutputTokens) {
|
|
61
|
+
const tokens = maxOutputTokens ?? DEFAULT_OUTPUT_TOKENS;
|
|
62
|
+
if (maxOutputTokens !== void 0) positiveFinite("max_output_tokens", maxOutputTokens);
|
|
63
|
+
return Math.max(1, Math.min(maxOutputBytes, Math.trunc(tokens * APPROX_BYTES_PER_TOKEN)));
|
|
64
|
+
}
|
|
65
|
+
function limitOutput(text, maxBytes) {
|
|
66
|
+
if (Buffer.byteLength(text, "utf8") <= maxBytes) return text;
|
|
67
|
+
let end = Math.min(text.length, maxBytes);
|
|
68
|
+
while (end > 0 && Buffer.byteLength(text.slice(0, end), "utf8") > maxBytes) end--;
|
|
69
|
+
return `${text.slice(0, end)}\n[output truncated]`;
|
|
70
|
+
}
|
|
71
|
+
function newChunkId() {
|
|
72
|
+
return randomBytes(3).toString("hex");
|
|
73
|
+
}
|
|
74
|
+
function withChunkId(result) {
|
|
75
|
+
return {
|
|
76
|
+
chunk_id: newChunkId(),
|
|
77
|
+
...result
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** Render the ordinary Responses tool result text used by Codex's unified exec tools. */
|
|
81
|
+
function renderExecResult(result) {
|
|
82
|
+
const sections = [];
|
|
83
|
+
if (result.chunk_id !== void 0) sections.push(`Chunk ID: ${result.chunk_id}`);
|
|
84
|
+
sections.push(`Wall time: ${result.wall_time_seconds.toFixed(4)} seconds`);
|
|
85
|
+
if (result.exit_code !== void 0) sections.push(`Process exited with code ${result.exit_code}`);
|
|
86
|
+
if (result.session_id !== void 0) sections.push(`Process running with session ID ${result.session_id}`);
|
|
87
|
+
if (result.job_id !== void 0) sections.push(`Background job ID: ${result.job_id}`);
|
|
88
|
+
if (result.original_token_count !== void 0) sections.push(`Original token count: ${result.original_token_count}`);
|
|
89
|
+
sections.push("Output:", result.output);
|
|
90
|
+
return sections.join("\n");
|
|
91
|
+
}
|
|
92
|
+
function sessionCwd(ctx, exec, workdir) {
|
|
93
|
+
const directories = ctx.get("workingDirectory");
|
|
94
|
+
const cwd = exec.agent === void 0 ? void 0 : directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd;
|
|
95
|
+
return workdir === void 0 ? cwd : resolve(cwd ?? process.cwd(), workdir);
|
|
96
|
+
}
|
|
97
|
+
/** Per-call shell selection belonged to legacy providers, not the current shell seam. */
|
|
98
|
+
function supportsLegacyShellOptions(ctx) {
|
|
99
|
+
const shell = ctx.get("shell");
|
|
100
|
+
if (shell === void 0) throw new Error("exec_command requires ctx.shell");
|
|
101
|
+
return typeof shell.execute !== "function";
|
|
102
|
+
}
|
|
103
|
+
/** Surface infrastructure failures from the current execution handle without reclassifying nonzero exits. */
|
|
104
|
+
async function assertShellCompleted(process, escalationAvailable = false) {
|
|
105
|
+
const result = process.result;
|
|
106
|
+
if (typeof result !== "function") return void 0;
|
|
107
|
+
try {
|
|
108
|
+
return await result.call(process);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
const notes = sandboxNotes(process.sandbox, escalationAvailable);
|
|
111
|
+
if (notes.length === 0) throw error;
|
|
112
|
+
const message = [error instanceof Error ? error.message : String(error), ...notes].join("\n");
|
|
113
|
+
const failure = error instanceof HarnessError ? new HarnessError(message, error.code, { cause: error }) : new Error(message, { cause: error });
|
|
114
|
+
if (error instanceof Error) failure.name = error.name;
|
|
115
|
+
throw failure;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Preserve policy/runner facts after bounding command output; never truncate these markers. */
|
|
119
|
+
function sandboxNotes(sandbox, escalationAvailable) {
|
|
120
|
+
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]`];
|
|
121
|
+
if (!sandbox?.denied) return [];
|
|
122
|
+
return [sandboxDenialMarker(sandbox.mode), ...escalationAvailable ? [escalationHintMarker("command")] : []];
|
|
123
|
+
}
|
|
124
|
+
/** Current executors prepare asynchronously; old providers published a handle synchronously. */
|
|
125
|
+
function startShell(ctx, request) {
|
|
126
|
+
const provider = ctx.get("shell");
|
|
127
|
+
if (provider === void 0) throw new Error("exec_command requires ctx.shell");
|
|
128
|
+
const shell = provider;
|
|
129
|
+
const spec = shell.resolve(request);
|
|
130
|
+
if (typeof shell.execute === "function") return shell.execute(spec);
|
|
131
|
+
if (typeof shell.start === "function") return shell.start(spec);
|
|
132
|
+
throw new Error("exec_command: the configured shell has no execution capability");
|
|
133
|
+
}
|
|
134
|
+
function readShellOutput(read, maxBytes, sandbox, escalationAvailable = false) {
|
|
135
|
+
const output = limitOutput(read.delta, maxBytes);
|
|
136
|
+
const notes = sandboxNotes(sandbox, escalationAvailable);
|
|
137
|
+
return notes.length === 0 ? output : `${output}${output.length > 0 && !output.endsWith("\n") ? "\n" : ""}${notes.join("\n")}`;
|
|
138
|
+
}
|
|
139
|
+
function terminalResult(result, maxBytes, startedAt) {
|
|
140
|
+
const output = limitOutput(result.viewport, maxBytes);
|
|
141
|
+
return withChunkId({
|
|
142
|
+
wall_time_seconds: (performance.now() - startedAt) / 1e3,
|
|
143
|
+
output,
|
|
144
|
+
...result.sessionStatus.kind === "exited" ? { ...result.sessionStatus.exitCode === null ? {} : { exit_code: result.sessionStatus.exitCode } } : {}
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/** Map a detached shell process onto the generic DSH job outcome contract. */
|
|
148
|
+
function backgroundOutcome(process, escalationAvailable, sandbox = process.sandbox) {
|
|
149
|
+
const base = process.status === "killed" ? {
|
|
150
|
+
status: "killed",
|
|
151
|
+
detail: process.signal !== null ? `signal: ${process.signal}` : "killed before exit"
|
|
152
|
+
} : {
|
|
153
|
+
status: "completed",
|
|
154
|
+
detail: `exit code: ${process.exitCode ?? 0}`
|
|
155
|
+
};
|
|
156
|
+
const notes = sandboxNotes(sandbox, escalationAvailable);
|
|
157
|
+
return notes.length === 0 ? base : {
|
|
158
|
+
...base,
|
|
159
|
+
detail: `${base.detail}; ${notes.join(" ")}`
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
async function waitForShell(process, ms, signal) {
|
|
163
|
+
let timer;
|
|
164
|
+
let onAbort = () => {};
|
|
165
|
+
const elapsed = new Promise((resolve) => {
|
|
166
|
+
onAbort = () => resolve(false);
|
|
167
|
+
if (signal.aborted) {
|
|
168
|
+
onAbort();
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
172
|
+
timer = setTimeout(() => resolve(void 0), ms);
|
|
173
|
+
});
|
|
174
|
+
try {
|
|
175
|
+
const completed = await Promise.race([process.done.then(() => true), elapsed]);
|
|
176
|
+
if (signal.aborted) signal.throwIfAborted();
|
|
177
|
+
return completed === true || process.status !== "running";
|
|
178
|
+
} finally {
|
|
179
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
180
|
+
signal.removeEventListener("abort", onAbort);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** Stop a pipe-backed session when the current Codex tool is cancelled. */
|
|
184
|
+
async function stopShellOnAbort(process, signal) {
|
|
185
|
+
if (!signal.aborted || process.status !== "running") return;
|
|
186
|
+
process.kill();
|
|
187
|
+
await process.done;
|
|
188
|
+
}
|
|
189
|
+
function allocateSession(agent, session) {
|
|
190
|
+
const state = stateFor(agent);
|
|
191
|
+
const id = ++state.nextId;
|
|
192
|
+
state.sessions.set(id, session);
|
|
193
|
+
return id;
|
|
194
|
+
}
|
|
195
|
+
function storedSession(agent, id) {
|
|
196
|
+
const session = stateFor(agent).sessions.get(id);
|
|
197
|
+
if (session === void 0) throw new Error(`unknown unified exec session ${id}`);
|
|
198
|
+
return session;
|
|
199
|
+
}
|
|
200
|
+
function forgetSession(agent, id) {
|
|
201
|
+
stateFor(agent).sessions.delete(id);
|
|
202
|
+
}
|
|
203
|
+
function commandFor(args) {
|
|
204
|
+
return args.cmd;
|
|
205
|
+
}
|
|
206
|
+
/** Execute one Codex command through the configured pipe or PTY capability. */
|
|
207
|
+
async function runExecCommand(ctx, args, exec, config) {
|
|
208
|
+
if (args.cmd.trim().length === 0) throw new Error("cmd must be a non-empty string");
|
|
209
|
+
positiveFinite("yield_time_ms", args.yield_time_ms);
|
|
210
|
+
const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens);
|
|
211
|
+
const legacyShellOptions = supportsLegacyShellOptions(ctx);
|
|
212
|
+
if (!legacyShellOptions && (args.shell !== void 0 || args.login !== void 0)) throw new Error("exec_command: this host selects the shell and startup mode in its configuration; per-call shell/login options are unavailable");
|
|
213
|
+
validateEscalationArgs(args.sandbox_permissions, args.justification);
|
|
214
|
+
const confines = ctx.get("shell")?.sandboxMode !== void 0;
|
|
215
|
+
const policyService = ctx.get("sandboxPolicy");
|
|
216
|
+
if (confines && policyService === void 0) throw new Error("exec_command: a sandboxing shell requires ctx.sandboxPolicy");
|
|
217
|
+
if (confines && args.tty === true) throw new Error("exec_command: tty=true cannot carry the sandbox policy; use pipe-backed execution on this host");
|
|
218
|
+
let policy = policyService?.resolve(exec.agent === void 0 ? {} : { session: exec.agent.session });
|
|
219
|
+
if (args.sandbox_permissions !== void 0) {
|
|
220
|
+
if (!confines) throw new Error("sandbox_permissions is not available in this composition (no sandboxing executor to escalate)");
|
|
221
|
+
const approvedMode = await approveEscalation({
|
|
222
|
+
requestedMode: args.sandbox_permissions,
|
|
223
|
+
justification: args.justification,
|
|
224
|
+
effectiveMode: policy.mode,
|
|
225
|
+
subject: "command"
|
|
226
|
+
}, {
|
|
227
|
+
approver: ctx.get("approval"),
|
|
228
|
+
agent: exec.agent,
|
|
229
|
+
callId: exec.callId,
|
|
230
|
+
toolName: "exec_command",
|
|
231
|
+
signal: exec.signal
|
|
232
|
+
});
|
|
233
|
+
exec.signal.throwIfAborted();
|
|
234
|
+
policy = {
|
|
235
|
+
...policy,
|
|
236
|
+
mode: approvedMode
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
const workdir = sessionCwd(ctx, exec, args.workdir);
|
|
240
|
+
const startedAt = performance.now();
|
|
241
|
+
if (args.run_in_background === true && args.tty === true) throw new Error("run_in_background is only supported for pipe-backed commands; omit tty");
|
|
242
|
+
if (args.tty === true) {
|
|
243
|
+
const agent = exec.agent;
|
|
244
|
+
const terminals = ctx.get("terminals");
|
|
245
|
+
if (agent === void 0 || terminals === void 0) throw new Error("exec_command with tty=true requires the dsh terminal capability and an owning agent session");
|
|
246
|
+
const spawnRequest = {
|
|
247
|
+
type: "shell",
|
|
248
|
+
...legacyShellOptions ? {
|
|
249
|
+
...args.shell === void 0 ? {} : { shell: args.shell },
|
|
250
|
+
login: args.login ?? true
|
|
251
|
+
} : {},
|
|
252
|
+
...workdir === void 0 ? {} : { cwd: workdir }
|
|
253
|
+
};
|
|
254
|
+
const spawned = await terminals.spawn(agent, spawnRequest, exec.signal);
|
|
255
|
+
let retained = false;
|
|
256
|
+
let closeReason = "Codex command failed";
|
|
257
|
+
try {
|
|
258
|
+
const sendRequest = {
|
|
259
|
+
text: commandFor(args),
|
|
260
|
+
submit: true,
|
|
261
|
+
waitMs: normalizeWaitMs(args.yield_time_ms, config.defaultYieldTimeMs, false, true),
|
|
262
|
+
signal: exec.signal
|
|
263
|
+
};
|
|
264
|
+
const result = await terminals.startSend(agent, spawned.sessionId, sendRequest).done;
|
|
265
|
+
const output = terminalResult(result, maxBytes, startedAt);
|
|
266
|
+
if (result.sessionStatus.kind === "running") {
|
|
267
|
+
output.session_id = allocateSession(agent, {
|
|
268
|
+
kind: "terminal",
|
|
269
|
+
owner: agent,
|
|
270
|
+
id: spawned.sessionId
|
|
271
|
+
});
|
|
272
|
+
retained = true;
|
|
273
|
+
} else closeReason = "Codex command exited";
|
|
274
|
+
return output;
|
|
275
|
+
} finally {
|
|
276
|
+
if (!retained) await terminals.kill(agent, spawned.sessionId, closeReason);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const dshEnv = ctx.get("shellEnv")?.collect(exec);
|
|
280
|
+
const shellRequest = {
|
|
281
|
+
command: commandFor(args),
|
|
282
|
+
onExpiry: "none",
|
|
283
|
+
...legacyShellOptions ? {
|
|
284
|
+
...args.shell === void 0 ? {} : { shell: args.shell },
|
|
285
|
+
login: args.login ?? true
|
|
286
|
+
} : {},
|
|
287
|
+
...workdir === void 0 ? {} : { workdir },
|
|
288
|
+
stdoutMaxBytes: maxBytes,
|
|
289
|
+
...dshEnv === void 0 ? {} : { dshEnv },
|
|
290
|
+
...policy === void 0 ? {} : { sandboxPolicy: policy }
|
|
291
|
+
};
|
|
292
|
+
if (args.run_in_background === true) {
|
|
293
|
+
const owner = exec.agent;
|
|
294
|
+
if (owner === void 0) throw new Error("run_in_background requires an owning agent session");
|
|
295
|
+
const jobs = ctx.get("jobs");
|
|
296
|
+
if (jobs === void 0) throw new Error("background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs");
|
|
297
|
+
if (exec.signal.aborted) {
|
|
298
|
+
exec.signal.throwIfAborted();
|
|
299
|
+
throw new Error("tool call aborted");
|
|
300
|
+
}
|
|
301
|
+
const ringBacked = typeof jobs.readAt === "function";
|
|
302
|
+
let process;
|
|
303
|
+
let cancelled = false;
|
|
304
|
+
const lifetime = new AbortController();
|
|
305
|
+
const start = () => {
|
|
306
|
+
const prepared = startShell(ctx, {
|
|
307
|
+
...shellRequest,
|
|
308
|
+
...ringBacked ? { signal: lifetime.signal } : {}
|
|
309
|
+
});
|
|
310
|
+
return {
|
|
311
|
+
cancel: () => {
|
|
312
|
+
cancelled = true;
|
|
313
|
+
lifetime.abort();
|
|
314
|
+
process?.kill();
|
|
315
|
+
},
|
|
316
|
+
done: (async () => {
|
|
317
|
+
try {
|
|
318
|
+
process = "then" in prepared ? await prepared : prepared;
|
|
319
|
+
if (cancelled) process.kill();
|
|
320
|
+
await process.done;
|
|
321
|
+
const completed = await assertShellCompleted(process, confines);
|
|
322
|
+
return backgroundOutcome(process, confines, completed?.sandbox ?? process.sandbox);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
if (cancelled) return {
|
|
325
|
+
status: "killed",
|
|
326
|
+
detail: "cancelled during shell preparation"
|
|
327
|
+
};
|
|
328
|
+
return {
|
|
329
|
+
status: "failed",
|
|
330
|
+
detail: [error instanceof Error ? error.message : String(error), ...sandboxNotes(process?.sandbox, confines)].join("; ")
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
})(),
|
|
334
|
+
...ringBacked ? {} : { readOutput: () => process === void 0 ? "" : readShellOutput(process.readOutput(), maxBytes, process.sandbox, confines) }
|
|
335
|
+
};
|
|
336
|
+
};
|
|
337
|
+
const output = ["stdout", "stderr"].map((channel) => ({
|
|
338
|
+
channel,
|
|
339
|
+
read: (fromByte) => process?.observed?.[channel].readFrom(fromByte) ?? {
|
|
340
|
+
text: "",
|
|
341
|
+
nextOffset: fromByte,
|
|
342
|
+
lossy: false
|
|
343
|
+
}
|
|
344
|
+
}));
|
|
345
|
+
const id = jobs.start({
|
|
346
|
+
kind: "bash",
|
|
347
|
+
label: args.cmd,
|
|
348
|
+
owner: ringBacked ? owner.id : owner,
|
|
349
|
+
outputLimitBytes: maxBytes,
|
|
350
|
+
...ringBacked ? { output } : {},
|
|
351
|
+
run: start
|
|
352
|
+
});
|
|
353
|
+
return withChunkId({
|
|
354
|
+
wall_time_seconds: (performance.now() - startedAt) / 1e3,
|
|
355
|
+
job_id: id,
|
|
356
|
+
output: `Started background job ${id}. Use job_output with job_id "${id}" to read output.`
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
const prepared = startShell(ctx, {
|
|
360
|
+
...shellRequest,
|
|
361
|
+
signal: exec.signal
|
|
362
|
+
});
|
|
363
|
+
const process = "then" in prepared ? await prepared : prepared;
|
|
364
|
+
try {
|
|
365
|
+
await waitForShell(process, normalizeWaitMs(args.yield_time_ms, config.defaultYieldTimeMs, false, true), exec.signal);
|
|
366
|
+
const read = process.readOutput();
|
|
367
|
+
if (process.status === "running") {
|
|
368
|
+
const output = readShellOutput(read, maxBytes, process.sandbox, confines);
|
|
369
|
+
if (exec.agent === void 0) {
|
|
370
|
+
process.kill();
|
|
371
|
+
await process.done;
|
|
372
|
+
const completed = await assertShellCompleted(process, confines);
|
|
373
|
+
return withChunkId({
|
|
374
|
+
wall_time_seconds: (performance.now() - startedAt) / 1e3,
|
|
375
|
+
output: readShellOutput({
|
|
376
|
+
...read,
|
|
377
|
+
delta: read.delta + process.readOutput().delta
|
|
378
|
+
}, maxBytes, completed?.sandbox ?? process.sandbox, confines)
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
return withChunkId({
|
|
382
|
+
wall_time_seconds: (performance.now() - startedAt) / 1e3,
|
|
383
|
+
output,
|
|
384
|
+
session_id: allocateSession(exec.agent, {
|
|
385
|
+
kind: "shell",
|
|
386
|
+
process,
|
|
387
|
+
escalationAvailable: confines
|
|
388
|
+
})
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
const completed = await assertShellCompleted(process, confines);
|
|
392
|
+
return withChunkId({
|
|
393
|
+
wall_time_seconds: (performance.now() - startedAt) / 1e3,
|
|
394
|
+
output: readShellOutput(read, maxBytes, completed?.sandbox ?? process.sandbox, confines),
|
|
395
|
+
...process.exitCode === null ? {} : { exit_code: process.exitCode }
|
|
396
|
+
});
|
|
397
|
+
} finally {
|
|
398
|
+
await stopShellOnAbort(process, exec.signal);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/** Poll or write to one session returned by {@link runExecCommand}. */
|
|
402
|
+
async function runWriteStdin(ctx, args, exec, config) {
|
|
403
|
+
const escalation = args;
|
|
404
|
+
if (escalation.sandbox_permissions !== void 0 || escalation.justification !== void 0) throw new Error("write_stdin cannot change an existing command sandbox; use exec_command for an approved one-shot retry");
|
|
405
|
+
positiveFinite("yield_time_ms", args.yield_time_ms);
|
|
406
|
+
if (!Number.isSafeInteger(args.session_id) || args.session_id <= 0) throw new Error("session_id must be a positive integer");
|
|
407
|
+
const agent = exec.agent;
|
|
408
|
+
if (agent === void 0) throw new Error("write_stdin requires an owning agent session");
|
|
409
|
+
const session = storedSession(agent, args.session_id);
|
|
410
|
+
const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens);
|
|
411
|
+
const startedAt = performance.now();
|
|
412
|
+
const chars = args.chars ?? "";
|
|
413
|
+
if (session.kind === "shell") {
|
|
414
|
+
if (chars.length > 0) throw new Error("this unified exec session uses pipes and does not accept stdin; rerun exec_command with tty=true");
|
|
415
|
+
try {
|
|
416
|
+
await waitForShell(session.process, normalizeWaitMs(args.yield_time_ms, config.pollYieldTimeMs, true), exec.signal);
|
|
417
|
+
const read = session.process.readOutput();
|
|
418
|
+
if (session.process.status !== "running") {
|
|
419
|
+
forgetSession(agent, args.session_id);
|
|
420
|
+
const completed = await assertShellCompleted(session.process, session.escalationAvailable);
|
|
421
|
+
return withChunkId({
|
|
422
|
+
wall_time_seconds: (performance.now() - startedAt) / 1e3,
|
|
423
|
+
output: readShellOutput(read, maxBytes, completed?.sandbox ?? session.process.sandbox, session.escalationAvailable),
|
|
424
|
+
...session.process.exitCode === null ? {} : { exit_code: session.process.exitCode }
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
return withChunkId({
|
|
428
|
+
wall_time_seconds: (performance.now() - startedAt) / 1e3,
|
|
429
|
+
output: readShellOutput(read, maxBytes, session.process.sandbox, session.escalationAvailable),
|
|
430
|
+
session_id: args.session_id
|
|
431
|
+
});
|
|
432
|
+
} finally {
|
|
433
|
+
if (exec.signal.aborted) try {
|
|
434
|
+
await stopShellOnAbort(session.process, exec.signal);
|
|
435
|
+
} finally {
|
|
436
|
+
forgetSession(agent, args.session_id);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const terminals = ctx.get("terminals");
|
|
441
|
+
if (terminals === void 0) throw new Error("the dsh terminal capability is no longer available");
|
|
442
|
+
const sendRequest = {
|
|
443
|
+
text: chars,
|
|
444
|
+
submit: false,
|
|
445
|
+
waitMs: normalizeWaitMs(args.yield_time_ms, chars.length > 0 ? config.writeYieldTimeMs : config.pollYieldTimeMs, chars.length === 0),
|
|
446
|
+
signal: exec.signal
|
|
447
|
+
};
|
|
448
|
+
let retained = false;
|
|
449
|
+
let closeReason = "Codex command failed";
|
|
450
|
+
try {
|
|
451
|
+
const result = await terminals.startSend(agent, session.id, sendRequest).done;
|
|
452
|
+
const output = terminalResult(result, maxBytes, startedAt);
|
|
453
|
+
if (result.sessionStatus.kind === "running") {
|
|
454
|
+
output.session_id = args.session_id;
|
|
455
|
+
retained = true;
|
|
456
|
+
} else {
|
|
457
|
+
closeReason = "Codex command exited";
|
|
458
|
+
forgetSession(agent, args.session_id);
|
|
459
|
+
}
|
|
460
|
+
return output;
|
|
461
|
+
} finally {
|
|
462
|
+
if (!retained) {
|
|
463
|
+
forgetSession(agent, args.session_id);
|
|
464
|
+
await terminals.kill(agent, session.id, closeReason);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
//#endregion
|
|
469
|
+
//#region lib/types/host-settings.js
|
|
470
|
+
/** Host-only reads: never expose the unredacted provider configuration to clients. */
|
|
471
|
+
function readHostSettings(ctx, namespace) {
|
|
472
|
+
const settings = ctx.get("settings");
|
|
473
|
+
if (typeof settings?.get === "function") return settings.get(namespace);
|
|
474
|
+
if (namespace === "codex") {
|
|
475
|
+
const preferences = ctx.get("codexPreferences");
|
|
476
|
+
if (preferences !== void 0) return preferences.current();
|
|
477
|
+
}
|
|
478
|
+
return settings?.describe?.().find((row) => row.ns === namespace)?.value;
|
|
479
|
+
}
|
|
480
|
+
new AsyncLocalStorage();
|
|
481
|
+
z$1.union([
|
|
482
|
+
z$1.object({
|
|
483
|
+
activity: z$1.literal("compaction"),
|
|
484
|
+
startedAt: z$1.number().int().nonnegative()
|
|
485
|
+
}),
|
|
486
|
+
z$1.object({
|
|
487
|
+
activity: z$1.literal("requesting-model"),
|
|
488
|
+
startedAt: z$1.number().int().nonnegative()
|
|
489
|
+
}),
|
|
490
|
+
z$1.object({
|
|
491
|
+
activity: z$1.literal("model-reply"),
|
|
492
|
+
startedAt: z$1.number().int().nonnegative()
|
|
493
|
+
}),
|
|
494
|
+
z$1.object({
|
|
495
|
+
activity: z$1.literal("awaiting-model"),
|
|
496
|
+
startedAt: z$1.number().int().nonnegative()
|
|
497
|
+
}),
|
|
498
|
+
z$1.null()
|
|
499
|
+
]);
|
|
500
|
+
//#endregion
|
|
501
|
+
//#region lib/types/prompt.js
|
|
502
|
+
/** Default plugin-owned Codex operating prompt. */
|
|
503
|
+
const DEFAULT_CODEX_SYSTEM_PROMPT = String.raw`## General
|
|
504
|
+
|
|
505
|
+
- Follow the current tool catalog, not assumptions from another Codex client. For unknown paths, use the available list/search tools instead of guessing and reuse the returned paths. If only shell search is available, prefer rg or rg --files.
|
|
506
|
+
|
|
507
|
+
## Editing constraints
|
|
508
|
+
|
|
509
|
+
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
|
|
510
|
+
- Add succinct code comments that explain non-obvious code. Do not add comments that merely narrate assignments or control flow.
|
|
511
|
+
- You may be in a dirty git worktree. Never revert existing changes you did not make unless the user explicitly requests it. If unrelated files are changed, leave them alone.
|
|
512
|
+
|
|
513
|
+
## Planning
|
|
514
|
+
|
|
515
|
+
- Use update_plan for work with multiple meaningful steps. Keep the plan current as the task progresses.
|
|
516
|
+
- Do not use a plan for a trivial one-step request.
|
|
517
|
+
|
|
518
|
+
## dsh session
|
|
519
|
+
|
|
520
|
+
- The user and you share one workspace. Inspect the repository and every applicable AGENTS.md before editing.
|
|
521
|
+
- For Harness APIs, first load the relevant Harness skill. When Inspect tools are available, start with cordis_inspect_list, then query the provider's directory before an exact Service contract. Reuse returned names; Inspect is read-only.
|
|
522
|
+
- A not-found path or unknown Service is a discovery error: check the file list or Service directory before retrying. Preserve actual failures; do not hide them or bypass permission denials.
|
|
523
|
+
|
|
524
|
+
## Task execution
|
|
525
|
+
|
|
526
|
+
- Keep the user informed with concise progress updates and lead with the result.
|
|
527
|
+
|
|
528
|
+
## Presenting your work
|
|
529
|
+
|
|
530
|
+
- Be concise, direct, friendly, and actionable.
|
|
531
|
+
- For substantial work, explain what changed and why, then briefly note how the work was verified and what comes next.
|
|
532
|
+
- Do not dump large files into the conversation; refer to their paths.
|
|
533
|
+
- Use plain text with short sections only when they improve scanability.
|
|
534
|
+
|
|
535
|
+
## Working principles
|
|
536
|
+
|
|
537
|
+
- Actively establish the user's current context rather than relying on stale assumptions or prior context. Before committing to an approach that could materially shape the outcome or direction of the work, state the intended path and align it with the user; clarify any material uncertainty first. Then pursue the user's goal through the clearest, most effective path.
|
|
538
|
+
- Keep only the essential logic and core actions. Don't explain or test what was removed or why something wasn't done, especially when writing documentation or communicating. Convey enough valuable information with as few words as possible.
|
|
539
|
+
- Solve problems by thinking from first principles and at a higher level.
|
|
540
|
+
`;
|
|
541
|
+
/** Default deployment Persona template used by the Codex preset. */
|
|
542
|
+
const DEFAULT_CODEX_PERSONA = String.raw`You are Codex, a coding agent based on the {{model}} model. Your working directory is {{cwd}}.`;
|
|
543
|
+
/** Default DSH Core source-checkout guidance template. */
|
|
544
|
+
const DEFAULT_DSH_CORE_SOURCE_PROMPT = String.raw`The DeepSeek Harness implementation checkout is at {{sourceRoot}}. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself. If the supplied path is inside app.asar, treat it as a packaged runtime rather than a source checkout. Discover the installed packageDir via Inspect and read its README and package.json exports; do not assume src or individual lib/types filenames exist. Use Host file-read tools for app.asar; native shell search and glob cannot traverse it.`;
|
|
545
|
+
/** Default DSH Web runtime guidance template. */
|
|
546
|
+
const DEFAULT_DSH_CORE_WEB_PROMPT = [
|
|
547
|
+
"You are interacting with the user through the DeepSeek Harness Web GUI at {{webUrl}}.",
|
|
548
|
+
"When the user refers to \"this page\", \"this GUI\", or \"this app\" without naming another target, they mean this GUI.",
|
|
549
|
+
"The browser provides no implicit DOM, route, or screenshot context.",
|
|
550
|
+
"The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates.",
|
|
551
|
+
"Every other change - the apps/web shell and plain packages - requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh.",
|
|
552
|
+
"Starting another server does not update this GUI.",
|
|
553
|
+
"The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__.",
|
|
554
|
+
"Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL."
|
|
555
|
+
].join(" ");
|
|
556
|
+
//#endregion
|
|
557
|
+
//#region lib/types/context.js
|
|
558
|
+
const CODEX_CONTEXT_MAX = 1e6;
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region lib/types/settings.js
|
|
561
|
+
/** Shared host-side Codex settings contract. */
|
|
562
|
+
/** Live Codex controls shared by the Web UI and agent layer. */
|
|
563
|
+
const CODEX_SETTINGS_NAMESPACE$1 = "codex";
|
|
564
|
+
/** Default settings exposed even before a Codex session is opened. */
|
|
565
|
+
const CODEX_SETTINGS_ENTRY = {
|
|
566
|
+
fast: false,
|
|
567
|
+
fastModeControlEnabled: true,
|
|
568
|
+
persona: DEFAULT_CODEX_PERSONA,
|
|
569
|
+
harnessSourcePrompt: DEFAULT_DSH_CORE_SOURCE_PROMPT,
|
|
570
|
+
webSurfacePrompt: DEFAULT_DSH_CORE_WEB_PROMPT,
|
|
571
|
+
systemPrompt: DEFAULT_CODEX_SYSTEM_PROMPT,
|
|
572
|
+
promptEnabled: true,
|
|
573
|
+
terminalToolsEnabled: true,
|
|
574
|
+
patchToolEnabled: true,
|
|
575
|
+
planToolEnabled: true,
|
|
576
|
+
hostedWebSearchEnabled: true,
|
|
577
|
+
remoteCompactionEnabled: true,
|
|
578
|
+
activityIndicatorEnabled: true
|
|
579
|
+
};
|
|
580
|
+
z.object({
|
|
581
|
+
fast: z.boolean().default(false),
|
|
582
|
+
fastModeControlEnabled: z.boolean().default(true),
|
|
583
|
+
contextWindow: z.number().step(1).min(1).max(CODEX_CONTEXT_MAX),
|
|
584
|
+
persona: z.string().default(DEFAULT_CODEX_PERSONA),
|
|
585
|
+
harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
|
|
586
|
+
webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
|
|
587
|
+
systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
|
|
588
|
+
promptEnabled: z.boolean().default(true),
|
|
589
|
+
terminalToolsEnabled: z.boolean().default(true).hidden(),
|
|
590
|
+
patchToolEnabled: z.boolean().default(true).hidden(),
|
|
591
|
+
planToolEnabled: z.boolean().default(true).hidden(),
|
|
592
|
+
hostedWebSearchEnabled: z.boolean().default(true),
|
|
593
|
+
remoteCompactionEnabled: z.boolean().default(true),
|
|
594
|
+
activityIndicatorEnabled: z.boolean().default(true)
|
|
595
|
+
});
|
|
596
|
+
//#endregion
|
|
597
|
+
//#region lib/types/compaction.js
|
|
598
|
+
/** Codex compaction backend that honors the latest durable request capacity. */
|
|
599
|
+
/**
|
|
600
|
+
* The main plugin entry and the compact-command subpath can be evaluated as
|
|
601
|
+
* separate bundles. Keep their async context carrier on the process global so
|
|
602
|
+
* an explicit command mode reaches the global llm/stream listener.
|
|
603
|
+
*/
|
|
604
|
+
const COMPACTION_MODE_KEY = Symbol.for("shuind.dsh-codex-harness.compaction-mode");
|
|
605
|
+
(() => {
|
|
606
|
+
const registry = globalThis;
|
|
607
|
+
const existing = registry[COMPACTION_MODE_KEY];
|
|
608
|
+
if (existing !== void 0) return existing;
|
|
609
|
+
const storage = new AsyncLocalStorage();
|
|
610
|
+
registry[COMPACTION_MODE_KEY] = storage;
|
|
611
|
+
return storage;
|
|
612
|
+
})();
|
|
613
|
+
const CODEX_SETTINGS_NAMESPACE = "codex";
|
|
614
|
+
/** Codex context overrides apply only to GPT-compatible model routes. */
|
|
615
|
+
function isGptModel(model) {
|
|
616
|
+
return /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(model);
|
|
617
|
+
}
|
|
618
|
+
/** Read the live Codex capacity without requiring a custom LLM service API. */
|
|
619
|
+
function configuredContextWindow(ctx) {
|
|
620
|
+
const settings = ctx.get("settings");
|
|
621
|
+
if (settings?.get === void 0 && settings?.describe === void 0) return { available: false };
|
|
622
|
+
const value = readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE);
|
|
623
|
+
return {
|
|
624
|
+
available: true,
|
|
625
|
+
...value?.contextWindow !== void 0 && Number.isSafeInteger(value.contextWindow) && value.contextWindow > 0 ? { value: value.contextWindow } : {}
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
/** Read an explicit capacity persisted in the request header when settings are unavailable. */
|
|
629
|
+
function requestContextWindow(session, provider, model) {
|
|
630
|
+
const config = session.requestHeader()?.config;
|
|
631
|
+
if (config?.provider !== provider || config.model !== model) return void 0;
|
|
632
|
+
const value = config.contextWindow;
|
|
633
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
634
|
+
}
|
|
635
|
+
/** Resolve the capacity currently in force for an active Codex compaction. */
|
|
636
|
+
function activeContextWindow(ctx, activeSession, provider, model) {
|
|
637
|
+
const session = activeSession.getStore();
|
|
638
|
+
const requestContext = session?.requestContext();
|
|
639
|
+
const configured = isGptModel(model) ? configuredContextWindow(ctx) : { available: false };
|
|
640
|
+
return configured.available ? configured.value : (session === void 0 ? void 0 : requestContextWindow(session, provider, model)) ?? (requestContext?.provider === provider && requestContext.model === model ? requestContext.contextWindow : void 0);
|
|
641
|
+
}
|
|
642
|
+
/** Overlay capacity lookup and auxiliary summary requests for compaction. */
|
|
643
|
+
function withDurableContextCapacity(llm, ctx, activeSession) {
|
|
644
|
+
return new Proxy(llm, { get(target, property) {
|
|
645
|
+
if (property === "resolveModelInfo") return async (provider, model, signal) => {
|
|
646
|
+
const info = await target.resolveModelInfo(provider, model, signal);
|
|
647
|
+
const contextWindow = activeContextWindow(ctx, activeSession, provider, model);
|
|
648
|
+
if (contextWindow === void 0) return info;
|
|
649
|
+
return {
|
|
650
|
+
...info,
|
|
651
|
+
context: {
|
|
652
|
+
...info.context,
|
|
653
|
+
contextWindow
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
};
|
|
657
|
+
if (property === "stream") return (options) => {
|
|
658
|
+
const contextWindow = activeContextWindow(ctx, activeSession, options.provider, options.model);
|
|
659
|
+
if (contextWindow === void 0 || options.contextWindow === contextWindow) return target.stream(options);
|
|
660
|
+
return target.stream({
|
|
661
|
+
...options,
|
|
662
|
+
contextWindow
|
|
663
|
+
});
|
|
664
|
+
};
|
|
665
|
+
const value = Reflect.get(target, property, target);
|
|
666
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
667
|
+
} });
|
|
668
|
+
}
|
|
669
|
+
(class extends BasicCompactionEngine {
|
|
670
|
+
static inject = BasicCompactionEngine.inject;
|
|
671
|
+
static Config = BasicCompactionEngine.Config;
|
|
672
|
+
activeSession;
|
|
673
|
+
constructor(ctx, config = {}) {
|
|
674
|
+
const activeSession = new AsyncLocalStorage();
|
|
675
|
+
const llm = ctx.get("llm");
|
|
676
|
+
if (llm === void 0) throw new Error("codex compaction requires ctx.llm");
|
|
677
|
+
super(ctx.extend({ llm: withDurableContextCapacity(llm, ctx, activeSession) }), config);
|
|
678
|
+
this.activeSession = activeSession;
|
|
679
|
+
}
|
|
680
|
+
compactIfNeeded(agent, trigger, signal) {
|
|
681
|
+
return this.activeSession.run(agent.session, () => super.compactIfNeeded(agent, trigger, signal));
|
|
682
|
+
}
|
|
683
|
+
compactRegion(...args) {
|
|
684
|
+
return this.activeSession.run(args[2].session, () => super.compactRegion(...args));
|
|
685
|
+
}
|
|
686
|
+
compactNow(agent, signal, sourceCommandId) {
|
|
687
|
+
return this.activeSession.run(agent.session, () => super.compactNow(agent, signal, sourceCommandId));
|
|
688
|
+
}
|
|
689
|
+
});
|
|
690
|
+
//#endregion
|
|
691
|
+
//#region lib/types/tool-capabilities.js
|
|
692
|
+
const OWNED_TOOL = Symbol.for("@shuind/dsh-codex-harness:tool-capability:v1");
|
|
693
|
+
const CAPABILITIES = [
|
|
694
|
+
"terminalToolsEnabled",
|
|
695
|
+
"planToolEnabled",
|
|
696
|
+
"patchToolEnabled"
|
|
697
|
+
];
|
|
698
|
+
function markCodexTool(definition, metadata) {
|
|
699
|
+
Object.defineProperty(definition, OWNED_TOOL, { value: Object.freeze({ ...metadata }) });
|
|
700
|
+
return definition;
|
|
701
|
+
}
|
|
702
|
+
function codexToolMetadata(definition) {
|
|
703
|
+
const value = definition[OWNED_TOOL];
|
|
704
|
+
if (value === null || typeof value !== "object") return void 0;
|
|
705
|
+
const data = value;
|
|
706
|
+
if (!CAPABILITIES.includes(data.capability) || typeof data.presetEnabled !== "boolean" || data.presetOverridesLegacy !== void 0 && typeof data.presetOverridesLegacy !== "boolean") return void 0;
|
|
707
|
+
return {
|
|
708
|
+
capability: data.capability,
|
|
709
|
+
presetEnabled: data.presetEnabled,
|
|
710
|
+
...data.presetOverridesLegacy === void 0 ? {} : { presetOverridesLegacy: data.presetOverridesLegacy }
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
/** Read once for a new Agent or catalog. No caller keeps the live preference object. */
|
|
714
|
+
function readLegacyCapabilities(ctx) {
|
|
715
|
+
const current = readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE$1);
|
|
716
|
+
return Object.freeze(Object.fromEntries(CAPABILITIES.map((key) => [key, current?.[key] ?? CODEX_SETTINGS_ENTRY[key]])));
|
|
717
|
+
}
|
|
718
|
+
function codexToolEnabled(ctx, agent, name, metadata, fallback, authority) {
|
|
719
|
+
if (!metadata.presetEnabled) return false;
|
|
720
|
+
if (authority !== void 0) return authority;
|
|
721
|
+
return (agent === void 0 ? void 0 : ctx.get("codexToolPolicy")?.enabled(agent, name, metadata)) ?? fallback()[metadata.capability] !== false;
|
|
722
|
+
}
|
|
723
|
+
//#endregion
|
|
724
|
+
//#region lib/types/preset-tool-catalog.js
|
|
725
|
+
async function readPresetToolCatalog(ctx, preset) {
|
|
726
|
+
if (typeof preset !== "string" || !preset.trim() || preset.length > 256) throw new Error("invalid-preset-id");
|
|
727
|
+
const registry = ctx.get("agentPresets");
|
|
728
|
+
const tools = ctx.get("tools");
|
|
729
|
+
if (registry === void 0 || typeof registry.acquireScope !== "function" || tools === void 0) throw new Error("preset-tool-catalog-unavailable");
|
|
730
|
+
const lease = await registry.acquireScope(preset);
|
|
731
|
+
let view;
|
|
732
|
+
try {
|
|
733
|
+
const key = {};
|
|
734
|
+
view = createScope(ctx, key, { parent: lease.key });
|
|
735
|
+
const definitions = tools.definitions(key);
|
|
736
|
+
const names = new Set(definitions.map((tool) => tool.name));
|
|
737
|
+
return {
|
|
738
|
+
preset,
|
|
739
|
+
registeredOnly: true,
|
|
740
|
+
legacyCapabilities: readLegacyCapabilities(ctx),
|
|
741
|
+
tools: definitions.map((definition) => {
|
|
742
|
+
const conditional = tools.executable(definition.name, key) !== definition;
|
|
743
|
+
const replacements = [];
|
|
744
|
+
const action = definition.name === "bash" || definition.name === "pwsh" ? "codex-exec" : definition.name === "todo_write" ? "codex-plan" : void 0;
|
|
745
|
+
if (action !== void 0) {
|
|
746
|
+
const targets = action === "codex-exec" ? ["exec_command", "write_stdin"] : ["update_plan"];
|
|
747
|
+
const reason = conditional ? "conditional" : targets.some((target) => names.has(target)) ? "target-exists" : void 0;
|
|
748
|
+
replacements.push({
|
|
749
|
+
action,
|
|
750
|
+
tools: targets,
|
|
751
|
+
available: reason === void 0,
|
|
752
|
+
...reason === void 0 ? {} : { reason }
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
const codexTool = codexToolMetadata(definition);
|
|
756
|
+
return {
|
|
757
|
+
name: definition.name,
|
|
758
|
+
description: definition.description.slice(0, 300),
|
|
759
|
+
conditional,
|
|
760
|
+
replacements,
|
|
761
|
+
...codexTool === void 0 ? {} : { codexTool }
|
|
762
|
+
};
|
|
763
|
+
}).sort((a, b) => a.name.localeCompare(b.name, "en"))
|
|
764
|
+
};
|
|
765
|
+
} finally {
|
|
766
|
+
try {
|
|
767
|
+
await view?.dispose();
|
|
768
|
+
} finally {
|
|
769
|
+
await lease[Symbol.asyncDispose]();
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
//#endregion
|
|
774
|
+
//#region lib/types/preset-prompt-catalog.js
|
|
775
|
+
/** Public, read-only preset prompt discovery. No private registry, Agent, or JS/YAML evaluation. */
|
|
776
|
+
function literal(map, key) {
|
|
777
|
+
const node = map.get(key, true);
|
|
778
|
+
return isScalar(node) && !node.tag ? node.value : void 0;
|
|
779
|
+
}
|
|
780
|
+
/** Native Persona's public source owns these exact names/placements/complete semantics. */
|
|
781
|
+
function candidates(content, placement) {
|
|
782
|
+
const doc = parseDocument(content, {
|
|
783
|
+
strict: true,
|
|
784
|
+
uniqueKeys: true
|
|
785
|
+
});
|
|
786
|
+
if (doc.errors.length || !isSeq(doc.contents)) throw new Error("invalid-preset-prompt-declaration");
|
|
787
|
+
const found = [];
|
|
788
|
+
const readonly = [];
|
|
789
|
+
function visit(rows, parent = "", conditionalParent = false, isolatedParent = false) {
|
|
790
|
+
if (!isSeq(rows)) return;
|
|
791
|
+
for (const [index, row] of rows.items.entries()) {
|
|
792
|
+
if (!isMap(row) || literal(row, "disabled") === true) continue;
|
|
793
|
+
const module = literal(row, "name");
|
|
794
|
+
const path = `${parent}/${String(literal(row, "id") ?? index)}`;
|
|
795
|
+
const conditionalRow = conditionalParent || row.has("disabled") && literal(row, "disabled") === void 0;
|
|
796
|
+
const isolation = row.get("isolate", true);
|
|
797
|
+
const isolated = isolatedParent || row.has("isolate") && (!isMap(isolation) || isolation.has("systemPrompt"));
|
|
798
|
+
let config = row.get("config", true);
|
|
799
|
+
if (isSeq(config)) {
|
|
800
|
+
visit(config, path, conditionalRow, isolated);
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
if (config === void 0 && module === "@shuind/dsh-codex-harness") config = new YAMLMap();
|
|
804
|
+
if (typeof module !== "string" || !isMap(config)) continue;
|
|
805
|
+
if (module === "@deepseek-ai/dsh-persona") {
|
|
806
|
+
const completeNode = config.get("complete", true);
|
|
807
|
+
const complete = literal(config, "complete");
|
|
808
|
+
const uncertain = conditionalRow || completeNode !== void 0 && typeof complete !== "boolean";
|
|
809
|
+
for (const [key, name, order, label] of [[
|
|
810
|
+
"prefix",
|
|
811
|
+
PERSONA_PREFIX_SECTION,
|
|
812
|
+
placement("DEPLOYMENT_PERSONA_PREFIX"),
|
|
813
|
+
"Persona"
|
|
814
|
+
], [
|
|
815
|
+
"suffix",
|
|
816
|
+
PERSONA_SUFFIX_SECTION,
|
|
817
|
+
placement("DEPLOYMENT_PERSONA_SUFFIX"),
|
|
818
|
+
"Persona · suffix"
|
|
819
|
+
]]) {
|
|
820
|
+
const text = literal(config, key);
|
|
821
|
+
const missingSuffix = key === "suffix" && !config.has(key);
|
|
822
|
+
const reason = isolated ? "isolated-prompt-registry" : uncertain ? "dynamic-declaration" : void 0;
|
|
823
|
+
found.push({
|
|
824
|
+
name,
|
|
825
|
+
label,
|
|
826
|
+
module,
|
|
827
|
+
order,
|
|
828
|
+
complete: key === "prefix" && complete === true,
|
|
829
|
+
interpolate: true,
|
|
830
|
+
...typeof text === "string" ? { literal: text } : missingSuffix ? { literal: "" } : {},
|
|
831
|
+
...reason === void 0 ? {} : { reason }
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
} else if (module === "@shuind/dsh-codex-harness" && literal(config, "codexCore") !== false) found.push({
|
|
835
|
+
name: "codex:base",
|
|
836
|
+
label: "Codex 操作提示词",
|
|
837
|
+
module,
|
|
838
|
+
order: 10,
|
|
839
|
+
complete: false,
|
|
840
|
+
interpolate: true,
|
|
841
|
+
...isolated ? { reason: "isolated-prompt-registry" } : conditionalRow || config.has("codexCore") && literal(config, "codexCore") === void 0 ? { reason: "dynamic-declaration" } : {}
|
|
842
|
+
});
|
|
843
|
+
else for (const key of [
|
|
844
|
+
"prefix",
|
|
845
|
+
"suffix",
|
|
846
|
+
"text",
|
|
847
|
+
"section",
|
|
848
|
+
"prompt",
|
|
849
|
+
"systemPrompt",
|
|
850
|
+
"instructions"
|
|
851
|
+
]) {
|
|
852
|
+
if (!config.has(key) || module === "@deepseek-ai/dsh-plan-mode") continue;
|
|
853
|
+
const text = literal(config, key);
|
|
854
|
+
readonly.push({
|
|
855
|
+
name: `declaration:${path}:${key}`,
|
|
856
|
+
label: `${module} · ${key}`,
|
|
857
|
+
text: typeof text === "string" ? text : "",
|
|
858
|
+
editable: false,
|
|
859
|
+
reason: typeof text === "string" ? "unknown-section-contract" : "dynamic-declaration"
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
visit(doc.contents);
|
|
865
|
+
return {
|
|
866
|
+
found,
|
|
867
|
+
readonly
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
function moduleSignature(rows) {
|
|
871
|
+
return JSON.stringify(rows.map((row) => [
|
|
872
|
+
row.moduleName,
|
|
873
|
+
row.baseUrl ?? "",
|
|
874
|
+
row.useHostBase
|
|
875
|
+
]));
|
|
876
|
+
}
|
|
877
|
+
/** The opaque scope identity is retained only for runtime revision validation, not sent over RPC. */
|
|
878
|
+
async function probePresetPrompts(ctx, preset, expectedScope) {
|
|
879
|
+
if (typeof preset !== "string" || !preset.trim() || preset.length > 256) throw new Error("invalid-preset-id");
|
|
880
|
+
const registry = ctx.get("agentPresets");
|
|
881
|
+
const prompt = ctx.get("systemPrompt");
|
|
882
|
+
if (registry === void 0 || prompt === void 0 || typeof registry.acquireScope !== "function" || typeof registry.readDocument !== "function" || typeof registry.inspectCompositions !== "function") throw new Error("preset-prompt-catalog-unavailable");
|
|
883
|
+
const document = await registry.readDocument(preset);
|
|
884
|
+
const lease = await registry.acquireScope(preset);
|
|
885
|
+
let view;
|
|
886
|
+
try {
|
|
887
|
+
if (expectedScope !== void 0 && lease.key !== expectedScope) throw new Error("preset-prompt-revision-mismatch");
|
|
888
|
+
const key = {};
|
|
889
|
+
view = createScope(ctx, key, { parent: lease.key });
|
|
890
|
+
const inspection = registry.inspectCompositions(view.ctx);
|
|
891
|
+
if (inspection.length !== 1 || inspection[0]?.id !== preset) throw new Error("preset-prompt-revision-unavailable");
|
|
892
|
+
const modules = moduleSignature(inspection[0].modules);
|
|
893
|
+
const active = new Set(inspection[0].modules.map((row) => row.moduleName));
|
|
894
|
+
const declared = candidates(document.content, (name) => prompt.getSectionOrder(name));
|
|
895
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
896
|
+
const sections = [];
|
|
897
|
+
let baseline;
|
|
898
|
+
try {
|
|
899
|
+
baseline = await prompt.assemble({ scope: key });
|
|
900
|
+
} catch {
|
|
901
|
+
return {
|
|
902
|
+
scope: lease.key,
|
|
903
|
+
modules,
|
|
904
|
+
definitions,
|
|
905
|
+
catalog: {
|
|
906
|
+
preset,
|
|
907
|
+
sections: [...declared.found.map((row) => ({
|
|
908
|
+
name: row.name,
|
|
909
|
+
label: row.label,
|
|
910
|
+
text: row.literal ?? "",
|
|
911
|
+
editable: false,
|
|
912
|
+
reason: "assembly-unavailable"
|
|
913
|
+
})), ...declared.readonly].slice(0, 200)
|
|
914
|
+
}
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
const seen = /* @__PURE__ */ new Set();
|
|
918
|
+
for (const row of declared.found) {
|
|
919
|
+
if (seen.has(row.name)) continue;
|
|
920
|
+
seen.add(row.name);
|
|
921
|
+
const actual = baseline.sections.find((section) => section.name === row.name);
|
|
922
|
+
let reason = row.reason ?? (!active.has(row.module) ? "inactive-contribution" : void 0) ?? (declared.found.filter((candidate) => candidate.name === row.name).length !== 1 ? "ambiguous-contribution" : void 0) ?? (actual === void 0 ? "not-effective-or-complete-suppressed" : void 0);
|
|
923
|
+
if (reason === void 0 && row.complete && (baseline.sections.length !== 1 || baseline.sections[0]?.name !== row.name)) reason = "complete-contract-mismatch";
|
|
924
|
+
if (reason === void 0) {
|
|
925
|
+
const marker = `preset-prompt-probe:${randomUUID()}`;
|
|
926
|
+
const undo = view.ctx.get("systemPrompt").section({
|
|
927
|
+
name: row.name,
|
|
928
|
+
order: row.order,
|
|
929
|
+
complete: row.complete,
|
|
930
|
+
interpolate: row.interpolate,
|
|
931
|
+
text: marker
|
|
932
|
+
});
|
|
933
|
+
try {
|
|
934
|
+
const probed = await prompt.assemble({
|
|
935
|
+
scope: key,
|
|
936
|
+
codexPresetPromptProbe: true
|
|
937
|
+
});
|
|
938
|
+
if (probed.sections.find((section) => section.name === row.name)?.text !== marker || JSON.stringify(probed.sections.map((section) => section.name)) !== JSON.stringify(baseline.sections.map((section) => section.name)) || row.complete && (probed.sections.length !== 1 || probed.sections[0]?.name !== row.name)) reason = "not-directly-overridable";
|
|
939
|
+
} catch {
|
|
940
|
+
reason = "not-directly-overridable";
|
|
941
|
+
} finally {
|
|
942
|
+
undo();
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
const text = actual?.text ?? row.literal ?? "";
|
|
946
|
+
if (text.length > 1e6) reason = "prompt-too-large";
|
|
947
|
+
sections.push({
|
|
948
|
+
name: row.name,
|
|
949
|
+
label: row.label,
|
|
950
|
+
text: text.slice(0, 1e6),
|
|
951
|
+
editable: reason === void 0,
|
|
952
|
+
order: row.order,
|
|
953
|
+
complete: row.complete,
|
|
954
|
+
interpolate: row.interpolate,
|
|
955
|
+
...reason === void 0 ? {} : { reason }
|
|
956
|
+
});
|
|
957
|
+
if (reason === void 0) definitions.set(row.name, {
|
|
958
|
+
name: row.name,
|
|
959
|
+
order: row.order,
|
|
960
|
+
complete: row.complete,
|
|
961
|
+
interpolate: row.interpolate,
|
|
962
|
+
text
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
for (const row of baseline.sections) if (!seen.has(row.name)) sections.push({
|
|
966
|
+
name: row.name,
|
|
967
|
+
label: row.name,
|
|
968
|
+
text: row.text.slice(0, 1e6),
|
|
969
|
+
editable: false,
|
|
970
|
+
reason: "unknown-or-host-owned-section"
|
|
971
|
+
});
|
|
972
|
+
sections.push(...declared.readonly);
|
|
973
|
+
if ((await registry.readDocument(preset)).content !== document.content) throw new Error("preset-prompt-revision-mismatch");
|
|
974
|
+
return {
|
|
975
|
+
scope: lease.key,
|
|
976
|
+
modules,
|
|
977
|
+
definitions,
|
|
978
|
+
catalog: {
|
|
979
|
+
preset,
|
|
980
|
+
sections: sections.slice(0, 200)
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
} finally {
|
|
984
|
+
try {
|
|
985
|
+
await view?.dispose();
|
|
986
|
+
} finally {
|
|
987
|
+
await lease[Symbol.asyncDispose]();
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
async function readPresetPromptCatalog(ctx, preset) {
|
|
992
|
+
return (await probePresetPrompts(ctx, preset)).catalog;
|
|
993
|
+
}
|
|
994
|
+
function preparePromptOverrides(probe, overrides) {
|
|
995
|
+
const sections = overrides.map((override) => {
|
|
996
|
+
const original = probe.definitions.get(override.name);
|
|
997
|
+
if (original === void 0) throw new Error(`unsupported-preset-prompt-override: ${override.name}`);
|
|
998
|
+
return {
|
|
999
|
+
...original,
|
|
1000
|
+
text: override.text
|
|
1001
|
+
};
|
|
1002
|
+
});
|
|
1003
|
+
return {
|
|
1004
|
+
scope: probe.scope,
|
|
1005
|
+
modules: probe.modules,
|
|
1006
|
+
sections
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
function matchesPromptRevision(ctx, preset, prepared) {
|
|
1010
|
+
const inspection = ctx.get("agentPresets")?.inspectCompositions(ctx);
|
|
1011
|
+
return inspection?.length === 1 && inspection[0]?.id === preset && moduleSignature(inspection[0].modules) === prepared.modules;
|
|
1012
|
+
}
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region lib/types/preset-editor.js
|
|
1015
|
+
let atomicWriteModule;
|
|
1016
|
+
function loadAtomicWrite() {
|
|
1017
|
+
return atomicWriteModule ??= import("@deepseek-ai/dsh-atomic-write");
|
|
1018
|
+
}
|
|
1019
|
+
const PRESET_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
1020
|
+
const DEFAULT_CODEX_PRESET_OPTIONS = {
|
|
1021
|
+
promptEnabled: true,
|
|
1022
|
+
terminalToolsEnabled: true,
|
|
1023
|
+
patchToolEnabled: true,
|
|
1024
|
+
planToolEnabled: true,
|
|
1025
|
+
hostedWebSearchEnabled: true,
|
|
1026
|
+
remoteCompactionEnabled: true
|
|
1027
|
+
};
|
|
1028
|
+
const CODEX_OPTION_KEYS = Object.keys(DEFAULT_CODEX_PRESET_OPTIONS);
|
|
1029
|
+
/** Parse tags as syntax only; never execute !!js or resolve aliases into objects. */
|
|
1030
|
+
function yaml(content) {
|
|
1031
|
+
const doc = parseDocument(content, {
|
|
1032
|
+
strict: true,
|
|
1033
|
+
uniqueKeys: true
|
|
1034
|
+
});
|
|
1035
|
+
if (doc.errors.length) throw new Error("invalid-preset-yaml");
|
|
1036
|
+
return doc;
|
|
1037
|
+
}
|
|
1038
|
+
function harnessConfig(content) {
|
|
1039
|
+
const doc = yaml(content);
|
|
1040
|
+
if (!isSeq(doc.contents)) throw new Error("unsupported-preset");
|
|
1041
|
+
const rows = doc.contents.items.filter((row) => isMap(row) && row.get("name") === "@shuind/dsh-codex-harness" && row.get("disabled") !== true);
|
|
1042
|
+
if (rows.length !== 1) throw new Error("unsupported-preset");
|
|
1043
|
+
const row = rows[0];
|
|
1044
|
+
let config = row.get("config", true);
|
|
1045
|
+
if (config === void 0) {
|
|
1046
|
+
config = new YAMLMap();
|
|
1047
|
+
row.set("config", config);
|
|
1048
|
+
}
|
|
1049
|
+
if (!isMap(config) || config.get("codexCore") === false) throw new Error("unsupported-preset");
|
|
1050
|
+
return {
|
|
1051
|
+
doc,
|
|
1052
|
+
config
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
function explicitPrompt(content) {
|
|
1056
|
+
const { config } = harnessConfig(content);
|
|
1057
|
+
const node = config.get("presetPrompt", true) ?? config.get("systemPrompt", true);
|
|
1058
|
+
if (node === void 0) return void 0;
|
|
1059
|
+
if (!isScalar(node) || typeof node.value !== "string" || node.tag) throw new Error("unsupported-prompt-expression");
|
|
1060
|
+
return node.value;
|
|
1061
|
+
}
|
|
1062
|
+
const SECTION_PLUGIN = "@shuind/dsh-codex-harness/prompt-sections";
|
|
1063
|
+
function promptFile(node) {
|
|
1064
|
+
if (!node.tag || typeof node.value !== "string") return void 0;
|
|
1065
|
+
return node.value.match(/^process\.getBuiltinModule\(['"]node:fs['"]\)\.readFileSync\(new URL\(['"]([^'"]+)['"],\s*baseUrl\),\s*['"]utf8['"]\)$/)?.[1];
|
|
1066
|
+
}
|
|
1067
|
+
/** Read the actual literal prompt fields, including nested groups, without evaluating YAML tags. */
|
|
1068
|
+
function promptFields(doc) {
|
|
1069
|
+
const fields = [];
|
|
1070
|
+
function visit(sequence, parents = []) {
|
|
1071
|
+
if (!isSeq(sequence)) return;
|
|
1072
|
+
for (const [index, row] of sequence.items.entries()) {
|
|
1073
|
+
if (!isMap(row) || row.get("disabled") === true) continue;
|
|
1074
|
+
const path = [...parents, String(row.get("id") ?? `row:${index}`)];
|
|
1075
|
+
const config = row.get("config", true);
|
|
1076
|
+
if (isSeq(config)) {
|
|
1077
|
+
visit(config, path);
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
if (!isMap(config)) continue;
|
|
1081
|
+
const plugin = String(row.get("name"));
|
|
1082
|
+
if (plugin === "@deepseek-ai/dsh-plan-mode") continue;
|
|
1083
|
+
const keys = plugin === "@deepseek-ai/dsh-persona" ? [
|
|
1084
|
+
"prefix",
|
|
1085
|
+
"text",
|
|
1086
|
+
"suffix"
|
|
1087
|
+
] : plugin === "@shuind/dsh-codex-harness" || plugin === SECTION_PLUGIN ? [] : [
|
|
1088
|
+
"prefix",
|
|
1089
|
+
"suffix",
|
|
1090
|
+
"text",
|
|
1091
|
+
"section",
|
|
1092
|
+
"prompt",
|
|
1093
|
+
"systemPrompt",
|
|
1094
|
+
"instructions"
|
|
1095
|
+
];
|
|
1096
|
+
for (const key of keys) {
|
|
1097
|
+
const node = config.get(key, true);
|
|
1098
|
+
if (!isScalar(node)) continue;
|
|
1099
|
+
fields.push({
|
|
1100
|
+
id: JSON.stringify([...path, key]),
|
|
1101
|
+
label: plugin === "@deepseek-ai/dsh-persona" ? key === "suffix" ? "Persona · suffix" : "Persona" : `${path.join(" / ")} · ${key}`,
|
|
1102
|
+
node,
|
|
1103
|
+
row: config,
|
|
1104
|
+
key
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
visit(doc.contents);
|
|
1110
|
+
return fields;
|
|
1111
|
+
}
|
|
1112
|
+
function sectionConfig(content) {
|
|
1113
|
+
if (supportsCodex(content)) {
|
|
1114
|
+
const value = harnessConfig(content).config.get("presetSections", true);
|
|
1115
|
+
return isMap(value) ? value : void 0;
|
|
1116
|
+
}
|
|
1117
|
+
const doc = yaml(content);
|
|
1118
|
+
if (!isSeq(doc.contents)) return void 0;
|
|
1119
|
+
const row = doc.contents.items.find((row) => isMap(row) && row.get("name") === SECTION_PLUGIN);
|
|
1120
|
+
const config = isMap(row) ? row.get("config", true) : void 0;
|
|
1121
|
+
return isMap(config) ? config : void 0;
|
|
1122
|
+
}
|
|
1123
|
+
/** Some presets intentionally shadow host prompt sections with empty entries. */
|
|
1124
|
+
function suppressesHostSections(content) {
|
|
1125
|
+
const doc = yaml(content);
|
|
1126
|
+
let suppressed = false;
|
|
1127
|
+
function visit(sequence) {
|
|
1128
|
+
if (!isSeq(sequence)) return;
|
|
1129
|
+
for (const row of sequence.items) {
|
|
1130
|
+
if (!isMap(row)) continue;
|
|
1131
|
+
const id = String(row.get("id") ?? "");
|
|
1132
|
+
const plugin = String(row.get("name") ?? "");
|
|
1133
|
+
if (id === "story-prompt-clean-slate" || plugin === "./tools/prompt/clean-slate.mjs" || /(?:^|[\\/])clean-slate\.mjs$/u.test(plugin)) {
|
|
1134
|
+
suppressed = true;
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
const config = row.get("config", true);
|
|
1138
|
+
if (isSeq(config)) visit(config);
|
|
1139
|
+
if (suppressed) return;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
visit(doc.contents);
|
|
1143
|
+
return suppressed;
|
|
1144
|
+
}
|
|
1145
|
+
function readPromptSections(content, shared = {}) {
|
|
1146
|
+
const codex = supportsCodex(content);
|
|
1147
|
+
const overrides = sectionConfig(content);
|
|
1148
|
+
const fields = promptFields(yaml(content));
|
|
1149
|
+
const sections = fields.map(({ id, label, node }) => ({
|
|
1150
|
+
id,
|
|
1151
|
+
label,
|
|
1152
|
+
text: String(node.value ?? ""),
|
|
1153
|
+
editable: !node.tag && typeof node.value === "string"
|
|
1154
|
+
}));
|
|
1155
|
+
const persona = sections.find((section) => section.label === "Persona");
|
|
1156
|
+
const personaOverride = !overrides?.has("persona") && codex ? shared.persona : void 0;
|
|
1157
|
+
if (persona && typeof personaOverride === "string" && personaOverride !== DEFAULT_CODEX_PERSONA) persona.text = personaOverride;
|
|
1158
|
+
const hostSections = !fields.some((field) => field.label.startsWith("Persona") && field.row.get("complete") === true) && !suppressesHostSections(content) ? [...overrides?.get("harnessSourcePrompt") === "" ? [] : [{
|
|
1159
|
+
id: "harness:source",
|
|
1160
|
+
label: "DSH Core 源码说明",
|
|
1161
|
+
text: String(overrides?.get("harnessSourcePrompt") ?? (codex ? shared.harnessSourcePrompt : void 0) ?? DEFAULT_DSH_CORE_SOURCE_PROMPT),
|
|
1162
|
+
editable: true
|
|
1163
|
+
}], ...overrides?.get("webSurfacePrompt") === "" ? [] : [{
|
|
1164
|
+
id: "app:web-surface",
|
|
1165
|
+
label: "DSH Core Web 说明",
|
|
1166
|
+
text: String(overrides?.get("webSurfacePrompt") ?? (codex ? shared.webSurfacePrompt : void 0) ?? DEFAULT_DSH_CORE_WEB_PROMPT),
|
|
1167
|
+
editable: true
|
|
1168
|
+
}]] : [];
|
|
1169
|
+
if (hostSections.length) sections.splice(persona ? 1 : 0, 0, ...hostSections);
|
|
1170
|
+
if (codex) {
|
|
1171
|
+
const index = persona ? hostSections.length + 1 : hostSections.length;
|
|
1172
|
+
sections.splice(index, 0, {
|
|
1173
|
+
id: "codex:base",
|
|
1174
|
+
label: "Codex 操作提示词",
|
|
1175
|
+
text: explicitPrompt(content) ?? shared.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT,
|
|
1176
|
+
editable: true
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
return sections;
|
|
1180
|
+
}
|
|
1181
|
+
/** Patch the contributing fields, not a disconnected secondary prompt. */
|
|
1182
|
+
function patchPromptSections(content, sections) {
|
|
1183
|
+
const doc = yaml(content);
|
|
1184
|
+
const fields = promptFields(doc);
|
|
1185
|
+
const known = new Map(readPromptSections(content).map((section) => [section.id, section]));
|
|
1186
|
+
const overrides = {};
|
|
1187
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1188
|
+
for (const section of sections) {
|
|
1189
|
+
const field = fields.find((field) => field.id === section.id);
|
|
1190
|
+
if (seen.has(section.id) || !known.get(section.id)?.editable && !(field && promptFile(field.node)) || typeof section.text !== "string" || section.text.length > 1e6) throw new Error("invalid-prompt-section");
|
|
1191
|
+
seen.add(section.id);
|
|
1192
|
+
if (field) {
|
|
1193
|
+
const node = new Scalar(section.text);
|
|
1194
|
+
node.type = Scalar.BLOCK_LITERAL;
|
|
1195
|
+
field.row.set(field.key, node);
|
|
1196
|
+
continue;
|
|
1197
|
+
}
|
|
1198
|
+
if (!supportsCodex(content) && known.get(section.id)?.text === section.text) continue;
|
|
1199
|
+
if (section.id === "harness:source") overrides.harnessSourcePrompt = section.text;
|
|
1200
|
+
if (section.id === "app:web-surface") overrides.webSurfacePrompt = section.text;
|
|
1201
|
+
}
|
|
1202
|
+
const personaFields = fields.filter((field) => known.get(field.id)?.label.startsWith("Persona"));
|
|
1203
|
+
if (supportsCodex(content) && personaFields.length) overrides.persona = personaFields.map((field) => sections.find((section) => section.id === field.id)?.text ?? String(field.node.value)).join("\n\n");
|
|
1204
|
+
let result = doc.toString({ lineWidth: 0 });
|
|
1205
|
+
if (supportsCodex(result)) {
|
|
1206
|
+
const { doc: next, config } = harnessConfig(result);
|
|
1207
|
+
const previous = config.get("presetSections", true);
|
|
1208
|
+
const merged = isMap(previous) ? previous : new YAMLMap();
|
|
1209
|
+
for (const [key, value] of Object.entries(overrides)) merged.set(key, value);
|
|
1210
|
+
config.set("presetSections", merged);
|
|
1211
|
+
result = next.toString({ lineWidth: 0 });
|
|
1212
|
+
const operating = sections.find((section) => section.id === "codex:base");
|
|
1213
|
+
if (operating) result = patchPresetComposition(result, operating.text);
|
|
1214
|
+
} else if (Object.keys(overrides).length) {
|
|
1215
|
+
const next = yaml(result);
|
|
1216
|
+
if (!isSeq(next.contents)) throw new Error("invalid-preset-yaml");
|
|
1217
|
+
let row = next.contents.items.find((row) => isMap(row) && row.get("name") === SECTION_PLUGIN);
|
|
1218
|
+
if (!isMap(row)) {
|
|
1219
|
+
const created = new YAMLMap();
|
|
1220
|
+
created.set("id", `prompt-sections-${randomUUID().slice(0, 8)}`);
|
|
1221
|
+
created.set("name", SECTION_PLUGIN);
|
|
1222
|
+
next.add(created);
|
|
1223
|
+
row = created;
|
|
1224
|
+
}
|
|
1225
|
+
const map = row;
|
|
1226
|
+
let config = map.get("config", true);
|
|
1227
|
+
if (!isMap(config)) {
|
|
1228
|
+
config = new YAMLMap();
|
|
1229
|
+
map.set("config", config);
|
|
1230
|
+
}
|
|
1231
|
+
for (const [key, value] of Object.entries(overrides)) config.set(key, value);
|
|
1232
|
+
result = next.toString({ lineWidth: 0 });
|
|
1233
|
+
}
|
|
1234
|
+
return result;
|
|
1235
|
+
}
|
|
1236
|
+
function readCodexPresetOptions(content) {
|
|
1237
|
+
try {
|
|
1238
|
+
const { config } = harnessConfig(content);
|
|
1239
|
+
const options = { ...DEFAULT_CODEX_PRESET_OPTIONS };
|
|
1240
|
+
for (const key of CODEX_OPTION_KEYS) {
|
|
1241
|
+
const value = config.get(key);
|
|
1242
|
+
if (typeof value === "boolean") options[key] = value;
|
|
1243
|
+
}
|
|
1244
|
+
return options;
|
|
1245
|
+
} catch {
|
|
1246
|
+
return { ...DEFAULT_CODEX_PRESET_OPTIONS };
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
function supportsCodex(content) {
|
|
1250
|
+
try {
|
|
1251
|
+
harnessConfig(content);
|
|
1252
|
+
return true;
|
|
1253
|
+
} catch {
|
|
1254
|
+
return false;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
/** Structural validation only: executable tags stay inert until DSH mounts a selected preset. */
|
|
1258
|
+
function validateComposition(content) {
|
|
1259
|
+
if (content.length > 1e6) throw new Error("invalid-preset-yaml");
|
|
1260
|
+
const doc = yaml(content);
|
|
1261
|
+
if (!isSeq(doc.contents) || !doc.contents.items.length) throw new Error("invalid-preset-yaml");
|
|
1262
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1263
|
+
for (const entry of doc.contents.items) {
|
|
1264
|
+
if (!isMap(entry)) throw new Error("invalid-preset-yaml");
|
|
1265
|
+
const row = entry;
|
|
1266
|
+
if (typeof row.get("name") !== "string") throw new Error("invalid-preset-yaml");
|
|
1267
|
+
const id = row.get("id");
|
|
1268
|
+
if (typeof id !== "string" || ids.has(id)) throw new Error("invalid-preset-yaml");
|
|
1269
|
+
ids.add(id);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
function enhanceComposition(content) {
|
|
1273
|
+
validateComposition(content);
|
|
1274
|
+
if (supportsCodex(content)) return content;
|
|
1275
|
+
const doc = yaml(content);
|
|
1276
|
+
if (!isSeq(doc.contents)) throw new Error("invalid-preset-yaml");
|
|
1277
|
+
if (doc.contents.items.some((row) => isMap(row) && row.get("name") === "@shuind/dsh-codex-harness")) throw new Error("ambiguous-harness-row");
|
|
1278
|
+
let wasCompletePersona = false;
|
|
1279
|
+
for (const row of doc.contents.items) {
|
|
1280
|
+
if (!isMap(row) || row.get("name") !== "@deepseek-ai/dsh-persona") continue;
|
|
1281
|
+
const persona = row.get("config", true);
|
|
1282
|
+
if (isMap(persona) && persona.get("complete") === true) {
|
|
1283
|
+
wasCompletePersona = true;
|
|
1284
|
+
persona.set("complete", false);
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
const config = {
|
|
1288
|
+
globalEnhancements: false,
|
|
1289
|
+
codexCore: true
|
|
1290
|
+
};
|
|
1291
|
+
if (wasCompletePersona) config.presetSections = {
|
|
1292
|
+
harnessSourcePrompt: "",
|
|
1293
|
+
webSurfacePrompt: ""
|
|
1294
|
+
};
|
|
1295
|
+
doc.add(doc.createNode({
|
|
1296
|
+
id: `codex-harness-${randomUUID().slice(0, 8)}`,
|
|
1297
|
+
name: "@shuind/dsh-codex-harness",
|
|
1298
|
+
config
|
|
1299
|
+
}));
|
|
1300
|
+
return doc.toString({ lineWidth: 0 });
|
|
1301
|
+
}
|
|
1302
|
+
function patchPresetComposition(content, prompt, inherit = false) {
|
|
1303
|
+
const { doc, config } = harnessConfig(content);
|
|
1304
|
+
config.delete("systemPrompt");
|
|
1305
|
+
if (inherit) config.delete("presetPrompt");
|
|
1306
|
+
else {
|
|
1307
|
+
const node = new Scalar(prompt);
|
|
1308
|
+
node.type = prompt.includes("\n") ? Scalar.BLOCK_LITERAL : Scalar.QUOTE_DOUBLE;
|
|
1309
|
+
config.set("presetPrompt", node);
|
|
1310
|
+
}
|
|
1311
|
+
return doc.toString({ lineWidth: 0 });
|
|
1312
|
+
}
|
|
1313
|
+
/** Store user-facing Codex capability switches in the Harness row. */
|
|
1314
|
+
function patchCodexPresetOptions(content, options) {
|
|
1315
|
+
const { doc, config } = harnessConfig(content);
|
|
1316
|
+
for (const key of CODEX_OPTION_KEYS) {
|
|
1317
|
+
const value = options[key];
|
|
1318
|
+
if (value !== void 0) config.set(key, value);
|
|
1319
|
+
}
|
|
1320
|
+
return doc.toString({ lineWidth: 0 });
|
|
1321
|
+
}
|
|
1322
|
+
function patchPresetMetadata(content, name, description) {
|
|
1323
|
+
const doc = yaml(content);
|
|
1324
|
+
if (doc.contents !== null && !isMap(doc.contents)) throw new Error("invalid-preset-metadata");
|
|
1325
|
+
for (const [key, value] of Object.entries({
|
|
1326
|
+
name,
|
|
1327
|
+
description
|
|
1328
|
+
})) {
|
|
1329
|
+
const node = new Scalar(value);
|
|
1330
|
+
node.type = Scalar.QUOTE_DOUBLE;
|
|
1331
|
+
doc.set(key, node);
|
|
1332
|
+
}
|
|
1333
|
+
return doc.toString({ lineWidth: 0 });
|
|
1334
|
+
}
|
|
1335
|
+
function validate(input) {
|
|
1336
|
+
if (typeof input.name !== "string" || !input.name.trim() || /[\r\n]/.test(input.name) || input.name.length > 200) throw new Error("invalid-preset-name");
|
|
1337
|
+
if (typeof input.description !== "string" || input.description.length > 4e3) throw new Error("invalid-preset-description");
|
|
1338
|
+
if (typeof input.systemPrompt !== "string" || input.systemPrompt.length > 1e6) throw new Error("invalid-preset-prompt");
|
|
1339
|
+
return {
|
|
1340
|
+
...input,
|
|
1341
|
+
name: input.name.trim()
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
function revision(composition, metadata) {
|
|
1345
|
+
return createHash("sha256").update(composition).update("\0").update(metadata ?? "").digest("hex");
|
|
1346
|
+
}
|
|
1347
|
+
async function optionalFile(path) {
|
|
1348
|
+
try {
|
|
1349
|
+
return await readFile(path, "utf8");
|
|
1350
|
+
} catch (error) {
|
|
1351
|
+
if (error.code === "ENOENT") return void 0;
|
|
1352
|
+
throw error;
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
async function mode(path) {
|
|
1356
|
+
try {
|
|
1357
|
+
return (await stat(path)).mode & 511;
|
|
1358
|
+
} catch {
|
|
1359
|
+
return 384;
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
async function assertWithinRoot(path, roots) {
|
|
1363
|
+
if (!roots?.length) throw new Error("preset-root-unavailable");
|
|
1364
|
+
const target = await realpath(path);
|
|
1365
|
+
for (const root of roots) {
|
|
1366
|
+
if (root.trust !== "user") continue;
|
|
1367
|
+
const home = process.env.DSH_HOME ?? process.env.USERPROFILE ?? process.env.HOME ?? "";
|
|
1368
|
+
const expanded = root.path.replace(/^~(?=[\\/]|$)/, home);
|
|
1369
|
+
try {
|
|
1370
|
+
const rel = relative(await realpath(resolve(expanded)), target);
|
|
1371
|
+
if (!isAbsolute(rel) && rel !== ".." && !rel.startsWith("../") && !rel.startsWith("..\\")) return;
|
|
1372
|
+
} catch {}
|
|
1373
|
+
}
|
|
1374
|
+
throw new Error("preset-outside-user-root");
|
|
1375
|
+
}
|
|
1376
|
+
var CodexPresetEditor = class extends TypertRemoteService {
|
|
1377
|
+
static inject = ["agentPresets", "settings"];
|
|
1378
|
+
agentPresets;
|
|
1379
|
+
toolContext;
|
|
1380
|
+
sharedSettings;
|
|
1381
|
+
indexed;
|
|
1382
|
+
constructor(ctx, _config) {
|
|
1383
|
+
super(ctx, "codexPresetEditor");
|
|
1384
|
+
this.toolContext = ctx;
|
|
1385
|
+
this.agentPresets = ctx.get("agentPresets");
|
|
1386
|
+
this.sharedSettings = () => readHostSettings(ctx, "codex") ?? {};
|
|
1387
|
+
}
|
|
1388
|
+
async catalog() {
|
|
1389
|
+
if (this.agentPresets.list) {
|
|
1390
|
+
const rows = await this.agentPresets.list();
|
|
1391
|
+
this.indexed = new Map(rows.map((row) => [row.id, row]));
|
|
1392
|
+
return {
|
|
1393
|
+
presets: rows.filter((row) => row.broken === void 0).map((row) => ({
|
|
1394
|
+
id: row.id,
|
|
1395
|
+
name: row.name || row.id,
|
|
1396
|
+
description: row.description ?? "",
|
|
1397
|
+
editable: !!row.path && row.trust === "user",
|
|
1398
|
+
isDefault: row.id === this.agentPresets.defaultId
|
|
1399
|
+
})),
|
|
1400
|
+
authorable: !!this.agentPresets.copy && !!this.agentPresets.remove && (this.agentPresets.authorable ?? false),
|
|
1401
|
+
excludedCount: rows.filter((row) => row.broken !== void 0).length
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
if (!this.agentPresets.remoteExportList) throw new Error("preset-catalog-unavailable");
|
|
1405
|
+
const roster = await this.agentPresets.remoteExportList();
|
|
1406
|
+
const presets = roster.presets.filter((row) => row.broken === void 0).map((row) => ({
|
|
1407
|
+
id: row.id,
|
|
1408
|
+
name: row.name || row.id,
|
|
1409
|
+
description: row.description ?? "",
|
|
1410
|
+
editable: row.trust === "user",
|
|
1411
|
+
isDefault: row.isDefault
|
|
1412
|
+
}));
|
|
1413
|
+
return {
|
|
1414
|
+
presets,
|
|
1415
|
+
authorable: !!this.agentPresets.copy && !!this.agentPresets.remove && (roster.authorable ?? false),
|
|
1416
|
+
excludedCount: roster.presets.length - presets.length
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
async tools(id) {
|
|
1420
|
+
return readPresetToolCatalog(this.toolContext, id);
|
|
1421
|
+
}
|
|
1422
|
+
async prompts(id) {
|
|
1423
|
+
return readPresetPromptCatalog(this.toolContext, id);
|
|
1424
|
+
}
|
|
1425
|
+
async read(id) {
|
|
1426
|
+
const preset = this.indexed?.get(id) ?? await this.preset(id);
|
|
1427
|
+
if (preset.broken !== void 0) throw new Error("invalid-preset");
|
|
1428
|
+
const inline = preset.path === void 0 ? await this.agentPresets.readDocument(id) : void 0;
|
|
1429
|
+
const [composition, metadata] = preset.path === void 0 ? [inline.content, void 0] : await Promise.all([readFile(preset.path, "utf8"), optionalFile(resolve(dirname(preset.path), "preset.yml"))]);
|
|
1430
|
+
const meta = metadata ? yaml(metadata) : void 0;
|
|
1431
|
+
if (inline) {
|
|
1432
|
+
const doc = yaml(composition);
|
|
1433
|
+
if (!isSeq(doc.contents) || doc.contents.items.some((row) => !isMap(row) || typeof row.get("name") !== "string")) throw new Error("invalid-preset-yaml");
|
|
1434
|
+
} else validateComposition(composition);
|
|
1435
|
+
const codex = supportsCodex(composition);
|
|
1436
|
+
const prompt = codex ? explicitPrompt(composition) : void 0;
|
|
1437
|
+
const shared = this.sharedSettings?.() ?? {};
|
|
1438
|
+
const promptSections = readPromptSections(composition, shared);
|
|
1439
|
+
for (const field of promptFields(yaml(composition))) {
|
|
1440
|
+
const reference = promptFile(field.node);
|
|
1441
|
+
if (!reference || preset.path === void 0) continue;
|
|
1442
|
+
const section = promptSections.find((section) => section.id === field.id);
|
|
1443
|
+
try {
|
|
1444
|
+
const root = await realpath(dirname(preset.path));
|
|
1445
|
+
const target = await realpath(resolve(root, reference));
|
|
1446
|
+
const rel = relative(root, target);
|
|
1447
|
+
if (isAbsolute(rel) || rel === ".." || rel.startsWith("../") || rel.startsWith("..\\")) continue;
|
|
1448
|
+
if ((await stat(target)).size > 1e6) continue;
|
|
1449
|
+
section.text = await readFile(target, "utf8");
|
|
1450
|
+
section.editable = true;
|
|
1451
|
+
} catch {}
|
|
1452
|
+
}
|
|
1453
|
+
if (inline) for (const section of promptSections) section.editable = false;
|
|
1454
|
+
return {
|
|
1455
|
+
id,
|
|
1456
|
+
name: String(meta?.get("name") ?? inline?.name ?? preset.name ?? id),
|
|
1457
|
+
description: String(meta?.get("description") ?? inline?.description ?? preset.description ?? ""),
|
|
1458
|
+
systemPrompt: prompt ?? shared.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT,
|
|
1459
|
+
inheritPrompt: prompt === void 0,
|
|
1460
|
+
revision: revision(composition, metadata),
|
|
1461
|
+
editable: !!preset.path && preset.trust === "user",
|
|
1462
|
+
codex,
|
|
1463
|
+
codexOptions: readCodexPresetOptions(composition),
|
|
1464
|
+
composition,
|
|
1465
|
+
promptSections
|
|
1466
|
+
};
|
|
1467
|
+
}
|
|
1468
|
+
async create(rawInput) {
|
|
1469
|
+
if (!this.agentPresets.copy || !this.agentPresets.remove) throw new Error("preset-registry-read-only: this host does not support preset copies");
|
|
1470
|
+
const input = validate(rawInput);
|
|
1471
|
+
await this.preset(input.sourceId);
|
|
1472
|
+
const id = `codex-${randomUUID().slice(0, 12)}`;
|
|
1473
|
+
await this.agentPresets.copy(input.sourceId, id, input.name);
|
|
1474
|
+
try {
|
|
1475
|
+
const copy = await this.read(id);
|
|
1476
|
+
const base = input.composition ?? copy.composition;
|
|
1477
|
+
let next = input.enableCodex ? enhanceComposition(base) : base;
|
|
1478
|
+
if (supportsCodex(next)) {
|
|
1479
|
+
next = patchPresetComposition(next, input.systemPrompt, input.inheritPrompt);
|
|
1480
|
+
next = patchCodexPresetOptions(next, input.codexOptions ?? {});
|
|
1481
|
+
}
|
|
1482
|
+
return await this.update({
|
|
1483
|
+
...input,
|
|
1484
|
+
id,
|
|
1485
|
+
revision: copy.revision,
|
|
1486
|
+
composition: next
|
|
1487
|
+
});
|
|
1488
|
+
} catch (error) {
|
|
1489
|
+
await this.agentPresets.remove(id);
|
|
1490
|
+
throw error;
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
async update(rawInput) {
|
|
1494
|
+
const input = validate(rawInput);
|
|
1495
|
+
const preset = await this.preset(input.id);
|
|
1496
|
+
if (preset.path === void 0) throw new Error("preset-registry-read-only: this host exposes presets for viewing only");
|
|
1497
|
+
if (preset.trust !== "user") throw new Error("built-in presets cannot be edited here");
|
|
1498
|
+
const composition = resolve(preset.path);
|
|
1499
|
+
if (composition.split(/[\\/]/).at(-1) !== "agent.cordis.yml") throw new Error("invalid-preset-path");
|
|
1500
|
+
await assertWithinRoot(composition, this.agentPresets.roots);
|
|
1501
|
+
const metadata = resolve(dirname(composition), "preset.yml");
|
|
1502
|
+
if (await optionalFile(metadata) !== void 0) await assertWithinRoot(metadata, this.agentPresets.roots);
|
|
1503
|
+
const { withFileLock, writeFileAtomic } = await loadAtomicWrite();
|
|
1504
|
+
return withFileLock(composition, async () => {
|
|
1505
|
+
const oldComposition = await readFile(composition, "utf8");
|
|
1506
|
+
const oldMetadata = await optionalFile(metadata);
|
|
1507
|
+
if (input.revision !== void 0 && input.revision !== revision(oldComposition, oldMetadata)) throw new Error("preset-conflict");
|
|
1508
|
+
const editedComposition = input.composition !== void 0 ? input.composition : oldComposition;
|
|
1509
|
+
let nextComposition = input.enableCodex && !supportsCodex(editedComposition) ? enhanceComposition(editedComposition) : editedComposition;
|
|
1510
|
+
if (supportsCodex(nextComposition)) {
|
|
1511
|
+
nextComposition = patchPresetComposition(nextComposition, input.systemPrompt, input.inheritPrompt);
|
|
1512
|
+
if (input.codexOptions !== void 0) nextComposition = patchCodexPresetOptions(nextComposition, input.codexOptions);
|
|
1513
|
+
}
|
|
1514
|
+
if (input.promptSections) nextComposition = patchPromptSections(nextComposition, input.promptSections);
|
|
1515
|
+
validateComposition(nextComposition);
|
|
1516
|
+
const nextMetadata = patchPresetMetadata(oldMetadata ?? "", input.name, input.description);
|
|
1517
|
+
const compositionMode = await mode(composition);
|
|
1518
|
+
const metadataMode = await mode(metadata);
|
|
1519
|
+
await writeFileAtomic(resolve(dirname(composition), ".codex-editor-backup.json"), JSON.stringify({
|
|
1520
|
+
composition: oldComposition,
|
|
1521
|
+
metadata: oldMetadata ?? null
|
|
1522
|
+
}), {
|
|
1523
|
+
mode: 384,
|
|
1524
|
+
dirMode: 448
|
|
1525
|
+
});
|
|
1526
|
+
try {
|
|
1527
|
+
await writeFileAtomic(composition, nextComposition, {
|
|
1528
|
+
mode: compositionMode,
|
|
1529
|
+
dirMode: 448
|
|
1530
|
+
});
|
|
1531
|
+
await writeFileAtomic(metadata, nextMetadata, {
|
|
1532
|
+
mode: metadataMode,
|
|
1533
|
+
dirMode: 448
|
|
1534
|
+
});
|
|
1535
|
+
const result = await this.agentPresets.resolve(input.id);
|
|
1536
|
+
if (result.broken !== void 0) throw new Error("invalid-preset-after-save");
|
|
1537
|
+
this.indexed?.set(input.id, result);
|
|
1538
|
+
return await this.read(input.id);
|
|
1539
|
+
} catch (error) {
|
|
1540
|
+
await writeFileAtomic(composition, oldComposition, {
|
|
1541
|
+
mode: compositionMode,
|
|
1542
|
+
dirMode: 448
|
|
1543
|
+
});
|
|
1544
|
+
if (oldMetadata !== void 0) await writeFileAtomic(metadata, oldMetadata, {
|
|
1545
|
+
mode: metadataMode,
|
|
1546
|
+
dirMode: 448
|
|
1547
|
+
});
|
|
1548
|
+
else await unlink(metadata).catch((cause) => {
|
|
1549
|
+
if (cause.code !== "ENOENT") throw cause;
|
|
1550
|
+
});
|
|
1551
|
+
throw error;
|
|
1552
|
+
}
|
|
1553
|
+
}, { waitMs: 1e4 });
|
|
1554
|
+
}
|
|
1555
|
+
async preset(id) {
|
|
1556
|
+
if (!PRESET_ID.test(id)) throw new Error("invalid-preset-id");
|
|
1557
|
+
const preset = await this.agentPresets.resolve(id);
|
|
1558
|
+
if (preset.broken !== void 0) throw new Error("invalid-preset");
|
|
1559
|
+
this.indexed ??= /* @__PURE__ */ new Map();
|
|
1560
|
+
this.indexed.set(id, preset);
|
|
1561
|
+
return preset;
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
function markRemoteMethod(methodName) {
|
|
1565
|
+
const descriptor = Object.getOwnPropertyDescriptor(CodexPresetEditor.prototype, methodName);
|
|
1566
|
+
const initializers = [];
|
|
1567
|
+
Remote(methodName)(descriptor.value, {
|
|
1568
|
+
kind: "method",
|
|
1569
|
+
name: methodName,
|
|
1570
|
+
static: false,
|
|
1571
|
+
private: false,
|
|
1572
|
+
addInitializer: (initializer) => {
|
|
1573
|
+
initializers.push(initializer);
|
|
1574
|
+
}
|
|
1575
|
+
});
|
|
1576
|
+
const receiver = Object.create(CodexPresetEditor.prototype);
|
|
1577
|
+
for (const initializer of initializers) initializer.call(receiver);
|
|
1578
|
+
}
|
|
1579
|
+
for (const method of [
|
|
1580
|
+
"read",
|
|
1581
|
+
"update",
|
|
1582
|
+
"catalog",
|
|
1583
|
+
"create",
|
|
1584
|
+
"tools",
|
|
1585
|
+
"prompts"
|
|
1586
|
+
]) markRemoteMethod(method);
|
|
1587
|
+
//#endregion
|
|
1588
|
+
//#region lib/types/prompt-sections.js
|
|
1589
|
+
const Config$2 = z.object({
|
|
1590
|
+
persona: z.string(),
|
|
1591
|
+
harnessSourcePrompt: z.string(),
|
|
1592
|
+
webSurfacePrompt: z.string()
|
|
1593
|
+
});
|
|
1594
|
+
//#endregion
|
|
1595
|
+
//#region lib/types/index.js
|
|
1596
|
+
/** Codex-compatible prompt overlay and core tools for a dsh agent preset. */
|
|
1597
|
+
const DEFAULT_MAX_OUTPUT_BYTES = 1048576;
|
|
1598
|
+
z.object({
|
|
1599
|
+
globalEnhancements: z.boolean().default(true),
|
|
1600
|
+
codexCore: z.boolean().default(true),
|
|
1601
|
+
defaultYieldTimeMs: z.number().step(1).min(0).default(1e4),
|
|
1602
|
+
pollYieldTimeMs: z.number().step(1).min(0).default(5e3),
|
|
1603
|
+
writeYieldTimeMs: z.number().step(1).min(0).default(250),
|
|
1604
|
+
maxOutputBytes: z.number().step(1).min(1).default(DEFAULT_MAX_OUTPUT_BYTES),
|
|
1605
|
+
hostedWebSearch: z.boolean().default(true),
|
|
1606
|
+
remoteCompact: z.boolean().default(true),
|
|
1607
|
+
systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
|
|
1608
|
+
presetPrompt: z.string(),
|
|
1609
|
+
presetSections: Config$2,
|
|
1610
|
+
promptEnabled: z.boolean(),
|
|
1611
|
+
terminalToolsEnabled: z.boolean(),
|
|
1612
|
+
patchToolEnabled: z.boolean(),
|
|
1613
|
+
planToolEnabled: z.boolean(),
|
|
1614
|
+
hostedWebSearchEnabled: z.boolean(),
|
|
1615
|
+
remoteCompactionEnabled: z.boolean(),
|
|
1616
|
+
persona: z.string().default(DEFAULT_CODEX_PERSONA),
|
|
1617
|
+
harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
|
|
1618
|
+
webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT)
|
|
1619
|
+
});
|
|
1620
|
+
const EXEC_COMMAND_DESCRIPTION = "Runs a shell command. 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.";
|
|
1621
|
+
const WRITE_STDIN_DESCRIPTION = "Polls output from an existing unified exec session. Non-empty chars can be sent only to a session created with tty=true; pipe-backed sessions accept empty chars for polling only.";
|
|
1622
|
+
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.";
|
|
1623
|
+
const PLAN_STATUSES = [
|
|
1624
|
+
"pending",
|
|
1625
|
+
"in_progress",
|
|
1626
|
+
"completed"
|
|
1627
|
+
];
|
|
1628
|
+
function assertCapabilityEnabled(ctx, current, toolName, agent, metadata, authority) {
|
|
1629
|
+
if (!codexToolEnabled(ctx, agent, toolName, metadata, current, authority)) throw new Error(`${toolName}: disabled in Codex Harness plugin settings`);
|
|
1630
|
+
}
|
|
1631
|
+
function planTodos(args) {
|
|
1632
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1633
|
+
let active = 0;
|
|
1634
|
+
const todos = [];
|
|
1635
|
+
for (const item of args.plan) {
|
|
1636
|
+
const content = item.step.trim();
|
|
1637
|
+
if (content.length === 0) throw new Error("update_plan: every step must be non-empty");
|
|
1638
|
+
if (seen.has(content)) throw new Error(`update_plan: duplicate step ${JSON.stringify(content)}`);
|
|
1639
|
+
seen.add(content);
|
|
1640
|
+
if (item.status === "in_progress") active++;
|
|
1641
|
+
todos.push({
|
|
1642
|
+
content,
|
|
1643
|
+
status: item.status
|
|
1644
|
+
});
|
|
1645
|
+
}
|
|
1646
|
+
if (active > 1) throw new Error("update_plan: at most one step may be in_progress");
|
|
1647
|
+
return todos;
|
|
1648
|
+
}
|
|
1649
|
+
/** Release every registration once, even when one release fails. */
|
|
1650
|
+
function composeToolDisposers(disposers) {
|
|
1651
|
+
return () => {
|
|
1652
|
+
const errors = [];
|
|
1653
|
+
for (const dispose of disposers.splice(0).reverse()) try {
|
|
1654
|
+
dispose();
|
|
1655
|
+
} catch (error) {
|
|
1656
|
+
errors.push(error);
|
|
1657
|
+
}
|
|
1658
|
+
if (errors.length > 0) throw new AggregateError(errors, "Could not unregister Codex tools");
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
function registerExecTools(ctx, config) {
|
|
1662
|
+
const tools = ctx.get("tools");
|
|
1663
|
+
if (tools === void 0) throw new Error("Codex execution tools require ctx.tools");
|
|
1664
|
+
const shell = ctx.get("shell");
|
|
1665
|
+
if (shell === void 0) throw new Error("Codex execution tools require ctx.shell");
|
|
1666
|
+
const confines = shell.sandboxMode !== void 0;
|
|
1667
|
+
if (confines && ctx.get("sandboxPolicy") === void 0) throw new Error("Codex execution tools: a sandboxing shell requires ctx.sandboxPolicy");
|
|
1668
|
+
const legacyShellOptions = supportsLegacyShellOptions(ctx);
|
|
1669
|
+
const metadata = {
|
|
1670
|
+
capability: "terminalToolsEnabled",
|
|
1671
|
+
presetEnabled: config.presetEnabled !== false,
|
|
1672
|
+
...config.presetOverridesLegacy ? { presetOverridesLegacy: true } : {}
|
|
1673
|
+
};
|
|
1674
|
+
const unregisterExec = tools.register(markCodexTool(defineTool({
|
|
1675
|
+
name: "exec_command",
|
|
1676
|
+
description: legacyShellOptions ? EXEC_COMMAND_DESCRIPTION : EXEC_COMMAND_DESCRIPTION.replace("Runs a shell command.", "Runs a command in the host-configured shell."),
|
|
1677
|
+
parameters: {
|
|
1678
|
+
cmd: {
|
|
1679
|
+
type: "string",
|
|
1680
|
+
required: true,
|
|
1681
|
+
description: "Shell command to execute."
|
|
1682
|
+
},
|
|
1683
|
+
workdir: {
|
|
1684
|
+
type: "string",
|
|
1685
|
+
description: "Working directory for the command. Defaults to the turn cwd."
|
|
1686
|
+
},
|
|
1687
|
+
tty: {
|
|
1688
|
+
type: "boolean",
|
|
1689
|
+
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."
|
|
1690
|
+
},
|
|
1691
|
+
run_in_background: {
|
|
1692
|
+
type: "boolean",
|
|
1693
|
+
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."
|
|
1694
|
+
},
|
|
1695
|
+
yield_time_ms: {
|
|
1696
|
+
type: "number",
|
|
1697
|
+
description: "Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms."
|
|
1698
|
+
},
|
|
1699
|
+
max_output_tokens: {
|
|
1700
|
+
type: "number",
|
|
1701
|
+
description: "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy."
|
|
1702
|
+
},
|
|
1703
|
+
...confines ? {
|
|
1704
|
+
sandbox_permissions: {
|
|
1705
|
+
type: "string",
|
|
1706
|
+
enum: [...ESCALATION_TARGETS],
|
|
1707
|
+
description: sandboxPermissionsDescription("command")
|
|
1708
|
+
},
|
|
1709
|
+
justification: {
|
|
1710
|
+
type: "string",
|
|
1711
|
+
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."
|
|
1712
|
+
}
|
|
1713
|
+
} : {},
|
|
1714
|
+
...legacyShellOptions ? {
|
|
1715
|
+
shell: {
|
|
1716
|
+
type: "string",
|
|
1717
|
+
description: "Shell binary to launch. Defaults to the user's default shell."
|
|
1718
|
+
},
|
|
1719
|
+
login: {
|
|
1720
|
+
type: "boolean",
|
|
1721
|
+
description: "True runs the shell with -l/-i semantics; false disables them. Defaults to true."
|
|
1722
|
+
}
|
|
1723
|
+
} : {}
|
|
1724
|
+
},
|
|
1725
|
+
output: {
|
|
1726
|
+
schema: {
|
|
1727
|
+
type: "object",
|
|
1728
|
+
additionalProperties: false,
|
|
1729
|
+
properties: {
|
|
1730
|
+
chunk_id: { type: "string" },
|
|
1731
|
+
wall_time_seconds: {
|
|
1732
|
+
type: "number",
|
|
1733
|
+
required: true
|
|
1734
|
+
},
|
|
1735
|
+
exit_code: { type: "number" },
|
|
1736
|
+
session_id: { type: "number" },
|
|
1737
|
+
job_id: { type: "string" },
|
|
1738
|
+
original_token_count: { type: "number" },
|
|
1739
|
+
output: {
|
|
1740
|
+
type: "string",
|
|
1741
|
+
required: true
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
},
|
|
1745
|
+
render: (_args, value) => [{
|
|
1746
|
+
type: "text",
|
|
1747
|
+
text: renderExecResult(value)
|
|
1748
|
+
}]
|
|
1749
|
+
},
|
|
1750
|
+
async execute(args, exec) {
|
|
1751
|
+
assertCapabilityEnabled(ctx, config.currentSettings, "exec_command", exec.agent, metadata, config.authority);
|
|
1752
|
+
return runExecCommand(ctx, args, exec, config);
|
|
1753
|
+
},
|
|
1754
|
+
presentCall: (args) => ({
|
|
1755
|
+
card: "terminal",
|
|
1756
|
+
title: args.cmd,
|
|
1757
|
+
...args.workdir === void 0 ? {} : { cwd: args.workdir }
|
|
1758
|
+
})
|
|
1759
|
+
}), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "exec_command", metadata, config.currentSettings, config.authority) });
|
|
1760
|
+
try {
|
|
1761
|
+
return composeToolDisposers([unregisterExec, tools.register(markCodexTool(defineTool({
|
|
1762
|
+
name: "write_stdin",
|
|
1763
|
+
description: WRITE_STDIN_DESCRIPTION,
|
|
1764
|
+
parameters: {
|
|
1765
|
+
session_id: {
|
|
1766
|
+
type: "number",
|
|
1767
|
+
required: true,
|
|
1768
|
+
description: "Identifier of the running unified exec session."
|
|
1769
|
+
},
|
|
1770
|
+
chars: {
|
|
1771
|
+
type: "string",
|
|
1772
|
+
description: "Characters to send to a PTY session created with tty=true. Leave empty to poll output without writing; pipe-backed sessions do not accept input."
|
|
1773
|
+
},
|
|
1774
|
+
yield_time_ms: {
|
|
1775
|
+
type: "number",
|
|
1776
|
+
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."
|
|
1777
|
+
},
|
|
1778
|
+
max_output_tokens: {
|
|
1779
|
+
type: "number",
|
|
1780
|
+
description: "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy."
|
|
1781
|
+
}
|
|
1782
|
+
},
|
|
1783
|
+
output: {
|
|
1784
|
+
schema: {
|
|
1785
|
+
type: "object",
|
|
1786
|
+
additionalProperties: false,
|
|
1787
|
+
properties: {
|
|
1788
|
+
chunk_id: { type: "string" },
|
|
1789
|
+
wall_time_seconds: {
|
|
1790
|
+
type: "number",
|
|
1791
|
+
required: true
|
|
1792
|
+
},
|
|
1793
|
+
exit_code: { type: "number" },
|
|
1794
|
+
session_id: { type: "number" },
|
|
1795
|
+
original_token_count: { type: "number" },
|
|
1796
|
+
output: {
|
|
1797
|
+
type: "string",
|
|
1798
|
+
required: true
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
},
|
|
1802
|
+
render: (_args, value) => [{
|
|
1803
|
+
type: "text",
|
|
1804
|
+
text: renderExecResult(value)
|
|
1805
|
+
}]
|
|
1806
|
+
},
|
|
1807
|
+
async execute(args, exec) {
|
|
1808
|
+
assertCapabilityEnabled(ctx, config.currentSettings, "write_stdin", exec.agent, metadata, config.authority);
|
|
1809
|
+
return runWriteStdin(ctx, args, exec, config);
|
|
1810
|
+
}
|
|
1811
|
+
}), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "write_stdin", metadata, config.currentSettings, config.authority) })]);
|
|
1812
|
+
} catch (error) {
|
|
1813
|
+
unregisterExec();
|
|
1814
|
+
throw error;
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
function registerPlanTool(ctx, currentSettings, presetEnabled = true, authority, presetOverridesLegacy = false) {
|
|
1818
|
+
const tools = ctx.get("tools");
|
|
1819
|
+
if (tools === void 0) throw new Error("Codex plan tools require ctx.tools");
|
|
1820
|
+
const metadata = {
|
|
1821
|
+
capability: "planToolEnabled",
|
|
1822
|
+
presetEnabled,
|
|
1823
|
+
...presetOverridesLegacy ? { presetOverridesLegacy: true } : {}
|
|
1824
|
+
};
|
|
1825
|
+
return tools.register(markCodexTool(defineTool({
|
|
1826
|
+
name: "update_plan",
|
|
1827
|
+
description: UPDATE_PLAN_DESCRIPTION,
|
|
1828
|
+
parameters: {
|
|
1829
|
+
explanation: {
|
|
1830
|
+
type: "string",
|
|
1831
|
+
description: "Optional explanation for this plan update."
|
|
1832
|
+
},
|
|
1833
|
+
plan: {
|
|
1834
|
+
type: "array",
|
|
1835
|
+
required: true,
|
|
1836
|
+
description: "The list of steps",
|
|
1837
|
+
items: {
|
|
1838
|
+
type: "object",
|
|
1839
|
+
additionalProperties: false,
|
|
1840
|
+
properties: {
|
|
1841
|
+
step: {
|
|
1842
|
+
type: "string",
|
|
1843
|
+
required: true,
|
|
1844
|
+
description: "Task step text."
|
|
1845
|
+
},
|
|
1846
|
+
status: {
|
|
1847
|
+
type: "string",
|
|
1848
|
+
required: true,
|
|
1849
|
+
enum: [...PLAN_STATUSES],
|
|
1850
|
+
description: "Step status."
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
},
|
|
1856
|
+
output: {
|
|
1857
|
+
schema: {
|
|
1858
|
+
type: "object",
|
|
1859
|
+
additionalProperties: false,
|
|
1860
|
+
properties: {}
|
|
1861
|
+
},
|
|
1862
|
+
render: () => [{
|
|
1863
|
+
type: "text",
|
|
1864
|
+
text: "Plan updated"
|
|
1865
|
+
}]
|
|
1866
|
+
},
|
|
1867
|
+
execute(args, exec) {
|
|
1868
|
+
assertCapabilityEnabled(ctx, currentSettings, "update_plan", exec.agent, metadata, authority);
|
|
1869
|
+
const agent = exec.agent;
|
|
1870
|
+
if (agent === void 0) throw new Error("update_plan requires an owning agent session");
|
|
1871
|
+
agent.session.append("todo/write", { todos: planTodos(args) });
|
|
1872
|
+
return Promise.resolve({});
|
|
1873
|
+
}
|
|
1874
|
+
}), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "update_plan", metadata, currentSettings, authority) });
|
|
1875
|
+
}
|
|
1876
|
+
/**
|
|
1877
|
+
* Register selected Codex tools through the existing pipeline, without file tools or prompt hooks.
|
|
1878
|
+
* Compiled adapters receive authority once; the disposer supports an additional owner.
|
|
1879
|
+
*/
|
|
1880
|
+
function registerCodexExecAndPlan(ctx, options = {}) {
|
|
1881
|
+
const currentSettings = () => ({
|
|
1882
|
+
...CODEX_SETTINGS_ENTRY,
|
|
1883
|
+
...readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE$1)
|
|
1884
|
+
});
|
|
1885
|
+
const disposers = [];
|
|
1886
|
+
const dispose = composeToolDisposers(disposers);
|
|
1887
|
+
try {
|
|
1888
|
+
if (options.terminal !== false) disposers.push(registerExecTools(ctx, {
|
|
1889
|
+
defaultYieldTimeMs: options.defaultYieldTimeMs ?? 1e4,
|
|
1890
|
+
pollYieldTimeMs: options.pollYieldTimeMs ?? 5e3,
|
|
1891
|
+
writeYieldTimeMs: options.writeYieldTimeMs ?? 250,
|
|
1892
|
+
maxOutputBytes: options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
|
|
1893
|
+
currentSettings,
|
|
1894
|
+
...options.capabilityAuthority?.terminalToolsEnabled === void 0 ? {} : { authority: options.capabilityAuthority.terminalToolsEnabled }
|
|
1895
|
+
}));
|
|
1896
|
+
if (options.plan !== false) disposers.push(registerPlanTool(ctx, currentSettings, true, options.capabilityAuthority?.planToolEnabled));
|
|
1897
|
+
return dispose;
|
|
1898
|
+
} catch (error) {
|
|
1899
|
+
dispose();
|
|
1900
|
+
throw error;
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
//#endregion
|
|
1904
|
+
//#region lib/types/preset-prompt-contract.js
|
|
1905
|
+
/** Client-safe current-preset prompt catalog; editable targets have reviewed native contracts. */
|
|
1906
|
+
const PRESET_PROMPT_NAMES = [
|
|
1907
|
+
"deployment:persona-prefix",
|
|
1908
|
+
"deployment:persona-suffix",
|
|
1909
|
+
"codex:base"
|
|
1910
|
+
];
|
|
1911
|
+
//#endregion
|
|
1912
|
+
//#region lib/types/tool-policy-contract.js
|
|
1913
|
+
/** Legacy configuration remains a baseline, never a live second veto of an explicit choice. */
|
|
1914
|
+
function legacyToolAction(rule, name, context = {}) {
|
|
1915
|
+
let action = "keep";
|
|
1916
|
+
if (rule !== void 0) {
|
|
1917
|
+
if (rule.allow !== void 0 && !rule.allow.includes(name) || rule.deny?.includes(name)) return "hide";
|
|
1918
|
+
if ((name === "bash" || name === "pwsh") && rule.replaceShell !== false) action = "codex-exec";
|
|
1919
|
+
if (name === "todo_write" && rule.replacePlan !== false) action = "codex-plan";
|
|
1920
|
+
}
|
|
1921
|
+
const capability = context.codexTool?.capability ?? (action === "codex-exec" ? "terminalToolsEnabled" : action === "codex-plan" ? "planToolEnabled" : void 0);
|
|
1922
|
+
if (!(context.codexTool?.presetOverridesLegacy === true && context.codexTool.presetEnabled) && capability !== void 0 && context.legacyCapabilities?.[capability] === false) return "hide";
|
|
1923
|
+
return action;
|
|
1924
|
+
}
|
|
1925
|
+
/** Policy action only: `keep` still respects the original preset's local enablement. */
|
|
1926
|
+
function effectiveToolAction(rule, name, context = {}) {
|
|
1927
|
+
return rule?.tools?.find((tool) => tool.name === name)?.action ?? legacyToolAction(rule, name, context);
|
|
1928
|
+
}
|
|
1929
|
+
//#endregion
|
|
1930
|
+
//#region lib/types/tool-policy.js
|
|
1931
|
+
/** Opt-in Host overlays for future Agents; source presets and Persona stay untouched. */
|
|
1932
|
+
const name = "codex-tool-policy";
|
|
1933
|
+
const inject = [
|
|
1934
|
+
"tools",
|
|
1935
|
+
"agents",
|
|
1936
|
+
"agentPresets"
|
|
1937
|
+
];
|
|
1938
|
+
const Config = z.object({ rules: z.array(z.object({
|
|
1939
|
+
preset: z.string().required().description("Exact preset id; only Agents created after this plugin loads are affected."),
|
|
1940
|
+
allow: z.union([z.array(z.string())]).description("Inherited source names to keep. Omit for no allowlist; [] removes all inherited tools, including file tools."),
|
|
1941
|
+
deny: z.union([z.array(z.string())]).description("Inherited source names to remove; unknown and Agent-local names are rejected."),
|
|
1942
|
+
replaceShell: z.boolean().default(true).description("Legacy default: replace permitted builtin bash/pwsh with exec_command/write_stdin. Explicit source choices override it; third-party name-specific policy is not transferred."),
|
|
1943
|
+
replacePlan: z.boolean().default(true).description("Legacy default: replace permitted builtin todo_write with update_plan; explicit source choices override it."),
|
|
1944
|
+
tools: z.union([z.array(z.object({
|
|
1945
|
+
name: z.string().required().description("Exact inherited source tool name."),
|
|
1946
|
+
action: z.union([
|
|
1947
|
+
z.const("keep"),
|
|
1948
|
+
z.const("hide"),
|
|
1949
|
+
z.const("codex-exec"),
|
|
1950
|
+
z.const("codex-plan")
|
|
1951
|
+
]).required().description("Per-tool override: keep/hide any inherited tool; codex-exec only for bash/pwsh and codex-plan only for todo_write.")
|
|
1952
|
+
}))]).description("Individual source choices, overriding allow/deny and legacy replacement defaults. Omission preserves legacy behavior."),
|
|
1953
|
+
promptOverrides: z.union([z.array(z.object({
|
|
1954
|
+
name: z.union(PRESET_PROMPT_NAMES.map((name) => z.const(name))).required(),
|
|
1955
|
+
text: z.string().max(1e6).required()
|
|
1956
|
+
}))]).description("Exact current-preset prompt replacements. Order, interpolation and complete semantics remain Host-owned.")
|
|
1957
|
+
})).default([]) }).volatile();
|
|
1958
|
+
/** Reject ambiguous/unsupported overrides before any Agent registrations change. */
|
|
1959
|
+
function resolveToolChoices(input) {
|
|
1960
|
+
if (input === void 0) return void 0;
|
|
1961
|
+
if (!Array.isArray(input)) throw new TypeError("codex-tool-policy: tools must be an array of source choices");
|
|
1962
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1963
|
+
const choices = [];
|
|
1964
|
+
for (const choice of input) {
|
|
1965
|
+
if (choice === null || typeof choice !== "object" || typeof choice.name !== "string" || choice.name.trim().length === 0) throw new TypeError("codex-tool-policy: every tool choice requires a non-empty source name");
|
|
1966
|
+
if (seen.has(choice.name)) throw new Error(`codex-tool-policy: duplicate tool choice ${JSON.stringify(choice.name)}`);
|
|
1967
|
+
seen.add(choice.name);
|
|
1968
|
+
if (![
|
|
1969
|
+
"keep",
|
|
1970
|
+
"hide",
|
|
1971
|
+
"codex-exec",
|
|
1972
|
+
"codex-plan"
|
|
1973
|
+
].includes(choice.action)) throw new TypeError(`codex-tool-policy: invalid action for source tool ${JSON.stringify(choice.name)}`);
|
|
1974
|
+
if (choice.action === "codex-exec" && choice.name !== "bash" && choice.name !== "pwsh" || choice.action === "codex-plan" && choice.name !== "todo_write") throw new Error(`codex-tool-policy: unsupported replacement ${JSON.stringify(choice.action)} for source tool ${JSON.stringify(choice.name)}`);
|
|
1975
|
+
choices.push({
|
|
1976
|
+
name: choice.name,
|
|
1977
|
+
action: choice.action
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
return choices;
|
|
1981
|
+
}
|
|
1982
|
+
function resolvePromptChoices(input) {
|
|
1983
|
+
if (input === void 0) return void 0;
|
|
1984
|
+
if (!Array.isArray(input) || input.length > PRESET_PROMPT_NAMES.length) throw new Error("invalid-preset-prompt-overrides");
|
|
1985
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1986
|
+
return input.map((value) => {
|
|
1987
|
+
if (value === null || typeof value !== "object" || !PRESET_PROMPT_NAMES.includes(value.name) || typeof value.text !== "string" || value.text.length > 1e6 || Object.keys(value).some((key) => key !== "name" && key !== "text") || seen.has(value.name)) throw new Error("invalid-preset-prompt-override");
|
|
1988
|
+
seen.add(value.name);
|
|
1989
|
+
return {
|
|
1990
|
+
name: value.name,
|
|
1991
|
+
text: value.text
|
|
1992
|
+
};
|
|
1993
|
+
});
|
|
1994
|
+
}
|
|
1995
|
+
/** Validate direct callers too, and detach configuration from later form mutations. */
|
|
1996
|
+
function resolveRules(config) {
|
|
1997
|
+
const input = config.rules ?? [];
|
|
1998
|
+
if (!Array.isArray(input)) throw new TypeError("codex-tool-policy: rules must be an array");
|
|
1999
|
+
const rules = /* @__PURE__ */ new Map();
|
|
2000
|
+
for (const rule of input) {
|
|
2001
|
+
if (rule === null || typeof rule !== "object" || typeof rule.preset !== "string" || rule.preset.trim().length === 0) throw new TypeError("codex-tool-policy: every rule requires a non-empty preset id");
|
|
2002
|
+
if (rules.has(rule.preset)) throw new Error(`codex-tool-policy: duplicate preset rule ${JSON.stringify(rule.preset)}`);
|
|
2003
|
+
for (const key of ["allow", "deny"]) {
|
|
2004
|
+
const names = rule[key];
|
|
2005
|
+
if (names !== void 0 && (!Array.isArray(names) || names.some((tool) => typeof tool !== "string" || tool.trim().length === 0))) throw new TypeError(`codex-tool-policy: ${key} must be an array of non-empty tool names`);
|
|
2006
|
+
}
|
|
2007
|
+
for (const key of ["replaceShell", "replacePlan"]) if (rule[key] !== void 0 && typeof rule[key] !== "boolean") throw new TypeError(`codex-tool-policy: ${key} must be a boolean`);
|
|
2008
|
+
const choices = resolveToolChoices(rule.tools);
|
|
2009
|
+
const prompts = resolvePromptChoices(rule.promptOverrides);
|
|
2010
|
+
rules.set(rule.preset, {
|
|
2011
|
+
preset: rule.preset,
|
|
2012
|
+
...rule.allow === void 0 ? {} : { allow: [...rule.allow] },
|
|
2013
|
+
...rule.deny === void 0 ? {} : { deny: [...rule.deny] },
|
|
2014
|
+
replaceShell: rule.replaceShell !== false,
|
|
2015
|
+
replacePlan: rule.replacePlan !== false,
|
|
2016
|
+
...choices === void 0 ? {} : { tools: choices },
|
|
2017
|
+
...prompts === void 0 ? {} : { promptOverrides: prompts }
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
return rules;
|
|
2021
|
+
}
|
|
2022
|
+
/**
|
|
2023
|
+
* Install only through an exact Agent scope. Replacement is deliberately limited
|
|
2024
|
+
* to builtin source names: arbitrary tools, argument adapters, and third-party
|
|
2025
|
+
* name-specific tools/pre-execute policy are not made equivalent by this overlay.
|
|
2026
|
+
*/
|
|
2027
|
+
function installOverlay(agent, rule, legacyCapabilities, preparedPrompts, onDispose) {
|
|
2028
|
+
if (scopeOf(agent.ctx) !== agent) throw new Error("codex-tool-policy: an exact Agent scope is required");
|
|
2029
|
+
if (preparedPrompts !== void 0 && (scopeParentOf(agent) !== preparedPrompts.scope || !matchesPromptRevision(agent.ctx, rule.preset, preparedPrompts))) throw new Error("preset-prompt-revision-mismatch");
|
|
2030
|
+
const tools = agent.ctx.get("tools");
|
|
2031
|
+
if (tools === void 0) throw new Error("codex-tool-policy: the Agent has no tools service");
|
|
2032
|
+
const upstream = scopeParentOf(agent);
|
|
2033
|
+
for (const choice of rule.tools ?? []) if (tools.get(choice.name, agent) === void 0) throw new Error(`codex-tool-policy: unknown or unavailable source tool ${JSON.stringify(choice.name)} in explicit choice`);
|
|
2034
|
+
for (const tool of [
|
|
2035
|
+
...rule.allow ?? [],
|
|
2036
|
+
...rule.deny ?? [],
|
|
2037
|
+
...rule.tools?.map((choice) => choice.name) ?? []
|
|
2038
|
+
]) {
|
|
2039
|
+
const visible = tools.get(tool, agent);
|
|
2040
|
+
if (visible !== void 0 && tools.get(tool, upstream) !== visible) throw new Error(`codex-tool-policy: cannot restrict Agent-local tool ${JSON.stringify(tool)}`);
|
|
2041
|
+
}
|
|
2042
|
+
const allow = rule.allow === void 0 ? void 0 : new Set(rule.allow);
|
|
2043
|
+
const deny = new Set(rule.deny);
|
|
2044
|
+
let hasDeny = rule.deny !== void 0;
|
|
2045
|
+
for (const choice of rule.tools ?? []) if (choice.action === "hide") {
|
|
2046
|
+
deny.add(choice.name);
|
|
2047
|
+
hasDeny = true;
|
|
2048
|
+
allow?.delete(choice.name);
|
|
2049
|
+
} else {
|
|
2050
|
+
deny.delete(choice.name);
|
|
2051
|
+
allow?.add(choice.name);
|
|
2052
|
+
}
|
|
2053
|
+
const actionFor = (name) => {
|
|
2054
|
+
const definition = tools.get(name, agent);
|
|
2055
|
+
const codexTool = definition === void 0 ? void 0 : codexToolMetadata(definition);
|
|
2056
|
+
return effectiveToolAction(rule, name, {
|
|
2057
|
+
legacyCapabilities,
|
|
2058
|
+
...codexTool === void 0 ? {} : { codexTool }
|
|
2059
|
+
});
|
|
2060
|
+
};
|
|
2061
|
+
for (const name of [
|
|
2062
|
+
"bash",
|
|
2063
|
+
"pwsh",
|
|
2064
|
+
"todo_write"
|
|
2065
|
+
]) {
|
|
2066
|
+
const oldAction = legacyToolAction(rule, name);
|
|
2067
|
+
if (tools.get(name, agent) !== void 0 && (oldAction === "codex-exec" || oldAction === "codex-plan") && actionFor(name) === "hide") {
|
|
2068
|
+
deny.add(name);
|
|
2069
|
+
hasDeny = true;
|
|
2070
|
+
allow?.delete(name);
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
const mask = {
|
|
2074
|
+
...allow === void 0 ? {} : { allow: [...allow] },
|
|
2075
|
+
...!hasDeny ? {} : { deny: [...deny] }
|
|
2076
|
+
};
|
|
2077
|
+
const permitted = (tool) => (allow === void 0 || allow.has(tool)) && !deny.has(tool);
|
|
2078
|
+
const shells = ["bash", "pwsh"].filter((tool) => actionFor(tool) === "codex-exec" && permitted(tool) && tools.get(tool, agent) !== void 0);
|
|
2079
|
+
const plan = actionFor("todo_write") === "codex-plan" && permitted("todo_write") && tools.get("todo_write", agent) !== void 0;
|
|
2080
|
+
const sources = [...shells, ...plan ? ["todo_write"] : []];
|
|
2081
|
+
for (const tool of sources) {
|
|
2082
|
+
const definition = tools.get(tool, agent);
|
|
2083
|
+
if (tools.executable(tool, agent) !== definition) throw new Error(`codex-tool-policy: cannot replace conditional source tool ${JSON.stringify(tool)}; its activation condition must not be discarded`);
|
|
2084
|
+
if (tools.get(tool, upstream) !== definition) throw new Error(`codex-tool-policy: cannot replace Agent-local source tool ${JSON.stringify(tool)}`);
|
|
2085
|
+
}
|
|
2086
|
+
const additions = [...shells.length > 0 ? ["exec_command", "write_stdin"] : [], ...plan ? ["update_plan"] : []];
|
|
2087
|
+
for (const tool of additions) if (tools.get(tool, agent) !== void 0) throw new Error(`codex-tool-policy: replacement tool ${JSON.stringify(tool)} already exists; refusing to shadow another implementation`);
|
|
2088
|
+
if (shells.length > 0 && agent.ctx.get("shell") === void 0) throw new Error("codex-tool-policy: builtin shell replacement requires the mounted shell capability");
|
|
2089
|
+
const needsPrompt = sources.length > 0 || (preparedPrompts?.sections.length ?? 0) > 0;
|
|
2090
|
+
const systemPrompt = needsPrompt ? agent.ctx.get("systemPrompt") : void 0;
|
|
2091
|
+
if (needsPrompt && systemPrompt === void 0) throw new Error("codex-tool-policy: replacements require the mounted systemPrompt service");
|
|
2092
|
+
const guidance = [...shells.length === 0 ? [] : [`For this Agent, ${shells.join("/")} is replaced by exec_command and write_stdin. Follow their current schemas; command status uses exit_code (rendered as Process exited with code N), not the old shell status markers.`], ...plan ? ["For this Agent, todo_write is replaced by update_plan. Follow its current schema; at most one plan item may be in_progress."] : []].join("\n");
|
|
2093
|
+
const dispose = agent.ctx.effect(function* () {
|
|
2094
|
+
yield onDispose;
|
|
2095
|
+
for (const section of preparedPrompts?.sections ?? []) yield systemPrompt.section(section);
|
|
2096
|
+
if (mask.allow !== void 0 || mask.deny !== void 0) yield tools.restrict(mask);
|
|
2097
|
+
for (const tool of mask.deny ?? []) if (tools.get(tool, agent) !== void 0) throw new Error(`codex-tool-policy: cannot hide Agent-local tool ${JSON.stringify(tool)}`);
|
|
2098
|
+
if (sources.length > 0) {
|
|
2099
|
+
yield tools.restrict({ deny: sources });
|
|
2100
|
+
for (const tool of sources) if (tools.get(tool, agent) !== void 0) throw new Error(`codex-tool-policy: cannot hide Agent-local source tool ${JSON.stringify(tool)}`);
|
|
2101
|
+
yield registerCodexExecAndPlan(agent.ctx, {
|
|
2102
|
+
terminal: shells.length > 0,
|
|
2103
|
+
plan,
|
|
2104
|
+
capabilityAuthority: {
|
|
2105
|
+
terminalToolsEnabled: shells.length > 0,
|
|
2106
|
+
planToolEnabled: plan
|
|
2107
|
+
}
|
|
2108
|
+
});
|
|
2109
|
+
yield systemPrompt.section({
|
|
2110
|
+
name: "codex:tool-policy",
|
|
2111
|
+
order: 1015,
|
|
2112
|
+
text: guidance
|
|
2113
|
+
});
|
|
2114
|
+
}
|
|
2115
|
+
}, `codex-tool-policy:${rule.preset}`);
|
|
2116
|
+
return () => {
|
|
2117
|
+
dispose();
|
|
2118
|
+
};
|
|
2119
|
+
}
|
|
2120
|
+
/**
|
|
2121
|
+
* Affect future Agent lifecycles only. No existing-agent scan, polling, prompt
|
|
2122
|
+
* rewrite, source-preset edit, or executor replacement is performed.
|
|
2123
|
+
*/
|
|
2124
|
+
function apply(ctx, config = {}) {
|
|
2125
|
+
const currentConfig = () => "get" in config ? config.get() ?? {} : config;
|
|
2126
|
+
resolveRules(currentConfig());
|
|
2127
|
+
const snapshots = /* @__PURE__ */ new WeakMap();
|
|
2128
|
+
const overlays = /* @__PURE__ */ new Map();
|
|
2129
|
+
let active = true;
|
|
2130
|
+
ctx.provide("codexToolPolicy", {
|
|
2131
|
+
enabled(agent, name, metadata) {
|
|
2132
|
+
const snapshot = snapshots.get(agent);
|
|
2133
|
+
if (snapshot === void 0) return void 0;
|
|
2134
|
+
if (!metadata.presetEnabled) return false;
|
|
2135
|
+
return effectiveToolAction(snapshot.activeRule, name, {
|
|
2136
|
+
legacyCapabilities: snapshot.legacyCapabilities,
|
|
2137
|
+
codexTool: metadata
|
|
2138
|
+
}) !== "hide";
|
|
2139
|
+
},
|
|
2140
|
+
hasPromptOverride(scope, name) {
|
|
2141
|
+
return snapshots.get(scope)?.activePromptNames?.has(name) === true;
|
|
2142
|
+
}
|
|
2143
|
+
});
|
|
2144
|
+
const remove = (agent) => {
|
|
2145
|
+
const snapshot = snapshots.get(agent);
|
|
2146
|
+
if (snapshot !== void 0) {
|
|
2147
|
+
delete snapshot.activeRule;
|
|
2148
|
+
delete snapshot.activePromptNames;
|
|
2149
|
+
}
|
|
2150
|
+
const previous = overlays.get(agent);
|
|
2151
|
+
if (previous === void 0) return;
|
|
2152
|
+
overlays.delete(agent);
|
|
2153
|
+
previous.dispose();
|
|
2154
|
+
};
|
|
2155
|
+
const reconcile = (agent) => {
|
|
2156
|
+
const preset = ctx.agentPresets.composedPreset(agent.ctx) ?? ctx.agentPresets.presetForSession(agent.session) ?? void 0;
|
|
2157
|
+
if (overlays.get(agent)?.preset === preset) return;
|
|
2158
|
+
remove(agent);
|
|
2159
|
+
const snapshot = snapshots.get(agent);
|
|
2160
|
+
const rule = preset === void 0 ? void 0 : snapshot?.rules.get(preset);
|
|
2161
|
+
if (rule === void 0 || snapshot === void 0) return;
|
|
2162
|
+
const prepared = snapshot.promptPlans.get(rule.preset);
|
|
2163
|
+
if (prepared instanceof Error) throw prepared;
|
|
2164
|
+
if ((rule.promptOverrides?.length ?? 0) > 0 && prepared === void 0) throw new Error("preset-prompt-plan-unavailable");
|
|
2165
|
+
let installed;
|
|
2166
|
+
const dispose = installOverlay(agent, rule, snapshot.legacyCapabilities, prepared, () => {
|
|
2167
|
+
if (installed !== void 0 && overlays.get(agent) === installed) {
|
|
2168
|
+
overlays.delete(agent);
|
|
2169
|
+
delete snapshot.activeRule;
|
|
2170
|
+
delete snapshot.activePromptNames;
|
|
2171
|
+
}
|
|
2172
|
+
});
|
|
2173
|
+
installed = {
|
|
2174
|
+
preset: rule.preset,
|
|
2175
|
+
dispose
|
|
2176
|
+
};
|
|
2177
|
+
overlays.set(agent, installed);
|
|
2178
|
+
snapshot.activeRule = rule;
|
|
2179
|
+
if (prepared !== void 0) snapshot.activePromptNames = new Set(prepared.sections.map((section) => section.name));
|
|
2180
|
+
};
|
|
2181
|
+
ctx.on("agent/created", ({ agent, signal }) => {
|
|
2182
|
+
if (!active) return;
|
|
2183
|
+
signal?.throwIfAborted();
|
|
2184
|
+
const snapshot = {
|
|
2185
|
+
rules: resolveRules(currentConfig()),
|
|
2186
|
+
legacyCapabilities: readLegacyCapabilities(ctx),
|
|
2187
|
+
promptPlans: /* @__PURE__ */ new Map()
|
|
2188
|
+
};
|
|
2189
|
+
snapshots.set(agent, snapshot);
|
|
2190
|
+
const targets = [...snapshot.rules.values()].filter((rule) => (rule.promptOverrides?.length ?? 0) > 0);
|
|
2191
|
+
if (targets.length === 0) {
|
|
2192
|
+
reconcile(agent);
|
|
2193
|
+
return;
|
|
2194
|
+
}
|
|
2195
|
+
return (async () => {
|
|
2196
|
+
const bound = ctx.agentPresets.composedPreset(agent.ctx) ?? ctx.agentPresets.presetForSession(agent.session);
|
|
2197
|
+
for (const rule of targets) try {
|
|
2198
|
+
const probe = await probePresetPrompts(ctx, rule.preset, rule.preset === bound ? scopeParentOf(agent) : void 0);
|
|
2199
|
+
snapshot.promptPlans.set(rule.preset, preparePromptOverrides(probe, rule.promptOverrides));
|
|
2200
|
+
} catch (error) {
|
|
2201
|
+
snapshot.promptPlans.set(rule.preset, error instanceof Error ? error : new Error(String(error)));
|
|
2202
|
+
}
|
|
2203
|
+
signal?.throwIfAborted();
|
|
2204
|
+
if (active) reconcile(agent);
|
|
2205
|
+
})();
|
|
2206
|
+
});
|
|
2207
|
+
ctx.on("agent-preset/selected", (sessionId) => {
|
|
2208
|
+
if (!active) return;
|
|
2209
|
+
const agent = ctx.agents.get(sessionId);
|
|
2210
|
+
if (agent === void 0 || !snapshots.has(agent) || agent.status !== "idle") return;
|
|
2211
|
+
const boundary = ctx.agents.turnBoundaryOf(agent.session);
|
|
2212
|
+
if (boundary.openTurnStartSeq !== null || boundary.lastTurn > 0) return;
|
|
2213
|
+
try {
|
|
2214
|
+
reconcile(agent);
|
|
2215
|
+
} catch (error) {
|
|
2216
|
+
ctx.logger.warn(`codex-tool-policy: preset selection overlay refused for ${agent.id}: ${String(error)}`);
|
|
2217
|
+
}
|
|
2218
|
+
});
|
|
2219
|
+
ctx.on("agent/disposed", ({ agent }) => {
|
|
2220
|
+
remove(agent);
|
|
2221
|
+
snapshots.delete(agent);
|
|
2222
|
+
});
|
|
2223
|
+
ctx.effect(() => () => {
|
|
2224
|
+
active = false;
|
|
2225
|
+
for (const agent of [...overlays.keys()].reverse()) remove(agent);
|
|
2226
|
+
}, "codex-tool-policy: Host overlay ownership");
|
|
2227
|
+
}
|
|
2228
|
+
var tool_policy_default = {
|
|
2229
|
+
name,
|
|
2230
|
+
inject,
|
|
2231
|
+
Config,
|
|
2232
|
+
apply
|
|
2233
|
+
};
|
|
2234
|
+
//#endregion
|
|
2235
|
+
export { Config, apply, tool_policy_default as default, inject, name };
|