@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,319 @@
1
+ /** OpenAI Responses `/responses/compact` and V2 `/responses` transport with local compaction fallback. */
2
+ import { credentialRef } from '@deepseek-ai/dsh-credentials';
3
+ import { isGptModel, readHostSettings } from "../contracts/settings.js";
4
+ import { collectTrustedCompactionMarkers, encodeRemoteCompactionCheckpoint, parseCompactResponsePayload, retainedUserMessagesFromInput, } from "./compact-checkpoint.js";
5
+ import { capabilityKey, CONTEXT_LIMIT_ERROR, hostedWebSearchStream, isCompactUnsupported, recordUnsupportedCapability, } from "./fetch-transport.js";
6
+ import { applyRequestWireOptions, replaceRemoteCompactions, rewriteCodexResponsesBody, serviceTierOf, } from "./wire-rewrite.js";
7
+ const SETTINGS_NAMESPACE = 'llm-pi-ai';
8
+ const MAX_COMPACT_RETRIES = 2;
9
+ const RETRYABLE_COMPACT_STATUS = new Set([429, 502, 503, 504]);
10
+ function profileOf(ctx, provider) {
11
+ return readHostSettings(ctx, SETTINGS_NAMESPACE)?.providers?.[provider];
12
+ }
13
+ function supportsResponses(profile, provider) {
14
+ return profile?.api === 'openai-responses'
15
+ || profile?.api === 'openai-codex-responses'
16
+ || (profile?.api === undefined && provider === 'openai');
17
+ }
18
+ /** True only when `llm-pi-ai` configures an OpenAI Responses route directly (never `openai-codex`). */
19
+ export function hasDirectResponsesCompactRoute(ctx, provider) {
20
+ if (provider === 'openai-codex')
21
+ return false;
22
+ const profile = profileOf(ctx, provider);
23
+ return supportsResponses(profile, provider) && typeof profile?.baseURL === 'string' && profile.baseURL.length > 0;
24
+ }
25
+ function responsesEndpoint(baseURL, suffix) {
26
+ return `${baseURL.replace(/\/+$/, '')}/${suffix}`;
27
+ }
28
+ function hasHeader(headers, name) {
29
+ return Object.keys(headers ?? {}).some(key => key.toLowerCase() === name.toLowerCase());
30
+ }
31
+ async function apiHeaders(ctx, profile, isV2Responses) {
32
+ const headers = { ...profile.headers, 'content-type': 'application/json' };
33
+ if (isV2Responses) {
34
+ if (!hasHeader(headers, 'openai-beta'))
35
+ headers['openai-beta'] = 'responses=experimental';
36
+ if (!hasHeader(headers, 'accept'))
37
+ headers['accept'] = 'text/event-stream, application/json';
38
+ }
39
+ if (profile.apiKeyEnv !== undefined && !hasHeader(headers, 'authorization')) {
40
+ const credentials = ctx.get('credentials');
41
+ const resolved = await credentials?.resolve(credentialRef(profile.apiKeyEnv));
42
+ if (resolved?.value === undefined)
43
+ return undefined;
44
+ headers.authorization = `Bearer ${resolved.value}`;
45
+ }
46
+ return headers;
47
+ }
48
+ function textOf(message) {
49
+ return message.content
50
+ .map(block => block.type === 'text' ? block.text : block.type === 'image' ? '[image omitted]' : '')
51
+ .join('');
52
+ }
53
+ function stripCompactionPrompt(messages) {
54
+ const last = messages.at(-1);
55
+ if (last !== undefined && last.role === 'user' && !('id' in last && last.id !== undefined)) {
56
+ return messages.slice(0, -1);
57
+ }
58
+ return messages;
59
+ }
60
+ function extractInstructions(options, messages) {
61
+ if (options.system !== undefined)
62
+ return options.system;
63
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
64
+ const message = messages[index];
65
+ if (message.role !== 'system')
66
+ continue;
67
+ const text = textOf(message);
68
+ return text.length > 0 ? text : undefined;
69
+ }
70
+ return undefined;
71
+ }
72
+ function responsesInput(messages) {
73
+ const result = [];
74
+ for (const message of messages) {
75
+ // This compact transport cannot serialize attachment file references losslessly.
76
+ if (message.content.some(block => block.type === 'file')) {
77
+ throw new Error('Codex remote compaction requires the DSH adapter for attachments');
78
+ }
79
+ if (message.role === 'system')
80
+ continue;
81
+ const text = textOf(message);
82
+ if (message.role === 'tool') {
83
+ result.push({ type: 'function_call_output', call_id: message.toolCallId.split('|')[0], output: text });
84
+ continue;
85
+ }
86
+ if (message.role === 'assistant') {
87
+ if (text.length > 0)
88
+ result.push({
89
+ type: 'message',
90
+ role: 'assistant',
91
+ content: [{ type: 'output_text', text }],
92
+ });
93
+ for (const block of message.content) {
94
+ if (block.type === 'tool-call') {
95
+ result.push({
96
+ type: 'function_call',
97
+ call_id: block.id.split('|')[0],
98
+ name: block.name,
99
+ arguments: block.arguments,
100
+ });
101
+ }
102
+ }
103
+ continue;
104
+ }
105
+ const role = message.role === 'developer' ? 'developer' : 'user';
106
+ if (text.length > 0)
107
+ result.push({
108
+ type: 'message',
109
+ role,
110
+ content: [{ type: 'input_text', text }],
111
+ });
112
+ }
113
+ return result;
114
+ }
115
+ function responsesTools(tools) {
116
+ if (tools === undefined)
117
+ return undefined;
118
+ return tools.map(tool => ({
119
+ type: 'function',
120
+ name: tool.name,
121
+ description: tool.description,
122
+ parameters: tool.parameters,
123
+ }));
124
+ }
125
+ function compactBody(options, wireOptions, isV2Responses) {
126
+ const messages = stripCompactionPrompt(options.messages);
127
+ const instructions = extractInstructions(options, messages);
128
+ const tools = responsesTools(options.tools);
129
+ const serviceTier = wireOptions.serviceTier ?? serviceTierOf(options);
130
+ const body = {
131
+ model: options.model,
132
+ input: responsesInput(messages),
133
+ ...instructions !== undefined ? { instructions } : isV2Responses ? { instructions: '' } : {},
134
+ ...tools === undefined ? {} : { tools },
135
+ ...typeof options.sessionId === 'string' && options.sessionId.length > 0
136
+ ? { prompt_cache_key: options.sessionId.slice(0, 64) }
137
+ : {},
138
+ ...options.reasoningEffort === undefined
139
+ ? {}
140
+ : { reasoning: isV2Responses ? { effort: options.reasoningEffort, summary: 'auto' } : { effort: options.reasoningEffort } },
141
+ ...isV2Responses ? {
142
+ store: false,
143
+ stream: true,
144
+ tool_choice: 'auto',
145
+ parallel_tool_calls: true,
146
+ include: ['reasoning.encrypted_content'],
147
+ } : {},
148
+ };
149
+ const withOptions = applyRequestWireOptions(body, {
150
+ ...wireOptions,
151
+ ...serviceTier === undefined ? {} : { serviceTier },
152
+ });
153
+ const expanded = replaceRemoteCompactions(withOptions, wireOptions.trustedCheckpoints);
154
+ const rewritten = rewriteCodexResponsesBody(expanded, wireOptions);
155
+ const preCompactInput = Array.isArray(rewritten.input)
156
+ ? rewritten.input.filter((item) => typeof item === 'object' && item !== null)
157
+ : [];
158
+ if (!isV2Responses)
159
+ return { body: rewritten, preCompactInput };
160
+ return {
161
+ body: { ...rewritten, input: [...preCompactInput, { type: 'compaction_trigger' }] },
162
+ preCompactInput,
163
+ };
164
+ }
165
+ function canRewriteCompactTools(options, wireOptions) {
166
+ if (!isGptModel(options.model) || options.tools === undefined)
167
+ return false;
168
+ return (wireOptions.hostedWebSearch !== false && options.tools.some(tool => tool.name === 'web_search'))
169
+ || (wireOptions.customApplyPatch !== false && options.tools.some(tool => tool.name === 'apply_patch'));
170
+ }
171
+ function nonNegativeInteger(value) {
172
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
173
+ }
174
+ /** Map the Responses compact usage object without inventing missing counts. */
175
+ function compactUsage(rawUsage) {
176
+ if (rawUsage === undefined)
177
+ return undefined;
178
+ const inputTokens = nonNegativeInteger(rawUsage.input_tokens);
179
+ const outputTokens = nonNegativeInteger(rawUsage.output_tokens);
180
+ if (inputTokens === undefined || outputTokens === undefined)
181
+ return undefined;
182
+ const details = typeof rawUsage.input_tokens_details === 'object' && rawUsage.input_tokens_details !== null
183
+ ? rawUsage.input_tokens_details
184
+ : undefined;
185
+ const cacheReadTokens = nonNegativeInteger(details?.cached_tokens);
186
+ const cacheWriteTokens = nonNegativeInteger(details?.cache_write_tokens);
187
+ const cached = cacheReadTokens ?? 0;
188
+ const writes = cacheWriteTokens ?? 0;
189
+ if (cached + writes > inputTokens)
190
+ return undefined;
191
+ return {
192
+ inputTokens: inputTokens - cached - writes,
193
+ outputTokens,
194
+ ...cacheReadTokens !== undefined && cacheReadTokens > 0 ? { cacheReadTokens } : {},
195
+ ...cacheWriteTokens !== undefined && cacheWriteTokens > 0 ? { cacheWriteTokens } : {},
196
+ };
197
+ }
198
+ function retryDelayMs(response, attempt) {
199
+ const retryAfter = response.headers.get('retry-after')?.trim();
200
+ if (retryAfter !== undefined && /^\d+(?:\.\d+)?$/u.test(retryAfter)) {
201
+ return Math.min(4_000, Math.max(0, Math.round(Number(retryAfter) * 1000)));
202
+ }
203
+ return 200 * 2 ** attempt;
204
+ }
205
+ async function waitForRetry(delay, signal) {
206
+ if (delay <= 0) {
207
+ signal?.throwIfAborted();
208
+ return;
209
+ }
210
+ await new Promise((resolve, reject) => {
211
+ if (signal?.aborted) {
212
+ reject(signal.reason);
213
+ return;
214
+ }
215
+ const onAbort = () => { clearTimeout(timer); reject(signal.reason); };
216
+ const timer = setTimeout(() => {
217
+ signal?.removeEventListener('abort', onAbort);
218
+ resolve();
219
+ }, delay);
220
+ signal?.addEventListener('abort', onAbort, { once: true });
221
+ });
222
+ }
223
+ async function sendWithRetry(endpoint, headers, payload, signal) {
224
+ const serialized = JSON.stringify(payload);
225
+ for (let attempt = 0; attempt <= MAX_COMPACT_RETRIES; attempt += 1) {
226
+ const response = await fetch(endpoint, {
227
+ method: 'POST',
228
+ headers,
229
+ body: serialized,
230
+ ...signal === undefined ? {} : { signal },
231
+ });
232
+ if (!RETRYABLE_COMPACT_STATUS.has(response.status) || attempt === MAX_COMPACT_RETRIES) {
233
+ return response;
234
+ }
235
+ const delay = retryDelayMs(response, attempt);
236
+ await response.body?.cancel().catch(() => undefined);
237
+ await waitForRetry(delay, signal);
238
+ }
239
+ throw new Error('Codex remote compaction retries exhausted');
240
+ }
241
+ async function remoteCompact(ctx, options, wireOptions = {}) {
242
+ if (!hasDirectResponsesCompactRoute(ctx, options.provider)) {
243
+ throw new Error('Codex remote compaction requires an OpenAI Responses provider with baseURL');
244
+ }
245
+ const profile = profileOf(ctx, options.provider);
246
+ const isV2Responses = profile.api === 'openai-codex-responses';
247
+ const headers = await apiHeaders(ctx, profile, isV2Responses);
248
+ if (headers === undefined)
249
+ throw new Error('Codex remote compaction has no configured API key');
250
+ const endpoint = responsesEndpoint(profile.baseURL, isV2Responses ? 'responses' : 'responses/compact');
251
+ const key = capabilityKey(endpoint, options.model);
252
+ if (isCompactUnsupported(key)) {
253
+ throw new Error('remote compaction is cached as unsupported for this endpoint');
254
+ }
255
+ const compactWireOptions = {
256
+ ...wireOptions,
257
+ trustedCheckpoints: wireOptions.trustedCheckpoints ?? collectTrustedCompactionMarkers(options.messages),
258
+ };
259
+ const initial = compactBody(options, compactWireOptions, isV2Responses);
260
+ let preCompactInput = initial.preCompactInput;
261
+ let response = await sendWithRetry(endpoint, headers, initial.body, options.signal);
262
+ if (!response.ok
263
+ && (response.status === 400 || response.status === 422)
264
+ && canRewriteCompactTools(options, wireOptions)) {
265
+ const errorText = await response.clone().text().catch(() => '');
266
+ if (!CONTEXT_LIMIT_ERROR.test(errorText)) {
267
+ const reduced = compactBody(options, {
268
+ ...compactWireOptions,
269
+ hostedWebSearch: false,
270
+ customApplyPatch: false,
271
+ }, isV2Responses);
272
+ preCompactInput = reduced.preCompactInput;
273
+ response = await sendWithRetry(endpoint, headers, reduced.body, options.signal);
274
+ }
275
+ }
276
+ if (!response.ok) {
277
+ if (response.status === 404 || response.status === 405 || response.status === 501) {
278
+ recordUnsupportedCapability(key, { remoteCompact: false });
279
+ }
280
+ throw new Error(`remote compaction returned HTTP ${response.status}`);
281
+ }
282
+ const parsed = await parseCompactResponsePayload(response);
283
+ if (parsed.compactions.length === 0)
284
+ throw new Error('remote compaction returned no compaction text');
285
+ const sourceBytes = Buffer.byteLength(JSON.stringify(preCompactInput), 'utf8');
286
+ const encryptedBytes = parsed.compactions.reduce((sum, item) => sum + Buffer.byteLength(JSON.stringify(item), 'utf8'), 0);
287
+ const retained = retainedUserMessagesFromInput(preCompactInput, sourceBytes, encryptedBytes);
288
+ const text = encodeRemoteCompactionCheckpoint(retained, parsed.compactions);
289
+ const usage = compactUsage(parsed.usage);
290
+ return { text, ...usage === undefined ? {} : { usage } };
291
+ }
292
+ /** Remote-first compaction waterfall with clean delegation for `openai-codex` and DSH fallback. */
293
+ export function remoteCompactStream(ctx, options, next, wireOptions = {}) {
294
+ if (options.provider === 'openai-codex')
295
+ return next();
296
+ return (async function* () {
297
+ try {
298
+ const result = await remoteCompact(ctx, options, wireOptions);
299
+ yield { type: 'block-start', index: 0, blockType: 'text' };
300
+ yield { type: 'text-delta', index: 0, text: result.text };
301
+ yield { type: 'block-end', index: 0, block: { type: 'text', text: result.text } };
302
+ if (result.usage !== undefined)
303
+ yield { type: 'usage', usage: result.usage };
304
+ yield { type: 'finish', reason: { kind: 'stop' } };
305
+ }
306
+ catch (error) {
307
+ if (options.signal?.aborted)
308
+ throw error;
309
+ ctx.logger.warn('codex: remote compaction failed; using dsh-compaction-basic fallback');
310
+ ctx.logger.warn(error);
311
+ const serviceTier = wireOptions.serviceTier ?? serviceTierOf(options);
312
+ yield* hostedWebSearchStream(next, {
313
+ ...wireOptions,
314
+ ...serviceTier === undefined ? {} : { serviceTier },
315
+ });
316
+ }
317
+ })();
318
+ }
319
+ //# sourceMappingURL=remote-compact.js.map
@@ -0,0 +1,9 @@
1
+ /** SSE error frame capture and legacy pi-ai context-overflow stream repair. */
2
+ import type { StreamChunk } from '@deepseek-ai/dsh-llm';
3
+ export declare function captureCodexErrors(response: Response): Response;
4
+ /**
5
+ * Correct the usage-only overflow verdict emitted by pi-ai adapters that do
6
+ * not yet consume the request-scoped Codex capacity.
7
+ */
8
+ export declare function repairLegacyPiAiContextOverflow(stream: AsyncIterable<StreamChunk>, model: string, contextWindow: unknown): AsyncIterable<StreamChunk>;
9
+ //# sourceMappingURL=sse-diagnostics.d.ts.map
@@ -0,0 +1,157 @@
1
+ /** SSE error frame capture and legacy pi-ai context-overflow stream repair. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdir, readdir, rename, unlink, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ const CONTEXT_WINDOW_EXCEEDED_CODE = 'CONTEXT_WINDOW_EXCEEDED';
7
+ const CODEX_ERROR_DIRECTORY = ['diagnostics', 'openai-codex-errors'];
8
+ const MAX_DIAGNOSTIC_FILES = 50;
9
+ function diagnosticsDirectory() {
10
+ const configured = process.env['DSH_HOME']?.trim();
11
+ const expanded = configured === undefined || configured.length === 0
12
+ ? join(homedir(), '.dsh')
13
+ : configured === '~'
14
+ ? homedir()
15
+ : configured.startsWith('~/') || configured.startsWith('~\\')
16
+ ? join(homedir(), configured.slice(2))
17
+ : configured;
18
+ return join(resolve(expanded), ...CODEX_ERROR_DIRECTORY);
19
+ }
20
+ async function saveCodexErrorPayload(payload) {
21
+ const directory = diagnosticsDirectory();
22
+ await mkdir(directory, { recursive: true, mode: 0o700 });
23
+ const filename = `${Date.now()}-${randomUUID()}.json`;
24
+ const tempPath = join(directory, `.${filename}.tmp`);
25
+ try {
26
+ await writeFile(tempPath, `${payload}\n`, { flag: 'wx', mode: 0o600 });
27
+ await rename(tempPath, join(directory, filename));
28
+ }
29
+ catch (error) {
30
+ await unlink(tempPath).catch(() => { });
31
+ throw error;
32
+ }
33
+ const entries = (await readdir(directory)).filter(name => name.endsWith('.json') && !name.startsWith('.')).sort();
34
+ for (const stale of entries.slice(0, Math.max(0, entries.length - MAX_DIAGNOSTIC_FILES))) {
35
+ await unlink(join(directory, stale)).catch(() => { });
36
+ }
37
+ }
38
+ function errorPayloadFromSseFrame(frame) {
39
+ const data = frame
40
+ .split(/\r?\n/u)
41
+ .filter(line => line.startsWith('data:'))
42
+ .map(line => line.slice(5).trimStart())
43
+ .join('\n')
44
+ .trim();
45
+ if (data.length === 0 || data === '[DONE]')
46
+ return undefined;
47
+ try {
48
+ const payload = JSON.parse(data);
49
+ return payload.type === 'error' || payload.type === 'response.failed' ? data : undefined;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ async function captureCodexErrorPayloads(response) {
56
+ if (response.body === null)
57
+ return;
58
+ const reader = response.body.getReader();
59
+ const decoder = new TextDecoder();
60
+ let buffer = '';
61
+ try {
62
+ while (true) {
63
+ const { done, value } = await reader.read();
64
+ buffer += decoder.decode(value, { stream: !done });
65
+ while (true) {
66
+ const delimiter = /\r?\n\r?\n/u.exec(buffer);
67
+ if (delimiter?.index === undefined)
68
+ break;
69
+ const frame = buffer.slice(0, delimiter.index);
70
+ buffer = buffer.slice(delimiter.index + delimiter[0].length);
71
+ const payload = errorPayloadFromSseFrame(frame);
72
+ if (payload === undefined)
73
+ continue;
74
+ try {
75
+ await saveCodexErrorPayload(payload);
76
+ }
77
+ catch {
78
+ // Diagnostics must never replace the provider response or failure.
79
+ }
80
+ }
81
+ if (done)
82
+ return;
83
+ }
84
+ }
85
+ finally {
86
+ reader.releaseLock();
87
+ }
88
+ }
89
+ export function captureCodexErrors(response) {
90
+ if (!response.headers.get('content-type')?.toLowerCase().includes('text/event-stream'))
91
+ return response;
92
+ try {
93
+ void captureCodexErrorPayloads(response.clone()).catch(() => {
94
+ // Reading the diagnostic branch must not affect the provider stream.
95
+ });
96
+ }
97
+ catch {
98
+ // An already-consumed response remains usable by its original consumer.
99
+ }
100
+ return response;
101
+ }
102
+ function contextTokens(usage) {
103
+ const fields = [
104
+ usage.inputTokens,
105
+ usage.outputTokens,
106
+ usage.cacheReadTokens ?? 0,
107
+ usage.cacheWriteTokens ?? 0,
108
+ ];
109
+ if (fields.some(value => !Number.isSafeInteger(value) || value < 0))
110
+ return undefined;
111
+ const total = fields.reduce((sum, value) => sum + value, 0);
112
+ return Number.isSafeInteger(total) ? total : undefined;
113
+ }
114
+ function isSyntheticPiAiOverflow(message, model) {
115
+ const prefix = `pi-ai detected context overflow for model "${model}"`;
116
+ if (message === prefix)
117
+ return true;
118
+ if (!message.startsWith(prefix))
119
+ return false;
120
+ return message.slice(prefix.length).trimStart().startsWith('[Codex diagnostics:');
121
+ }
122
+ /**
123
+ * Correct the usage-only overflow verdict emitted by pi-ai adapters that do
124
+ * not yet consume the request-scoped Codex capacity.
125
+ */
126
+ export function repairLegacyPiAiContextOverflow(stream, model, contextWindow) {
127
+ return (async function* () {
128
+ let usage;
129
+ let hasStreamedOutput = false;
130
+ for await (const chunk of stream) {
131
+ if (chunk.type === 'usage')
132
+ usage = chunk.usage;
133
+ else if (chunk.type === 'tool-call-delta'
134
+ || (chunk.type === 'block-start' && chunk.blockType === 'tool-call')
135
+ || ((chunk.type === 'text-delta' || chunk.type === 'reasoning-delta') && chunk.text.length > 0)) {
136
+ hasStreamedOutput = true;
137
+ }
138
+ const usedTokens = usage === undefined ? undefined : contextTokens(usage);
139
+ if (chunk.type === 'finish'
140
+ && chunk.reason.kind === 'error'
141
+ && chunk.reason.failure.code === CONTEXT_WINDOW_EXCEEDED_CODE
142
+ && isSyntheticPiAiOverflow(chunk.reason.failure.message, model)
143
+ && typeof contextWindow === 'number'
144
+ && Number.isSafeInteger(contextWindow)
145
+ && contextWindow > 0
146
+ && usage !== undefined
147
+ && (usage.outputTokens > 0 || hasStreamedOutput)
148
+ && usedTokens !== undefined
149
+ && usedTokens <= contextWindow) {
150
+ yield { ...chunk, reason: { kind: 'stop' } };
151
+ continue;
152
+ }
153
+ yield chunk;
154
+ }
155
+ })();
156
+ }
157
+ //# sourceMappingURL=sse-diagnostics.js.map
@@ -0,0 +1,35 @@
1
+ /** Pure Responses wire transformations for hosted search, custom `apply_patch`, and compaction items. */
2
+ import type { GenerateOptions } from '@deepseek-ai/dsh-llm';
3
+ import { REMOTE_COMPACTION_OPEN, REMOTE_COMPACTION_CLOSE, decodeRemoteCompactionMarker, extractMarkerBody, type JsonObject } from './compact-checkpoint.ts';
4
+ export { REMOTE_COMPACTION_OPEN, REMOTE_COMPACTION_CLOSE, decodeRemoteCompactionMarker, extractMarkerBody };
5
+ export type { JsonObject };
6
+ export interface CodexRequestWireOptions {
7
+ /** Provider-facing request option preserved by older DSH LLM adapters. */
8
+ serviceTier?: string;
9
+ /** Whether local web_search should become the hosted Responses tool. */
10
+ hostedWebSearch?: boolean;
11
+ /** Whether apply_patch should use the Responses custom grammar tool. */
12
+ customApplyPatch?: boolean;
13
+ /** Marker bodies verified to come from persisted compaction checkpoint sources. */
14
+ trustedCheckpoints?: ReadonlySet<string>;
15
+ }
16
+ export declare function serviceTierOf(options: GenerateOptions): string | undefined;
17
+ export declare function isWebSearchTool(tool: unknown): boolean;
18
+ export declare function hasWebSearchTool(body: JsonObject): boolean;
19
+ export declare function hasFunctionApplyPatchTool(body: JsonObject): boolean;
20
+ /** Replace DSH's JSON function declaration with the Responses custom grammar tool. */
21
+ export declare function addCodexApplyPatch(body: JsonObject): JsonObject;
22
+ export declare function canRewriteApplyPatchHistory(body: JsonObject): boolean;
23
+ /** Replay apply_patch calls as custom tool items after pi-ai's generic conversion. */
24
+ export declare function rewriteCodexApplyPatchHistory(body: JsonObject): JsonObject;
25
+ /** Detect provider-native compaction triggers owned by adapters such as `dsh-codex-connect`. */
26
+ export declare function isNativeCompactionTriggerBody(body: JsonObject): boolean;
27
+ /** Compose the plugin-only Responses rewrites without changing DSH's tool API. */
28
+ export declare function rewriteCodexResponsesBody(body: JsonObject, options?: Pick<CodexRequestWireOptions, 'hostedWebSearch' | 'customApplyPatch' | 'trustedCheckpoints'>): JsonObject;
29
+ /** Convert a generic DSH Responses tool list to the hosted Codex variant. */
30
+ export declare function addHostedWebSearch(body: JsonObject, trustedCheckpoints?: ReadonlySet<string>): JsonObject;
31
+ /** Replace trusted checkpoint placeholders written by compaction with native wire items. */
32
+ export declare function replaceRemoteCompactions(body: JsonObject, trustedCheckpoints?: ReadonlySet<string>): JsonObject;
33
+ export declare function hasRemoteCompaction(body: JsonObject, trustedCheckpoints?: ReadonlySet<string>): boolean;
34
+ export declare function applyRequestWireOptions(body: JsonObject, options: CodexRequestWireOptions): JsonObject;
35
+ //# sourceMappingURL=wire-rewrite.d.ts.map