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