@shuind/dsh-codex-harness 0.2.21 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +185 -0
- package/README.md +38 -50
- package/RELEASE.md +61 -0
- package/assets/codex.svg +5 -0
- package/cordis.patch.yml +181 -6
- package/docs/preset-library.md +33 -23
- package/docs/tool-policy-benchmark.json +310 -0
- package/docs/tool-policy.md +148 -0
- package/lib/client.js +4774 -2416
- package/lib/compact-command.js +416 -0
- package/lib/compaction.js +141 -12
- package/lib/hybrid-executor.js +1196 -0
- package/lib/index.js +3658 -2334
- package/lib/preferences.js +117 -0
- package/lib/tool-policy.js +2422 -0
- package/lib/typert.js +86 -79
- package/lib/types/client/activity.d.ts +33 -9
- package/lib/types/client/activity.js +4 -3
- package/lib/types/client/desktop.d.ts +67 -0
- package/lib/types/client/desktop.js +229 -0
- package/lib/types/client/index.d.ts +207 -110
- package/lib/types/client/index.js +99 -492
- package/lib/types/client/policy-drafts.d.ts +25 -0
- package/lib/types/client/policy-drafts.js +47 -0
- package/lib/types/client/policy-locale.d.ts +260 -0
- package/lib/types/client/policy-locale.js +357 -0
- package/lib/types/client/preset-manager.d.ts +38 -10
- package/lib/types/client/preset-manager.js +235 -185
- package/lib/types/client/preset-requests.d.ts +12 -0
- package/lib/types/client/preset-requests.js +101 -0
- package/lib/types/client/tool-policy.d.ts +33 -0
- package/lib/types/client/tool-policy.js +336 -0
- package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
- package/lib/types/contracts/preset-editor-schema.js +95 -0
- package/lib/types/{prompt.js → contracts/prompt.js} +13 -7
- package/lib/types/{settings.d.ts → contracts/settings.d.ts} +11 -4
- package/lib/types/{settings.js → contracts/settings.js} +22 -6
- package/lib/types/contracts/tool-policy-contract.d.ts +63 -0
- package/lib/types/contracts/tool-policy-contract.js +33 -0
- package/lib/types/contracts/ui-contracts.d.ts +92 -0
- package/lib/types/contracts/ui-contracts.js +83 -0
- package/lib/types/entries/client.d.ts +10 -0
- package/lib/types/entries/client.js +10 -0
- package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
- package/lib/types/entries/compact-command.js +176 -0
- package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +15 -3
- package/lib/types/{compaction.js → entries/compaction.js} +47 -11
- package/lib/types/entries/hybrid-executor.d.ts +19 -0
- package/lib/types/entries/hybrid-executor.js +57 -0
- package/lib/types/entries/index.d.ts +66 -0
- package/lib/types/entries/index.js +192 -0
- package/lib/types/entries/preferences.d.ts +11 -0
- package/lib/types/entries/preferences.js +16 -0
- package/lib/types/entries/tool-policy.d.ts +97 -0
- package/lib/types/entries/tool-policy.js +158 -0
- package/lib/types/entries/typert.host.d.ts +23 -0
- package/lib/types/entries/typert.host.js +24 -0
- package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
- package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
- package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
- package/lib/types/hybrid/hybrid-sdk.js +196 -0
- package/lib/types/hybrid/program-calls.d.ts +28 -0
- package/lib/types/hybrid/program-calls.js +193 -0
- package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
- package/lib/types/hybrid/subcall-scheduler.js +343 -0
- package/lib/types/policy/deferred-tools.d.ts +42 -0
- package/lib/types/policy/deferred-tools.js +264 -0
- package/lib/types/policy/overlay-installer.d.ts +12 -0
- package/lib/types/policy/overlay-installer.js +179 -0
- package/lib/types/policy/rule-resolver.d.ts +94 -0
- package/lib/types/policy/rule-resolver.js +114 -0
- package/lib/types/policy/tool-capabilities.d.ts +33 -0
- package/lib/types/policy/tool-capabilities.js +46 -0
- package/lib/types/{activity.d.ts → presets/activity.d.ts} +3 -5
- package/lib/types/{activity.js → presets/activity.js} +51 -27
- package/lib/types/presets/desktop-preset.d.ts +22 -0
- package/lib/types/presets/desktop-preset.js +43 -0
- package/lib/types/presets/preset-editor.d.ts +47 -0
- package/lib/types/presets/preset-editor.js +81 -0
- package/lib/types/presets/preset-prompt-catalog.d.ts +23 -0
- package/lib/types/presets/preset-prompt-catalog.js +215 -0
- package/lib/types/presets/preset-tool-catalog.d.ts +5 -0
- package/lib/types/presets/preset-tool-catalog.js +58 -0
- package/lib/types/presets/runtime-enhancements.d.ts +45 -0
- package/lib/types/presets/runtime-enhancements.js +349 -0
- package/lib/types/presets/small-window-compaction.d.ts +15 -0
- package/lib/types/presets/small-window-compaction.js +121 -0
- package/lib/types/responses/compact-checkpoint.d.ts +27 -0
- package/lib/types/responses/compact-checkpoint.js +257 -0
- package/lib/types/responses/fetch-transport.d.ts +16 -0
- package/lib/types/responses/fetch-transport.js +257 -0
- package/lib/types/responses/remote-compact.d.ts +13 -0
- package/lib/types/responses/remote-compact.js +319 -0
- package/lib/types/responses/sse-diagnostics.d.ts +9 -0
- package/lib/types/responses/sse-diagnostics.js +157 -0
- package/lib/types/responses/wire-rewrite.d.ts +35 -0
- package/lib/types/responses/wire-rewrite.js +237 -0
- package/lib/types/tools/exec-output.d.ts +58 -0
- package/lib/types/tools/exec-output.js +173 -0
- package/lib/types/tools/exec-plan-tools.d.ts +37 -0
- package/lib/types/tools/exec-plan-tools.js +265 -0
- package/lib/types/tools/exec-runner.d.ts +21 -0
- package/lib/types/tools/exec-runner.js +385 -0
- package/lib/types/tools/patch-tool.d.ts +16 -0
- package/lib/types/tools/patch-tool.js +258 -0
- package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
- package/lib/types/{patch.js → tools/patch.js} +96 -21
- package/locale/en.json +6 -0
- package/locale/hybrid-executor/en.json +6 -0
- package/locale/hybrid-executor/zh.json +6 -0
- package/locale/tool-policy/en.json +6 -0
- package/locale/tool-policy/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +297 -299
- package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
- package/presets/codex-hybrid/preset.yml +3 -0
- package/scripts/benchmark-tool-policy.mjs +186 -0
- package/scripts/build-preset.mjs +19 -0
- package/scripts/clean-build.mjs +11 -0
- package/src/client/activity.ts +83 -0
- package/src/client/desktop.tsx +276 -0
- package/src/client/index.tsx +391 -0
- package/src/client/policy-drafts.ts +56 -0
- package/src/client/policy-locale.ts +362 -0
- package/src/client/preset-manager.tsx +376 -0
- package/src/client/preset-requests.ts +113 -0
- package/src/client/tool-policy.tsx +402 -0
- package/src/contracts/preset-editor-schema.ts +110 -0
- package/src/contracts/prompt.ts +66 -0
- package/src/contracts/settings.ts +103 -0
- package/src/contracts/tool-policy-contract.ts +93 -0
- package/src/contracts/ui-contracts.ts +173 -0
- package/src/entries/client.tsx +14 -0
- package/src/entries/compact-command.ts +256 -0
- package/src/entries/compaction.ts +218 -0
- package/src/entries/hybrid-executor.ts +76 -0
- package/src/entries/index.ts +298 -0
- package/src/entries/preferences.ts +17 -0
- package/src/entries/tool-policy.ts +162 -0
- package/src/entries/typert.host.ts +29 -0
- package/src/hybrid/codex-hybrid-executor.ts +310 -0
- package/src/hybrid/hybrid-sdk.ts +217 -0
- package/src/hybrid/program-calls.ts +202 -0
- package/src/hybrid/subcall-scheduler.ts +446 -0
- package/src/policy/deferred-tools.ts +331 -0
- package/src/policy/overlay-installer.ts +191 -0
- package/src/policy/rule-resolver.ts +128 -0
- package/src/policy/tool-capabilities.ts +88 -0
- package/src/presets/activity.ts +146 -0
- package/src/presets/desktop-preset.ts +60 -0
- package/src/presets/preset-editor.ts +101 -0
- package/src/presets/preset-prompt-catalog.ts +221 -0
- package/src/presets/preset-tool-catalog.ts +58 -0
- package/src/presets/runtime-enhancements.ts +415 -0
- package/src/presets/small-window-compaction.ts +166 -0
- package/src/responses/compact-checkpoint.ts +264 -0
- package/src/responses/fetch-transport.ts +290 -0
- package/src/responses/remote-compact.ts +393 -0
- package/src/responses/sse-diagnostics.ts +156 -0
- package/src/responses/wire-rewrite.ts +261 -0
- package/src/tools/exec-output.ts +211 -0
- package/src/tools/exec-plan-tools.ts +307 -0
- package/src/tools/exec-runner.ts +445 -0
- package/src/tools/patch-tool.ts +331 -0
- package/src/tools/patch.ts +328 -0
- package/tsconfig.json +29 -0
- package/tsdown.config.ts +110 -0
- package/lib/installer.js +0 -237
- package/lib/invariant.js +0 -23
- package/lib/types/activity-types.d.ts +0 -6
- package/lib/types/activity-types.js +0 -3
- package/lib/types/client/preset-copy.d.ts +0 -42
- package/lib/types/client/preset-copy.js +0 -81
- package/lib/types/compact-command.js +0 -79
- package/lib/types/context.d.ts +0 -8
- package/lib/types/context.js +0 -14
- package/lib/types/exec.d.ts +0 -46
- package/lib/types/exec.js +0 -365
- package/lib/types/index.d.ts +0 -95
- package/lib/types/index.js +0 -738
- package/lib/types/installer.d.ts +0 -27
- package/lib/types/installer.js +0 -146
- package/lib/types/invariant.d.ts +0 -16
- package/lib/types/invariant.js +0 -22
- package/lib/types/preset-contract.d.ts +0 -69
- package/lib/types/preset-contract.js +0 -22
- package/lib/types/preset-editor-remote.d.ts +0 -30
- package/lib/types/preset-editor-remote.js +0 -37
- package/lib/types/preset-editor.d.ts +0 -69
- package/lib/types/preset-editor.js +0 -557
- package/lib/types/preset-templates.d.ts +0 -36
- package/lib/types/preset-templates.js +0 -12
- package/lib/types/prompt-sections.d.ts +0 -15
- package/lib/types/prompt-sections.js +0 -23
- package/lib/types/remote.d.ts +0 -40
- package/lib/types/remote.js +0 -683
- package/lib/types/typert.host.d.ts +0 -47
- package/lib/types/typert.host.js +0 -99
- package/presets/codex-collaboration/preset.yml +0 -3
- /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
|
@@ -0,0 +1,1196 @@
|
|
|
1
|
+
import { scopeOf, scopeParentOf, scopeTarget } from "@deepseek-ai/dsh-scope";
|
|
2
|
+
import { symbols } from "@deepseek-ai/cordis";
|
|
3
|
+
import z from "@deepseek-ai/schemastery";
|
|
4
|
+
import { HarnessError, ToolCallId, createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
5
|
+
import { ESCALATION_TARGETS, approveEscalation, validateEscalationArgs } from "@deepseek-ai/dsh-sandbox";
|
|
6
|
+
import { RUN_CODE_NAME, TOOL_ABORTED, ToolNotFoundError, assertSupportedJsonSchema, defineTool, parameterSchemaSpecToJsonSchema, projectToolSchema } from "@deepseek-ai/dsh-tools";
|
|
7
|
+
import { ToolExecutionPipeline, executeToolBatch, toolErrorMessage } from "@deepseek-ai/dsh-tools/pipeline";
|
|
8
|
+
//#region lib/types/hybrid/hybrid-sdk.js
|
|
9
|
+
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
10
|
+
function renderKey(name) {
|
|
11
|
+
return IDENTIFIER.test(name) ? name : JSON.stringify(name);
|
|
12
|
+
}
|
|
13
|
+
function pad(indent) {
|
|
14
|
+
return " ".repeat(indent);
|
|
15
|
+
}
|
|
16
|
+
function docLines(description, indent) {
|
|
17
|
+
if (typeof description !== "string" || description.length === 0) return [];
|
|
18
|
+
const collapsed = description.replace(/\s+/gu, " ").trim();
|
|
19
|
+
if (collapsed.length === 0) return [];
|
|
20
|
+
return [`${pad(indent)}/** ${collapsed.replaceAll("*/", String.raw`*\/`)} */`];
|
|
21
|
+
}
|
|
22
|
+
function renderScalar(node, type) {
|
|
23
|
+
const broad = type === "integer" ? "number" : type;
|
|
24
|
+
if (Object.hasOwn(node, "const")) return JSON.stringify(node.const);
|
|
25
|
+
if (Object.hasOwn(node, "enum")) return node.enum.map((value) => JSON.stringify(value)).join(" | ");
|
|
26
|
+
return broad;
|
|
27
|
+
}
|
|
28
|
+
function containsUnion(text) {
|
|
29
|
+
return text.includes(" | ");
|
|
30
|
+
}
|
|
31
|
+
function renderObjectNode(node, indent) {
|
|
32
|
+
const properties = node.properties ?? {};
|
|
33
|
+
const required = new Set(node.required ?? []);
|
|
34
|
+
const keys = Object.keys(properties).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
35
|
+
const lines = [];
|
|
36
|
+
for (const key of keys) {
|
|
37
|
+
const child = properties[key];
|
|
38
|
+
if (child === void 0) continue;
|
|
39
|
+
lines.push(...docLines(child.description, indent + 1));
|
|
40
|
+
const optional = required.has(key) ? "" : "?";
|
|
41
|
+
lines.push(`${pad(indent + 1)}${renderKey(key)}${optional}: ${renderNode(child, indent + 1)};`);
|
|
42
|
+
}
|
|
43
|
+
if (node.additionalProperties !== false) lines.push(`${pad(indent + 1)}[key: string]: JsonValue;`);
|
|
44
|
+
if (lines.length === 0) return "{}";
|
|
45
|
+
return `{\n${lines.join("\n")}\n${pad(indent)}}`;
|
|
46
|
+
}
|
|
47
|
+
function renderNode(node, indent) {
|
|
48
|
+
if (Array.isArray(node.oneOf) && node.oneOf.length > 0) return node.oneOf.map((branch) => renderNode(branch, indent)).join(" | ");
|
|
49
|
+
switch (node.type) {
|
|
50
|
+
case void 0: return "JsonValue";
|
|
51
|
+
case "object": return renderObjectNode(node, indent);
|
|
52
|
+
case "array": {
|
|
53
|
+
const itemText = node.items === void 0 ? "JsonValue" : renderNode(node.items, indent);
|
|
54
|
+
return containsUnion(itemText) ? `(${itemText})[]` : `${itemText}[]`;
|
|
55
|
+
}
|
|
56
|
+
case "string":
|
|
57
|
+
case "number":
|
|
58
|
+
case "integer":
|
|
59
|
+
case "boolean":
|
|
60
|
+
case "null": return renderScalar(node, node.type);
|
|
61
|
+
default: return "unknown";
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Render one supported JSON Schema node to TypeScript, degrading invalid schemas safely. */
|
|
65
|
+
function jsonSchemaToTs(schema, indent = 0) {
|
|
66
|
+
try {
|
|
67
|
+
assertSupportedJsonSchema(schema);
|
|
68
|
+
return renderNode(schema, indent);
|
|
69
|
+
} catch {
|
|
70
|
+
return "unknown";
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function renderPythonAnnotation(node) {
|
|
74
|
+
if (Array.isArray(node.oneOf) && node.oneOf.length > 0) return node.oneOf.map(renderPythonAnnotation).join(" | ");
|
|
75
|
+
switch (node.type) {
|
|
76
|
+
case "object": return "dict[str, Any]";
|
|
77
|
+
case "array": return node.items === void 0 ? "list[Any]" : `list[${renderPythonAnnotation(node.items)}]`;
|
|
78
|
+
case "string": return "str";
|
|
79
|
+
case "integer": return "int";
|
|
80
|
+
case "number": return "float";
|
|
81
|
+
case "boolean": return "bool";
|
|
82
|
+
case "null": return "None";
|
|
83
|
+
default: return "Any";
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function safePyIdentifier(name) {
|
|
87
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) ? name : `tool_${name.replace(/[^A-Za-z0-9_]+/gu, "_")}`;
|
|
88
|
+
}
|
|
89
|
+
function renderPythonSdk(sorted, programFormat) {
|
|
90
|
+
const methods = sorted.map((schema) => {
|
|
91
|
+
let returnType = "Any";
|
|
92
|
+
try {
|
|
93
|
+
assertSupportedJsonSchema(schema.output);
|
|
94
|
+
returnType = renderPythonAnnotation(schema.output);
|
|
95
|
+
} catch {
|
|
96
|
+
returnType = "Any";
|
|
97
|
+
}
|
|
98
|
+
const doc = schema.description.replace(/\s+/gu, " ").trim().replaceAll("\"\"\"", "\\\"\\\"\\\"");
|
|
99
|
+
return [
|
|
100
|
+
` async def ${safePyIdentifier(schema.name)}(self, args: dict[str, Any]) -> ${returnType}:`,
|
|
101
|
+
...doc ? [` """${doc}"""`] : [],
|
|
102
|
+
" ..."
|
|
103
|
+
].join("\n");
|
|
104
|
+
});
|
|
105
|
+
return [
|
|
106
|
+
"## Hybrid SDK bindings (`run_code`)",
|
|
107
|
+
"",
|
|
108
|
+
"Invoke the SDK tools below only inside `run_code` via `await tools.<name>(args)`. Direct wire tools must still be called directly, not through `tools`.",
|
|
109
|
+
`Batch independent read/search calls with \`asyncio.gather\`. ${programFormat === "function-body" ? "Print results cleanly with `print(...)` or `return`." : "Emit only concise summaries for the conversation."}`,
|
|
110
|
+
"",
|
|
111
|
+
"```python",
|
|
112
|
+
"from typing import Any",
|
|
113
|
+
"",
|
|
114
|
+
"class ToolCallError(Exception):",
|
|
115
|
+
" toolName: str",
|
|
116
|
+
"",
|
|
117
|
+
"class _ToolsSdk:",
|
|
118
|
+
...methods,
|
|
119
|
+
"",
|
|
120
|
+
"tools: _ToolsSdk",
|
|
121
|
+
"```"
|
|
122
|
+
].join("\n");
|
|
123
|
+
}
|
|
124
|
+
/** Render deterministic SDK declarations for hybrid `run_code` bindings. */
|
|
125
|
+
function renderHybridToolsSdk(schemas, language = "typescript", programFormat = "function-body") {
|
|
126
|
+
if (schemas.length === 0) return [
|
|
127
|
+
"## Hybrid SDK bindings (`run_code`)",
|
|
128
|
+
"",
|
|
129
|
+
"No SDK tools are currently active in this step. Direct tools remain callable directly without `run_code`. If you need a deferred tool, call `activate_tools` first and invoke it on the next step."
|
|
130
|
+
].join("\n");
|
|
131
|
+
const sorted = [...schemas].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
132
|
+
if (language === "python") return renderPythonSdk(sorted, programFormat);
|
|
133
|
+
const programDescription = programFormat === "function-body" ? "the body of an async TypeScript function (erasable syntax only; top-level `await` and `return` work)" : "the TypeScript program to execute";
|
|
134
|
+
const outputInstruction = programFormat === "function-body" ? "Emit curated output with `return` and/or `console.log(...)`." : "Only printed/emitted program output enters the conversation.";
|
|
135
|
+
const argsMembers = [];
|
|
136
|
+
const outputMembers = [];
|
|
137
|
+
for (const schema of sorted) {
|
|
138
|
+
argsMembers.push(...docLines(schema.description, 1));
|
|
139
|
+
argsMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1)};`);
|
|
140
|
+
outputMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.output, 1)};`);
|
|
141
|
+
}
|
|
142
|
+
const declaration = [
|
|
143
|
+
`interface ToolArgsMap {\n${argsMembers.join("\n")}\n}`,
|
|
144
|
+
`interface ToolOutputMap {\n${outputMembers.join("\n")}\n}`,
|
|
145
|
+
"type ToolName = keyof ToolOutputMap",
|
|
146
|
+
[
|
|
147
|
+
"declare class ToolCallError extends Error {",
|
|
148
|
+
" readonly name: \"ToolCallError\";",
|
|
149
|
+
" readonly toolName: ToolName;",
|
|
150
|
+
"}"
|
|
151
|
+
].join("\n"),
|
|
152
|
+
[
|
|
153
|
+
"declare const tools: {",
|
|
154
|
+
" [K in ToolName]: (args: ToolArgsMap[K]) => Promise<ToolOutputMap[K]>;",
|
|
155
|
+
"}"
|
|
156
|
+
].join("\n")
|
|
157
|
+
].join("\n\n");
|
|
158
|
+
return [
|
|
159
|
+
"## Hybrid SDK bindings (`run_code`)",
|
|
160
|
+
"",
|
|
161
|
+
`\`run_code\` executes ${programDescription}. Direct wire tools are NOT available on \`tools\` unless explicitly configured — call those directly. Call every SDK tool below only inside \`run_code\`:`,
|
|
162
|
+
"",
|
|
163
|
+
"- Call tools as `await tools.name(args)` (quoted for exotic names: `tools[\"my-tool\"](args)`). Each resolves to its typed canonical JSON value; arguments must be lossless JSON.",
|
|
164
|
+
"- A failed tool call rejects with `ToolCallError` (carrying `.toolName` and `.message`); handle errors with `try/catch`.",
|
|
165
|
+
"- Batch independent read/search calls concurrently with `Promise.all`; sequence dependent steps with `await`.",
|
|
166
|
+
`- ${outputInstruction} Image-bearing subtool results are attached automatically after the run; extract only what you need from text/JSON results.`,
|
|
167
|
+
"",
|
|
168
|
+
"```ts",
|
|
169
|
+
"type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }",
|
|
170
|
+
"",
|
|
171
|
+
declaration,
|
|
172
|
+
"```"
|
|
173
|
+
].join("\n");
|
|
174
|
+
}
|
|
175
|
+
//#endregion
|
|
176
|
+
//#region lib/types/hybrid/program-calls.js
|
|
177
|
+
var CodeRunFailedError = class extends HarnessError {
|
|
178
|
+
constructor(message) {
|
|
179
|
+
super(message, "PTC_RUN_FAILED");
|
|
180
|
+
this.name = "CodeRunFailedError";
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
var CodeResetFailedError = class extends HarnessError {
|
|
184
|
+
constructor(message) {
|
|
185
|
+
super(message, "PTC_RESET_FAILED");
|
|
186
|
+
this.name = "CodeResetFailedError";
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
function snapshotJsonValue(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
190
|
+
if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") return;
|
|
191
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return value;
|
|
192
|
+
if (typeof value === "number") {
|
|
193
|
+
if (!Number.isFinite(value)) throw new Error("non-finite number is not lossless JSON");
|
|
194
|
+
return Object.is(value, -0) ? 0 : value;
|
|
195
|
+
}
|
|
196
|
+
if (typeof value !== "object") return void 0;
|
|
197
|
+
if (seen.has(value)) throw new Error("cyclic structure is not lossless JSON");
|
|
198
|
+
seen.add(value);
|
|
199
|
+
try {
|
|
200
|
+
if (Array.isArray(value)) {
|
|
201
|
+
const copy = [];
|
|
202
|
+
for (let i = 0; i < value.length; i++) {
|
|
203
|
+
if (!Object.hasOwn(value, i)) throw new Error("sparse array is not lossless JSON");
|
|
204
|
+
const item = snapshotJsonValue(value[i], seen);
|
|
205
|
+
if (item === void 0) throw new Error("array element is not lossless JSON");
|
|
206
|
+
copy.push(item);
|
|
207
|
+
}
|
|
208
|
+
return copy;
|
|
209
|
+
}
|
|
210
|
+
const proto = Object.getPrototypeOf(value);
|
|
211
|
+
if (proto !== Object.prototype && proto !== null) throw new Error("non-plain object is not lossless JSON");
|
|
212
|
+
const copy = {};
|
|
213
|
+
for (const key of Object.keys(value)) {
|
|
214
|
+
const prop = value[key];
|
|
215
|
+
if (prop === void 0) continue;
|
|
216
|
+
const snapped = snapshotJsonValue(prop, seen);
|
|
217
|
+
if (snapped === void 0) throw new Error(`property ${JSON.stringify(key)} is not lossless JSON`);
|
|
218
|
+
copy[key] = snapped;
|
|
219
|
+
}
|
|
220
|
+
return copy;
|
|
221
|
+
} finally {
|
|
222
|
+
seen.delete(value);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function deepFreeze(value) {
|
|
226
|
+
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
227
|
+
Object.freeze(value);
|
|
228
|
+
for (const child of Object.values(value)) deepFreeze(child);
|
|
229
|
+
}
|
|
230
|
+
return value;
|
|
231
|
+
}
|
|
232
|
+
function jsonNormalizeArgs(value) {
|
|
233
|
+
let snapshot;
|
|
234
|
+
try {
|
|
235
|
+
snapshot = snapshotJsonValue(value);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
throw new Error(`tool arguments must be lossless JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
238
|
+
}
|
|
239
|
+
if (snapshot === void 0) throw new Error("tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)");
|
|
240
|
+
const logged = snapshotJsonValue(snapshot);
|
|
241
|
+
if (logged === void 0) throw new Error("tool arguments could not be detached for durable logging");
|
|
242
|
+
return {
|
|
243
|
+
dispatched: snapshot,
|
|
244
|
+
logged
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
function renderRunCodeValue(value) {
|
|
248
|
+
if (typeof value === "string") return value;
|
|
249
|
+
return JSON.stringify(value, null, 2) ?? String(value);
|
|
250
|
+
}
|
|
251
|
+
var HybridProgramCalls = class {
|
|
252
|
+
calls = /* @__PURE__ */ new Map();
|
|
253
|
+
resets = /* @__PURE__ */ new Map();
|
|
254
|
+
disposed = false;
|
|
255
|
+
constructor(ctx) {
|
|
256
|
+
if (typeof ctx.on === "function") ctx.on("session/event", (session, event) => {
|
|
257
|
+
if (event.type !== "sandbox/mode") return;
|
|
258
|
+
for (const call of this.calls.get(session.id) ?? []) if (call.mode !== void 0 && call.mode !== event.data.mode) call.controller.abort(/* @__PURE__ */ new Error("sandbox mode changed"));
|
|
259
|
+
}, { global: true });
|
|
260
|
+
if (typeof ctx.effect === "function") ctx.effect(() => async () => {
|
|
261
|
+
this.disposed = true;
|
|
262
|
+
const active = [...this.calls.values()].flatMap((set) => [...set]);
|
|
263
|
+
for (const call of active) call.controller.abort(/* @__PURE__ */ new Error("Hybrid tool executor disposed"));
|
|
264
|
+
await Promise.allSettled([...active.map((call) => call.done), ...[...this.resets.values()].map((reset) => reset.done)]);
|
|
265
|
+
}, "Codex hybrid PTC calls");
|
|
266
|
+
}
|
|
267
|
+
async run(sessionId, signal, mode, fn) {
|
|
268
|
+
for (;;) {
|
|
269
|
+
const reset = this.resets.get(sessionId);
|
|
270
|
+
if (reset !== void 0) {
|
|
271
|
+
try {
|
|
272
|
+
await reset.done;
|
|
273
|
+
} catch (error) {
|
|
274
|
+
throw new CodeRunFailedError(`Program environment unavailable: ${toolErrorMessage(error)}. Ask the host to reset it before running more code.`);
|
|
275
|
+
}
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
const pending = [...this.calls.get(sessionId) ?? []].filter((call) => call.signal.aborted);
|
|
279
|
+
if (pending.length === 0) break;
|
|
280
|
+
await Promise.all(pending.map((call) => call.done));
|
|
281
|
+
}
|
|
282
|
+
signal.throwIfAborted();
|
|
283
|
+
if (this.disposed) throw new Error("Hybrid tool executor disposed");
|
|
284
|
+
const controller = new AbortController();
|
|
285
|
+
const done = Promise.withResolvers();
|
|
286
|
+
const callSignal = AbortSignal.any([signal, controller.signal]);
|
|
287
|
+
const call = {
|
|
288
|
+
mode: mode(),
|
|
289
|
+
controller,
|
|
290
|
+
signal: callSignal,
|
|
291
|
+
done: done.promise
|
|
292
|
+
};
|
|
293
|
+
let sessionCalls = this.calls.get(sessionId);
|
|
294
|
+
if (sessionCalls === void 0) {
|
|
295
|
+
sessionCalls = /* @__PURE__ */ new Set();
|
|
296
|
+
this.calls.set(sessionId, sessionCalls);
|
|
297
|
+
}
|
|
298
|
+
sessionCalls.add(call);
|
|
299
|
+
try {
|
|
300
|
+
return await fn(callSignal);
|
|
301
|
+
} finally {
|
|
302
|
+
sessionCalls.delete(call);
|
|
303
|
+
if (sessionCalls.size === 0) this.calls.delete(sessionId);
|
|
304
|
+
done.resolve(void 0);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
reset(sessionId, release, notify) {
|
|
308
|
+
if (this.disposed) return Promise.reject(/* @__PURE__ */ new Error("Hybrid tool executor disposed"));
|
|
309
|
+
const previous = this.resets.get(sessionId);
|
|
310
|
+
if (previous !== void 0 && !previous.settled) return previous.done;
|
|
311
|
+
const done = Promise.withResolvers();
|
|
312
|
+
const reset = {
|
|
313
|
+
done: done.promise,
|
|
314
|
+
settled: false
|
|
315
|
+
};
|
|
316
|
+
this.resets.set(sessionId, reset);
|
|
317
|
+
const calls = [...this.calls.get(sessionId) ?? []];
|
|
318
|
+
for (const call of calls) call.controller.abort(/* @__PURE__ */ new Error("PTC environment reset"));
|
|
319
|
+
Promise.allSettled([Promise.resolve().then(release), ...calls.map((call) => call.done)]).then((results) => {
|
|
320
|
+
const failure = results.find((result) => result.status === "rejected");
|
|
321
|
+
if (failure !== void 0) throw failure.reason;
|
|
322
|
+
notify?.();
|
|
323
|
+
}).then(() => {
|
|
324
|
+
reset.settled = true;
|
|
325
|
+
this.resets.delete(sessionId);
|
|
326
|
+
done.resolve(void 0);
|
|
327
|
+
}, (error) => {
|
|
328
|
+
reset.settled = true;
|
|
329
|
+
done.reject(error);
|
|
330
|
+
});
|
|
331
|
+
return reset.done;
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
//#endregion
|
|
335
|
+
//#region lib/types/hybrid/subcall-scheduler.js
|
|
336
|
+
var ToolCallLimitExceededError = class extends Error {
|
|
337
|
+
constructor(limit, windowMs) {
|
|
338
|
+
super(`run_code exceeded its tool-call budget (${limit} calls in ${windowMs}ms)`);
|
|
339
|
+
this.name = "ToolCallLimitExceededError";
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
function requirePtcRuntime(ctx) {
|
|
343
|
+
const runtime = ctx.get("ptcRuntime");
|
|
344
|
+
if (runtime === void 0) throw new Error("codex-hybrid-executor: requires a mounted ctx.ptcRuntime implementation");
|
|
345
|
+
if (runtime.language !== "typescript" && runtime.language !== "python") throw new Error(`codex-hybrid-executor: unsupported PTC runtime language ${JSON.stringify(runtime.language)}`);
|
|
346
|
+
return runtime;
|
|
347
|
+
}
|
|
348
|
+
function resolveProgramFormat(runtime) {
|
|
349
|
+
return runtime.programFormat ?? "function-body";
|
|
350
|
+
}
|
|
351
|
+
function escalationGuidance(mode) {
|
|
352
|
+
return mode === void 0 ? "" : " A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying.";
|
|
353
|
+
}
|
|
354
|
+
function resolveRunCodeDescription(runtime) {
|
|
355
|
+
const langLabel = runtime.language === "python" ? "Python" : "TypeScript";
|
|
356
|
+
const formatNote = runtime.language === "typescript" && resolveProgramFormat(runtime) === "function-body" ? "the BODY of an async TypeScript function (erasable syntax only; top-level `await` and `return` work)" : `the ${langLabel} program to execute`;
|
|
357
|
+
const extra = runtime.executionInstructions ? ` ${runtime.executionInstructions}` : "";
|
|
358
|
+
return `Execute a ${langLabel} program against the SDK tools declared in \`tools:sdk\`. Takes \`code\` (${formatNote}) and \`description\`. Call SDK tools via \`await tools.name(args)\`. Direct wire tools stay outside \`run_code\`. Image-bearing subtool results are attached after the run.` + extra + " Each program starts in the Session current directory." + escalationGuidance(runtime.sandboxMode);
|
|
359
|
+
}
|
|
360
|
+
async function resolveWorkingDirectory(ctx, exec) {
|
|
361
|
+
if (exec.agent === void 0) return void 0;
|
|
362
|
+
const directories = exec.agent.ctx.get("workingDirectory") ?? ctx.get("workingDirectory");
|
|
363
|
+
if (directories === void 0) throw new Error("codex-hybrid: run_code with an Agent requires workingDirectory");
|
|
364
|
+
return directories.ensure(exec.agent, exec.signal);
|
|
365
|
+
}
|
|
366
|
+
function resolveSandboxPolicy(ctx, exec) {
|
|
367
|
+
const policy = exec.agent?.ctx.get("sandboxPolicy") ?? ctx.get("sandboxPolicy");
|
|
368
|
+
if (policy === void 0) throw new Error("codex-hybrid: confined PTC runtime requires sandboxPolicy");
|
|
369
|
+
return policy.resolve(exec.agent === void 0 ? {} : { session: exec.agent.session });
|
|
370
|
+
}
|
|
371
|
+
async function executeHybridRunCode(host, rawArgs, exec, callSignal) {
|
|
372
|
+
const { ctx, pipeline } = host;
|
|
373
|
+
const tools = ctx.tools;
|
|
374
|
+
const runtime = requirePtcRuntime(ctx);
|
|
375
|
+
validateEscalationArgs(rawArgs.sandbox_permissions, rawArgs.justification);
|
|
376
|
+
if (rawArgs.timeoutMs !== void 0 && runtime.timeout === void 0) throw new Error("timeoutMs is not available for this PTC runtime");
|
|
377
|
+
if (rawArgs.timeoutMs !== void 0 && (!Number.isFinite(rawArgs.timeoutMs) || rawArgs.timeoutMs <= 0)) throw new Error("invalid timeoutMs: expected a positive finite number");
|
|
378
|
+
const standingPolicy = runtime.sandboxMode === void 0 ? void 0 : resolveSandboxPolicy(ctx, exec);
|
|
379
|
+
let policy = standingPolicy;
|
|
380
|
+
if (rawArgs.sandbox_permissions !== void 0 && rawArgs.justification !== void 0) {
|
|
381
|
+
if (standingPolicy === void 0) throw new Error("sandbox_permissions is not available for this PTC runtime");
|
|
382
|
+
const approver = exec.agent?.ctx.get("approval") ?? ctx.get("approval");
|
|
383
|
+
const approvedMode = await approveEscalation({
|
|
384
|
+
requestedMode: rawArgs.sandbox_permissions,
|
|
385
|
+
justification: rawArgs.justification,
|
|
386
|
+
effectiveMode: standingPolicy.mode,
|
|
387
|
+
subject: "program"
|
|
388
|
+
}, {
|
|
389
|
+
approver,
|
|
390
|
+
agent: exec.agent,
|
|
391
|
+
callId: exec.callId,
|
|
392
|
+
toolName: RUN_CODE_NAME,
|
|
393
|
+
signal: callSignal
|
|
394
|
+
});
|
|
395
|
+
policy = {
|
|
396
|
+
...standingPolicy,
|
|
397
|
+
mode: approvedMode
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
const cwd = await resolveWorkingDirectory(ctx, {
|
|
401
|
+
...exec,
|
|
402
|
+
signal: callSignal
|
|
403
|
+
});
|
|
404
|
+
callSignal.throwIfAborted();
|
|
405
|
+
const runController = new AbortController();
|
|
406
|
+
const onOuterAbort = () => {
|
|
407
|
+
runController.abort(callSignal.reason);
|
|
408
|
+
};
|
|
409
|
+
callSignal.addEventListener("abort", onOuterAbort, { once: true });
|
|
410
|
+
let dispatches = 0;
|
|
411
|
+
let maxSubCalls = Infinity;
|
|
412
|
+
let subCallWindowMs = 6e4;
|
|
413
|
+
let subSeq = 1;
|
|
414
|
+
let closed = false;
|
|
415
|
+
const pendingQueue = [];
|
|
416
|
+
const commitQueue = [];
|
|
417
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
418
|
+
const logWork = /* @__PURE__ */ new Set();
|
|
419
|
+
let exclusiveActive = false;
|
|
420
|
+
let driving = false;
|
|
421
|
+
let driverRun = Promise.resolve();
|
|
422
|
+
let wake;
|
|
423
|
+
const wakeup = () => {
|
|
424
|
+
const release = wake;
|
|
425
|
+
wake = void 0;
|
|
426
|
+
release?.();
|
|
427
|
+
};
|
|
428
|
+
const shapeDispatchLog = async (dispatch) => {
|
|
429
|
+
try {
|
|
430
|
+
return await ctx.waterfall(scopeTarget(tools, dispatch.agent), "tools/ptc-dispatch-log", dispatch, () => Promise.resolve(dispatch.content));
|
|
431
|
+
} catch (error) {
|
|
432
|
+
ctx.logger.warn(`codex-hybrid: ptc-dispatch-log listener failed for ${dispatch.name}: ${toolErrorMessage(error)}`);
|
|
433
|
+
return dispatch.content;
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
const drive = () => {
|
|
437
|
+
if (driving) return driverRun;
|
|
438
|
+
driving = true;
|
|
439
|
+
driverRun = (async () => {
|
|
440
|
+
try {
|
|
441
|
+
for (;;) {
|
|
442
|
+
const waitSignal = new Promise((resolve) => {
|
|
443
|
+
wake = resolve;
|
|
444
|
+
});
|
|
445
|
+
const commitHead = commitQueue[0];
|
|
446
|
+
if (commitHead !== void 0 && commitHead.settled) {
|
|
447
|
+
commitQueue.shift();
|
|
448
|
+
await commitHead.commit();
|
|
449
|
+
if (commitHead.mode === "exclusive") exclusiveActive = false;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
const head = pendingQueue[0];
|
|
453
|
+
if (head !== void 0 && !closed && !runController.signal.aborted && !exclusiveActive) {
|
|
454
|
+
const mode = head.classify();
|
|
455
|
+
if (mode === "parallel" ? inFlight.size < host.maxParallelSubCalls && commitQueue.every((entry) => entry.mode !== "exclusive") : inFlight.size === 0 && commitQueue.length === 0) {
|
|
456
|
+
pendingQueue.shift();
|
|
457
|
+
head.mode = mode;
|
|
458
|
+
if (mode === "exclusive") exclusiveActive = true;
|
|
459
|
+
await head.start();
|
|
460
|
+
commitQueue.push(head);
|
|
461
|
+
if (!head.settled) {
|
|
462
|
+
const wrapped = head.flight.finally(() => {
|
|
463
|
+
inFlight.delete(wrapped);
|
|
464
|
+
wakeup();
|
|
465
|
+
});
|
|
466
|
+
inFlight.add(wrapped);
|
|
467
|
+
}
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
if (pendingQueue.length === 0 && commitQueue.length === 0 && inFlight.size === 0) break;
|
|
472
|
+
if ((closed || runController.signal.aborted) && commitQueue.length === 0 && inFlight.size === 0) break;
|
|
473
|
+
await waitSignal;
|
|
474
|
+
}
|
|
475
|
+
} finally {
|
|
476
|
+
driving = false;
|
|
477
|
+
}
|
|
478
|
+
})();
|
|
479
|
+
return driverRun;
|
|
480
|
+
};
|
|
481
|
+
const drainDispatches = async () => {
|
|
482
|
+
closed = true;
|
|
483
|
+
while (pendingQueue.length > 0) pendingQueue.shift().abandon();
|
|
484
|
+
wakeup();
|
|
485
|
+
await drive();
|
|
486
|
+
await Promise.allSettled(inFlight);
|
|
487
|
+
while (commitQueue.length > 0) {
|
|
488
|
+
const entry = commitQueue.shift();
|
|
489
|
+
if (entry.settled) await entry.commit();
|
|
490
|
+
}
|
|
491
|
+
await Promise.allSettled(logWork);
|
|
492
|
+
};
|
|
493
|
+
const runOver = () => closed || runController.signal.aborted || callSignal.aborted;
|
|
494
|
+
const binding = (schema) => async (rawBindingArgs) => {
|
|
495
|
+
if (runOver()) throw new Error(`run_code run is over (${String(runController.signal.reason)}); cannot start ${schema.name}`);
|
|
496
|
+
dispatches++;
|
|
497
|
+
if (dispatches > maxSubCalls) {
|
|
498
|
+
const limitError = new ToolCallLimitExceededError(maxSubCalls, subCallWindowMs);
|
|
499
|
+
runController.abort(limitError);
|
|
500
|
+
throw limitError;
|
|
501
|
+
}
|
|
502
|
+
const normalized = jsonNormalizeArgs(rawBindingArgs);
|
|
503
|
+
const subCallId = ToolCallId(`${exec.callId}:ptc:${subSeq++}`);
|
|
504
|
+
const input = {
|
|
505
|
+
callId: subCallId,
|
|
506
|
+
rootCallId: exec.rootCallId,
|
|
507
|
+
name: schema.name,
|
|
508
|
+
arguments: normalized.dispatched,
|
|
509
|
+
...exec.agent === void 0 ? {} : { agent: exec.agent },
|
|
510
|
+
...exec.toolSet === void 0 ? {} : { toolSet: exec.toolSet },
|
|
511
|
+
schema,
|
|
512
|
+
signal: runController.signal,
|
|
513
|
+
parent: exec.token
|
|
514
|
+
};
|
|
515
|
+
const outcome = await new Promise((resolve, reject) => {
|
|
516
|
+
let parked;
|
|
517
|
+
const settle = (result) => {
|
|
518
|
+
resolve(result.isError ? {
|
|
519
|
+
isError: true,
|
|
520
|
+
message: result.error.message
|
|
521
|
+
} : {
|
|
522
|
+
isError: false,
|
|
523
|
+
value: result.value
|
|
524
|
+
});
|
|
525
|
+
if (exec.agent === void 0) return;
|
|
526
|
+
const agent = exec.agent;
|
|
527
|
+
const task = (async () => {
|
|
528
|
+
const logged = await shapeDispatchLog({
|
|
529
|
+
exec,
|
|
530
|
+
agent,
|
|
531
|
+
subCallId,
|
|
532
|
+
name: schema.name,
|
|
533
|
+
isError: result.isError,
|
|
534
|
+
content: result.content
|
|
535
|
+
});
|
|
536
|
+
agent.session.append("tool/ptc-dispatch", {
|
|
537
|
+
rootCallId: exec.rootCallId,
|
|
538
|
+
parentCallId: exec.callId,
|
|
539
|
+
subCallId,
|
|
540
|
+
name: schema.name,
|
|
541
|
+
arguments: normalized.logged,
|
|
542
|
+
isError: result.isError,
|
|
543
|
+
...result.error?.info === void 0 ? {} : { error: result.error.info },
|
|
544
|
+
content: logged,
|
|
545
|
+
...result.meta === void 0 ? {} : { meta: result.meta }
|
|
546
|
+
});
|
|
547
|
+
})().finally(() => {
|
|
548
|
+
logWork.delete(task);
|
|
549
|
+
});
|
|
550
|
+
logWork.add(task);
|
|
551
|
+
};
|
|
552
|
+
pendingQueue.push({
|
|
553
|
+
flight: Promise.resolve(),
|
|
554
|
+
settled: false,
|
|
555
|
+
classify: () => pipeline.executionMode(input).kind,
|
|
556
|
+
abandon: () => {
|
|
557
|
+
reject(/* @__PURE__ */ new Error(`run_code run is over (${String(runController.signal.reason)}); ${schema.name} tool call abandoned`));
|
|
558
|
+
},
|
|
559
|
+
async start() {
|
|
560
|
+
exec.agent?.session.append("tool/ptc-dispatch-start", {
|
|
561
|
+
rootCallId: exec.rootCallId,
|
|
562
|
+
parentCallId: exec.callId,
|
|
563
|
+
subCallId,
|
|
564
|
+
name: schema.name,
|
|
565
|
+
arguments: normalized.logged
|
|
566
|
+
});
|
|
567
|
+
const prepared = await pipeline.prepare(input);
|
|
568
|
+
if (prepared.kind === "dispatch") {
|
|
569
|
+
this.flight = pipeline.dispatch(prepared.exec).then((dispatchOutcome) => {
|
|
570
|
+
parked = {
|
|
571
|
+
...dispatchOutcome,
|
|
572
|
+
exec: prepared.exec
|
|
573
|
+
};
|
|
574
|
+
this.settled = true;
|
|
575
|
+
});
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
parked = {
|
|
579
|
+
kind: prepared.kind,
|
|
580
|
+
exec: prepared.exec,
|
|
581
|
+
result: prepared.result
|
|
582
|
+
};
|
|
583
|
+
this.settled = true;
|
|
584
|
+
},
|
|
585
|
+
async commit() {
|
|
586
|
+
if (parked === void 0) return;
|
|
587
|
+
const result = await pipeline.complete(parked.exec, parked);
|
|
588
|
+
if (!result.isError && result.content.some((block) => block.type === "image")) exec.deferContext(createUserMessage({
|
|
589
|
+
content: result.content,
|
|
590
|
+
source: { kind: "ptc-mode" }
|
|
591
|
+
}));
|
|
592
|
+
for (const context of result.additionalContexts ?? []) exec.deferContext(context);
|
|
593
|
+
if (result.concludesTurn) exec.concludeTurn();
|
|
594
|
+
settle(result);
|
|
595
|
+
while (logWork.size > host.maxParallelSubCalls) await Promise.race(logWork);
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
wakeup();
|
|
599
|
+
drive();
|
|
600
|
+
});
|
|
601
|
+
if (runOver()) throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${schema.name} result discarded`);
|
|
602
|
+
if (outcome.isError) throw new Error(outcome.message);
|
|
603
|
+
return outcome.value;
|
|
604
|
+
};
|
|
605
|
+
const functions = Object.create(null);
|
|
606
|
+
for (const schema of tools.schemas(exec.agent, exec.toolSet)) {
|
|
607
|
+
if (!host.allowNestedDirectTools && host.isDirect(schema.name)) continue;
|
|
608
|
+
Object.defineProperty(functions, schema.name, {
|
|
609
|
+
enumerable: true,
|
|
610
|
+
value: binding(deepFreeze(schema))
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
try {
|
|
614
|
+
let result;
|
|
615
|
+
try {
|
|
616
|
+
if (exec.agent !== void 0 && typeof runtime.release === "function") {
|
|
617
|
+
const agent = exec.agent;
|
|
618
|
+
let runtimes = host.stateOwners.get(agent);
|
|
619
|
+
if (runtimes === void 0) {
|
|
620
|
+
runtimes = /* @__PURE__ */ new WeakSet();
|
|
621
|
+
host.stateOwners.set(agent, runtimes);
|
|
622
|
+
}
|
|
623
|
+
const provider = host.unwrapRuntime(runtime);
|
|
624
|
+
if (!runtimes.has(provider)) {
|
|
625
|
+
agent.ctx.effect(() => () => runtime.release(agent), "Codex hybrid PTC retained environment");
|
|
626
|
+
runtimes.add(provider);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
const spec = runtime.resolve({
|
|
630
|
+
program: rawArgs.code,
|
|
631
|
+
...exec.agent === void 0 || policy?.mode !== standingPolicy?.mode ? {} : { stateOwner: exec.agent },
|
|
632
|
+
bindings: [{
|
|
633
|
+
global: "tools",
|
|
634
|
+
functions,
|
|
635
|
+
errorClass: {
|
|
636
|
+
name: "ToolCallError",
|
|
637
|
+
memberNameProperty: "toolName"
|
|
638
|
+
}
|
|
639
|
+
}],
|
|
640
|
+
signal: runController.signal,
|
|
641
|
+
...cwd === void 0 ? {} : { cwd },
|
|
642
|
+
...policy === void 0 ? {} : { sandboxPolicy: policy },
|
|
643
|
+
...rawArgs.timeoutMs === void 0 ? {} : { timeoutMs: rawArgs.timeoutMs }
|
|
644
|
+
});
|
|
645
|
+
subCallWindowMs = spec.timeoutMs ?? 6e4;
|
|
646
|
+
maxSubCalls = spec.timeoutMs === null ? Infinity : Math.max(1, Math.floor(spec.timeoutMs / 6e4 * host.maxSubCallsPerMinute));
|
|
647
|
+
result = await runtime.run(spec);
|
|
648
|
+
} finally {
|
|
649
|
+
runController.abort("run_code settled");
|
|
650
|
+
await drainDispatches();
|
|
651
|
+
}
|
|
652
|
+
if (result.error) {
|
|
653
|
+
const limitError = runController.signal.reason instanceof ToolCallLimitExceededError ? runController.signal.reason : void 0;
|
|
654
|
+
if (result.error.kind === "abort" && exec.signal.aborted && limitError === void 0) {
|
|
655
|
+
const message = runtime.retainsState ? `tool call aborted: ${result.error.message}` : "tool call aborted";
|
|
656
|
+
const error = new HarnessError(message, TOOL_ABORTED);
|
|
657
|
+
error.name = "AbortError";
|
|
658
|
+
throw error;
|
|
659
|
+
}
|
|
660
|
+
const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join("\n")}` : "";
|
|
661
|
+
const sandboxText = result.sandbox === void 0 ? "" : `\nFile sandbox: ${result.sandbox.mode}${result.sandbox.enforcement === void 0 ? "" : `; enforcement: ${result.sandbox.enforcement}`}${result.sandbox.denied ? "; operation denied" : ""}.`;
|
|
662
|
+
const failureText = limitError === void 0 || limitError.message === result.error.message ? result.error.message : `${limitError.message}\n${result.error.message}`;
|
|
663
|
+
throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${failureText}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime.sandboxMode) : ""}`);
|
|
664
|
+
}
|
|
665
|
+
return {
|
|
666
|
+
logs: result.logs,
|
|
667
|
+
...result.sandbox === void 0 ? {} : { sandbox: result.sandbox },
|
|
668
|
+
...result.value === void 0 ? {} : { result: result.value }
|
|
669
|
+
};
|
|
670
|
+
} finally {
|
|
671
|
+
callSignal.removeEventListener("abort", onOuterAbort);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
//#endregion
|
|
675
|
+
//#region lib/types/hybrid/codex-hybrid-executor.js
|
|
676
|
+
/** Experimental asymmetric hybrid executor: direct Codex wire tools + `run_code` SDK batching. */
|
|
677
|
+
/** Direct wire tools called natively alongside `run_code` (omitted from `tools:sdk`). */
|
|
678
|
+
const DEFAULT_HYBRID_DIRECT_TOOLS = [
|
|
679
|
+
"exec_command",
|
|
680
|
+
"write_stdin",
|
|
681
|
+
"apply_patch",
|
|
682
|
+
"update_plan",
|
|
683
|
+
"activate_tools",
|
|
684
|
+
"read_image",
|
|
685
|
+
"web_search",
|
|
686
|
+
"ask_user_question",
|
|
687
|
+
"exit_plan_mode",
|
|
688
|
+
"skill",
|
|
689
|
+
"present",
|
|
690
|
+
"ralph",
|
|
691
|
+
"workflow",
|
|
692
|
+
"create_goal",
|
|
693
|
+
"get_goal",
|
|
694
|
+
"update_goal",
|
|
695
|
+
"goal"
|
|
696
|
+
];
|
|
697
|
+
const Config = z.object({
|
|
698
|
+
directTools: z.array(z.string()).default([...DEFAULT_HYBRID_DIRECT_TOOLS]),
|
|
699
|
+
hiddenTools: z.array(z.string()).default([]),
|
|
700
|
+
deferredTools: z.array(z.string()).default([]),
|
|
701
|
+
allowNestedDirectTools: z.boolean().default(false),
|
|
702
|
+
maxParallelToolCalls: z.natural().min(1).default(10),
|
|
703
|
+
maxParallelSubCalls: z.natural().min(1).default(10),
|
|
704
|
+
maxSubCallsPerMinute: z.natural().min(1).default(1024)
|
|
705
|
+
});
|
|
706
|
+
const HYBRID_INSTRUCTION = [
|
|
707
|
+
"This session uses an asymmetric hybrid tool architecture:",
|
|
708
|
+
`- Direct wire tools (such as \`apply_patch\`, \`exec_command\`, \`write_stdin\`, \`update_plan\`, \`activate_tools\`, etc.) are declared natively — call them directly as normal tool calls, NOT inside \`${RUN_CODE_NAME}\`.`,
|
|
709
|
+
`- SDK-only tools (listed under \`tools:sdk\`, such as file reading/searching, \`web_fetch\`, and subagent helpers) are callable ONLY inside \`${RUN_CODE_NAME}\` via \`await tools.<name>(args)\` — direct tool calls to SDK-only names fail.`,
|
|
710
|
+
`- Prefer batching multiple independent reads/searches in a single \`${RUN_CODE_NAME}\` program with \`Promise.all\`, filtering raw data in code, and returning concise findings before applying edits with \`apply_patch\`.`
|
|
711
|
+
].join("\n");
|
|
712
|
+
const RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION = "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI).";
|
|
713
|
+
const RUN_CODE_CONTROLS = {
|
|
714
|
+
timeoutMs: {
|
|
715
|
+
type: "number",
|
|
716
|
+
description: "Positive elapsed-time budget in milliseconds, capped by the deployment maximum."
|
|
717
|
+
},
|
|
718
|
+
sandbox_permissions: {
|
|
719
|
+
type: "string",
|
|
720
|
+
enum: [...ESCALATION_TARGETS],
|
|
721
|
+
description: "Wider sandbox mode for this complete program execution; requires justification and approval."
|
|
722
|
+
},
|
|
723
|
+
justification: {
|
|
724
|
+
type: "string",
|
|
725
|
+
description: "Reason this complete program needs wider access, shown to the user for approval. Use the language of the user's current request."
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
function unwrapRuntime(runtime) {
|
|
729
|
+
let provider = runtime;
|
|
730
|
+
for (;;) {
|
|
731
|
+
const original = provider[symbols.original];
|
|
732
|
+
if (original === void 0) return provider;
|
|
733
|
+
provider = original;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
/** Asymmetric hybrid executor: direct Codex tools on the wire + SDK batching via `run_code`. */
|
|
737
|
+
var CodexHybridExecutor = class {
|
|
738
|
+
ctx;
|
|
739
|
+
sections;
|
|
740
|
+
pipeline;
|
|
741
|
+
config;
|
|
742
|
+
directTools;
|
|
743
|
+
hiddenTools;
|
|
744
|
+
calls;
|
|
745
|
+
runCodeTool;
|
|
746
|
+
constructor(ctx, config = {}) {
|
|
747
|
+
this.ctx = ctx;
|
|
748
|
+
this.config = Config(config);
|
|
749
|
+
this.directTools = new Set(this.config.directTools.map((item) => item.trim()).filter(Boolean));
|
|
750
|
+
this.hiddenTools = new Set(this.config.hiddenTools.map((item) => item.trim()).filter(Boolean));
|
|
751
|
+
this.calls = new HybridProgramCalls(ctx);
|
|
752
|
+
const tools = ctx.tools;
|
|
753
|
+
this.sections = [{
|
|
754
|
+
name: "tools:hybrid",
|
|
755
|
+
order: ctx.systemPrompt.getSectionOrder("PTC_ONLY"),
|
|
756
|
+
text: HYBRID_INSTRUCTION,
|
|
757
|
+
interpolate: false
|
|
758
|
+
}, {
|
|
759
|
+
name: "tools:sdk",
|
|
760
|
+
order: ctx.systemPrompt.getSectionOrder("TOOLS_SDK"),
|
|
761
|
+
text: (visibleTools) => this.renderSdk(visibleTools),
|
|
762
|
+
interpolate: false
|
|
763
|
+
}];
|
|
764
|
+
this.pipeline = new ToolExecutionPipeline(ctx, {
|
|
765
|
+
get: (name, scope, toolSet) => this.hiddenTools.has(name) ? void 0 : name === RUN_CODE_NAME ? this.requireRunCodeTool() : tools.executable(name, scope, toolSet),
|
|
766
|
+
reject: (name, nested) => {
|
|
767
|
+
if (this.hiddenTools.has(name)) return new ToolNotFoundError(name, `\`${name}\` is hidden in this preset`);
|
|
768
|
+
if (!nested) {
|
|
769
|
+
if (name === RUN_CODE_NAME || this.isDirectTool(name)) return void 0;
|
|
770
|
+
return new ToolNotFoundError(name, `only callable inside \`${RUN_CODE_NAME}\` via \`await tools.${name}(...)\` in hybrid mode`);
|
|
771
|
+
}
|
|
772
|
+
if (!this.config.allowNestedDirectTools && (name === RUN_CODE_NAME || this.isDirectTool(name))) return new ToolNotFoundError(name, `call \`${name}\` directly as a tool call rather than inside \`${RUN_CODE_NAME}\``);
|
|
773
|
+
}
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
isDirectTool(name) {
|
|
777
|
+
return this.directTools.has(name);
|
|
778
|
+
}
|
|
779
|
+
describe(tools) {
|
|
780
|
+
return { schemas: [...tools.filter((definition) => !this.hiddenTools.has(definition.name) && this.isDirectTool(definition.name)).map((definition) => projectToolSchema(definition, false)), projectToolSchema(this.requireRunCodeTool(), false)] };
|
|
781
|
+
}
|
|
782
|
+
renderSdk(tools) {
|
|
783
|
+
const runtime = requirePtcRuntime(this.ctx);
|
|
784
|
+
return renderHybridToolsSdk(tools.filter((definition) => !this.hiddenTools.has(definition.name) && (this.config.allowNestedDirectTools || !this.isDirectTool(definition.name))).map((definition) => ({
|
|
785
|
+
...projectToolSchema(definition, false),
|
|
786
|
+
output: definition.output.schema
|
|
787
|
+
})), runtime.language, resolveProgramFormat(runtime));
|
|
788
|
+
}
|
|
789
|
+
execute(input) {
|
|
790
|
+
return executeToolBatch(input, this.pipeline, () => this.config.maxParallelToolCalls);
|
|
791
|
+
}
|
|
792
|
+
async reset(agent) {
|
|
793
|
+
const runtime = requirePtcRuntime(this.ctx);
|
|
794
|
+
if (!runtime.retainsState) throw new CodeResetFailedError("The PTC runtime does not retain an environment");
|
|
795
|
+
try {
|
|
796
|
+
await this.calls.reset(agent.session.id, () => runtime.release(agent), () => {
|
|
797
|
+
agent.inject(createUserMessage({
|
|
798
|
+
content: [{
|
|
799
|
+
type: "text",
|
|
800
|
+
text: "Program environment reset; retained variables cleared. Completed tool effects remain."
|
|
801
|
+
}],
|
|
802
|
+
source: { kind: "ptc-mode" }
|
|
803
|
+
}));
|
|
804
|
+
});
|
|
805
|
+
} catch (error) {
|
|
806
|
+
throw new CodeResetFailedError(`Program environment reset failed: ${toolErrorMessage(error)}. State may not be cleared; retry the host reset before running more code.`);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
requireRunCodeTool() {
|
|
810
|
+
this.runCodeTool ??= this.createRunCodeTool();
|
|
811
|
+
return this.runCodeTool;
|
|
812
|
+
}
|
|
813
|
+
createRunCodeTool() {
|
|
814
|
+
const ctx = this.ctx;
|
|
815
|
+
const config = this.config;
|
|
816
|
+
const calls = this.calls;
|
|
817
|
+
const stateOwners = /* @__PURE__ */ new WeakMap();
|
|
818
|
+
const runHost = {
|
|
819
|
+
ctx,
|
|
820
|
+
pipeline: this.pipeline,
|
|
821
|
+
allowNestedDirectTools: config.allowNestedDirectTools,
|
|
822
|
+
maxParallelSubCalls: config.maxParallelSubCalls,
|
|
823
|
+
maxSubCallsPerMinute: config.maxSubCallsPerMinute,
|
|
824
|
+
stateOwners,
|
|
825
|
+
isDirect: (toolName) => this.isDirectTool(toolName),
|
|
826
|
+
unwrapRuntime
|
|
827
|
+
};
|
|
828
|
+
const definition = defineTool({
|
|
829
|
+
name: RUN_CODE_NAME,
|
|
830
|
+
description: "Execute a program against SDK tools declared in `tools:sdk`.",
|
|
831
|
+
parameters: {
|
|
832
|
+
code: {
|
|
833
|
+
type: "string",
|
|
834
|
+
required: true,
|
|
835
|
+
description: "The program to execute."
|
|
836
|
+
},
|
|
837
|
+
description: {
|
|
838
|
+
type: "string",
|
|
839
|
+
required: true,
|
|
840
|
+
description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION
|
|
841
|
+
},
|
|
842
|
+
...RUN_CODE_CONTROLS
|
|
843
|
+
},
|
|
844
|
+
output: {
|
|
845
|
+
schema: {
|
|
846
|
+
type: "object",
|
|
847
|
+
additionalProperties: false,
|
|
848
|
+
properties: {
|
|
849
|
+
logs: {
|
|
850
|
+
type: "array",
|
|
851
|
+
required: true,
|
|
852
|
+
items: { type: "string" }
|
|
853
|
+
},
|
|
854
|
+
result: { type: "json" },
|
|
855
|
+
sandbox: {
|
|
856
|
+
type: "object",
|
|
857
|
+
additionalProperties: false,
|
|
858
|
+
properties: {
|
|
859
|
+
mode: {
|
|
860
|
+
type: "string",
|
|
861
|
+
required: true,
|
|
862
|
+
enum: [
|
|
863
|
+
"read-only",
|
|
864
|
+
"workspace-write",
|
|
865
|
+
"danger-full-access"
|
|
866
|
+
]
|
|
867
|
+
},
|
|
868
|
+
denied: {
|
|
869
|
+
type: "boolean",
|
|
870
|
+
required: true
|
|
871
|
+
},
|
|
872
|
+
enforcement: {
|
|
873
|
+
type: "string",
|
|
874
|
+
enum: ["full", "partial"]
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
},
|
|
880
|
+
render: (_args, value) => {
|
|
881
|
+
const rendered = value.result === void 0 ? "" : renderRunCodeValue(value.result);
|
|
882
|
+
const parts = [value.logs.join("\n"), rendered].filter((part) => part.length > 0);
|
|
883
|
+
if (value.sandbox?.enforcement === "partial") parts.push("File sandbox enforcement is partial on this host.");
|
|
884
|
+
if (value.sandbox?.denied) parts.push(`The ${value.sandbox.mode} file sandbox denied an operation.${escalationGuidance(ctx.get("ptcRuntime")?.sandboxMode)}`);
|
|
885
|
+
return [{
|
|
886
|
+
type: "text",
|
|
887
|
+
text: parts.length > 0 ? parts.join("\n") : "(run_code completed with no output)"
|
|
888
|
+
}];
|
|
889
|
+
}
|
|
890
|
+
},
|
|
891
|
+
async execute(rawArgs, exec) {
|
|
892
|
+
if (rawArgs.description.trim().length === 0) throw new Error("invalid description: expected a non-empty string");
|
|
893
|
+
const runtime = requirePtcRuntime(ctx);
|
|
894
|
+
const run = (callSignal) => executeHybridRunCode(runHost, rawArgs, exec, callSignal);
|
|
895
|
+
return exec.agent === void 0 || runtime.sandboxMode === void 0 && !runtime.retainsState ? run(exec.signal) : calls.run(exec.agent.session.id, exec.signal, () => runtime.sandboxMode === void 0 ? void 0 : resolveSandboxPolicy(ctx, exec).mode, run);
|
|
896
|
+
},
|
|
897
|
+
presentCall: (args) => ({
|
|
898
|
+
card: "generic",
|
|
899
|
+
title: args.description,
|
|
900
|
+
kind: "execute",
|
|
901
|
+
rawInput: args.code
|
|
902
|
+
})
|
|
903
|
+
});
|
|
904
|
+
Object.defineProperty(definition, "description", {
|
|
905
|
+
enumerable: true,
|
|
906
|
+
get: () => resolveRunCodeDescription(requirePtcRuntime(ctx))
|
|
907
|
+
});
|
|
908
|
+
Object.defineProperty(definition, "parameters", {
|
|
909
|
+
enumerable: true,
|
|
910
|
+
get: () => {
|
|
911
|
+
const runtime = requirePtcRuntime(ctx);
|
|
912
|
+
const codeDescription = runtime.language === "python" ? "The Python program to execute against `tools`." : "The TypeScript program (function body supporting top-level `await` and `return`) to execute against `tools`.";
|
|
913
|
+
return parameterSchemaSpecToJsonSchema({
|
|
914
|
+
code: {
|
|
915
|
+
type: "string",
|
|
916
|
+
required: true,
|
|
917
|
+
description: codeDescription
|
|
918
|
+
},
|
|
919
|
+
description: {
|
|
920
|
+
type: "string",
|
|
921
|
+
required: true,
|
|
922
|
+
description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION
|
|
923
|
+
},
|
|
924
|
+
...runtime.timeout === void 0 ? {} : { timeoutMs: {
|
|
925
|
+
...RUN_CODE_CONTROLS.timeoutMs,
|
|
926
|
+
description: `Positive elapsed-time budget in milliseconds, including nested waits. Default ${runtime.timeout.defaultMs}; capped at ${runtime.timeout.maxMs}.`
|
|
927
|
+
} },
|
|
928
|
+
...runtime.sandboxMode === void 0 ? {} : {
|
|
929
|
+
sandbox_permissions: RUN_CODE_CONTROLS.sandbox_permissions,
|
|
930
|
+
justification: RUN_CODE_CONTROLS.justification
|
|
931
|
+
}
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
});
|
|
935
|
+
return definition;
|
|
936
|
+
}
|
|
937
|
+
};
|
|
938
|
+
//#endregion
|
|
939
|
+
//#region lib/types/policy/deferred-tools.js
|
|
940
|
+
const ACTIVATE_TOOLS_NAME = "activate_tools";
|
|
941
|
+
const CODEX_HYBRID_DEFAULTS_SERVICE = "codexHybridDefaults";
|
|
942
|
+
const HYBRID_DEFAULTS_KEY = Symbol.for("@shuind/dsh-codex-harness:hybrid-defaults:v1");
|
|
943
|
+
const HYBRID_HIDDEN_KEY = Symbol.for("@shuind/dsh-codex-harness:hybrid-hidden:v1");
|
|
944
|
+
function scopeSetMap(registryKey) {
|
|
945
|
+
const registry = globalThis;
|
|
946
|
+
const existing = registry[registryKey];
|
|
947
|
+
if (existing instanceof WeakMap) return existing;
|
|
948
|
+
const created = /* @__PURE__ */ new WeakMap();
|
|
949
|
+
registry[registryKey] = created;
|
|
950
|
+
return created;
|
|
951
|
+
}
|
|
952
|
+
function registerScopedToolSet(ctx, registryKey, toolNames, serviceKey) {
|
|
953
|
+
const copy = new Set(toolNames);
|
|
954
|
+
const scope = scopeOf(ctx);
|
|
955
|
+
const disposers = [];
|
|
956
|
+
if (scope !== void 0) {
|
|
957
|
+
const map = scopeSetMap(registryKey);
|
|
958
|
+
map.set(scope, copy);
|
|
959
|
+
disposers.push(() => {
|
|
960
|
+
if (map.get(scope) === copy) map.delete(scope);
|
|
961
|
+
});
|
|
962
|
+
} else if (serviceKey === "deferredTools" && typeof ctx.provide === "function") ctx.provide(CODEX_HYBRID_DEFAULTS_SERVICE, { deferredTools: copy });
|
|
963
|
+
return () => {
|
|
964
|
+
for (const dispose of disposers.splice(0).reverse()) dispose();
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
/** Register preset-level default deferred tools for descendant Agent and catalog scopes. */
|
|
968
|
+
function registerHybridDefaultDeferredTools(ctx, deferredTools) {
|
|
969
|
+
return registerScopedToolSet(ctx, HYBRID_DEFAULTS_KEY, deferredTools, "deferredTools");
|
|
970
|
+
}
|
|
971
|
+
/** Register preset-level hidden tools for descendant Agent and catalog scopes. */
|
|
972
|
+
function registerHybridDefaultHiddenTools(ctx, hiddenTools) {
|
|
973
|
+
return registerScopedToolSet(ctx, HYBRID_HIDDEN_KEY, hiddenTools, "hiddenTools");
|
|
974
|
+
}
|
|
975
|
+
const MAX_SUMMARY_CHARS = 140;
|
|
976
|
+
/** Collapse a tool description to a single-line summary capped for prompt stability. */
|
|
977
|
+
function summarizeToolDescription(description) {
|
|
978
|
+
const collapsed = (description.trim().split(/\r?\n/u)[0] ?? "").replace(/\s+/gu, " ").trim();
|
|
979
|
+
if (collapsed.length === 0) return "No description provided.";
|
|
980
|
+
const sentenceEnd = collapsed.search(/[.!?。!?](?:\s|$)/u);
|
|
981
|
+
const sentence = sentenceEnd >= 0 ? collapsed.slice(0, sentenceEnd + 1).trim() : collapsed;
|
|
982
|
+
if (sentence.length <= MAX_SUMMARY_CHARS) return sentence;
|
|
983
|
+
return `${sentence.slice(0, 137).trimEnd()}...`;
|
|
984
|
+
}
|
|
985
|
+
/** Deterministic catalog guidance naming every deferred tool for `activate_tools`. */
|
|
986
|
+
function buildDeferredToolsGuidance(definitions) {
|
|
987
|
+
const sorted = [...definitions].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
988
|
+
return [`Deferred tools are omitted until activated. Call \`${ACTIVATE_TOOLS_NAME}\` with exact names to enable them on the next model step (do not call a deferred tool in the same step):`, ...sorted.map((def) => `- \`${def.name}\`: ${summarizeToolDescription(def.description)}`)].join("\n");
|
|
989
|
+
}
|
|
990
|
+
function wrapDeferredExecution(definition, onTouch) {
|
|
991
|
+
const descriptors = Object.getOwnPropertyDescriptors(definition);
|
|
992
|
+
descriptors.execute = {
|
|
993
|
+
value(args, exec) {
|
|
994
|
+
onTouch(definition.name);
|
|
995
|
+
return Reflect.apply(definition.execute, this, [args, exec]);
|
|
996
|
+
},
|
|
997
|
+
enumerable: true,
|
|
998
|
+
configurable: true
|
|
999
|
+
};
|
|
1000
|
+
return Object.defineProperties(Object.create(Object.getPrototypeOf(definition)), descriptors);
|
|
1001
|
+
}
|
|
1002
|
+
/** Build the per-Agent `activate_tools` capability that flips `when` admission on next step. */
|
|
1003
|
+
function createActivateToolsDefinition(allowedDefinitions, activated, onTouch) {
|
|
1004
|
+
const availableNames = [...allowedDefinitions.keys()].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
1005
|
+
return defineTool({
|
|
1006
|
+
name: ACTIVATE_TOOLS_NAME,
|
|
1007
|
+
description: "Activate deferred tools by name so their schemas become callable on the next model step.",
|
|
1008
|
+
parameters: { names: {
|
|
1009
|
+
type: "array",
|
|
1010
|
+
required: true,
|
|
1011
|
+
items: { type: "string" },
|
|
1012
|
+
description: "Exact deferred tool names to activate (1-32)."
|
|
1013
|
+
} },
|
|
1014
|
+
isConcurrencySafe: () => true,
|
|
1015
|
+
output: {
|
|
1016
|
+
schema: {
|
|
1017
|
+
type: "object",
|
|
1018
|
+
additionalProperties: false,
|
|
1019
|
+
properties: {
|
|
1020
|
+
activated: {
|
|
1021
|
+
type: "array",
|
|
1022
|
+
required: true,
|
|
1023
|
+
items: { type: "string" }
|
|
1024
|
+
},
|
|
1025
|
+
alreadyActive: {
|
|
1026
|
+
type: "array",
|
|
1027
|
+
required: true,
|
|
1028
|
+
items: { type: "string" }
|
|
1029
|
+
},
|
|
1030
|
+
unknown: {
|
|
1031
|
+
type: "array",
|
|
1032
|
+
required: true,
|
|
1033
|
+
items: { type: "string" }
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
},
|
|
1037
|
+
render: (_args, value) => {
|
|
1038
|
+
const lines = [];
|
|
1039
|
+
if (value.activated.length > 0) lines.push(`Activated for the next step: ${value.activated.join(", ")}. Wait for the next step before calling them.`);
|
|
1040
|
+
if (value.alreadyActive.length > 0) lines.push(`Already active: ${value.alreadyActive.join(", ")}.`);
|
|
1041
|
+
if (value.unknown.length > 0) {
|
|
1042
|
+
const valid = availableNames.length > 0 ? availableNames.join(", ") : "(none)";
|
|
1043
|
+
lines.push(`Unknown deferred tools: ${value.unknown.join(", ")}. Available: ${valid}.`);
|
|
1044
|
+
}
|
|
1045
|
+
return [{
|
|
1046
|
+
type: "text",
|
|
1047
|
+
text: lines.length > 0 ? lines.join("\n") : "No tools activated."
|
|
1048
|
+
}];
|
|
1049
|
+
}
|
|
1050
|
+
},
|
|
1051
|
+
async execute(args) {
|
|
1052
|
+
const names = args.names;
|
|
1053
|
+
if (!Array.isArray(names) || names.length < 1 || names.length > 32) throw new Error(`${ACTIVATE_TOOLS_NAME}: names must contain between 1 and 32 tool names`);
|
|
1054
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1055
|
+
const newlyActivated = [];
|
|
1056
|
+
const alreadyActive = [];
|
|
1057
|
+
const unknown = [];
|
|
1058
|
+
for (const raw of names) {
|
|
1059
|
+
if (typeof raw !== "string") throw new Error(`${ACTIVATE_TOOLS_NAME}: every entry in names must be a string`);
|
|
1060
|
+
const name = raw.trim();
|
|
1061
|
+
if (name.length === 0) throw new Error(`${ACTIVATE_TOOLS_NAME}: tool names must be non-empty strings`);
|
|
1062
|
+
if (seen.has(name)) continue;
|
|
1063
|
+
seen.add(name);
|
|
1064
|
+
if (!allowedDefinitions.has(name)) unknown.push(name);
|
|
1065
|
+
else if (activated.has(name)) {
|
|
1066
|
+
onTouch?.(name);
|
|
1067
|
+
alreadyActive.push(name);
|
|
1068
|
+
} else {
|
|
1069
|
+
activated.add(name);
|
|
1070
|
+
onTouch?.(name);
|
|
1071
|
+
newlyActivated.push(name);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
return {
|
|
1075
|
+
activated: newlyActivated,
|
|
1076
|
+
alreadyActive,
|
|
1077
|
+
unknown
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Shadow deferred definitions with step-conditional admission and publish
|
|
1084
|
+
* `activate_tools` + a deterministic prompt section inside the Agent scope.
|
|
1085
|
+
* Cold tools untouched for more than `DEFERRED_RECENT_TURN_WINDOW` turns are
|
|
1086
|
+
* reclaimed after local or remote compaction completes.
|
|
1087
|
+
*/
|
|
1088
|
+
function* yieldDeferredToolsOverlay(tools, systemPrompt, definitions, agent) {
|
|
1089
|
+
const sorted = [...definitions].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
1090
|
+
if (sorted.length === 0) return;
|
|
1091
|
+
const activated = /* @__PURE__ */ new Set();
|
|
1092
|
+
const allowedDefinitions = /* @__PURE__ */ new Map();
|
|
1093
|
+
let currentTurn = typeof agent?.ctx?.get === "function" ? agent.ctx.get("agents")?.turnBoundaryOf(agent.session).lastTurn ?? 0 : 0;
|
|
1094
|
+
const lastTouchTurn = /* @__PURE__ */ new Map();
|
|
1095
|
+
const touch = (name) => {
|
|
1096
|
+
lastTouchTurn.set(name, currentTurn);
|
|
1097
|
+
};
|
|
1098
|
+
const isCold = (name) => {
|
|
1099
|
+
const touched = lastTouchTurn.get(name);
|
|
1100
|
+
return touched === void 0 || currentTurn - touched > 2;
|
|
1101
|
+
};
|
|
1102
|
+
for (const definition of sorted) {
|
|
1103
|
+
allowedDefinitions.set(definition.name, definition);
|
|
1104
|
+
yield tools.register(wrapDeferredExecution(definition, touch), { when: () => activated.has(definition.name) });
|
|
1105
|
+
}
|
|
1106
|
+
yield tools.register(createActivateToolsDefinition(allowedDefinitions, activated, touch));
|
|
1107
|
+
yield systemPrompt.section({
|
|
1108
|
+
name: "codex:deferred-tools",
|
|
1109
|
+
order: 1018,
|
|
1110
|
+
interpolate: false,
|
|
1111
|
+
text: buildDeferredToolsGuidance(sorted)
|
|
1112
|
+
});
|
|
1113
|
+
if (agent !== void 0 && typeof agent.ctx.on === "function") {
|
|
1114
|
+
let pending;
|
|
1115
|
+
yield agent.ctx.on("session/event", (session, event) => {
|
|
1116
|
+
if (session.id !== agent.session.id) return;
|
|
1117
|
+
if (event.type === "turn/start") {
|
|
1118
|
+
if (typeof event.data.turn === "number" && event.data.turn > currentTurn) currentTurn = event.data.turn;
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
if (event.type === "compaction/start") {
|
|
1122
|
+
if (typeof event.data.turn === "number" && event.data.turn > currentTurn) currentTurn = event.data.turn;
|
|
1123
|
+
pending = {
|
|
1124
|
+
compactionId: event.data.compactionId,
|
|
1125
|
+
cold: new Set([...activated].filter(isCold)),
|
|
1126
|
+
hasSummary: false
|
|
1127
|
+
};
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (event.type === "compaction/summary") {
|
|
1131
|
+
if (pending === void 0 || event.data.compactionId !== pending.compactionId) return;
|
|
1132
|
+
pending.hasSummary = true;
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
if (event.type === "compaction/end") {
|
|
1136
|
+
if (pending === void 0 || event.data.compactionId !== pending.compactionId) return;
|
|
1137
|
+
const current = pending;
|
|
1138
|
+
pending = void 0;
|
|
1139
|
+
if (event.data.error !== void 0 || !current.hasSummary) return;
|
|
1140
|
+
for (const name of current.cold) {
|
|
1141
|
+
if (!isCold(name)) continue;
|
|
1142
|
+
activated.delete(name);
|
|
1143
|
+
lastTouchTurn.delete(name);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}, { global: true });
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
//#endregion
|
|
1150
|
+
//#region lib/types/entries/hybrid-executor.js
|
|
1151
|
+
const name = "codex-hybrid-executor";
|
|
1152
|
+
const inject = [
|
|
1153
|
+
"tools",
|
|
1154
|
+
"systemPrompt",
|
|
1155
|
+
"ptcRuntime"
|
|
1156
|
+
];
|
|
1157
|
+
/** Mount `CodexHybridExecutor` and publish default hidden/deferred tools for the owning scope. */
|
|
1158
|
+
function apply(ctx, config = {}) {
|
|
1159
|
+
const resolved = Config(config);
|
|
1160
|
+
const executor = new CodexHybridExecutor(ctx, resolved);
|
|
1161
|
+
ctx.tools.setExecutor(executor);
|
|
1162
|
+
const hiddenSet = new Set(resolved.hiddenTools.map((item) => item.trim()).filter(Boolean));
|
|
1163
|
+
const deferredSet = new Set(resolved.deferredTools.map((item) => item.trim()).filter(Boolean));
|
|
1164
|
+
if (hiddenSet.size > 0) ctx.effect(() => registerHybridDefaultHiddenTools(ctx, hiddenSet), "codex-hybrid: default hidden tools");
|
|
1165
|
+
if (deferredSet.size > 0) ctx.effect(() => registerHybridDefaultDeferredTools(ctx, deferredSet), "codex-hybrid: default deferred tools");
|
|
1166
|
+
if ((deferredSet.size > 0 || hiddenSet.size > 0) && typeof ctx.on === "function") {
|
|
1167
|
+
const parentScope = scopeOf(ctx);
|
|
1168
|
+
ctx.on("agent/created", ({ agent }) => {
|
|
1169
|
+
if (agent.ctx.get("codexToolPolicy") !== void 0) return;
|
|
1170
|
+
if (parentScope !== void 0 && scopeParentOf(agent) !== parentScope) return;
|
|
1171
|
+
const agentTools = agent.ctx.get("tools");
|
|
1172
|
+
const agentPrompt = agent.ctx.get("systemPrompt");
|
|
1173
|
+
if (agentTools === void 0 || agentPrompt === void 0) return;
|
|
1174
|
+
if (agentTools.get("activate_tools", agent) !== void 0) return;
|
|
1175
|
+
const upstream = scopeParentOf(agent);
|
|
1176
|
+
const hiddenUpstream = [...hiddenSet].filter((tool) => {
|
|
1177
|
+
const visible = agentTools.get(tool, agent);
|
|
1178
|
+
return visible !== void 0 && agentTools.get(tool, upstream) === visible;
|
|
1179
|
+
});
|
|
1180
|
+
const deferredDefs = agentTools.definitions(upstream).filter((def) => def.name !== "activate_tools" && !hiddenSet.has(def.name) && deferredSet.has(def.name) && agentTools.get(def.name, agent) !== void 0 && agentTools.executable(def.name, agent) === def && agentTools.get(def.name, upstream) === def);
|
|
1181
|
+
if (hiddenUpstream.length === 0 && deferredDefs.length === 0) return;
|
|
1182
|
+
agent.ctx.effect(function* () {
|
|
1183
|
+
if (hiddenUpstream.length > 0) yield agentTools.restrict({ deny: hiddenUpstream });
|
|
1184
|
+
if (deferredDefs.length > 0) yield* yieldDeferredToolsOverlay(agentTools, agentPrompt, deferredDefs, agent);
|
|
1185
|
+
}, "codex-hybrid: standalone baseline tools");
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
var hybrid_executor_default = {
|
|
1190
|
+
name,
|
|
1191
|
+
inject,
|
|
1192
|
+
Config,
|
|
1193
|
+
apply
|
|
1194
|
+
};
|
|
1195
|
+
//#endregion
|
|
1196
|
+
export { CodeResetFailedError, CodeRunFailedError, CodexHybridExecutor, Config, DEFAULT_HYBRID_DIRECT_TOOLS, apply, hybrid_executor_default as default, inject, name };
|