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