@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,446 @@
1
+ /** Concurrent/exclusive nested subcall queue and `run_code` execution runtime for hybrid mode. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import type { Agent } from '@deepseek-ai/dsh-agent'
4
+ import { createUserMessage, HarnessError, ToolCallId } from '@deepseek-ai/dsh-llm'
5
+ import type { ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm'
6
+ import type { PtcBindingFunction, PtcJsonValue, PtcProgramFormat, PtcRunResult, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
7
+ import { approveEscalation, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
8
+ import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
9
+ import { scopeTarget } from '@deepseek-ai/dsh-scope'
10
+ import type { Scoped } from '@deepseek-ai/dsh-scope'
11
+ import { RUN_CODE_NAME, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
12
+ import type { ToolExecution, ToolExecutionInput, ToolExecutionResult, ToolRunContext, ToolsService } from '@deepseek-ai/dsh-tools'
13
+ import { toolErrorMessage, ToolExecutionPipeline, type ScheduledToolDispatch } from '@deepseek-ai/dsh-tools/pipeline'
14
+ import { CodeRunFailedError, deepFreeze, jsonNormalizeArgs } from './program-calls.ts'
15
+
16
+ export interface PtcDispatchStartEventData {
17
+ rootCallId: ToolCallId
18
+ parentCallId: ToolCallId
19
+ subCallId: ToolCallId
20
+ name: string
21
+ arguments: unknown
22
+ }
23
+
24
+ export interface PtcDispatchEventData extends PtcDispatchStartEventData {
25
+ isError: boolean
26
+ content: ContentBlock[]
27
+ meta?: PtcJsonValue
28
+ error?: { name: string; code: string; reason?: string }
29
+ }
30
+
31
+ export interface PtcDispatchLog {
32
+ readonly exec: ToolExecution
33
+ readonly agent?: Agent
34
+ readonly subCallId: ToolCallId
35
+ readonly name: string
36
+ readonly isError: boolean
37
+ readonly content: ContentBlock[]
38
+ }
39
+
40
+ declare module '@deepseek-ai/cordis' {
41
+ interface Events {
42
+ 'tools/ptc-dispatch-log'(
43
+ this: Scoped<ToolsService>,
44
+ dispatch: PtcDispatchLog,
45
+ next: () => Promise<ContentBlock[]>,
46
+ ): Promise<ContentBlock[]>
47
+ }
48
+ }
49
+
50
+ declare module '@deepseek-ai/dsh-session/types' {
51
+ interface SessionEventMap {
52
+ 'tool/ptc-dispatch-start': PtcDispatchStartEventData
53
+ 'tool/ptc-dispatch': PtcDispatchEventData
54
+ }
55
+ }
56
+
57
+ declare module '@deepseek-ai/dsh-llm' {
58
+ interface MessageSourceMap {
59
+ 'ptc-mode': { kind: 'ptc-mode' }
60
+ }
61
+ }
62
+
63
+ export type PtcSdkLanguage = 'typescript' | 'python'
64
+ export type SupportedPtcRuntime = PtcRuntime & { readonly language: PtcSdkLanguage }
65
+
66
+ export interface RunCodeOutput {
67
+ logs: string[]
68
+ result?: PtcJsonValue
69
+ sandbox?: {
70
+ mode: SandboxMode
71
+ denied: boolean
72
+ enforcement?: 'full' | 'partial'
73
+ }
74
+ }
75
+
76
+ export interface RunCodeArgs {
77
+ code: string
78
+ description: string
79
+ timeoutMs?: number
80
+ sandbox_permissions?: string
81
+ justification?: string
82
+ }
83
+
84
+ class ToolCallLimitExceededError extends Error {
85
+ constructor(limit: number, windowMs: number) {
86
+ super(`run_code exceeded its tool-call budget (${limit} calls in ${windowMs}ms)`)
87
+ this.name = 'ToolCallLimitExceededError'
88
+ }
89
+ }
90
+
91
+ export function requirePtcRuntime(ctx: Context): SupportedPtcRuntime {
92
+ const runtime = ctx.get('ptcRuntime')
93
+ if (runtime === undefined) {
94
+ throw new Error('codex-hybrid-executor: requires a mounted ctx.ptcRuntime implementation')
95
+ }
96
+ if (runtime.language !== 'typescript' && runtime.language !== 'python') {
97
+ throw new Error(`codex-hybrid-executor: unsupported PTC runtime language ${JSON.stringify(runtime.language)}`)
98
+ }
99
+ return runtime as SupportedPtcRuntime
100
+ }
101
+
102
+ export function resolveProgramFormat(runtime: PtcRuntime): PtcProgramFormat {
103
+ return runtime.programFormat ?? 'function-body'
104
+ }
105
+
106
+ export function escalationGuidance(mode: PtcRuntime['sandboxMode']): string {
107
+ return mode === undefined ? ''
108
+ : ' A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying.'
109
+ }
110
+
111
+ export function resolveRunCodeDescription(runtime: SupportedPtcRuntime): string {
112
+ const langLabel = runtime.language === 'python' ? 'Python' : 'TypeScript'
113
+ const formatNote = runtime.language === 'typescript' && resolveProgramFormat(runtime) === 'function-body'
114
+ ? 'the BODY of an async TypeScript function (erasable syntax only; top-level `await` and `return` work)'
115
+ : `the ${langLabel} program to execute`
116
+ const extra = runtime.executionInstructions ? ` ${runtime.executionInstructions}` : ''
117
+ return `Execute a ${langLabel} program against the SDK tools declared in \`tools:sdk\`. Takes \`code\` (${formatNote}) and \`description\`. `
118
+ + 'Call SDK tools via `await tools.name(args)`. Direct wire tools stay outside `run_code`. Image-bearing subtool results are attached after the run.'
119
+ + extra
120
+ + ' Each program starts in the Session current directory.'
121
+ + escalationGuidance(runtime.sandboxMode)
122
+ }
123
+
124
+ async function resolveWorkingDirectory(ctx: Context, exec: ToolRunContext): Promise<string | undefined> {
125
+ if (exec.agent === undefined) return undefined
126
+ const directories = exec.agent.ctx.get('workingDirectory') ?? ctx.get('workingDirectory')
127
+ if (directories === undefined) throw new Error('codex-hybrid: run_code with an Agent requires workingDirectory')
128
+ return directories.ensure(exec.agent, exec.signal)
129
+ }
130
+
131
+ export function resolveSandboxPolicy(ctx: Context, exec: ToolRunContext): SandboxExecutionPolicy {
132
+ const policy = exec.agent?.ctx.get('sandboxPolicy') ?? ctx.get('sandboxPolicy')
133
+ if (policy === undefined) throw new Error('codex-hybrid: confined PTC runtime requires sandboxPolicy')
134
+ return policy.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
135
+ }
136
+
137
+ export interface HybridRunHost {
138
+ readonly ctx: Context
139
+ readonly pipeline: ToolExecutionPipeline
140
+ readonly allowNestedDirectTools: boolean
141
+ readonly maxParallelSubCalls: number
142
+ readonly maxSubCallsPerMinute: number
143
+ readonly stateOwners: WeakMap<object, WeakSet<PtcRuntime>>
144
+ readonly isDirect: (name: string) => boolean
145
+ readonly unwrapRuntime: (runtime: PtcRuntime) => PtcRuntime
146
+ }
147
+
148
+ export async function executeHybridRunCode(
149
+ host: HybridRunHost,
150
+ rawArgs: RunCodeArgs,
151
+ exec: ToolRunContext,
152
+ callSignal: AbortSignal,
153
+ ): Promise<RunCodeOutput> {
154
+ const { ctx, pipeline } = host
155
+ const tools = ctx.tools
156
+ const runtime = requirePtcRuntime(ctx)
157
+ validateEscalationArgs(rawArgs.sandbox_permissions, rawArgs.justification)
158
+ if (rawArgs.timeoutMs !== undefined && runtime.timeout === undefined) {
159
+ throw new Error('timeoutMs is not available for this PTC runtime')
160
+ }
161
+ if (rawArgs.timeoutMs !== undefined && (!Number.isFinite(rawArgs.timeoutMs) || rawArgs.timeoutMs <= 0)) {
162
+ throw new Error('invalid timeoutMs: expected a positive finite number')
163
+ }
164
+ const standingPolicy = runtime.sandboxMode === undefined ? undefined : resolveSandboxPolicy(ctx, exec)
165
+ let policy = standingPolicy
166
+ if (rawArgs.sandbox_permissions !== undefined && rawArgs.justification !== undefined) {
167
+ if (standingPolicy === undefined) throw new Error('sandbox_permissions is not available for this PTC runtime')
168
+ const approver = exec.agent?.ctx.get('approval') ?? ctx.get('approval')
169
+ const approvedMode = await approveEscalation({
170
+ requestedMode: rawArgs.sandbox_permissions,
171
+ justification: rawArgs.justification,
172
+ effectiveMode: standingPolicy.mode,
173
+ subject: 'program',
174
+ }, { approver, agent: exec.agent, callId: exec.callId, toolName: RUN_CODE_NAME, signal: callSignal })
175
+ policy = { ...standingPolicy, mode: approvedMode }
176
+ }
177
+ const cwd = await resolveWorkingDirectory(ctx, { ...exec, signal: callSignal })
178
+ callSignal.throwIfAborted()
179
+
180
+ const runController = new AbortController()
181
+ const onOuterAbort = (): void => { runController.abort(callSignal.reason) }
182
+ callSignal.addEventListener('abort', onOuterAbort, { once: true })
183
+
184
+ let dispatches = 0
185
+ let maxSubCalls = Infinity
186
+ let subCallWindowMs = 60_000
187
+ let subSeq = 1
188
+ let closed = false
189
+
190
+ interface PendingDispatch {
191
+ start(): Promise<void>
192
+ classify(): 'parallel' | 'exclusive'
193
+ abandon(): void
194
+ commit(): Promise<void>
195
+ flight: Promise<void>
196
+ settled: boolean
197
+ mode?: 'parallel' | 'exclusive'
198
+ }
199
+
200
+ const pendingQueue: PendingDispatch[] = []
201
+ const commitQueue: PendingDispatch[] = []
202
+ const inFlight = new Set<Promise<void>>()
203
+ const logWork = new Set<Promise<void>>()
204
+ let exclusiveActive = false
205
+ let driving = false
206
+ let driverRun: Promise<void> = Promise.resolve()
207
+ let wake: (() => void) | undefined
208
+ const wakeup = (): void => {
209
+ const release = wake
210
+ wake = undefined
211
+ release?.()
212
+ }
213
+
214
+ const shapeDispatchLog = async (dispatch: PtcDispatchLog): Promise<ContentBlock[]> => {
215
+ try {
216
+ return await ctx.waterfall(
217
+ scopeTarget(tools, dispatch.agent),
218
+ 'tools/ptc-dispatch-log',
219
+ dispatch,
220
+ () => Promise.resolve(dispatch.content),
221
+ )
222
+ } catch (error: unknown) {
223
+ ctx.logger.warn(`codex-hybrid: ptc-dispatch-log listener failed for ${dispatch.name}: ${toolErrorMessage(error)}`)
224
+ return dispatch.content
225
+ }
226
+ }
227
+
228
+ const drive = (): Promise<void> => {
229
+ if (driving) return driverRun
230
+ driving = true
231
+ driverRun = (async () => {
232
+ try {
233
+ for (;;) {
234
+ const waitSignal = new Promise<void>((resolve) => { wake = resolve })
235
+ const commitHead = commitQueue[0]
236
+ if (commitHead !== undefined && commitHead.settled) {
237
+ commitQueue.shift()
238
+ await commitHead.commit()
239
+ if (commitHead.mode === 'exclusive') exclusiveActive = false
240
+ continue
241
+ }
242
+ const head = pendingQueue[0]
243
+ if (head !== undefined && !closed && !runController.signal.aborted && !exclusiveActive) {
244
+ const mode = head.classify()
245
+ const canStart = mode === 'parallel'
246
+ ? inFlight.size < host.maxParallelSubCalls && commitQueue.every(entry => entry.mode !== 'exclusive')
247
+ : inFlight.size === 0 && commitQueue.length === 0
248
+ if (canStart) {
249
+ pendingQueue.shift()
250
+ head.mode = mode
251
+ if (mode === 'exclusive') exclusiveActive = true
252
+ await head.start()
253
+ commitQueue.push(head)
254
+ if (!head.settled) {
255
+ const wrapped = head.flight.finally(() => {
256
+ inFlight.delete(wrapped)
257
+ wakeup()
258
+ })
259
+ inFlight.add(wrapped)
260
+ }
261
+ continue
262
+ }
263
+ }
264
+ if (pendingQueue.length === 0 && commitQueue.length === 0 && inFlight.size === 0) break
265
+ if ((closed || runController.signal.aborted) && commitQueue.length === 0 && inFlight.size === 0) break
266
+ await waitSignal
267
+ }
268
+ } finally {
269
+ driving = false
270
+ }
271
+ })()
272
+ return driverRun
273
+ }
274
+
275
+ const drainDispatches = async (): Promise<void> => {
276
+ closed = true
277
+ while (pendingQueue.length > 0) pendingQueue.shift()!.abandon()
278
+ wakeup()
279
+ await drive()
280
+ await Promise.allSettled(inFlight)
281
+ while (commitQueue.length > 0) {
282
+ const entry = commitQueue.shift()!
283
+ if (entry.settled) await entry.commit()
284
+ }
285
+ await Promise.allSettled(logWork)
286
+ }
287
+
288
+ const runOver = (): boolean => closed || runController.signal.aborted || callSignal.aborted
289
+
290
+ const binding = (schema: Readonly<ToolSchema>): PtcBindingFunction => async (rawBindingArgs: unknown): Promise<PtcJsonValue> => {
291
+ if (runOver()) {
292
+ throw new Error(`run_code run is over (${String(runController.signal.reason)}); cannot start ${schema.name}`)
293
+ }
294
+ dispatches++
295
+ if (dispatches > maxSubCalls) {
296
+ const limitError = new ToolCallLimitExceededError(maxSubCalls, subCallWindowMs)
297
+ runController.abort(limitError)
298
+ throw limitError
299
+ }
300
+ const normalized = jsonNormalizeArgs(rawBindingArgs)
301
+ const subCallId = ToolCallId(`${exec.callId}:ptc:${subSeq++}`)
302
+ const input: ToolExecutionInput = {
303
+ callId: subCallId,
304
+ rootCallId: exec.rootCallId,
305
+ name: schema.name,
306
+ arguments: normalized.dispatched,
307
+ ...(exec.agent === undefined ? {} : { agent: exec.agent }),
308
+ ...(exec.toolSet === undefined ? {} : { toolSet: exec.toolSet }),
309
+ schema,
310
+ signal: runController.signal,
311
+ parent: exec.token,
312
+ }
313
+ const outcome = await new Promise<{ isError: false; value: PtcJsonValue } | { isError: true; message: string }>((resolve, reject) => {
314
+ let parked: (ScheduledToolDispatch & { exec: ToolRunContext }) | undefined
315
+ const settle = (result: ToolExecutionResult): void => {
316
+ resolve(result.isError
317
+ ? { isError: true, message: result.error.message }
318
+ : { isError: false, value: result.value as PtcJsonValue })
319
+ if (exec.agent === undefined) return
320
+ const agent = exec.agent
321
+ const task = (async () => {
322
+ const logged = await shapeDispatchLog({
323
+ exec, agent, subCallId, name: schema.name, isError: result.isError, content: result.content,
324
+ })
325
+ agent.session.append('tool/ptc-dispatch', {
326
+ rootCallId: exec.rootCallId,
327
+ parentCallId: exec.callId,
328
+ subCallId,
329
+ name: schema.name,
330
+ arguments: normalized.logged,
331
+ isError: result.isError,
332
+ ...(result.error?.info === undefined ? {} : { error: result.error.info }),
333
+ content: logged,
334
+ ...(result.meta === undefined ? {} : { meta: result.meta as PtcJsonValue }),
335
+ })
336
+ })().finally(() => { logWork.delete(task) })
337
+ logWork.add(task)
338
+ }
339
+ pendingQueue.push({
340
+ flight: Promise.resolve(),
341
+ settled: false,
342
+ classify: () => pipeline.executionMode(input).kind,
343
+ abandon: () => {
344
+ reject(new Error(`run_code run is over (${String(runController.signal.reason)}); ${schema.name} tool call abandoned`))
345
+ },
346
+ async start(): Promise<void> {
347
+ exec.agent?.session.append('tool/ptc-dispatch-start', {
348
+ rootCallId: exec.rootCallId, parentCallId: exec.callId, subCallId, name: schema.name, arguments: normalized.logged,
349
+ })
350
+ const prepared = await pipeline.prepare(input)
351
+ if (prepared.kind === 'dispatch') {
352
+ this.flight = pipeline.dispatch(prepared.exec).then((dispatchOutcome) => {
353
+ parked = { ...dispatchOutcome, exec: prepared.exec }
354
+ this.settled = true
355
+ })
356
+ return
357
+ }
358
+ parked = { kind: prepared.kind, exec: prepared.exec, result: prepared.result }
359
+ this.settled = true
360
+ },
361
+ async commit(): Promise<void> {
362
+ if (parked === undefined) return
363
+ const result = await pipeline.complete(parked.exec, parked)
364
+ if (!result.isError && result.content.some(block => block.type === 'image')) {
365
+ exec.deferContext(createUserMessage({ content: result.content, source: { kind: 'ptc-mode' } }))
366
+ }
367
+ for (const context of result.additionalContexts ?? []) exec.deferContext(context)
368
+ if (result.concludesTurn) exec.concludeTurn()
369
+ settle(result)
370
+ while (logWork.size > host.maxParallelSubCalls) await Promise.race(logWork)
371
+ },
372
+ })
373
+ wakeup()
374
+ void drive()
375
+ })
376
+ if (runOver()) {
377
+ throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${schema.name} result discarded`)
378
+ }
379
+ if (outcome.isError) throw new Error(outcome.message)
380
+ return outcome.value
381
+ }
382
+
383
+ const functions: Record<string, PtcBindingFunction> = Object.create(null) as Record<string, PtcBindingFunction>
384
+ for (const schema of tools.schemas(exec.agent, exec.toolSet)) {
385
+ if (!host.allowNestedDirectTools && host.isDirect(schema.name)) continue
386
+ Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(deepFreeze(schema)) })
387
+ }
388
+
389
+ try {
390
+ let result: PtcRunResult
391
+ try {
392
+ if (exec.agent !== undefined && typeof runtime.release === 'function') {
393
+ const agent = exec.agent
394
+ let runtimes = host.stateOwners.get(agent)
395
+ if (runtimes === undefined) {
396
+ runtimes = new WeakSet()
397
+ host.stateOwners.set(agent, runtimes)
398
+ }
399
+ const provider = host.unwrapRuntime(runtime)
400
+ if (!runtimes.has(provider)) {
401
+ agent.ctx.effect(() => () => runtime.release(agent), 'Codex hybrid PTC retained environment')
402
+ runtimes.add(provider)
403
+ }
404
+ }
405
+ const spec = runtime.resolve({
406
+ program: rawArgs.code,
407
+ ...(exec.agent === undefined || policy?.mode !== standingPolicy?.mode ? {} : { stateOwner: exec.agent }),
408
+ bindings: [{ global: 'tools', functions, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' } }],
409
+ signal: runController.signal,
410
+ ...(cwd === undefined ? {} : { cwd }),
411
+ ...(policy === undefined ? {} : { sandboxPolicy: policy }),
412
+ ...(rawArgs.timeoutMs === undefined ? {} : { timeoutMs: rawArgs.timeoutMs }),
413
+ })
414
+ subCallWindowMs = spec.timeoutMs ?? 60_000
415
+ maxSubCalls = spec.timeoutMs === null ? Infinity : Math.max(1, Math.floor(spec.timeoutMs / 60_000 * host.maxSubCallsPerMinute))
416
+ result = await runtime.run(spec)
417
+ } finally {
418
+ runController.abort('run_code settled')
419
+ await drainDispatches()
420
+ }
421
+
422
+ if (result.error) {
423
+ const limitError = runController.signal.reason instanceof ToolCallLimitExceededError ? runController.signal.reason : undefined
424
+ if (result.error.kind === 'abort' && exec.signal.aborted && limitError === undefined) {
425
+ const message = runtime.retainsState ? `tool call aborted: ${result.error.message}` : 'tool call aborted'
426
+ const error = new HarnessError(message, TOOL_ABORTED)
427
+ error.name = 'AbortError'
428
+ throw error
429
+ }
430
+ const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : ''
431
+ const sandboxText = result.sandbox === undefined ? ''
432
+ : `\nFile sandbox: ${result.sandbox.mode}${result.sandbox.enforcement === undefined ? '' : `; enforcement: ${result.sandbox.enforcement}`}${result.sandbox.denied ? '; operation denied' : ''}.`
433
+ const failureText = limitError === undefined || limitError.message === result.error.message
434
+ ? result.error.message
435
+ : `${limitError.message}\n${result.error.message}`
436
+ throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${failureText}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime.sandboxMode) : ''}`)
437
+ }
438
+ return {
439
+ logs: result.logs,
440
+ ...(result.sandbox === undefined ? {} : { sandbox: result.sandbox }),
441
+ ...(result.value === undefined ? {} : { result: result.value }),
442
+ }
443
+ } finally {
444
+ callSignal.removeEventListener('abort', onOuterAbort)
445
+ }
446
+ }