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