@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,217 @@
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 { assertSupportedJsonSchema } from '@deepseek-ai/dsh-tools'
5
+ import type { JsonSchemaNode, JsonSchemaScalar } from '@deepseek-ai/dsh-tools'
6
+
7
+ /** Hybrid SDK projection: model-facing schema plus validated canonical output schema. */
8
+ export interface HybridToolSdkSchema extends Readonly<ToolSchema> {
9
+ readonly output: JsonSchemaNode
10
+ }
11
+
12
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
13
+
14
+ function renderKey(name: string): string {
15
+ return IDENTIFIER.test(name) ? name : JSON.stringify(name)
16
+ }
17
+
18
+ function pad(indent: number): string {
19
+ return ' '.repeat(indent)
20
+ }
21
+
22
+ function docLines(description: unknown, indent: number): string[] {
23
+ if (typeof description !== 'string' || description.length === 0) return []
24
+ const collapsed = description.replace(/\s+/gu, ' ').trim()
25
+ if (collapsed.length === 0) return []
26
+ return [`${pad(indent)}/** ${collapsed.replaceAll('*/', String.raw`*\/`)} */`]
27
+ }
28
+
29
+ function renderScalar(node: JsonSchemaNode, type: string): string {
30
+ const broad = type === 'integer' ? 'number' : type
31
+ if (Object.hasOwn(node, 'const')) return JSON.stringify(node.const as JsonSchemaScalar)
32
+ if (Object.hasOwn(node, 'enum')) {
33
+ return (node.enum as JsonSchemaScalar[]).map(value => JSON.stringify(value)).join(' | ')
34
+ }
35
+ return broad
36
+ }
37
+
38
+ function containsUnion(text: string): boolean {
39
+ return text.includes(' | ')
40
+ }
41
+
42
+ function renderObjectNode(node: JsonSchemaNode, indent: number): string {
43
+ const properties = node.properties ?? {}
44
+ const required = new Set(node.required ?? [])
45
+ const keys = Object.keys(properties).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
46
+ const lines: string[] = []
47
+ for (const key of keys) {
48
+ const child = properties[key]
49
+ if (child === undefined) continue
50
+ lines.push(...docLines(child.description, indent + 1))
51
+ const optional = required.has(key) ? '' : '?'
52
+ lines.push(`${pad(indent + 1)}${renderKey(key)}${optional}: ${renderNode(child, indent + 1)};`)
53
+ }
54
+ if (node.additionalProperties !== false) {
55
+ lines.push(`${pad(indent + 1)}[key: string]: JsonValue;`)
56
+ }
57
+ if (lines.length === 0) return '{}'
58
+ return `{\n${lines.join('\n')}\n${pad(indent)}}`
59
+ }
60
+
61
+ function renderNode(node: JsonSchemaNode, indent: number): string {
62
+ if (Array.isArray(node.oneOf) && node.oneOf.length > 0) {
63
+ return node.oneOf.map(branch => renderNode(branch, indent)).join(' | ')
64
+ }
65
+ switch (node.type) {
66
+ case undefined:
67
+ return 'JsonValue'
68
+ case 'object':
69
+ return renderObjectNode(node, indent)
70
+ case 'array': {
71
+ const itemText = node.items === undefined ? 'JsonValue' : renderNode(node.items, indent)
72
+ return containsUnion(itemText) ? `(${itemText})[]` : `${itemText}[]`
73
+ }
74
+ case 'string':
75
+ case 'number':
76
+ case 'integer':
77
+ case 'boolean':
78
+ case 'null':
79
+ return renderScalar(node, node.type)
80
+ default:
81
+ return 'unknown'
82
+ }
83
+ }
84
+
85
+ /** Render one supported JSON Schema node to TypeScript, degrading invalid schemas safely. */
86
+ export function jsonSchemaToTs(schema: unknown, indent = 0): string {
87
+ try {
88
+ assertSupportedJsonSchema(schema)
89
+ return renderNode(schema, indent)
90
+ } catch {
91
+ return 'unknown'
92
+ }
93
+ }
94
+
95
+ function renderPythonAnnotation(node: JsonSchemaNode): string {
96
+ if (Array.isArray(node.oneOf) && node.oneOf.length > 0) {
97
+ return node.oneOf.map(renderPythonAnnotation).join(' | ')
98
+ }
99
+ switch (node.type) {
100
+ case 'object':
101
+ return 'dict[str, Any]'
102
+ case 'array':
103
+ return node.items === undefined ? 'list[Any]' : `list[${renderPythonAnnotation(node.items)}]`
104
+ case 'string':
105
+ return 'str'
106
+ case 'integer':
107
+ return 'int'
108
+ case 'number':
109
+ return 'float'
110
+ case 'boolean':
111
+ return 'bool'
112
+ case 'null':
113
+ return 'None'
114
+ default:
115
+ return 'Any'
116
+ }
117
+ }
118
+
119
+ function safePyIdentifier(name: string): string {
120
+ return /^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) ? name : `tool_${name.replace(/[^A-Za-z0-9_]+/gu, '_')}`
121
+ }
122
+
123
+ function renderPythonSdk(sorted: readonly HybridToolSdkSchema[], programFormat: PtcProgramFormat): string {
124
+ const methods = sorted.map((schema) => {
125
+ let returnType = 'Any'
126
+ try {
127
+ assertSupportedJsonSchema(schema.output)
128
+ returnType = renderPythonAnnotation(schema.output)
129
+ } catch {
130
+ returnType = 'Any'
131
+ }
132
+ const doc = schema.description.replace(/\s+/gu, ' ').trim().replaceAll('"""', '\\"\\"\\"')
133
+ return [
134
+ ` async def ${safePyIdentifier(schema.name)}(self, args: dict[str, Any]) -> ${returnType}:`,
135
+ ...(doc ? [` """${doc}"""`] : []),
136
+ ' ...',
137
+ ].join('\n')
138
+ })
139
+ const outputRule = programFormat === 'function-body'
140
+ ? 'Print results cleanly with `print(...)` or `return`.'
141
+ : 'Emit only concise summaries for the conversation.'
142
+ return [
143
+ '## Hybrid SDK bindings (`run_code`)',
144
+ '',
145
+ 'Invoke the SDK tools below only inside `run_code` via `await tools.<name>(args)`. Direct wire tools must still be called directly, not through `tools`.',
146
+ `Batch independent read/search calls with \`asyncio.gather\`. ${outputRule}`,
147
+ '',
148
+ '```python',
149
+ 'from typing import Any',
150
+ '',
151
+ 'class ToolCallError(Exception):',
152
+ ' toolName: str',
153
+ '',
154
+ 'class _ToolsSdk:',
155
+ ...methods,
156
+ '',
157
+ 'tools: _ToolsSdk',
158
+ '```',
159
+ ].join('\n')
160
+ }
161
+
162
+ /** Render deterministic SDK declarations for hybrid `run_code` bindings. */
163
+ export function renderHybridToolsSdk(
164
+ schemas: readonly HybridToolSdkSchema[],
165
+ language: 'typescript' | 'python' = 'typescript',
166
+ programFormat: PtcProgramFormat = 'function-body',
167
+ ): string {
168
+ if (schemas.length === 0) {
169
+ return [
170
+ '## Hybrid SDK bindings (`run_code`)',
171
+ '',
172
+ 'No SDK tools are currently active in this step. Direct tools remain callable directly without `run_code`. If you need a deferred tool, call `activate_tools` first and invoke it on the next step.',
173
+ ].join('\n')
174
+ }
175
+ const sorted = [...schemas].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
176
+ if (language === 'python') return renderPythonSdk(sorted, programFormat)
177
+
178
+ const programDescription = programFormat === 'function-body'
179
+ ? 'the body of an async TypeScript function (erasable syntax only; top-level `await` and `return` work)'
180
+ : 'the TypeScript program to execute'
181
+ const outputInstruction = programFormat === 'function-body'
182
+ ? 'Emit curated output with `return` and/or `console.log(...)`.'
183
+ : 'Only printed/emitted program output enters the conversation.'
184
+
185
+ const argsMembers: string[] = []
186
+ const outputMembers: string[] = []
187
+ for (const schema of sorted) {
188
+ argsMembers.push(...docLines(schema.description, 1))
189
+ argsMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1)};`)
190
+ outputMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.output, 1)};`)
191
+ }
192
+
193
+ const declaration = [
194
+ `interface ToolArgsMap {\n${argsMembers.join('\n')}\n}`,
195
+ `interface ToolOutputMap {\n${outputMembers.join('\n')}\n}`,
196
+ 'type ToolName = keyof ToolOutputMap',
197
+ ['declare class ToolCallError extends Error {', ' readonly name: "ToolCallError";', ' readonly toolName: ToolName;', '}'].join('\n'),
198
+ ['declare const tools: {', ' [K in ToolName]: (args: ToolArgsMap[K]) => Promise<ToolOutputMap[K]>;', '}'].join('\n'),
199
+ ].join('\n\n')
200
+
201
+ return [
202
+ '## Hybrid SDK bindings (`run_code`)',
203
+ '',
204
+ `\`run_code\` executes ${programDescription}. Direct wire tools are NOT available on \`tools\` unless explicitly configured — call those directly. Call every SDK tool below only inside \`run_code\`:`,
205
+ '',
206
+ '- Call tools as `await tools.name(args)` (quoted for exotic names: `tools["my-tool"](args)`). Each resolves to its typed canonical JSON value; arguments must be lossless JSON.',
207
+ '- A failed tool call rejects with `ToolCallError` (carrying `.toolName` and `.message`); handle errors with `try/catch`.',
208
+ '- Batch independent read/search calls concurrently with `Promise.all`; sequence dependent steps with `await`.',
209
+ `- ${outputInstruction} Image-bearing subtool results are attached automatically after the run; extract only what you need from text/JSON results.`,
210
+ '',
211
+ '```ts',
212
+ 'type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }',
213
+ '',
214
+ declaration,
215
+ '```',
216
+ ].join('\n')
217
+ }
@@ -0,0 +1,202 @@
1
+ /** Lossless JSON helpers, hybrid PTC errors, and per-session run/reset coordination. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import { HarnessError } from '@deepseek-ai/dsh-llm'
4
+ import type { PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime'
5
+ import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
6
+ import type { SessionId } from '@deepseek-ai/dsh-session'
7
+ import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline'
8
+
9
+ export class CodeRunFailedError extends HarnessError {
10
+ constructor(message: string) {
11
+ super(message, 'PTC_RUN_FAILED')
12
+ this.name = 'CodeRunFailedError'
13
+ }
14
+ }
15
+
16
+ export class CodeResetFailedError extends HarnessError {
17
+ constructor(message: string) {
18
+ super(message, 'PTC_RESET_FAILED')
19
+ this.name = 'CodeResetFailedError'
20
+ }
21
+ }
22
+
23
+ export function snapshotJsonValue(value: unknown, seen = new WeakSet<object>()): PtcJsonValue | undefined {
24
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') {
25
+ return undefined
26
+ }
27
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') return value
28
+ if (typeof value === 'number') {
29
+ if (!Number.isFinite(value)) throw new Error('non-finite number is not lossless JSON')
30
+ return Object.is(value, -0) ? 0 : value
31
+ }
32
+ if (typeof value !== 'object') return undefined
33
+ if (seen.has(value)) throw new Error('cyclic structure is not lossless JSON')
34
+ seen.add(value)
35
+ try {
36
+ if (Array.isArray(value)) {
37
+ const copy: PtcJsonValue[] = []
38
+ for (let i = 0; i < value.length; i++) {
39
+ if (!Object.hasOwn(value, i)) throw new Error('sparse array is not lossless JSON')
40
+ const item = snapshotJsonValue(value[i], seen)
41
+ if (item === undefined) throw new Error('array element is not lossless JSON')
42
+ copy.push(item)
43
+ }
44
+ return copy
45
+ }
46
+ const proto = Object.getPrototypeOf(value) as object | null
47
+ if (proto !== Object.prototype && proto !== null) {
48
+ throw new Error('non-plain object is not lossless JSON')
49
+ }
50
+ const copy: { [key: string]: PtcJsonValue } = {}
51
+ for (const key of Object.keys(value)) {
52
+ const prop = (value as Record<string, unknown>)[key]
53
+ if (prop === undefined) continue
54
+ const snapped = snapshotJsonValue(prop, seen)
55
+ if (snapped === undefined) throw new Error(`property ${JSON.stringify(key)} is not lossless JSON`)
56
+ copy[key] = snapped
57
+ }
58
+ return copy
59
+ } finally {
60
+ seen.delete(value)
61
+ }
62
+ }
63
+
64
+ export function deepFreeze<T>(value: T): T {
65
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
66
+ Object.freeze(value)
67
+ for (const child of Object.values(value as Record<string, unknown>)) {
68
+ deepFreeze(child)
69
+ }
70
+ }
71
+ return value
72
+ }
73
+
74
+ export function jsonNormalizeArgs(value: unknown): { dispatched: unknown; logged: unknown } {
75
+ let snapshot: PtcJsonValue | undefined
76
+ try {
77
+ snapshot = snapshotJsonValue(value)
78
+ } catch (error: unknown) {
79
+ throw new Error(`tool arguments must be lossless JSON: ${error instanceof Error ? error.message : String(error)}`)
80
+ }
81
+ if (snapshot === undefined) {
82
+ throw new Error('tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)')
83
+ }
84
+ const logged = snapshotJsonValue(snapshot)
85
+ if (logged === undefined) {
86
+ throw new Error('tool arguments could not be detached for durable logging')
87
+ }
88
+ return { dispatched: snapshot, logged }
89
+ }
90
+
91
+ export function renderRunCodeValue(value: PtcJsonValue): string {
92
+ if (typeof value === 'string') return value
93
+ const encoded = JSON.stringify(value, null, 2)
94
+ return encoded ?? String(value)
95
+ }
96
+
97
+ interface ActiveCall {
98
+ mode: SandboxMode | undefined
99
+ controller: AbortController
100
+ signal: AbortSignal
101
+ done: Promise<void>
102
+ }
103
+
104
+ interface ActiveReset {
105
+ done: Promise<void>
106
+ settled: boolean
107
+ }
108
+
109
+ export class HybridProgramCalls {
110
+ private readonly calls = new Map<SessionId, Set<ActiveCall>>()
111
+ private readonly resets = new Map<SessionId, ActiveReset>()
112
+ private disposed = false
113
+
114
+ constructor(ctx: Context) {
115
+ if (typeof (ctx as Partial<Context>).on === 'function') {
116
+ ctx.on('session/event', (session, event) => {
117
+ if (event.type !== 'sandbox/mode') return
118
+ for (const call of this.calls.get(session.id) ?? []) {
119
+ if (call.mode !== undefined && call.mode !== event.data.mode) {
120
+ call.controller.abort(new Error('sandbox mode changed'))
121
+ }
122
+ }
123
+ }, { global: true })
124
+ }
125
+ if (typeof (ctx as Partial<Context>).effect === 'function') {
126
+ ctx.effect(() => async () => {
127
+ this.disposed = true
128
+ const active = [...this.calls.values()].flatMap(set => [...set])
129
+ for (const call of active) call.controller.abort(new Error('Hybrid tool executor disposed'))
130
+ await Promise.allSettled([
131
+ ...active.map(call => call.done),
132
+ ...[...this.resets.values()].map(reset => reset.done),
133
+ ])
134
+ }, 'Codex hybrid PTC calls')
135
+ }
136
+ }
137
+
138
+ async run<T>(
139
+ sessionId: SessionId,
140
+ signal: AbortSignal,
141
+ mode: () => SandboxMode | undefined,
142
+ fn: (callSignal: AbortSignal) => Promise<T>,
143
+ ): Promise<T> {
144
+ for (;;) {
145
+ const reset = this.resets.get(sessionId)
146
+ if (reset !== undefined) {
147
+ try {
148
+ await reset.done
149
+ } catch (error) {
150
+ throw new CodeRunFailedError(`Program environment unavailable: ${toolErrorMessage(error)}. Ask the host to reset it before running more code.`)
151
+ }
152
+ continue
153
+ }
154
+ const pending = [...this.calls.get(sessionId) ?? []].filter(call => call.signal.aborted)
155
+ if (pending.length === 0) break
156
+ await Promise.all(pending.map(call => call.done))
157
+ }
158
+ signal.throwIfAborted()
159
+ if (this.disposed) throw new Error('Hybrid tool executor disposed')
160
+ const controller = new AbortController()
161
+ const done = Promise.withResolvers<undefined>()
162
+ const callSignal = AbortSignal.any([signal, controller.signal])
163
+ const call: ActiveCall = { mode: mode(), controller, signal: callSignal, done: done.promise }
164
+ let sessionCalls = this.calls.get(sessionId)
165
+ if (sessionCalls === undefined) {
166
+ sessionCalls = new Set()
167
+ this.calls.set(sessionId, sessionCalls)
168
+ }
169
+ sessionCalls.add(call)
170
+ try {
171
+ return await fn(callSignal)
172
+ } finally {
173
+ sessionCalls.delete(call)
174
+ if (sessionCalls.size === 0) this.calls.delete(sessionId)
175
+ done.resolve(undefined)
176
+ }
177
+ }
178
+
179
+ reset(sessionId: SessionId, release: () => Promise<void>, notify?: () => void): Promise<void> {
180
+ if (this.disposed) return Promise.reject(new Error('Hybrid tool executor disposed'))
181
+ const previous = this.resets.get(sessionId)
182
+ if (previous !== undefined && !previous.settled) return previous.done
183
+ const done = Promise.withResolvers<undefined>()
184
+ const reset: ActiveReset = { done: done.promise, settled: false }
185
+ this.resets.set(sessionId, reset)
186
+ const calls = [...this.calls.get(sessionId) ?? []]
187
+ for (const call of calls) call.controller.abort(new Error('PTC environment reset'))
188
+ void Promise.allSettled([Promise.resolve().then(release), ...calls.map(call => call.done)]).then((results) => {
189
+ const failure = results.find(result => result.status === 'rejected')
190
+ if (failure !== undefined) throw failure.reason
191
+ notify?.()
192
+ }).then(() => {
193
+ reset.settled = true
194
+ this.resets.delete(sessionId)
195
+ done.resolve(undefined)
196
+ }, (error: unknown) => {
197
+ reset.settled = true
198
+ done.reject(error)
199
+ })
200
+ return reset.done
201
+ }
202
+ }