@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,261 @@
1
+ /** Pure Responses wire transformations for hosted search, custom `apply_patch`, and compaction items. */
2
+
3
+ import type { GenerateOptions } from '@deepseek-ai/dsh-llm'
4
+ import { isGptModel } from '../contracts/settings.ts'
5
+ import { APPLY_PATCH_DESCRIPTION, APPLY_PATCH_GRAMMAR } from '../tools/patch.ts'
6
+ import {
7
+ REMOTE_COMPACTION_OPEN,
8
+ REMOTE_COMPACTION_CLOSE,
9
+ decodeRemoteCompactionMarker,
10
+ extractMarkerBody,
11
+ type JsonObject,
12
+ } from './compact-checkpoint.ts'
13
+
14
+ export { REMOTE_COMPACTION_OPEN, REMOTE_COMPACTION_CLOSE, decodeRemoteCompactionMarker, extractMarkerBody }
15
+ export type { JsonObject }
16
+
17
+ export interface CodexRequestWireOptions {
18
+ /** Provider-facing request option preserved by older DSH LLM adapters. */
19
+ serviceTier?: string
20
+ /** Whether local web_search should become the hosted Responses tool. */
21
+ hostedWebSearch?: boolean
22
+ /** Whether apply_patch should use the Responses custom grammar tool. */
23
+ customApplyPatch?: boolean
24
+ /** Marker bodies verified to come from persisted compaction checkpoint sources. */
25
+ trustedCheckpoints?: ReadonlySet<string>
26
+ }
27
+
28
+ export function serviceTierOf(options: GenerateOptions): string | undefined {
29
+ const value = (options as GenerateOptions & { serviceTier?: unknown }).serviceTier
30
+ return typeof value === 'string' ? value : undefined
31
+ }
32
+
33
+ export function isWebSearchTool(tool: unknown): boolean {
34
+ if (typeof tool !== 'object' || tool === null) return false
35
+ const value = tool as JsonObject
36
+ if (value.defer_loading === true) return false
37
+ if (value.name === 'web_search') return true
38
+ const fn = value.function
39
+ return typeof fn === 'object'
40
+ && fn !== null
41
+ && (fn as JsonObject).defer_loading !== true
42
+ && (fn as JsonObject).name === 'web_search'
43
+ }
44
+
45
+ export function hasWebSearchTool(body: JsonObject): boolean {
46
+ return Array.isArray(body.tools) && body.tools.some(isWebSearchTool)
47
+ }
48
+
49
+ function toolName(tool: unknown): string | undefined {
50
+ if (typeof tool !== 'object' || tool === null) return undefined
51
+ const value = tool as JsonObject
52
+ if (typeof value.name === 'string') return value.name
53
+ const fn = value.function
54
+ return typeof fn === 'object' && fn !== null && typeof (fn as JsonObject).name === 'string'
55
+ ? (fn as JsonObject).name as string
56
+ : undefined
57
+ }
58
+
59
+ function isApplyPatchTool(tool: unknown): boolean {
60
+ return toolName(tool) === 'apply_patch'
61
+ }
62
+
63
+ function isFunctionApplyPatchTool(tool: unknown): boolean {
64
+ if (!isApplyPatchTool(tool) || typeof tool !== 'object' || tool === null) return false
65
+ return (tool as JsonObject).type !== 'custom'
66
+ }
67
+
68
+ export function hasFunctionApplyPatchTool(body: JsonObject): boolean {
69
+ return Array.isArray(body.tools) && body.tools.some(isFunctionApplyPatchTool)
70
+ }
71
+
72
+ function applyPatchTool(tool: unknown): JsonObject {
73
+ const value = tool as JsonObject
74
+ const fn = value.function
75
+ const description = typeof value.description === 'string'
76
+ ? value.description
77
+ : typeof fn === 'object' && fn !== null && typeof (fn as JsonObject).description === 'string'
78
+ ? (fn as JsonObject).description as string
79
+ : APPLY_PATCH_DESCRIPTION
80
+ const custom: JsonObject = {
81
+ type: 'custom',
82
+ name: 'apply_patch',
83
+ description,
84
+ format: {
85
+ type: 'grammar',
86
+ syntax: 'lark',
87
+ definition: APPLY_PATCH_GRAMMAR,
88
+ },
89
+ }
90
+ if (value.defer_loading !== undefined) custom.defer_loading = value.defer_loading
91
+ return custom
92
+ }
93
+
94
+ /** Replace DSH's JSON function declaration with the Responses custom grammar tool. */
95
+ export function addCodexApplyPatch(body: JsonObject): JsonObject {
96
+ if (!Array.isArray(body.tools)) return body
97
+ let changed = false
98
+ const tools = body.tools.map(tool => {
99
+ if (!isApplyPatchTool(tool) || typeof tool !== 'object' || tool === null) return tool
100
+ if ((tool as JsonObject).type === 'custom') return tool
101
+ changed = true
102
+ return applyPatchTool(tool)
103
+ })
104
+ return changed ? { ...body, tools } : body
105
+ }
106
+
107
+ function applyPatchInputOfCall(item: JsonObject): { callId: string; input: string } | undefined {
108
+ if (item.type !== 'function_call' || item.name !== 'apply_patch') return undefined
109
+ if (typeof item.call_id !== 'string' || item.call_id.length === 0) return undefined
110
+ const raw = item.arguments
111
+ const argumentsObject = typeof raw === 'string'
112
+ ? (() => {
113
+ try {
114
+ return JSON.parse(raw) as unknown
115
+ } catch {
116
+ return undefined
117
+ }
118
+ })()
119
+ : raw
120
+ if (typeof argumentsObject !== 'object' || argumentsObject === null) return undefined
121
+ const input = (argumentsObject as JsonObject).input
122
+ return typeof input === 'string' ? { callId: item.call_id, input } : undefined
123
+ }
124
+
125
+ export function canRewriteApplyPatchHistory(body: JsonObject): boolean {
126
+ if (!Array.isArray(body.input)) return true
127
+ return body.input.every(item => {
128
+ if (typeof item !== 'object' || item === null) return true
129
+ const value = item as JsonObject
130
+ return value.type !== 'function_call' || value.name !== 'apply_patch'
131
+ || applyPatchInputOfCall(value) !== undefined
132
+ })
133
+ }
134
+
135
+ /** Replay apply_patch calls as custom tool items after pi-ai's generic conversion. */
136
+ export function rewriteCodexApplyPatchHistory(body: JsonObject): JsonObject {
137
+ if (!Array.isArray(body.input) || !canRewriteApplyPatchHistory(body)) return body
138
+ const applyCallIds = new Set<string>()
139
+ for (const item of body.input) {
140
+ if (typeof item !== 'object' || item === null) continue
141
+ const value = item as JsonObject
142
+ if (value.type === 'custom_tool_call' && value.name === 'apply_patch' && typeof value.call_id === 'string') {
143
+ applyCallIds.add(value.call_id)
144
+ }
145
+ const call = applyPatchInputOfCall(value)
146
+ if (call !== undefined) applyCallIds.add(call.callId)
147
+ }
148
+ if (applyCallIds.size === 0) return body
149
+
150
+ let changed = false
151
+ const input = body.input.map(item => {
152
+ if (typeof item !== 'object' || item === null) return item
153
+ const value = item as JsonObject
154
+ const call = applyPatchInputOfCall(value)
155
+ if (call !== undefined) {
156
+ const next: JsonObject = {
157
+ type: 'custom_tool_call',
158
+ call_id: call.callId,
159
+ name: 'apply_patch',
160
+ input: call.input,
161
+ }
162
+ if (typeof value.id === 'string' && !value.id.startsWith('fc_')) next.id = value.id
163
+ changed = true
164
+ return next
165
+ }
166
+ if (value.type === 'function_call_output'
167
+ && typeof value.call_id === 'string'
168
+ && applyCallIds.has(value.call_id)) {
169
+ changed = true
170
+ return {
171
+ type: 'custom_tool_call_output',
172
+ call_id: value.call_id,
173
+ output: value.output,
174
+ }
175
+ }
176
+ return item
177
+ })
178
+ return changed ? { ...body, input } : body
179
+ }
180
+
181
+ /** Detect provider-native compaction triggers owned by adapters such as `dsh-codex-connect`. */
182
+ export function isNativeCompactionTriggerBody(body: JsonObject): boolean {
183
+ return Array.isArray(body.input) && body.input.some(
184
+ item => typeof item === 'object' && item !== null && (item as JsonObject).type === 'compaction_trigger',
185
+ )
186
+ }
187
+
188
+ /** Compose the plugin-only Responses rewrites without changing DSH's tool API. */
189
+ export function rewriteCodexResponsesBody(
190
+ body: JsonObject,
191
+ options: Pick<CodexRequestWireOptions, 'hostedWebSearch' | 'customApplyPatch' | 'trustedCheckpoints'> = {},
192
+ ): JsonObject {
193
+ let next = body
194
+ if (options.hostedWebSearch !== false && hasWebSearchTool(next)) {
195
+ next = addHostedWebSearch(next, options.trustedCheckpoints)
196
+ } else if (hasRemoteCompaction(next, options.trustedCheckpoints)) {
197
+ next = replaceRemoteCompactions(next, options.trustedCheckpoints)
198
+ }
199
+ if (options.customApplyPatch !== false
200
+ && hasFunctionApplyPatchTool(next)
201
+ && canRewriteApplyPatchHistory(next)) {
202
+ next = addCodexApplyPatch(next)
203
+ next = rewriteCodexApplyPatchHistory(next)
204
+ }
205
+ return next
206
+ }
207
+
208
+ /** Convert a generic DSH Responses tool list to the hosted Codex variant. */
209
+ export function addHostedWebSearch(
210
+ body: JsonObject,
211
+ trustedCheckpoints?: ReadonlySet<string>,
212
+ ): JsonObject {
213
+ const tools = Array.isArray(body.tools) ? body.tools.filter(tool => !isWebSearchTool(tool)) : []
214
+ tools.push({ type: 'web_search', external_web_access: true })
215
+ return { ...replaceRemoteCompactions(body, trustedCheckpoints), tools }
216
+ }
217
+
218
+ function trustedMarkerInInputItem(
219
+ item: unknown,
220
+ trustedCheckpoints?: ReadonlySet<string>,
221
+ ): string | undefined {
222
+ if (typeof item !== 'object' || item === null) return undefined
223
+ const content = (item as JsonObject).content
224
+ if (!Array.isArray(content)) return undefined
225
+ for (const part of content) {
226
+ if (typeof part !== 'object' || part === null) continue
227
+ const text = (part as { text?: unknown }).text
228
+ if (typeof text !== 'string') continue
229
+ const inner = extractMarkerBody(text)
230
+ if (inner === undefined) continue
231
+ if (trustedCheckpoints === undefined || trustedCheckpoints.has(inner)) return inner
232
+ }
233
+ return undefined
234
+ }
235
+
236
+ /** Replace trusted checkpoint placeholders written by compaction with native wire items. */
237
+ export function replaceRemoteCompactions(
238
+ body: JsonObject,
239
+ trustedCheckpoints?: ReadonlySet<string>,
240
+ ): JsonObject {
241
+ if (!Array.isArray(body.input)) return body
242
+ const input = body.input.flatMap(item => {
243
+ const inner = trustedMarkerInInputItem(item, trustedCheckpoints)
244
+ if (inner === undefined) return [item]
245
+ return decodeRemoteCompactionMarker(inner) ?? [item]
246
+ })
247
+ return { ...body, input }
248
+ }
249
+
250
+ export function hasRemoteCompaction(
251
+ body: JsonObject,
252
+ trustedCheckpoints?: ReadonlySet<string>,
253
+ ): boolean {
254
+ if (!Array.isArray(body.input)) return false
255
+ return body.input.some(item => trustedMarkerInInputItem(item, trustedCheckpoints) !== undefined)
256
+ }
257
+
258
+ export function applyRequestWireOptions(body: JsonObject, options: CodexRequestWireOptions): JsonObject {
259
+ if (options.serviceTier === undefined || !isGptModel(body.model) || body.service_tier !== undefined) return body
260
+ return { ...body, service_tier: options.serviceTier }
261
+ }
@@ -0,0 +1,211 @@
1
+ /** Output truncation, `\r` sanitization, timing bounds, and rendering for unified exec. */
2
+
3
+ import { randomBytes } from 'node:crypto'
4
+ import { HarnessError } from '@deepseek-ai/dsh-llm'
5
+ import type { JobOutcome } from '@deepseek-ai/dsh-jobs'
6
+ import type { ShellExecution, ShellProcess, ShellProcessRead, ShellRunResult } from '@deepseek-ai/dsh-shell'
7
+ import { escalationHintMarker, sandboxDenialMarker } from '@deepseek-ai/dsh-sandbox'
8
+ import type { TerminalSendResult } from '@deepseek-ai/dsh-terminal'
9
+
10
+ /** The exact model-facing argument vocabulary of Codex's unified exec tool. */
11
+ export interface ExecCommandArgs {
12
+ cmd: string
13
+ workdir?: string
14
+ tty?: boolean
15
+ run_in_background?: boolean
16
+ yield_time_ms?: number
17
+ max_output_tokens?: number
18
+ sandbox_permissions?: string
19
+ justification?: string
20
+ }
21
+
22
+ /** The exact model-facing argument vocabulary of Codex's stdin poll tool. */
23
+ export interface WriteStdinArgs {
24
+ session_id: number
25
+ chars?: string
26
+ yield_time_ms?: number
27
+ max_output_tokens?: number
28
+ }
29
+
30
+ /** Canonical result fields shared by both unified exec tools. */
31
+ export interface ExecResult {
32
+ chunk_id?: string
33
+ wall_time_seconds: number
34
+ output: string
35
+ session_id?: number
36
+ job_id?: string
37
+ exit_code?: number
38
+ original_token_count?: number
39
+ }
40
+
41
+ const MIN_YIELD_TIME_MS = 250
42
+ const WINDOWS_INITIAL_EXEC_YIELD_TIME_MS = 10_000
43
+ const MIN_EMPTY_YIELD_TIME_MS = 5_000
44
+ const MAX_YIELD_TIME_MS = 30_000
45
+ const MAX_EMPTY_YIELD_TIME_MS = 300_000
46
+ const DEFAULT_OUTPUT_TOKENS = 10_000
47
+ const APPROX_BYTES_PER_TOKEN = 4
48
+ const INTERACTIVE_PROMPT_RE = /(?:\[(?:y\/n|yes\/no)\]|\((?:y\/n|yes\/no)\)|(?:password|passphrase|overwrite|continue)\s*[?:]\s*$)/i
49
+
50
+ export function positiveFinite(name: string, value: number | undefined): void {
51
+ if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
52
+ throw new Error(`${name} must be a non-negative finite number`)
53
+ }
54
+ }
55
+
56
+ export function normalizeWaitMs(
57
+ value: number | undefined,
58
+ fallback: number,
59
+ empty = false,
60
+ initialExec = false,
61
+ ): number {
62
+ const lower = empty
63
+ ? MIN_EMPTY_YIELD_TIME_MS
64
+ : initialExec && process.platform === 'win32'
65
+ ? WINDOWS_INITIAL_EXEC_YIELD_TIME_MS
66
+ : MIN_YIELD_TIME_MS
67
+ const upper = empty ? MAX_EMPTY_YIELD_TIME_MS : MAX_YIELD_TIME_MS
68
+ return Math.max(lower, Math.min(upper, Math.trunc(value ?? fallback)))
69
+ }
70
+
71
+ export function outputLimit(maxOutputBytes: number, maxOutputTokens: number | undefined): number {
72
+ const tokens = maxOutputTokens ?? DEFAULT_OUTPUT_TOKENS
73
+ if (maxOutputTokens !== undefined) positiveFinite('max_output_tokens', maxOutputTokens)
74
+ return Math.max(1, Math.min(maxOutputBytes, Math.trunc(tokens * APPROX_BYTES_PER_TOKEN)))
75
+ }
76
+
77
+ /** O(N) symmetric head+tail UTF-8 truncation that never splits a code point. */
78
+ export function truncateOutput(text: string, maxBytes: number): { text: string; originalTokenCount?: number } {
79
+ const totalBytes = Buffer.byteLength(text, 'utf8')
80
+ if (totalBytes <= maxBytes) return { text }
81
+ const buf = Buffer.from(text, 'utf8')
82
+ const headBudget = Math.ceil(maxBytes / 2)
83
+ const tailBudget = Math.floor(maxBytes / 2)
84
+ let headEnd = Math.min(headBudget, buf.length)
85
+ // Walk back past UTF-8 continuation bytes (10xxxxxx) to land on a code point boundary.
86
+ while (headEnd > 0 && headEnd < buf.length && (buf[headEnd]! & 0xc0) === 0x80) headEnd--
87
+ let tailStart = Math.max(headEnd, buf.length - tailBudget)
88
+ // Walk forward past continuation bytes so tail starts cleanly at a code point boundary.
89
+ while (tailStart < buf.length && (buf[tailStart]! & 0xc0) === 0x80) tailStart++
90
+ const omittedBytes = tailStart - headEnd
91
+ if (omittedBytes <= 0) return { text }
92
+ const marker = `…${Math.ceil(omittedBytes / APPROX_BYTES_PER_TOKEN)} tokens truncated…`
93
+ const head = headEnd > 0 ? buf.subarray(0, headEnd).toString('utf8') : ''
94
+ const tail = tailStart < buf.length ? buf.subarray(tailStart).toString('utf8') : ''
95
+ const formatted = head.length > 0 && tail.length > 0
96
+ ? `${head}\n${marker}\n${tail}`
97
+ : head.length > 0
98
+ ? `${head}\n${marker}`
99
+ : tail.length > 0
100
+ ? `${marker}\n${tail}`
101
+ : marker
102
+ return {
103
+ text: formatted,
104
+ originalTokenCount: Math.ceil(totalBytes / APPROX_BYTES_PER_TOKEN),
105
+ }
106
+ }
107
+
108
+ /** Strip NULs and collapse bare `\r` progress overwrites on pipe output while preserving `\r\n`. */
109
+ export function sanitizePipeOutput(delta: string): string {
110
+ if (!delta.includes('\x00') && !delta.includes('\r')) return delta
111
+ const withoutNulls = delta.includes('\x00') ? delta.replaceAll('\x00', '') : delta
112
+ if (!/\r(?!\n)/.test(withoutNulls)) return withoutNulls
113
+ const lines = withoutNulls.split('\n')
114
+ return lines.map((line, index) => {
115
+ const hasCrlf = index < lines.length - 1 && line.endsWith('\r')
116
+ const body = hasCrlf ? line.slice(0, -1) : line
117
+ if (!body.includes('\r')) return hasCrlf ? `${body}\r` : body
118
+ const segments = body.split('\r')
119
+ const collapsed = segments.findLast(segment => segment.length > 0) ?? ''
120
+ return hasCrlf ? `${collapsed}\r` : collapsed
121
+ }).join('\n')
122
+ }
123
+
124
+ export function hasInteractivePrompt(output: string): boolean {
125
+ const lines = output.split(/\r?\n/)
126
+ for (let i = lines.length - 1; i >= 0; i--) {
127
+ const line = lines[i]!.trimEnd()
128
+ if (line.length === 0) continue
129
+ return INTERACTIVE_PROMPT_RE.test(line)
130
+ }
131
+ return false
132
+ }
133
+
134
+ export function withChunkId(result: Omit<ExecResult, 'chunk_id'>): ExecResult {
135
+ return { chunk_id: randomBytes(3).toString('hex'), ...result }
136
+ }
137
+
138
+ /** Render the ordinary Responses tool result text used by Codex's unified exec tools. */
139
+ export function renderExecResult(result: ExecResult): string {
140
+ const sections: string[] = []
141
+ if (result.chunk_id !== undefined) sections.push(`Chunk ID: ${result.chunk_id}`)
142
+ sections.push(`Wall time: ${result.wall_time_seconds.toFixed(4)} seconds`)
143
+ if (result.exit_code !== undefined) sections.push(`Process exited with code ${result.exit_code}`)
144
+ if (result.session_id !== undefined) sections.push(`Process running with session ID ${result.session_id}`)
145
+ if (result.job_id !== undefined) sections.push(`Background job ID: ${result.job_id}`)
146
+ if (result.original_token_count !== undefined) sections.push(`Original token count: ${result.original_token_count}`)
147
+ sections.push('Output:', result.output)
148
+ return sections.join('\n')
149
+ }
150
+
151
+ /** Preserve policy/runner facts after bounding command output; never truncate these markers. */
152
+ export function sandboxNotes(sandbox: ShellProcess['sandbox'], escalationAvailable: boolean): string[] {
153
+ if (sandbox?.runnerFailed) return [`[sandbox: the sandbox runner itself failed under ${sandbox.mode} mode — the command did not run; this is a sandbox problem, not a command failure]`]
154
+ if (!sandbox?.denied) return []
155
+ return [sandboxDenialMarker(sandbox.mode), ...escalationAvailable ? [escalationHintMarker('command')] : []]
156
+ }
157
+
158
+ /** Surface infrastructure failures from the execution handle without reclassifying nonzero exits. */
159
+ export async function assertShellCompleted(process: ShellProcess, escalationAvailable = false): Promise<ShellRunResult | undefined> {
160
+ const result = (process as Partial<ShellExecution>).result
161
+ if (typeof result !== 'function') return undefined
162
+ try {
163
+ return await result.call(process)
164
+ } catch (error) {
165
+ const notes = sandboxNotes(process.sandbox, escalationAvailable)
166
+ if (notes.length === 0) throw error
167
+ const message = [error instanceof Error ? error.message : String(error), ...notes].join('\n')
168
+ const failure = error instanceof HarnessError
169
+ ? new HarnessError(message, error.code, { cause: error })
170
+ : new Error(message, { cause: error })
171
+ if (error instanceof Error) failure.name = error.name
172
+ throw failure
173
+ }
174
+ }
175
+
176
+ export function readShellOutput(
177
+ read: ShellProcessRead,
178
+ maxBytes: number,
179
+ sandbox?: ShellProcess['sandbox'],
180
+ escalationAvailable = false,
181
+ ): { output: string; originalTokenCount?: number } {
182
+ const truncated = truncateOutput(sanitizePipeOutput(read.delta), maxBytes)
183
+ const notes = sandboxNotes(sandbox, escalationAvailable)
184
+ const output = notes.length === 0
185
+ ? truncated.text
186
+ : `${truncated.text}${truncated.text.length > 0 && !truncated.text.endsWith('\n') ? '\n' : ''}${notes.join('\n')}`
187
+ return truncated.originalTokenCount === undefined
188
+ ? { output }
189
+ : { output, originalTokenCount: truncated.originalTokenCount }
190
+ }
191
+
192
+ export function terminalResult(result: TerminalSendResult, maxBytes: number, startedAt: number): ExecResult {
193
+ const truncated = truncateOutput(result.viewport, maxBytes)
194
+ return withChunkId({
195
+ wall_time_seconds: (performance.now() - startedAt) / 1000,
196
+ output: truncated.text,
197
+ ...truncated.originalTokenCount === undefined ? {} : { original_token_count: truncated.originalTokenCount },
198
+ ...result.sessionStatus.kind === 'exited' ? {
199
+ ...result.sessionStatus.exitCode === null ? {} : { exit_code: result.sessionStatus.exitCode },
200
+ } : {},
201
+ })
202
+ }
203
+
204
+ /** Map a detached shell process onto the generic DSH job outcome contract. */
205
+ export function backgroundOutcome(process: ShellProcess, escalationAvailable: boolean, sandbox = process.sandbox): JobOutcome {
206
+ const base: JobOutcome = process.status === 'killed'
207
+ ? { status: 'killed', detail: process.signal !== null ? `signal: ${process.signal}` : 'killed before exit' }
208
+ : { status: 'completed', detail: `exit code: ${process.exitCode ?? 0}` }
209
+ const notes = sandboxNotes(sandbox, escalationAvailable)
210
+ return notes.length === 0 ? base : { ...base, detail: `${base.detail}; ${notes.join(' ')}` }
211
+ }