@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.
Files changed (200) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +38 -50
  3. package/RELEASE.md +61 -0
  4. package/assets/codex.svg +5 -0
  5. package/cordis.patch.yml +181 -6
  6. package/docs/preset-library.md +33 -23
  7. package/docs/tool-policy-benchmark.json +310 -0
  8. package/docs/tool-policy.md +148 -0
  9. package/lib/client.js +4774 -2416
  10. package/lib/compact-command.js +416 -0
  11. package/lib/compaction.js +141 -12
  12. package/lib/hybrid-executor.js +1196 -0
  13. package/lib/index.js +3658 -2334
  14. package/lib/preferences.js +117 -0
  15. package/lib/tool-policy.js +2422 -0
  16. package/lib/typert.js +86 -79
  17. package/lib/types/client/activity.d.ts +33 -9
  18. package/lib/types/client/activity.js +4 -3
  19. package/lib/types/client/desktop.d.ts +67 -0
  20. package/lib/types/client/desktop.js +229 -0
  21. package/lib/types/client/index.d.ts +207 -110
  22. package/lib/types/client/index.js +99 -492
  23. package/lib/types/client/policy-drafts.d.ts +25 -0
  24. package/lib/types/client/policy-drafts.js +47 -0
  25. package/lib/types/client/policy-locale.d.ts +260 -0
  26. package/lib/types/client/policy-locale.js +357 -0
  27. package/lib/types/client/preset-manager.d.ts +38 -10
  28. package/lib/types/client/preset-manager.js +235 -185
  29. package/lib/types/client/preset-requests.d.ts +12 -0
  30. package/lib/types/client/preset-requests.js +101 -0
  31. package/lib/types/client/tool-policy.d.ts +33 -0
  32. package/lib/types/client/tool-policy.js +336 -0
  33. package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
  34. package/lib/types/contracts/preset-editor-schema.js +95 -0
  35. package/lib/types/{prompt.js → contracts/prompt.js} +13 -7
  36. package/lib/types/{settings.d.ts → contracts/settings.d.ts} +11 -4
  37. package/lib/types/{settings.js → contracts/settings.js} +22 -6
  38. package/lib/types/contracts/tool-policy-contract.d.ts +63 -0
  39. package/lib/types/contracts/tool-policy-contract.js +33 -0
  40. package/lib/types/contracts/ui-contracts.d.ts +92 -0
  41. package/lib/types/contracts/ui-contracts.js +83 -0
  42. package/lib/types/entries/client.d.ts +10 -0
  43. package/lib/types/entries/client.js +10 -0
  44. package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
  45. package/lib/types/entries/compact-command.js +176 -0
  46. package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +15 -3
  47. package/lib/types/{compaction.js → entries/compaction.js} +47 -11
  48. package/lib/types/entries/hybrid-executor.d.ts +19 -0
  49. package/lib/types/entries/hybrid-executor.js +57 -0
  50. package/lib/types/entries/index.d.ts +66 -0
  51. package/lib/types/entries/index.js +192 -0
  52. package/lib/types/entries/preferences.d.ts +11 -0
  53. package/lib/types/entries/preferences.js +16 -0
  54. package/lib/types/entries/tool-policy.d.ts +97 -0
  55. package/lib/types/entries/tool-policy.js +158 -0
  56. package/lib/types/entries/typert.host.d.ts +23 -0
  57. package/lib/types/entries/typert.host.js +24 -0
  58. package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
  59. package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
  60. package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
  61. package/lib/types/hybrid/hybrid-sdk.js +196 -0
  62. package/lib/types/hybrid/program-calls.d.ts +28 -0
  63. package/lib/types/hybrid/program-calls.js +193 -0
  64. package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
  65. package/lib/types/hybrid/subcall-scheduler.js +343 -0
  66. package/lib/types/policy/deferred-tools.d.ts +42 -0
  67. package/lib/types/policy/deferred-tools.js +264 -0
  68. package/lib/types/policy/overlay-installer.d.ts +12 -0
  69. package/lib/types/policy/overlay-installer.js +179 -0
  70. package/lib/types/policy/rule-resolver.d.ts +94 -0
  71. package/lib/types/policy/rule-resolver.js +114 -0
  72. package/lib/types/policy/tool-capabilities.d.ts +33 -0
  73. package/lib/types/policy/tool-capabilities.js +46 -0
  74. package/lib/types/{activity.d.ts → presets/activity.d.ts} +3 -5
  75. package/lib/types/{activity.js → presets/activity.js} +51 -27
  76. package/lib/types/presets/desktop-preset.d.ts +22 -0
  77. package/lib/types/presets/desktop-preset.js +43 -0
  78. package/lib/types/presets/preset-editor.d.ts +47 -0
  79. package/lib/types/presets/preset-editor.js +81 -0
  80. package/lib/types/presets/preset-prompt-catalog.d.ts +23 -0
  81. package/lib/types/presets/preset-prompt-catalog.js +215 -0
  82. package/lib/types/presets/preset-tool-catalog.d.ts +5 -0
  83. package/lib/types/presets/preset-tool-catalog.js +58 -0
  84. package/lib/types/presets/runtime-enhancements.d.ts +45 -0
  85. package/lib/types/presets/runtime-enhancements.js +349 -0
  86. package/lib/types/presets/small-window-compaction.d.ts +15 -0
  87. package/lib/types/presets/small-window-compaction.js +121 -0
  88. package/lib/types/responses/compact-checkpoint.d.ts +27 -0
  89. package/lib/types/responses/compact-checkpoint.js +257 -0
  90. package/lib/types/responses/fetch-transport.d.ts +16 -0
  91. package/lib/types/responses/fetch-transport.js +257 -0
  92. package/lib/types/responses/remote-compact.d.ts +13 -0
  93. package/lib/types/responses/remote-compact.js +319 -0
  94. package/lib/types/responses/sse-diagnostics.d.ts +9 -0
  95. package/lib/types/responses/sse-diagnostics.js +157 -0
  96. package/lib/types/responses/wire-rewrite.d.ts +35 -0
  97. package/lib/types/responses/wire-rewrite.js +237 -0
  98. package/lib/types/tools/exec-output.d.ts +58 -0
  99. package/lib/types/tools/exec-output.js +173 -0
  100. package/lib/types/tools/exec-plan-tools.d.ts +37 -0
  101. package/lib/types/tools/exec-plan-tools.js +265 -0
  102. package/lib/types/tools/exec-runner.d.ts +21 -0
  103. package/lib/types/tools/exec-runner.js +385 -0
  104. package/lib/types/tools/patch-tool.d.ts +16 -0
  105. package/lib/types/tools/patch-tool.js +258 -0
  106. package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
  107. package/lib/types/{patch.js → tools/patch.js} +96 -21
  108. package/locale/en.json +6 -0
  109. package/locale/hybrid-executor/en.json +6 -0
  110. package/locale/hybrid-executor/zh.json +6 -0
  111. package/locale/tool-policy/en.json +6 -0
  112. package/locale/tool-policy/zh.json +6 -0
  113. package/locale/zh.json +6 -0
  114. package/package.json +297 -299
  115. package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
  116. package/presets/codex-hybrid/preset.yml +3 -0
  117. package/scripts/benchmark-tool-policy.mjs +186 -0
  118. package/scripts/build-preset.mjs +19 -0
  119. package/scripts/clean-build.mjs +11 -0
  120. package/src/client/activity.ts +83 -0
  121. package/src/client/desktop.tsx +276 -0
  122. package/src/client/index.tsx +391 -0
  123. package/src/client/policy-drafts.ts +56 -0
  124. package/src/client/policy-locale.ts +362 -0
  125. package/src/client/preset-manager.tsx +376 -0
  126. package/src/client/preset-requests.ts +113 -0
  127. package/src/client/tool-policy.tsx +402 -0
  128. package/src/contracts/preset-editor-schema.ts +110 -0
  129. package/src/contracts/prompt.ts +66 -0
  130. package/src/contracts/settings.ts +103 -0
  131. package/src/contracts/tool-policy-contract.ts +93 -0
  132. package/src/contracts/ui-contracts.ts +173 -0
  133. package/src/entries/client.tsx +14 -0
  134. package/src/entries/compact-command.ts +256 -0
  135. package/src/entries/compaction.ts +218 -0
  136. package/src/entries/hybrid-executor.ts +76 -0
  137. package/src/entries/index.ts +298 -0
  138. package/src/entries/preferences.ts +17 -0
  139. package/src/entries/tool-policy.ts +162 -0
  140. package/src/entries/typert.host.ts +29 -0
  141. package/src/hybrid/codex-hybrid-executor.ts +310 -0
  142. package/src/hybrid/hybrid-sdk.ts +217 -0
  143. package/src/hybrid/program-calls.ts +202 -0
  144. package/src/hybrid/subcall-scheduler.ts +446 -0
  145. package/src/policy/deferred-tools.ts +331 -0
  146. package/src/policy/overlay-installer.ts +191 -0
  147. package/src/policy/rule-resolver.ts +128 -0
  148. package/src/policy/tool-capabilities.ts +88 -0
  149. package/src/presets/activity.ts +146 -0
  150. package/src/presets/desktop-preset.ts +60 -0
  151. package/src/presets/preset-editor.ts +101 -0
  152. package/src/presets/preset-prompt-catalog.ts +221 -0
  153. package/src/presets/preset-tool-catalog.ts +58 -0
  154. package/src/presets/runtime-enhancements.ts +415 -0
  155. package/src/presets/small-window-compaction.ts +166 -0
  156. package/src/responses/compact-checkpoint.ts +264 -0
  157. package/src/responses/fetch-transport.ts +290 -0
  158. package/src/responses/remote-compact.ts +393 -0
  159. package/src/responses/sse-diagnostics.ts +156 -0
  160. package/src/responses/wire-rewrite.ts +261 -0
  161. package/src/tools/exec-output.ts +211 -0
  162. package/src/tools/exec-plan-tools.ts +307 -0
  163. package/src/tools/exec-runner.ts +445 -0
  164. package/src/tools/patch-tool.ts +331 -0
  165. package/src/tools/patch.ts +328 -0
  166. package/tsconfig.json +29 -0
  167. package/tsdown.config.ts +110 -0
  168. package/lib/installer.js +0 -237
  169. package/lib/invariant.js +0 -23
  170. package/lib/types/activity-types.d.ts +0 -6
  171. package/lib/types/activity-types.js +0 -3
  172. package/lib/types/client/preset-copy.d.ts +0 -42
  173. package/lib/types/client/preset-copy.js +0 -81
  174. package/lib/types/compact-command.js +0 -79
  175. package/lib/types/context.d.ts +0 -8
  176. package/lib/types/context.js +0 -14
  177. package/lib/types/exec.d.ts +0 -46
  178. package/lib/types/exec.js +0 -365
  179. package/lib/types/index.d.ts +0 -95
  180. package/lib/types/index.js +0 -738
  181. package/lib/types/installer.d.ts +0 -27
  182. package/lib/types/installer.js +0 -146
  183. package/lib/types/invariant.d.ts +0 -16
  184. package/lib/types/invariant.js +0 -22
  185. package/lib/types/preset-contract.d.ts +0 -69
  186. package/lib/types/preset-contract.js +0 -22
  187. package/lib/types/preset-editor-remote.d.ts +0 -30
  188. package/lib/types/preset-editor-remote.js +0 -37
  189. package/lib/types/preset-editor.d.ts +0 -69
  190. package/lib/types/preset-editor.js +0 -557
  191. package/lib/types/preset-templates.d.ts +0 -36
  192. package/lib/types/preset-templates.js +0 -12
  193. package/lib/types/prompt-sections.d.ts +0 -15
  194. package/lib/types/prompt-sections.js +0 -23
  195. package/lib/types/remote.d.ts +0 -40
  196. package/lib/types/remote.js +0 -683
  197. package/lib/types/typert.host.d.ts +0 -47
  198. package/lib/types/typert.host.js +0 -99
  199. package/presets/codex-collaboration/preset.yml +0 -3
  200. /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
@@ -0,0 +1,158 @@
1
+ /** Opt-in Host overlays for future Agents; source presets and Persona stay untouched. */
2
+ import { scopeParentOf } from '@deepseek-ai/dsh-scope';
3
+ import { effectiveToolAction } from "../contracts/tool-policy-contract.js";
4
+ import { readDefaultDeferredTools, readDefaultHiddenTools } from "../policy/deferred-tools.js";
5
+ import { installOverlay } from "../policy/overlay-installer.js";
6
+ import { Config, resolveRules } from "../policy/rule-resolver.js";
7
+ import { readLegacyCapabilities } from "../policy/tool-capabilities.js";
8
+ import { preparePromptOverrides, probePresetPromptsCached } from "../presets/preset-prompt-catalog.js";
9
+ export { Config } from "../policy/rule-resolver.js";
10
+ export const name = 'codex-tool-policy';
11
+ export const inject = ['tools', 'agents', 'agentPresets'];
12
+ /**
13
+ * Affect future Agent lifecycles only. No existing-agent scan, polling, prompt
14
+ * rewrite, source-preset edit, or executor replacement is performed.
15
+ */
16
+ export function apply(ctx, config = {}) {
17
+ const currentConfig = () => 'get' in config ? config.get() ?? {} : config;
18
+ resolveRules(currentConfig());
19
+ // A save changes only future Agents, including their later blank-preset switches.
20
+ const snapshots = new WeakMap();
21
+ const overlays = new Map();
22
+ let active = true;
23
+ ctx.provide('codexToolPolicy', {
24
+ enabled(agent, name, metadata) {
25
+ const snapshot = snapshots.get(agent);
26
+ if (snapshot === undefined)
27
+ return undefined;
28
+ if (!metadata.presetEnabled)
29
+ return false;
30
+ return effectiveToolAction(snapshot.activeRule, name, {
31
+ legacyCapabilities: snapshot.legacyCapabilities, codexTool: metadata,
32
+ }) !== 'hide';
33
+ },
34
+ hasPromptOverride(scope, name) { return snapshots.get(scope)?.activePromptNames?.has(name) === true; },
35
+ });
36
+ const remove = (agent) => {
37
+ const snapshot = snapshots.get(agent);
38
+ if (snapshot !== undefined) {
39
+ delete snapshot.activeRule;
40
+ delete snapshot.activePromptNames;
41
+ }
42
+ const previous = overlays.get(agent);
43
+ if (previous === undefined)
44
+ return;
45
+ overlays.delete(agent);
46
+ previous.dispose();
47
+ };
48
+ const reconcile = (agent) => {
49
+ const preset = ctx.agentPresets.composedPreset(agent.ctx)
50
+ ?? ctx.agentPresets.presetForSession(agent.session)
51
+ ?? undefined;
52
+ if (overlays.get(agent)?.preset === preset)
53
+ return;
54
+ remove(agent);
55
+ const snapshot = snapshots.get(agent);
56
+ const defaultDeferred = readDefaultDeferredTools(agent.ctx, agent);
57
+ const defaultHidden = readDefaultHiddenTools(agent.ctx, agent);
58
+ const rule = preset === undefined
59
+ ? undefined
60
+ : snapshot?.rules.get(preset)
61
+ ?? (((defaultDeferred !== undefined && defaultDeferred.size > 0) || (defaultHidden !== undefined && defaultHidden.size > 0))
62
+ ? { preset, replaceShell: false, replacePlan: false, replacePatch: false }
63
+ : undefined);
64
+ if (rule === undefined || snapshot === undefined)
65
+ return;
66
+ const prepared = snapshot.promptPlans.get(rule.preset);
67
+ if (prepared instanceof Error)
68
+ throw prepared;
69
+ if ((rule.promptOverrides?.length ?? 0) > 0 && prepared === undefined)
70
+ throw new Error('preset-prompt-plan-unavailable');
71
+ let installed;
72
+ const dispose = installOverlay(agent, rule, snapshot.legacyCapabilities, prepared, () => {
73
+ if (installed !== undefined && overlays.get(agent) === installed) {
74
+ overlays.delete(agent);
75
+ delete snapshot.activeRule;
76
+ delete snapshot.activePromptNames;
77
+ }
78
+ });
79
+ installed = { preset: rule.preset, dispose };
80
+ overlays.set(agent, installed);
81
+ snapshot.activeRule = rule;
82
+ if (prepared !== undefined)
83
+ snapshot.activePromptNames = new Set(prepared.sections.map(section => section.name));
84
+ };
85
+ const isBlankSession = (agent) => {
86
+ const boundary = ctx.agents.turnBoundaryOf(agent.session);
87
+ return boundary.openTurnStartSeq === null && boundary.lastTurn === 0;
88
+ };
89
+ ctx.on('agent/created', ({ agent, signal }) => {
90
+ if (!active)
91
+ return;
92
+ signal?.throwIfAborted();
93
+ const snapshot = {
94
+ rules: resolveRules(currentConfig()),
95
+ legacyCapabilities: readLegacyCapabilities(ctx),
96
+ promptPlans: new Map(),
97
+ };
98
+ snapshots.set(agent, snapshot);
99
+ const targets = [...snapshot.rules.values()].filter(rule => (rule.promptOverrides?.length ?? 0) > 0);
100
+ if (targets.length === 0) {
101
+ reconcile(agent);
102
+ return;
103
+ }
104
+ const bound = ctx.agentPresets.composedPreset(agent.ctx) ?? ctx.agentPresets.presetForSession(agent.session);
105
+ const activeTargets = isBlankSession(agent)
106
+ ? targets
107
+ : bound === undefined
108
+ ? []
109
+ : targets.filter(rule => rule.preset === bound);
110
+ // Factory setup is finished; queued model work is held until this returns.
111
+ if (activeTargets.length === 0) {
112
+ reconcile(agent);
113
+ return;
114
+ }
115
+ return (async () => {
116
+ for (const rule of activeTargets) {
117
+ try {
118
+ const probe = await probePresetPromptsCached(ctx, rule.preset, rule.preset === bound ? scopeParentOf(agent) : undefined);
119
+ snapshot.promptPlans.set(rule.preset, preparePromptOverrides(probe, rule.promptOverrides));
120
+ }
121
+ catch (error) {
122
+ // A stale/unsupported sibling target cannot block the current preset.
123
+ snapshot.promptPlans.set(rule.preset, error instanceof Error ? error : new Error(String(error)));
124
+ }
125
+ }
126
+ signal?.throwIfAborted();
127
+ if (active)
128
+ reconcile(agent);
129
+ return undefined;
130
+ })();
131
+ });
132
+ ctx.on('agent-preset/selected', sessionId => {
133
+ if (!active)
134
+ return;
135
+ const agent = ctx.agents.get(sessionId);
136
+ if (agent === undefined || !snapshots.has(agent) || agent.status !== 'idle')
137
+ return;
138
+ if (!isBlankSession(agent))
139
+ return;
140
+ // This event is emit, not serial: keep reconciliation entirely synchronous.
141
+ // A rejected new overlay leaves the newly selected preset's baseline intact.
142
+ try {
143
+ reconcile(agent);
144
+ }
145
+ catch (error) {
146
+ ctx.logger.warn(`codex-tool-policy: preset selection overlay refused for ${agent.id}: ${String(error)}`);
147
+ }
148
+ });
149
+ ctx.on('agent/disposed', ({ agent }) => { remove(agent); snapshots.delete(agent); });
150
+ // Registrations belong to agent.ctx, but must also unwind on Host-plugin unload.
151
+ ctx.effect(() => () => {
152
+ active = false;
153
+ for (const agent of [...overlays.keys()].reverse())
154
+ remove(agent);
155
+ }, 'codex-tool-policy: Host overlay ownership');
156
+ }
157
+ export default { name, inject, Config, apply };
158
+ //# sourceMappingURL=tool-policy.js.map
@@ -0,0 +1,23 @@
1
+ /** Host-side Remote contract consumed by the browser's preset inspector. */
2
+ export declare const TYPERT: {
3
+ package: string;
4
+ face: "host";
5
+ schemas: never[];
6
+ invocations: readonly import("@deepseek-ai/dsh-typert-protocol").InvocationDescriptor[];
7
+ model: {
8
+ services: {
9
+ description: string;
10
+ summary: string;
11
+ tags: never[];
12
+ jsDoc: string;
13
+ key: string;
14
+ exportName: string;
15
+ members: never[];
16
+ types: never[];
17
+ }[];
18
+ events: never[];
19
+ objects: never[];
20
+ };
21
+ };
22
+ export default TYPERT;
23
+ //# sourceMappingURL=typert.host.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { buildPresetEditorDescriptors, PRESET_EDITOR_PACKAGE, PRESET_EDITOR_SERVICE, } from "../contracts/preset-editor-schema.js";
2
+ /** Host-side Remote contract consumed by the browser's preset inspector. */
3
+ export const TYPERT = {
4
+ package: PRESET_EDITOR_PACKAGE,
5
+ face: 'host',
6
+ schemas: [],
7
+ invocations: buildPresetEditorDescriptors(),
8
+ model: {
9
+ services: [{
10
+ description: 'Inspect DSH agent presets, registered tools, and prompt sections.',
11
+ summary: 'Codex preset inspector.',
12
+ tags: [],
13
+ jsDoc: '',
14
+ key: PRESET_EDITOR_SERVICE,
15
+ exportName: 'CodexPresetEditor',
16
+ members: [],
17
+ types: [],
18
+ }],
19
+ events: [],
20
+ objects: [],
21
+ },
22
+ };
23
+ export default TYPERT;
24
+ //# sourceMappingURL=typert.host.js.map
@@ -0,0 +1,44 @@
1
+ /** Experimental asymmetric hybrid executor: direct Codex wire tools + `run_code` SDK batching. */
2
+ import { type Context } from '@deepseek-ai/cordis';
3
+ import z from '@deepseek-ai/schemastery';
4
+ import type { Agent } from '@deepseek-ai/dsh-agent';
5
+ import type { ToolBatchInput, ToolBatchResult, ToolDefinition, ToolExecutor, ToolModelInput, ToolPromptSection } from '@deepseek-ai/dsh-tools';
6
+ /** Direct wire tools called natively alongside `run_code` (omitted from `tools:sdk`). */
7
+ export declare const DEFAULT_HYBRID_DIRECT_TOOLS: readonly ["exec_command", "write_stdin", "apply_patch", "update_plan", "activate_tools", "read_image", "web_search", "ask_user_question", "exit_plan_mode", "skill", "present", "ralph", "workflow", "create_goal", "get_goal", "update_goal", "goal"];
8
+ export interface Config {
9
+ /** Native wire tools kept directly callable (not placed in `tools:sdk`). */
10
+ directTools: string[];
11
+ /** Source tools hidden from the preset scope while keeping companion plugins (e.g. `todos` projection). */
12
+ hiddenTools: string[];
13
+ /** Unconditional tools deferred via `activate_tools` / `deferLoading: true` by default. */
14
+ deferredTools: string[];
15
+ /** Permit calling direct wire tools inside `run_code` as well (default false). */
16
+ allowNestedDirectTools: boolean;
17
+ /** Maximum concurrent direct/outer calls in one model batch. */
18
+ maxParallelToolCalls: number;
19
+ /** Maximum overlapping concurrency-safe subcalls inside `run_code`. */
20
+ maxParallelSubCalls: number;
21
+ /** Nested tool-call attempts per minute of runtime timeout budget. */
22
+ maxSubCallsPerMinute: number;
23
+ }
24
+ export declare const Config: z<Partial<Config>, Config>;
25
+ /** Asymmetric hybrid executor: direct Codex tools on the wire + SDK batching via `run_code`. */
26
+ export declare class CodexHybridExecutor implements ToolExecutor {
27
+ private readonly ctx;
28
+ readonly sections: readonly ToolPromptSection[];
29
+ private readonly pipeline;
30
+ private readonly config;
31
+ private readonly directTools;
32
+ private readonly hiddenTools;
33
+ private readonly calls;
34
+ private runCodeTool;
35
+ constructor(ctx: Context, config?: Partial<Config>);
36
+ isDirectTool(name: string): boolean;
37
+ describe(tools: readonly ToolDefinition[]): ToolModelInput;
38
+ private renderSdk;
39
+ execute(input: ToolBatchInput): Promise<ToolBatchResult>;
40
+ reset(agent: Agent): Promise<void>;
41
+ private requireRunCodeTool;
42
+ private createRunCodeTool;
43
+ }
44
+ //# sourceMappingURL=codex-hybrid-executor.d.ts.map
@@ -0,0 +1,257 @@
1
+ /** Experimental asymmetric hybrid executor: direct Codex wire tools + `run_code` SDK batching. */
2
+ import { symbols } from '@deepseek-ai/cordis';
3
+ import z from '@deepseek-ai/schemastery';
4
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
5
+ import { ESCALATION_TARGETS } from '@deepseek-ai/dsh-sandbox';
6
+ import { defineTool, parameterSchemaSpecToJsonSchema, projectToolSchema, RUN_CODE_NAME, ToolNotFoundError } from '@deepseek-ai/dsh-tools';
7
+ import { executeToolBatch, toolErrorMessage, ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline';
8
+ import { renderHybridToolsSdk } from "./hybrid-sdk.js";
9
+ import { CodeResetFailedError, HybridProgramCalls, renderRunCodeValue } from "./program-calls.js";
10
+ import { escalationGuidance, executeHybridRunCode, requirePtcRuntime, resolveProgramFormat, resolveRunCodeDescription, resolveSandboxPolicy, } from "./subcall-scheduler.js";
11
+ /** Direct wire tools called natively alongside `run_code` (omitted from `tools:sdk`). */
12
+ export const DEFAULT_HYBRID_DIRECT_TOOLS = [
13
+ 'exec_command',
14
+ 'write_stdin',
15
+ 'apply_patch',
16
+ 'update_plan',
17
+ 'activate_tools',
18
+ 'read_image',
19
+ 'web_search',
20
+ 'ask_user_question',
21
+ 'exit_plan_mode',
22
+ 'skill',
23
+ 'present',
24
+ 'ralph',
25
+ 'workflow',
26
+ 'create_goal',
27
+ 'get_goal',
28
+ 'update_goal',
29
+ 'goal',
30
+ ];
31
+ export const Config = z.object({
32
+ directTools: z.array(z.string()).default([...DEFAULT_HYBRID_DIRECT_TOOLS]),
33
+ hiddenTools: z.array(z.string()).default([]),
34
+ deferredTools: z.array(z.string()).default([]),
35
+ allowNestedDirectTools: z.boolean().default(false),
36
+ maxParallelToolCalls: z.natural().min(1).default(10),
37
+ maxParallelSubCalls: z.natural().min(1).default(10),
38
+ maxSubCallsPerMinute: z.natural().min(1).default(1024),
39
+ });
40
+ const HYBRID_INSTRUCTION = [
41
+ 'This session uses an asymmetric hybrid tool architecture:',
42
+ `- 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}\`.`,
43
+ `- 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.`,
44
+ `- 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\`.`,
45
+ ].join('\n');
46
+ const RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION = 'Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI).';
47
+ const RUN_CODE_CONTROLS = {
48
+ timeoutMs: { type: 'number', description: 'Positive elapsed-time budget in milliseconds, capped by the deployment maximum.' },
49
+ sandbox_permissions: { type: 'string', enum: [...ESCALATION_TARGETS], description: 'Wider sandbox mode for this complete program execution; requires justification and approval.' },
50
+ justification: { type: 'string', description: 'Reason this complete program needs wider access, shown to the user for approval. Use the language of the user\'s current request.' },
51
+ };
52
+ function unwrapRuntime(runtime) {
53
+ let provider = runtime;
54
+ for (;;) {
55
+ const original = provider[symbols.original];
56
+ if (original === undefined)
57
+ return provider;
58
+ provider = original;
59
+ }
60
+ }
61
+ /** Asymmetric hybrid executor: direct Codex tools on the wire + SDK batching via `run_code`. */
62
+ export class CodexHybridExecutor {
63
+ ctx;
64
+ sections;
65
+ pipeline;
66
+ config;
67
+ directTools;
68
+ hiddenTools;
69
+ calls;
70
+ runCodeTool;
71
+ constructor(ctx, config = {}) {
72
+ this.ctx = ctx;
73
+ this.config = Config(config);
74
+ this.directTools = new Set(this.config.directTools.map(item => item.trim()).filter(Boolean));
75
+ this.hiddenTools = new Set(this.config.hiddenTools.map(item => item.trim()).filter(Boolean));
76
+ this.calls = new HybridProgramCalls(ctx);
77
+ const tools = ctx.tools;
78
+ this.sections = [
79
+ {
80
+ name: 'tools:hybrid',
81
+ order: ctx.systemPrompt.getSectionOrder('PTC_ONLY'),
82
+ text: HYBRID_INSTRUCTION,
83
+ interpolate: false,
84
+ },
85
+ {
86
+ name: 'tools:sdk',
87
+ order: ctx.systemPrompt.getSectionOrder('TOOLS_SDK'),
88
+ text: visibleTools => this.renderSdk(visibleTools),
89
+ interpolate: false,
90
+ },
91
+ ];
92
+ this.pipeline = new ToolExecutionPipeline(ctx, {
93
+ get: (name, scope, toolSet) => (this.hiddenTools.has(name)
94
+ ? undefined
95
+ : name === RUN_CODE_NAME
96
+ ? this.requireRunCodeTool()
97
+ : tools.executable(name, scope, toolSet)),
98
+ reject: (name, nested) => {
99
+ if (this.hiddenTools.has(name)) {
100
+ return new ToolNotFoundError(name, `\`${name}\` is hidden in this preset`);
101
+ }
102
+ if (!nested) {
103
+ if (name === RUN_CODE_NAME || this.isDirectTool(name))
104
+ return undefined;
105
+ return new ToolNotFoundError(name, `only callable inside \`${RUN_CODE_NAME}\` via \`await tools.${name}(...)\` in hybrid mode`);
106
+ }
107
+ if (!this.config.allowNestedDirectTools && (name === RUN_CODE_NAME || this.isDirectTool(name))) {
108
+ return new ToolNotFoundError(name, `call \`${name}\` directly as a tool call rather than inside \`${RUN_CODE_NAME}\``);
109
+ }
110
+ return undefined;
111
+ },
112
+ });
113
+ }
114
+ isDirectTool(name) {
115
+ return this.directTools.has(name);
116
+ }
117
+ describe(tools) {
118
+ const directSchemas = tools
119
+ .filter(definition => !this.hiddenTools.has(definition.name) && this.isDirectTool(definition.name))
120
+ .map(definition => projectToolSchema(definition, false));
121
+ return {
122
+ schemas: [...directSchemas, projectToolSchema(this.requireRunCodeTool(), false)],
123
+ };
124
+ }
125
+ renderSdk(tools) {
126
+ const runtime = requirePtcRuntime(this.ctx);
127
+ const sdkTools = tools.filter(definition => !this.hiddenTools.has(definition.name)
128
+ && (this.config.allowNestedDirectTools || !this.isDirectTool(definition.name)));
129
+ return renderHybridToolsSdk(sdkTools.map(definition => ({
130
+ ...projectToolSchema(definition, false),
131
+ output: definition.output.schema,
132
+ })), runtime.language, resolveProgramFormat(runtime));
133
+ }
134
+ execute(input) {
135
+ return executeToolBatch(input, this.pipeline, () => this.config.maxParallelToolCalls);
136
+ }
137
+ async reset(agent) {
138
+ const runtime = requirePtcRuntime(this.ctx);
139
+ if (!runtime.retainsState) {
140
+ throw new CodeResetFailedError('The PTC runtime does not retain an environment');
141
+ }
142
+ try {
143
+ await this.calls.reset(agent.session.id, () => runtime.release(agent), () => {
144
+ agent.inject(createUserMessage({
145
+ content: [{ type: 'text', text: 'Program environment reset; retained variables cleared. Completed tool effects remain.' }],
146
+ source: { kind: 'ptc-mode' },
147
+ }));
148
+ });
149
+ }
150
+ catch (error) {
151
+ throw new CodeResetFailedError(`Program environment reset failed: ${toolErrorMessage(error)}. State may not be cleared; retry the host reset before running more code.`);
152
+ }
153
+ }
154
+ requireRunCodeTool() {
155
+ this.runCodeTool ??= this.createRunCodeTool();
156
+ return this.runCodeTool;
157
+ }
158
+ createRunCodeTool() {
159
+ const ctx = this.ctx;
160
+ const config = this.config;
161
+ const calls = this.calls;
162
+ const stateOwners = new WeakMap();
163
+ const runHost = {
164
+ ctx,
165
+ pipeline: this.pipeline,
166
+ allowNestedDirectTools: config.allowNestedDirectTools,
167
+ maxParallelSubCalls: config.maxParallelSubCalls,
168
+ maxSubCallsPerMinute: config.maxSubCallsPerMinute,
169
+ stateOwners,
170
+ isDirect: (toolName) => this.isDirectTool(toolName),
171
+ unwrapRuntime,
172
+ };
173
+ const definition = defineTool({
174
+ name: RUN_CODE_NAME,
175
+ description: 'Execute a program against SDK tools declared in `tools:sdk`.',
176
+ parameters: {
177
+ code: { type: 'string', required: true, description: 'The program to execute.' },
178
+ description: { type: 'string', required: true, description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION },
179
+ ...RUN_CODE_CONTROLS,
180
+ },
181
+ output: {
182
+ schema: {
183
+ type: 'object',
184
+ additionalProperties: false,
185
+ properties: {
186
+ logs: { type: 'array', required: true, items: { type: 'string' } },
187
+ result: { type: 'json' },
188
+ sandbox: {
189
+ type: 'object',
190
+ additionalProperties: false,
191
+ properties: {
192
+ mode: { type: 'string', required: true, enum: ['read-only', 'workspace-write', 'danger-full-access'] },
193
+ denied: { type: 'boolean', required: true },
194
+ enforcement: { type: 'string', enum: ['full', 'partial'] },
195
+ },
196
+ },
197
+ },
198
+ },
199
+ render: (_args, value) => {
200
+ const rendered = value.result === undefined ? '' : renderRunCodeValue(value.result);
201
+ const parts = [value.logs.join('\n'), rendered].filter(part => part.length > 0);
202
+ if (value.sandbox?.enforcement === 'partial')
203
+ parts.push('File sandbox enforcement is partial on this host.');
204
+ if (value.sandbox?.denied) {
205
+ parts.push(`The ${value.sandbox.mode} file sandbox denied an operation.${escalationGuidance(ctx.get('ptcRuntime')?.sandboxMode)}`);
206
+ }
207
+ return [{ type: 'text', text: parts.length > 0 ? parts.join('\n') : '(run_code completed with no output)' }];
208
+ },
209
+ },
210
+ async execute(rawArgs, exec) {
211
+ if (rawArgs.description.trim().length === 0) {
212
+ throw new Error('invalid description: expected a non-empty string');
213
+ }
214
+ const runtime = requirePtcRuntime(ctx);
215
+ const run = (callSignal) => executeHybridRunCode(runHost, rawArgs, exec, callSignal);
216
+ return exec.agent === undefined || (runtime.sandboxMode === undefined && !runtime.retainsState)
217
+ ? run(exec.signal)
218
+ : calls.run(exec.agent.session.id, exec.signal, () => runtime.sandboxMode === undefined ? undefined : resolveSandboxPolicy(ctx, exec).mode, run);
219
+ },
220
+ presentCall: args => ({
221
+ card: 'generic',
222
+ title: args.description,
223
+ kind: 'execute',
224
+ rawInput: args.code,
225
+ }),
226
+ });
227
+ Object.defineProperty(definition, 'description', {
228
+ enumerable: true,
229
+ get: () => resolveRunCodeDescription(requirePtcRuntime(ctx)),
230
+ });
231
+ Object.defineProperty(definition, 'parameters', {
232
+ enumerable: true,
233
+ get: () => {
234
+ const runtime = requirePtcRuntime(ctx);
235
+ const codeDescription = runtime.language === 'python'
236
+ ? 'The Python program to execute against `tools`.'
237
+ : 'The TypeScript program (function body supporting top-level `await` and `return`) to execute against `tools`.';
238
+ return parameterSchemaSpecToJsonSchema({
239
+ code: { type: 'string', required: true, description: codeDescription },
240
+ description: { type: 'string', required: true, description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION },
241
+ ...(runtime.timeout === undefined ? {} : {
242
+ timeoutMs: {
243
+ ...RUN_CODE_CONTROLS.timeoutMs,
244
+ description: `Positive elapsed-time budget in milliseconds, including nested waits. Default ${runtime.timeout.defaultMs}; capped at ${runtime.timeout.maxMs}.`,
245
+ },
246
+ }),
247
+ ...(runtime.sandboxMode === undefined ? {} : {
248
+ sandbox_permissions: RUN_CODE_CONTROLS.sandbox_permissions,
249
+ justification: RUN_CODE_CONTROLS.justification,
250
+ }),
251
+ });
252
+ },
253
+ });
254
+ return definition;
255
+ }
256
+ }
257
+ //# sourceMappingURL=codex-hybrid-executor.js.map
@@ -0,0 +1,13 @@
1
+ /** Deterministic schema-to-SDK renderer for Codex hybrid `run_code` execution. */
2
+ import type { ToolSchema } from '@deepseek-ai/dsh-llm';
3
+ import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime';
4
+ import type { JsonSchemaNode } from '@deepseek-ai/dsh-tools';
5
+ /** Hybrid SDK projection: model-facing schema plus validated canonical output schema. */
6
+ export interface HybridToolSdkSchema extends Readonly<ToolSchema> {
7
+ readonly output: JsonSchemaNode;
8
+ }
9
+ /** Render one supported JSON Schema node to TypeScript, degrading invalid schemas safely. */
10
+ export declare function jsonSchemaToTs(schema: unknown, indent?: number): string;
11
+ /** Render deterministic SDK declarations for hybrid `run_code` bindings. */
12
+ export declare function renderHybridToolsSdk(schemas: readonly HybridToolSdkSchema[], language?: 'typescript' | 'python', programFormat?: PtcProgramFormat): string;
13
+ //# sourceMappingURL=hybrid-sdk.d.ts.map