@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,307 @@
1
+ /** Shared Codex execution and plan tool registration (decoupled from Host preset editor). */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import type { Agent } from '@deepseek-ai/dsh-agent'
5
+ import { ESCALATION_TARGETS, sandboxPermissionsDescription } from '@deepseek-ai/dsh-sandbox'
6
+ import type {} from '@deepseek-ai/dsh-sandbox-policy'
7
+ import type {} from '@deepseek-ai/dsh-shell'
8
+ import type { TodoItem } from '@deepseek-ai/dsh-tool-todo'
9
+ import { defineTool } from '@deepseek-ai/dsh-tools'
10
+ import type { TerminalResultView, ToolResult } from '@deepseek-ai/dsh-tools'
11
+ import { disposeAgentExecSessions, renderExecResult, runExecCommand, runWriteStdin } from './exec-runner.ts'
12
+ import type { ExecCommandArgs, ExecResult, WriteStdinArgs } from './exec-output.ts'
13
+ import { registerPatchTool } from './patch-tool.ts'
14
+ import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE, readHostSettings } from '../contracts/settings.ts'
15
+ import type { CodexSettings } from '../contracts/settings.ts'
16
+ import { assertCapabilityEnabled, codexToolEnabled, markCodexTool } from '../policy/tool-capabilities.ts'
17
+ import type { CodexCapability } from '../contracts/tool-policy-contract.ts'
18
+
19
+ export const DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024
20
+
21
+ const EXEC_COMMAND_DESCRIPTION =
22
+ 'Runs a command in the host-configured shell. By default it uses pipes: a running session can be polled for output but does not accept stdin. Set tty=true before starting a command that needs interactive input; background jobs use pipes.'
23
+ const WRITE_STDIN_DESCRIPTION =
24
+ 'Polls output from an existing unified exec session. Non-empty chars can be sent to a session created with tty=true; pipe-backed sessions accept empty chars for polling or "\\u0003" to interrupt.'
25
+ const UPDATE_PLAN_DESCRIPTION =
26
+ 'Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.'
27
+
28
+ const PLAN_STATUSES = ['pending', 'in_progress', 'completed'] as const
29
+ type PlanStatus = typeof PLAN_STATUSES[number]
30
+
31
+ interface PlanArgumentItem {
32
+ step: string
33
+ status: PlanStatus
34
+ }
35
+
36
+ interface UpdatePlanArgs {
37
+ explanation?: string
38
+ plan: PlanArgumentItem[]
39
+ }
40
+
41
+ export interface ExecToolConfig {
42
+ defaultYieldTimeMs: number
43
+ pollYieldTimeMs: number
44
+ writeYieldTimeMs: number
45
+ maxOutputBytes: number
46
+ currentSettings: () => CodexSettings
47
+ presetEnabled?: boolean
48
+ authority?: boolean
49
+ presetOverridesLegacy?: boolean
50
+ }
51
+
52
+ function planTodos(args: UpdatePlanArgs): TodoItem[] {
53
+ const seen = new Set<string>()
54
+ let active = 0
55
+ const todos: TodoItem[] = []
56
+ for (const item of args.plan) {
57
+ const content = item.step.trim()
58
+ if (content.length === 0) throw new Error('update_plan: every step must be non-empty')
59
+ if (seen.has(content)) throw new Error(`update_plan: duplicate step ${JSON.stringify(content)}`)
60
+ seen.add(content)
61
+ if (item.status === 'in_progress') active++
62
+ todos.push({ content, status: item.status })
63
+ }
64
+ if (active > 1) throw new Error('update_plan: at most one step may be in_progress')
65
+ return todos
66
+ }
67
+
68
+ /** Release every registration once, even when one release fails. */
69
+ export function composeToolDisposers(disposers: Array<() => void>): () => void {
70
+ return () => {
71
+ const errors: unknown[] = []
72
+ for (const dispose of disposers.splice(0).reverse()) {
73
+ try { dispose() } catch (error) { errors.push(error) }
74
+ }
75
+ if (errors.length > 0) throw new AggregateError(errors, 'Could not unregister Codex tools')
76
+ }
77
+ }
78
+
79
+ function terminalResultView(result: ToolResult): TerminalResultView | undefined {
80
+ if (result.isError) return undefined
81
+ const meta = typeof result.meta === 'object' && result.meta !== null && !Array.isArray(result.meta)
82
+ ? result.meta as { output?: unknown; exitCode?: unknown }
83
+ : undefined
84
+ if (typeof meta?.output !== 'string') return undefined
85
+ return {
86
+ card: 'terminal',
87
+ output: meta.output,
88
+ ...typeof meta.exitCode === 'number' ? { exitCode: meta.exitCode } : {},
89
+ }
90
+ }
91
+
92
+ export function registerExecTools(ctx: Context, config: ExecToolConfig): () => void {
93
+ const tools = ctx.get('tools')
94
+ if (tools === undefined) throw new Error('Codex execution tools require ctx.tools')
95
+ const shell = ctx.get('shell')
96
+ if (shell === undefined) throw new Error('Codex execution tools require ctx.shell')
97
+ const confines = shell.sandboxMode !== undefined
98
+ if (confines && ctx.get('sandboxPolicy') === undefined) throw new Error('Codex execution tools: a sandboxing shell requires ctx.sandboxPolicy')
99
+ const metadata = {
100
+ capability: 'terminalToolsEnabled' as const,
101
+ presetEnabled: config.presetEnabled !== false,
102
+ ...(config.presetOverridesLegacy ? { presetOverridesLegacy: true } : {}),
103
+ }
104
+ const ownedAgents = new Set<Agent>()
105
+ const offDisposed = typeof (ctx as Partial<Context>).on === 'function'
106
+ ? ctx.on('agent/disposed', ({ agent }) => {
107
+ ownedAgents.delete(agent)
108
+ disposeAgentExecSessions(agent)
109
+ })
110
+ : () => {}
111
+ const cleanupOwned = (): void => {
112
+ offDisposed()
113
+ for (const agent of [...ownedAgents]) {
114
+ ownedAgents.delete(agent)
115
+ disposeAgentExecSessions(agent)
116
+ }
117
+ }
118
+
119
+ let unregisterExec: (() => void) | undefined
120
+ try {
121
+ unregisterExec = tools.register(markCodexTool(defineTool({
122
+ name: 'exec_command',
123
+ description: EXEC_COMMAND_DESCRIPTION,
124
+ parameters: {
125
+ cmd: { type: 'string', required: true, description: 'Shell command to execute.' },
126
+ workdir: { type: 'string', description: 'Working directory for the command. Defaults to the turn cwd.' },
127
+ tty: { type: 'boolean', description: confines ? 'This host cannot carry sandbox policy into a PTY; omit tty or use false.' : 'True allocates a PTY for the command; false or omitted uses plain pipes.' },
128
+ run_in_background: { type: 'boolean', description: 'Run as a DSH background job and return its job id immediately; collect output with job_output and stop it with job_kill. Only supported for pipe-backed commands.' },
129
+ yield_time_ms: { type: 'number', description: 'Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.' },
130
+ max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
131
+ ...confines ? {
132
+ sandbox_permissions: { type: 'string' as const, enum: [...ESCALATION_TARGETS], description: sandboxPermissionsDescription('command') },
133
+ justification: { type: 'string' as const, description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request.' },
134
+ } : {},
135
+ },
136
+ output: {
137
+ schema: {
138
+ type: 'object',
139
+ additionalProperties: false,
140
+ properties: {
141
+ chunk_id: { type: 'string' },
142
+ wall_time_seconds: { type: 'number', required: true },
143
+ exit_code: { type: 'number' },
144
+ session_id: { type: 'number' },
145
+ job_id: { type: 'string' },
146
+ original_token_count: { type: 'number' },
147
+ output: { type: 'string', required: true },
148
+ },
149
+ },
150
+ render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
151
+ presentationMeta: (_args, value) => ({
152
+ output: value.output,
153
+ ...value.exit_code === undefined ? {} : { exitCode: value.exit_code },
154
+ ...value.job_id === undefined ? {} : { jobId: value.job_id },
155
+ }),
156
+ },
157
+ async execute(args: ExecCommandArgs, exec): Promise<ExecResult> {
158
+ assertCapabilityEnabled(ctx, config.currentSettings, 'exec_command', exec.agent, metadata, config.authority)
159
+ const result = await runExecCommand(ctx, args, exec, config)
160
+ if (result.session_id !== undefined && exec.agent !== undefined) ownedAgents.add(exec.agent)
161
+ return result
162
+ },
163
+ presentCall: args => args.run_in_background === true
164
+ ? { card: 'generic', title: args.cmd, kind: 'execute', rawInput: args.cmd }
165
+ : { card: 'terminal', title: args.cmd, ...args.workdir === undefined ? {} : { cwd: args.workdir } },
166
+ presentResult: (args, result) => args.run_in_background === true ? undefined : terminalResultView(result),
167
+ }), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'exec_command', metadata, config.currentSettings, config.authority) })
168
+
169
+ const unregisterStdin = tools.register(markCodexTool(defineTool({
170
+ name: 'write_stdin',
171
+ description: WRITE_STDIN_DESCRIPTION,
172
+ parameters: {
173
+ session_id: { type: 'number', required: true, description: 'Identifier of the running unified exec session.' },
174
+ chars: { type: 'string', description: 'Characters to send to a PTY session created with tty=true. Leave empty to poll output without writing; pipe-backed sessions accept empty chars to poll or "\\u0003" to interrupt.' },
175
+ yield_time_ms: { type: 'number', description: 'Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default.' },
176
+ max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
177
+ },
178
+ output: {
179
+ schema: {
180
+ type: 'object',
181
+ additionalProperties: false,
182
+ properties: {
183
+ chunk_id: { type: 'string' },
184
+ wall_time_seconds: { type: 'number', required: true },
185
+ exit_code: { type: 'number' },
186
+ session_id: { type: 'number' },
187
+ original_token_count: { type: 'number' },
188
+ output: { type: 'string', required: true },
189
+ },
190
+ },
191
+ render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
192
+ presentationMeta: (_args, value) => ({
193
+ output: value.output,
194
+ ...value.exit_code === undefined ? {} : { exitCode: value.exit_code },
195
+ }),
196
+ },
197
+ async execute(args: WriteStdinArgs, exec): Promise<ExecResult> {
198
+ assertCapabilityEnabled(ctx, config.currentSettings, 'write_stdin', exec.agent, metadata, config.authority)
199
+ return runWriteStdin(ctx, args, exec, config)
200
+ },
201
+ presentCall: args => ({ card: 'terminal', title: `write_stdin #${args.session_id}` }),
202
+ presentResult: (_args, result) => terminalResultView(result),
203
+ }), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'write_stdin', metadata, config.currentSettings, config.authority) })
204
+
205
+ return composeToolDisposers([cleanupOwned, unregisterExec, unregisterStdin])
206
+ } catch (error) {
207
+ cleanupOwned()
208
+ unregisterExec?.()
209
+ throw error
210
+ }
211
+ }
212
+
213
+ export function registerPlanTool(
214
+ ctx: Context,
215
+ currentSettings: () => CodexSettings,
216
+ presetEnabled = true,
217
+ authority?: boolean,
218
+ presetOverridesLegacy = false,
219
+ ): () => void {
220
+ const tools = ctx.get('tools')
221
+ if (tools === undefined) throw new Error('Codex plan tools require ctx.tools')
222
+ const metadata = {
223
+ capability: 'planToolEnabled' as const,
224
+ presetEnabled,
225
+ ...(presetOverridesLegacy ? { presetOverridesLegacy: true } : {}),
226
+ }
227
+ return tools.register(markCodexTool(defineTool({
228
+ name: 'update_plan',
229
+ description: UPDATE_PLAN_DESCRIPTION,
230
+ parameters: {
231
+ explanation: { type: 'string', description: 'Optional explanation for this plan update.' },
232
+ plan: {
233
+ type: 'array',
234
+ required: true,
235
+ description: 'The list of steps',
236
+ items: {
237
+ type: 'object',
238
+ additionalProperties: false,
239
+ properties: {
240
+ step: { type: 'string', required: true, description: 'Task step text.' },
241
+ status: { type: 'string', required: true, enum: [...PLAN_STATUSES], description: 'Step status.' },
242
+ },
243
+ },
244
+ },
245
+ },
246
+ output: {
247
+ schema: { type: 'object', additionalProperties: false, properties: {} },
248
+ render: () => [{ type: 'text', text: 'Plan updated' }],
249
+ },
250
+ execute(args: UpdatePlanArgs, exec): Promise<Record<string, never>> {
251
+ assertCapabilityEnabled(ctx, currentSettings, 'update_plan', exec.agent, metadata, authority)
252
+ const agent = exec.agent
253
+ if (agent === undefined) throw new Error('update_plan requires an owning agent session')
254
+ const events = typeof agent.session.snapshotEvents === 'function'
255
+ ? agent.session.snapshotEvents() as ReadonlyArray<{ type: string; data?: unknown }>
256
+ : undefined
257
+ const planEvent = events?.findLast(event => event.type === 'plan/mode')
258
+ if ((planEvent?.data as { active?: unknown } | undefined)?.active === true) {
259
+ throw new Error('update_plan is a task-execution checklist tool and is not allowed in plan mode; submit your plan via exit_plan_mode')
260
+ }
261
+ agent.session.append('todo/write', { todos: planTodos(args) })
262
+ return Promise.resolve({})
263
+ },
264
+ }), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'update_plan', metadata, currentSettings, authority) })
265
+ }
266
+
267
+ /** Select only the execution/plan/patch contributions; omitted execution/plan flags mean enabled, patch defaults false. */
268
+ export interface CodexExecAndPlanOptions {
269
+ terminal?: boolean
270
+ plan?: boolean
271
+ patch?: boolean
272
+ defaultYieldTimeMs?: number
273
+ pollYieldTimeMs?: number
274
+ writeYieldTimeMs?: number
275
+ maxOutputBytes?: number
276
+ /** Internal compiled-plan authority; omitted preserves the unsnapshotted compatibility path. */
277
+ capabilityAuthority?: Partial<Record<CodexCapability, boolean>>
278
+ }
279
+
280
+ /**
281
+ * Register selected Codex tools through the existing pipeline, without prompt hooks.
282
+ * Compiled adapters receive authority once; the disposer supports an additional owner.
283
+ */
284
+ export function registerCodexExecAndPlan(ctx: Context, options: CodexExecAndPlanOptions = {}): () => void {
285
+ const currentSettings = (): CodexSettings => ({
286
+ ...CODEX_SETTINGS_ENTRY,
287
+ ...readHostSettings<CodexSettings>(ctx, CODEX_SETTINGS_NAMESPACE),
288
+ })
289
+ const disposers: Array<() => void> = []
290
+ const dispose = composeToolDisposers(disposers)
291
+ try {
292
+ if (options.terminal !== false) disposers.push(registerExecTools(ctx, {
293
+ defaultYieldTimeMs: options.defaultYieldTimeMs ?? 10_000,
294
+ pollYieldTimeMs: options.pollYieldTimeMs ?? 5_000,
295
+ writeYieldTimeMs: options.writeYieldTimeMs ?? 250,
296
+ maxOutputBytes: options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
297
+ currentSettings,
298
+ ...(options.capabilityAuthority?.terminalToolsEnabled === undefined ? {} : { authority: options.capabilityAuthority.terminalToolsEnabled }),
299
+ }))
300
+ if (options.plan !== false) disposers.push(registerPlanTool(ctx, currentSettings, true, options.capabilityAuthority?.planToolEnabled))
301
+ if (options.patch === true) disposers.push(registerPatchTool(ctx, currentSettings, true, options.capabilityAuthority?.patchToolEnabled))
302
+ return dispose
303
+ } catch (error) {
304
+ dispose()
305
+ throw error
306
+ }
307
+ }