@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
@@ -1,683 +0,0 @@
1
- import { credentialRef } from '@deepseek-ai/dsh-credentials';
2
- import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { randomUUID } from 'node:crypto';
4
- import { mkdirSync, writeFileSync } from 'node:fs';
5
- import { homedir } from 'node:os';
6
- import { join, resolve } from 'node:path';
7
- import { APPLY_PATCH_DESCRIPTION, APPLY_PATCH_GRAMMAR } from "./patch.js";
8
- const SETTINGS_NAMESPACE = 'llm-pi-ai';
9
- const REMOTE_COMPACTION_OPEN = '<codex-remote-compaction>';
10
- const REMOTE_COMPACTION_CLOSE = '</codex-remote-compaction>';
11
- const CONTEXT_WINDOW_EXCEEDED_CODE = 'CONTEXT_WINDOW_EXCEEDED';
12
- const CODEX_ERROR_DIRECTORY = ['diagnostics', 'openai-codex-errors'];
13
- const HOSTED_REQUESTS = new AsyncLocalStorage();
14
- let hostedPatchUsers = 0;
15
- let hostedPatchRestore;
16
- function serviceTierOf(options) {
17
- const value = options.serviceTier;
18
- return typeof value === 'string' ? value : undefined;
19
- }
20
- function isGptModel(model) {
21
- return typeof model === 'string' && /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(model);
22
- }
23
- function settingsOf(ctx) {
24
- const provider = ctx.get('settings');
25
- return provider?.get?.(SETTINGS_NAMESPACE);
26
- }
27
- function profileOf(ctx, provider) {
28
- return settingsOf(ctx)?.providers?.[provider];
29
- }
30
- function supportsResponses(profile, provider) {
31
- return profile?.api === 'openai-responses'
32
- || profile?.api === 'openai-codex-responses'
33
- || (profile?.api === undefined && provider === 'openai');
34
- }
35
- function responsesEndpoint(baseURL, suffix) {
36
- return `${baseURL.replace(/\/+$/, '')}/${suffix}`;
37
- }
38
- function hasHeader(headers, name) {
39
- return Object.keys(headers ?? {}).some(key => key.toLowerCase() === name.toLowerCase());
40
- }
41
- async function apiHeaders(ctx, profile) {
42
- const headers = { ...profile.headers, 'content-type': 'application/json' };
43
- if (profile.apiKeyEnv !== undefined && !hasHeader(headers, 'authorization')) {
44
- const credentials = ctx.get('credentials');
45
- const resolved = await credentials?.resolve(credentialRef(profile.apiKeyEnv));
46
- if (resolved?.value === undefined)
47
- return undefined;
48
- headers.authorization = `Bearer ${resolved.value}`;
49
- }
50
- return headers;
51
- }
52
- function isResponsesRequest(url) {
53
- try {
54
- const path = new URL(url).pathname.replace(/\/+$/, '');
55
- return path.endsWith('/responses');
56
- }
57
- catch {
58
- return url.replace(/\/+$/, '').endsWith('/responses');
59
- }
60
- }
61
- function diagnosticsDirectory() {
62
- const configured = process.env['DSH_HOME']?.trim();
63
- const expanded = configured === undefined || configured.length === 0
64
- ? join(homedir(), '.dsh')
65
- : configured === '~'
66
- ? homedir()
67
- : configured.startsWith('~/') || configured.startsWith('~\\')
68
- ? join(homedir(), configured.slice(2))
69
- : configured;
70
- return join(resolve(expanded), ...CODEX_ERROR_DIRECTORY);
71
- }
72
- function saveCodexErrorPayload(payload) {
73
- const directory = diagnosticsDirectory();
74
- mkdirSync(directory, { recursive: true, mode: 0o700 });
75
- const filename = `${Date.now()}-${randomUUID()}.json`;
76
- writeFileSync(join(directory, filename), `${payload}\n`, { flag: 'wx', mode: 0o600 });
77
- }
78
- function errorPayloadFromSseFrame(frame) {
79
- const data = frame
80
- .split(/\r?\n/u)
81
- .filter(line => line.startsWith('data:'))
82
- .map(line => line.slice(5).trimStart())
83
- .join('\n')
84
- .trim();
85
- if (data.length === 0 || data === '[DONE]')
86
- return undefined;
87
- try {
88
- const payload = JSON.parse(data);
89
- return payload.type === 'error' || payload.type === 'response.failed' ? data : undefined;
90
- }
91
- catch {
92
- return undefined;
93
- }
94
- }
95
- async function captureCodexErrorPayloads(response) {
96
- if (response.body === null)
97
- return;
98
- const reader = response.body.getReader();
99
- const decoder = new TextDecoder();
100
- let buffer = '';
101
- try {
102
- while (true) {
103
- const { done, value } = await reader.read();
104
- buffer += decoder.decode(value, { stream: !done });
105
- while (true) {
106
- const delimiter = /\r?\n\r?\n/u.exec(buffer);
107
- if (delimiter?.index === undefined)
108
- break;
109
- const frame = buffer.slice(0, delimiter.index);
110
- buffer = buffer.slice(delimiter.index + delimiter[0].length);
111
- const payload = errorPayloadFromSseFrame(frame);
112
- if (payload === undefined)
113
- continue;
114
- try {
115
- saveCodexErrorPayload(payload);
116
- }
117
- catch {
118
- // Diagnostics must never replace the provider response or failure.
119
- }
120
- }
121
- if (done)
122
- return;
123
- }
124
- }
125
- finally {
126
- reader.releaseLock();
127
- }
128
- }
129
- function captureCodexErrors(response) {
130
- if (!response.headers.get('content-type')?.toLowerCase().includes('text/event-stream'))
131
- return response;
132
- try {
133
- void captureCodexErrorPayloads(response.clone()).catch(() => {
134
- // Reading the diagnostic branch must not affect the provider stream.
135
- });
136
- }
137
- catch {
138
- // An already-consumed response remains usable by its original consumer.
139
- }
140
- return response;
141
- }
142
- function isWebSearchTool(tool) {
143
- if (typeof tool !== 'object' || tool === null)
144
- return false;
145
- const value = tool;
146
- if (value.name === 'web_search')
147
- return true;
148
- const fn = value.function;
149
- return typeof fn === 'object' && fn !== null && fn.name === 'web_search';
150
- }
151
- function hasWebSearchTool(body) {
152
- return Array.isArray(body.tools) && body.tools.some(isWebSearchTool);
153
- }
154
- function toolName(tool) {
155
- if (typeof tool !== 'object' || tool === null)
156
- return undefined;
157
- const value = tool;
158
- if (typeof value.name === 'string')
159
- return value.name;
160
- const fn = value.function;
161
- return typeof fn === 'object' && fn !== null && typeof fn.name === 'string'
162
- ? fn.name
163
- : undefined;
164
- }
165
- function isApplyPatchTool(tool) {
166
- return toolName(tool) === 'apply_patch';
167
- }
168
- function isFunctionApplyPatchTool(tool) {
169
- if (!isApplyPatchTool(tool) || typeof tool !== 'object' || tool === null)
170
- return false;
171
- return tool.type !== 'custom';
172
- }
173
- function hasFunctionApplyPatchTool(body) {
174
- return Array.isArray(body.tools) && body.tools.some(isFunctionApplyPatchTool);
175
- }
176
- function applyPatchTool(tool) {
177
- const value = tool;
178
- const fn = value.function;
179
- const description = typeof value.description === 'string'
180
- ? value.description
181
- : typeof fn === 'object' && fn !== null && typeof fn.description === 'string'
182
- ? fn.description
183
- : APPLY_PATCH_DESCRIPTION;
184
- const custom = {
185
- type: 'custom',
186
- name: 'apply_patch',
187
- description,
188
- format: {
189
- type: 'grammar',
190
- syntax: 'lark',
191
- definition: APPLY_PATCH_GRAMMAR,
192
- },
193
- };
194
- if (value.defer_loading !== undefined)
195
- custom.defer_loading = value.defer_loading;
196
- return custom;
197
- }
198
- /** Replace DSH's JSON function declaration with the Responses custom grammar tool. */
199
- export function addCodexApplyPatch(body) {
200
- if (!Array.isArray(body.tools))
201
- return body;
202
- let changed = false;
203
- const tools = body.tools.map(tool => {
204
- if (!isApplyPatchTool(tool) || typeof tool !== 'object' || tool === null)
205
- return tool;
206
- if (tool.type === 'custom')
207
- return tool;
208
- changed = true;
209
- return applyPatchTool(tool);
210
- });
211
- return changed ? { ...body, tools } : body;
212
- }
213
- function applyPatchInputOfCall(item) {
214
- if (item.type !== 'function_call' || item.name !== 'apply_patch')
215
- return undefined;
216
- if (typeof item.call_id !== 'string' || item.call_id.length === 0)
217
- return undefined;
218
- const raw = item.arguments;
219
- const argumentsObject = typeof raw === 'string'
220
- ? (() => {
221
- try {
222
- return JSON.parse(raw);
223
- }
224
- catch {
225
- return undefined;
226
- }
227
- })()
228
- : raw;
229
- if (typeof argumentsObject !== 'object' || argumentsObject === null)
230
- return undefined;
231
- const input = argumentsObject.input;
232
- return typeof input === 'string' ? { callId: item.call_id, input } : undefined;
233
- }
234
- function canRewriteApplyPatchHistory(body) {
235
- if (!Array.isArray(body.input))
236
- return true;
237
- return body.input.every(item => {
238
- if (typeof item !== 'object' || item === null)
239
- return true;
240
- const value = item;
241
- return value.type !== 'function_call' || value.name !== 'apply_patch'
242
- || applyPatchInputOfCall(value) !== undefined;
243
- });
244
- }
245
- /** Replay apply_patch calls as custom tool items after pi-ai's generic conversion. */
246
- export function rewriteCodexApplyPatchHistory(body) {
247
- if (!Array.isArray(body.input) || !canRewriteApplyPatchHistory(body))
248
- return body;
249
- const applyCallIds = new Set();
250
- for (const item of body.input) {
251
- if (typeof item !== 'object' || item === null)
252
- continue;
253
- const value = item;
254
- if (value.type === 'custom_tool_call' && value.name === 'apply_patch' && typeof value.call_id === 'string') {
255
- applyCallIds.add(value.call_id);
256
- }
257
- const call = applyPatchInputOfCall(value);
258
- if (call !== undefined)
259
- applyCallIds.add(call.callId);
260
- }
261
- if (applyCallIds.size === 0)
262
- return body;
263
- let changed = false;
264
- const input = body.input.map(item => {
265
- if (typeof item !== 'object' || item === null)
266
- return item;
267
- const value = item;
268
- const call = applyPatchInputOfCall(value);
269
- if (call !== undefined) {
270
- const next = {
271
- type: 'custom_tool_call',
272
- call_id: call.callId,
273
- name: 'apply_patch',
274
- input: call.input,
275
- };
276
- if (typeof value.id === 'string')
277
- next.id = value.id;
278
- changed = true;
279
- return next;
280
- }
281
- if (value.type === 'function_call_output'
282
- && typeof value.call_id === 'string'
283
- && applyCallIds.has(value.call_id)) {
284
- changed = true;
285
- return {
286
- type: 'custom_tool_call_output',
287
- call_id: value.call_id,
288
- output: value.output,
289
- };
290
- }
291
- return item;
292
- });
293
- return changed ? { ...body, input } : body;
294
- }
295
- /** Compose the plugin-only Responses rewrites without changing DSH's tool API. */
296
- export function rewriteCodexResponsesBody(body, options = {}) {
297
- let next = body;
298
- if (options.hostedWebSearch !== false && hasWebSearchTool(next)) {
299
- next = addHostedWebSearch(next);
300
- }
301
- else if (hasRemoteCompaction(next)) {
302
- next = replaceRemoteCompactions(next);
303
- }
304
- if (options.customApplyPatch !== false
305
- && hasFunctionApplyPatchTool(next)
306
- && canRewriteApplyPatchHistory(next)) {
307
- next = addCodexApplyPatch(next);
308
- next = rewriteCodexApplyPatchHistory(next);
309
- }
310
- return next;
311
- }
312
- /** Convert a generic DSH Responses tool list to the hosted Codex variant. */
313
- export function addHostedWebSearch(body) {
314
- const tools = Array.isArray(body.tools) ? body.tools.filter(tool => !isWebSearchTool(tool)) : [];
315
- tools.push({ type: 'web_search', external_web_access: true });
316
- return { ...replaceRemoteCompactions(body), tools };
317
- }
318
- /** Replace the text placeholder written by dsh-compaction-basic with the native item. */
319
- export function replaceRemoteCompactions(body) {
320
- if (!Array.isArray(body.input))
321
- return body;
322
- const input = body.input.map(item => {
323
- if (typeof item !== 'object' || item === null)
324
- return item;
325
- const value = item;
326
- const content = Array.isArray(value.content) ? value.content : [];
327
- const marker = content.find(part => (typeof part === 'object'
328
- && part !== null
329
- && typeof part.text === 'string'
330
- && String(part.text).includes(REMOTE_COMPACTION_OPEN)));
331
- if (marker === undefined)
332
- return item;
333
- const text = String(marker.text);
334
- const start = text.indexOf(REMOTE_COMPACTION_OPEN) + REMOTE_COMPACTION_OPEN.length;
335
- const end = text.indexOf(REMOTE_COMPACTION_CLOSE, start);
336
- if (end < start)
337
- return item;
338
- return {
339
- type: 'compaction',
340
- encrypted_content: text.slice(start, end),
341
- };
342
- });
343
- return { ...body, input };
344
- }
345
- function hasRemoteCompaction(body) {
346
- if (!Array.isArray(body.input))
347
- return false;
348
- return body.input.some(item => {
349
- if (typeof item !== 'object' || item === null)
350
- return false;
351
- const content = item.content;
352
- return Array.isArray(content) && content.some(part => (typeof part === 'object'
353
- && part !== null
354
- && typeof part.text === 'string'
355
- && String(part.text).includes(REMOTE_COMPACTION_OPEN)));
356
- });
357
- }
358
- function canPatchBody(body, options) {
359
- return isGptModel(body.model)
360
- && ((options.hostedWebSearch !== false && hasWebSearchTool(body))
361
- || hasRemoteCompaction(body)
362
- || (options.customApplyPatch !== false
363
- && hasFunctionApplyPatchTool(body)
364
- && canRewriteApplyPatchHistory(body)));
365
- }
366
- /** Add provider options that older pi-ai adapters do not copy themselves. */
367
- function applyRequestWireOptions(body, options) {
368
- if (options.serviceTier === undefined || !isGptModel(body.model))
369
- return body;
370
- return { ...body, service_tier: options.serviceTier };
371
- }
372
- /**
373
- * Install a scoped fetch shim for pi-ai's already-built Responses request.
374
- * The generic DSH adapter remains the owner of auth, streaming, replay, and
375
- * attachments; this shim changes only Codex's Responses tool and compaction
376
- * representation at the wire boundary.
377
- */
378
- function installGlobalHostedWebSearchPatch() {
379
- const original = globalThis.fetch;
380
- const patched = async (input, init) => {
381
- const options = HOSTED_REQUESTS.getStore();
382
- if (options === undefined)
383
- return original(input, init);
384
- const request = new Request(input, init);
385
- if (!isResponsesRequest(request.url))
386
- return original(input, init);
387
- const requestAndCapture = async (target, requestInit) => captureCodexErrors(await original(target, requestInit));
388
- let body;
389
- try {
390
- body = JSON.parse(await request.clone().text());
391
- }
392
- catch {
393
- return requestAndCapture(input, init);
394
- }
395
- const requestBody = applyRequestWireOptions(body, options);
396
- if (!canPatchBody(requestBody, options)) {
397
- if (requestBody === body)
398
- return requestAndCapture(input, init);
399
- const headers = new Headers(request.headers);
400
- headers.delete('content-length');
401
- return requestAndCapture(new Request(request, {
402
- body: JSON.stringify(requestBody),
403
- headers,
404
- }));
405
- }
406
- const fallbackHeaders = new Headers(request.headers);
407
- fallbackHeaders.delete('content-length');
408
- const fallbackRequest = requestBody === body
409
- ? request.clone()
410
- : new Request(request, {
411
- body: JSON.stringify(requestBody),
412
- headers: fallbackHeaders,
413
- });
414
- const headers = new Headers(request.headers);
415
- headers.delete('content-length');
416
- const hostedRequest = new Request(request, {
417
- body: JSON.stringify(rewriteCodexResponsesBody(requestBody, options)),
418
- headers,
419
- });
420
- try {
421
- const hostedResponse = await requestAndCapture(hostedRequest);
422
- // A rejected hosted-tool request is retried with the untouched request so
423
- // dsh-tool-web can still produce the normal local function-tool path.
424
- if (!hostedResponse.ok)
425
- return requestAndCapture(fallbackRequest);
426
- return hostedResponse;
427
- }
428
- catch {
429
- // Network and transport failures must have the same fallback behavior as
430
- // an HTTP rejection; the local function-tool path remains available.
431
- return requestAndCapture(fallbackRequest);
432
- }
433
- };
434
- globalThis.fetch = patched;
435
- return () => {
436
- if (globalThis.fetch === patched)
437
- globalThis.fetch = original;
438
- };
439
- }
440
- /** Enable the transport patch for this Codex plugin scope only. */
441
- export function installHostedWebSearch() {
442
- hostedPatchUsers += 1;
443
- hostedPatchRestore ??= installGlobalHostedWebSearchPatch();
444
- return () => {
445
- hostedPatchUsers = Math.max(0, hostedPatchUsers - 1);
446
- if (hostedPatchUsers === 0) {
447
- hostedPatchRestore?.();
448
- hostedPatchRestore = undefined;
449
- }
450
- };
451
- }
452
- /** Iterate an existing DSH stream with the hosted-request context installed. */
453
- export function hostedWebSearchStream(next, options = {}) {
454
- return (async function* () {
455
- const iterator = next()[Symbol.asyncIterator]();
456
- let completed = false;
457
- try {
458
- while (true) {
459
- const item = await HOSTED_REQUESTS.run(options, () => iterator.next());
460
- if (item.done) {
461
- completed = true;
462
- return;
463
- }
464
- yield item.value;
465
- }
466
- }
467
- finally {
468
- if (!completed)
469
- await iterator.return?.();
470
- }
471
- })();
472
- }
473
- function contextTokens(usage) {
474
- const fields = [
475
- usage.inputTokens,
476
- usage.outputTokens,
477
- usage.cacheReadTokens ?? 0,
478
- usage.cacheWriteTokens ?? 0,
479
- ];
480
- if (fields.some(value => !Number.isSafeInteger(value) || value < 0))
481
- return undefined;
482
- const total = fields.reduce((sum, value) => sum + value, 0);
483
- return Number.isSafeInteger(total) ? total : undefined;
484
- }
485
- /**
486
- * Correct the usage-only overflow verdict emitted by pi-ai adapters that do
487
- * not yet consume the request-scoped Codex capacity.
488
- */
489
- export function repairLegacyPiAiContextOverflow(stream, model, contextWindow) {
490
- return (async function* () {
491
- let usage;
492
- for await (const chunk of stream) {
493
- if (chunk.type === 'usage')
494
- usage = chunk.usage;
495
- const usedTokens = usage === undefined ? undefined : contextTokens(usage);
496
- if (chunk.type === 'finish'
497
- && chunk.reason.kind === 'error'
498
- && chunk.reason.failure.code === CONTEXT_WINDOW_EXCEEDED_CODE
499
- && chunk.reason.failure.message === `pi-ai detected context overflow for model "${model}"`
500
- && typeof contextWindow === 'number'
501
- && Number.isSafeInteger(contextWindow)
502
- && contextWindow > 0
503
- && usage !== undefined
504
- && usage.outputTokens > 0
505
- && usedTokens !== undefined
506
- && usedTokens <= contextWindow) {
507
- yield { ...chunk, reason: { kind: 'stop' } };
508
- continue;
509
- }
510
- yield chunk;
511
- }
512
- })();
513
- }
514
- function textOf(message) {
515
- return message.content
516
- .filter(block => block.type === 'text')
517
- .map(block => block.text)
518
- .join('');
519
- }
520
- function responsesInput(messages) {
521
- const result = [];
522
- for (const message of messages) {
523
- const text = textOf(message);
524
- if (message.role === 'assistant') {
525
- if (text.length > 0)
526
- result.push({
527
- type: 'message',
528
- role: 'assistant',
529
- content: [{ type: 'output_text', text }],
530
- });
531
- for (const block of message.content) {
532
- if (block.type === 'tool-call') {
533
- result.push({
534
- type: 'function_call',
535
- call_id: block.id,
536
- name: block.name,
537
- arguments: block.arguments,
538
- });
539
- }
540
- }
541
- continue;
542
- }
543
- const role = message.role === 'system' ? 'developer' : 'user';
544
- if (text.length > 0)
545
- result.push({
546
- type: 'message',
547
- role,
548
- content: [{ type: 'input_text', text }],
549
- });
550
- for (const block of message.content) {
551
- if (block.type !== 'tool-result')
552
- continue;
553
- result.push({
554
- type: 'function_call_output',
555
- call_id: block.toolCallId,
556
- output: block.content.filter(item => item.type === 'text').map(item => item.text).join(''),
557
- });
558
- }
559
- }
560
- return result;
561
- }
562
- function responsesTools(tools) {
563
- if (tools === undefined)
564
- return undefined;
565
- return tools.filter(tool => tool.name !== 'web_search').map(tool => ({
566
- type: 'function',
567
- name: tool.name,
568
- description: tool.description,
569
- parameters: tool.parameters,
570
- }));
571
- }
572
- function compactBody(options, wireOptions = {}) {
573
- const tools = responsesTools(options.tools);
574
- const body = {
575
- model: options.model,
576
- // dsh-compaction-basic appends an instruction for its local summarizer.
577
- // The hosted compact endpoint owns summarization and must not receive it.
578
- input: responsesInput(options.messages.slice(0, -1)),
579
- ...options.system === undefined ? {} : { instructions: options.system },
580
- ...tools === undefined ? {} : { tools },
581
- ...options.maxTokens === undefined ? {} : { max_output_tokens: options.maxTokens },
582
- ...options.reasoningEffort === undefined ? {} : { reasoning: { effort: options.reasoningEffort } },
583
- };
584
- const compacted = replaceRemoteCompactions(body);
585
- return wireOptions.hostedWebSearch !== false
586
- && options.tools?.some(tool => tool.name === 'web_search')
587
- ? addHostedWebSearch(compacted)
588
- : compacted;
589
- }
590
- function compactText(body) {
591
- const output = Array.isArray(body.output) ? body.output : [];
592
- const text = [];
593
- for (const item of output) {
594
- if (typeof item !== 'object' || item === null)
595
- continue;
596
- const value = item;
597
- if (typeof value.encrypted_content === 'string')
598
- text.push(value.encrypted_content);
599
- }
600
- const encrypted = text.join('\n\n').trim();
601
- return encrypted.length === 0 ? '' : `${REMOTE_COMPACTION_OPEN}${encrypted}${REMOTE_COMPACTION_CLOSE}`;
602
- }
603
- function nonNegativeInteger(value) {
604
- return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
605
- }
606
- /** Map the Responses compact usage object without inventing missing counts. */
607
- function compactUsage(body) {
608
- if (typeof body.usage !== 'object' || body.usage === null)
609
- return undefined;
610
- const raw = body.usage;
611
- const inputTokens = nonNegativeInteger(raw.input_tokens);
612
- const outputTokens = nonNegativeInteger(raw.output_tokens);
613
- if (inputTokens === undefined || outputTokens === undefined)
614
- return undefined;
615
- const details = typeof raw.input_tokens_details === 'object' && raw.input_tokens_details !== null
616
- ? raw.input_tokens_details
617
- : undefined;
618
- const cacheReadTokens = nonNegativeInteger(details?.cached_tokens);
619
- const cacheWriteTokens = nonNegativeInteger(details?.cache_write_tokens);
620
- const cached = cacheReadTokens ?? 0;
621
- const writes = cacheWriteTokens ?? 0;
622
- // Responses input_tokens includes the cache buckets. Reject an inconsistent
623
- // response instead of clamping it and reporting numbers that no longer sum.
624
- if (cached + writes > inputTokens)
625
- return undefined;
626
- return {
627
- inputTokens: inputTokens - cached - writes,
628
- outputTokens,
629
- ...cacheReadTokens !== undefined && cacheReadTokens > 0 ? { cacheReadTokens } : {},
630
- ...cacheWriteTokens !== undefined && cacheWriteTokens > 0 ? { cacheWriteTokens } : {},
631
- };
632
- }
633
- async function remoteCompact(ctx, options, wireOptions = {}) {
634
- const profile = profileOf(ctx, options.provider);
635
- if (!supportsResponses(profile, options.provider) || profile?.baseURL === undefined) {
636
- throw new Error('Codex remote compaction requires an OpenAI Responses provider with baseURL');
637
- }
638
- const headers = await apiHeaders(ctx, profile);
639
- if (headers === undefined)
640
- throw new Error('Codex remote compaction has no configured API key');
641
- const response = await fetch(responsesEndpoint(profile.baseURL, 'responses/compact'), {
642
- method: 'POST',
643
- headers,
644
- body: JSON.stringify(compactBody(options, wireOptions)),
645
- ...options.signal === undefined ? {} : { signal: options.signal },
646
- });
647
- if (!response.ok)
648
- throw new Error(`remote compaction returned HTTP ${response.status}`);
649
- const body = await response.json();
650
- const text = compactText(body);
651
- if (text.length === 0)
652
- throw new Error('remote compaction returned no compaction text');
653
- const usage = compactUsage(body);
654
- return { text, ...usage === undefined ? {} : { usage } };
655
- }
656
- /** Remote-first compaction waterfall with the existing DSH path as fallback. */
657
- export function remoteCompactStream(ctx, options, next, wireOptions = {}) {
658
- return (async function* () {
659
- try {
660
- const result = await remoteCompact(ctx, options, wireOptions);
661
- yield { type: 'block-start', index: 0, blockType: 'text' };
662
- yield { type: 'text-delta', index: 0, text: result.text };
663
- yield { type: 'block-end', index: 0, block: { type: 'text', text: result.text } };
664
- if (result.usage !== undefined)
665
- yield { type: 'usage', usage: result.usage };
666
- yield { type: 'finish', reason: { kind: 'stop' } };
667
- }
668
- catch (error) {
669
- if (options.signal?.aborted)
670
- throw error;
671
- ctx.logger.warn('codex: remote compaction failed; using dsh-compaction-basic fallback');
672
- ctx.logger.warn(error);
673
- // The local fallback still replays the marker through a later GPT
674
- // Responses request, so it needs the same scoped wire context.
675
- const serviceTier = serviceTierOf(options);
676
- yield* hostedWebSearchStream(next, {
677
- ...wireOptions,
678
- ...serviceTier === undefined ? {} : { serviceTier },
679
- });
680
- }
681
- })();
682
- }
683
- //# sourceMappingURL=remote.js.map