@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,264 @@
1
+ /** Trusted remote-compaction checkpoints (V1 & V2), retained-user budgeting, and SSE parsing. */
2
+
3
+ import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction'
4
+ import type { GenerateOptions } from '@deepseek-ai/dsh-llm'
5
+
6
+ export interface JsonObject {
7
+ [key: string]: unknown
8
+ }
9
+
10
+ export const REMOTE_COMPACTION_OPEN = '<codex-remote-compaction>'
11
+ export const REMOTE_COMPACTION_CLOSE = '</codex-remote-compaction>'
12
+ export const CODEX_CONNECT_COMPACTION_OPEN = '<dsh-codex-connect-native-compaction-v1>'
13
+ export const MAX_RETAINED_USER_BYTES = 64_000
14
+
15
+ const V2_PREFIX = 'v2:'
16
+ const MAX_CHECKPOINT_PAYLOAD_BYTES = 2 * 1024 * 1024
17
+ const MAX_COMPACT_STREAM_BYTES = 8 * 1024 * 1024
18
+
19
+ function isJsonObject(value: unknown): value is JsonObject {
20
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
21
+ }
22
+
23
+ function asCompactionItem(item: unknown): JsonObject | undefined {
24
+ if (!isJsonObject(item) || item.type !== 'compaction') return undefined
25
+ if (typeof item.encrypted_content !== 'string') return undefined
26
+ const encrypted = item.encrypted_content.trim()
27
+ if (encrypted.length === 0) return undefined
28
+ if (item.id !== undefined && (typeof item.id !== 'string' || item.id.length === 0)) {
29
+ return undefined
30
+ }
31
+ return {
32
+ type: 'compaction',
33
+ encrypted_content: encrypted,
34
+ ...typeof item.id === 'string' && item.id.length > 0 ? { id: item.id } : {},
35
+ }
36
+ }
37
+
38
+ function validateCheckpointItems(items: readonly unknown[]): JsonObject[] {
39
+ if (items.length === 0 || items.length > 1024) {
40
+ throw new Error('Invalid Codex v2 compaction checkpoint')
41
+ }
42
+ let compactionCount = 0
43
+ const validated: JsonObject[] = []
44
+ for (const raw of items) {
45
+ const compaction = asCompactionItem(raw)
46
+ if (compaction !== undefined) {
47
+ compactionCount += 1
48
+ validated.push(compaction)
49
+ continue
50
+ }
51
+ if (!isJsonObject(raw)
52
+ || raw.role !== 'user'
53
+ || (raw.type !== undefined && raw.type !== 'message')
54
+ || !Array.isArray(raw.content)) {
55
+ throw new Error('Invalid Codex v2 compaction checkpoint')
56
+ }
57
+ validated.push(raw)
58
+ }
59
+ if (compactionCount === 0 || validated.at(-1)?.type !== 'compaction') {
60
+ throw new Error('Invalid Codex v2 compaction checkpoint')
61
+ }
62
+ return validated
63
+ }
64
+
65
+ /** Recognize either harness-owned or `dsh-codex-connect`-owned remote compaction text. */
66
+ export function isAnyRemoteCompactionText(text: string): boolean {
67
+ return text.includes(REMOTE_COMPACTION_OPEN) || text.includes(CODEX_CONNECT_COMPACTION_OPEN)
68
+ }
69
+
70
+ /** Extract inner checkpoint payload bounded by `<codex-remote-compaction>...</codex-remote-compaction>`. */
71
+ export function extractMarkerBody(text: string): string | undefined {
72
+ const startOffset = text.indexOf(REMOTE_COMPACTION_OPEN)
73
+ if (startOffset < 0) return undefined
74
+ const start = startOffset + REMOTE_COMPACTION_OPEN.length
75
+ const end = text.indexOf(REMOTE_COMPACTION_CLOSE, start)
76
+ return end > start ? text.slice(start, end) : undefined
77
+ }
78
+
79
+ /** Read-only scan of request messages returning trusted checkpoint marker bodies. */
80
+ export function collectTrustedCompactionMarkers(messages: GenerateOptions['messages']): ReadonlySet<string> {
81
+ const trusted = new Set<string>()
82
+ for (const message of messages) {
83
+ const source = 'source' in message ? message.source : undefined
84
+ const isTrustedSource = source === undefined
85
+ || (typeof source === 'object' && source !== null
86
+ && isCompactCheckpointSource(source as Parameters<typeof isCompactCheckpointSource>[0]))
87
+ if (!isTrustedSource) continue
88
+ for (const block of message.content) {
89
+ if (block.type !== 'text' || typeof block.text !== 'string') continue
90
+ const inner = extractMarkerBody(block.text)
91
+ if (inner !== undefined) trusted.add(inner)
92
+ }
93
+ }
94
+ return trusted
95
+ }
96
+
97
+ /** Retain newest user-role input items within an adaptive byte budget below compacted source size. */
98
+ export function retainedUserMessagesFromInput(
99
+ input: readonly JsonObject[],
100
+ sourceBytes: number,
101
+ encryptedBytes: number,
102
+ ): JsonObject[] {
103
+ const adaptiveBudget = Math.floor(sourceBytes * 0.45) - Math.ceil(encryptedBytes * 1.4)
104
+ const budget = Math.max(0, Math.min(MAX_RETAINED_USER_BYTES, adaptiveBudget))
105
+ if (budget <= 2) return []
106
+
107
+ const retained: JsonObject[] = []
108
+ let used = 0
109
+ for (let index = input.length - 1; index >= 0; index -= 1) {
110
+ const item = input[index]!
111
+ if (item.role !== 'user'
112
+ || (item.type !== undefined && item.type !== 'message')
113
+ || !Array.isArray(item.content)) {
114
+ continue
115
+ }
116
+ const size = Buffer.byteLength(JSON.stringify(item), 'utf8') + (retained.length === 0 ? 0 : 1)
117
+ if (!Number.isFinite(size) || size <= 0 || size > budget - used) continue
118
+ retained.push(item)
119
+ used += size
120
+ }
121
+ return retained.reverse()
122
+ }
123
+
124
+ /** Encode encrypted compaction items plus retained user turns into a replay marker string. */
125
+ export function encodeRemoteCompactionCheckpoint(
126
+ retained: readonly JsonObject[],
127
+ compactions: readonly JsonObject[],
128
+ ): string {
129
+ if (compactions.length === 0) {
130
+ throw new Error('Codex remote compaction requires at least one compaction item')
131
+ }
132
+ const validatedCompactions = compactions.map(item => {
133
+ const valid = asCompactionItem(item)
134
+ if (valid === undefined) {
135
+ throw new Error('Codex remote compaction returned an invalid compaction item')
136
+ }
137
+ return valid
138
+ })
139
+ if (retained.length === 0 && validatedCompactions.length === 1 && validatedCompactions[0]!.id === undefined) {
140
+ return `${REMOTE_COMPACTION_OPEN}${String(validatedCompactions[0]!.encrypted_content)}${REMOTE_COMPACTION_CLOSE}`
141
+ }
142
+ const items = validateCheckpointItems([...retained, ...validatedCompactions])
143
+ const payload = JSON.stringify({ version: 2, items })
144
+ if (Buffer.byteLength(payload, 'utf8') > MAX_CHECKPOINT_PAYLOAD_BYTES) {
145
+ throw new Error('Codex remote compaction checkpoint exceeds 2 MiB')
146
+ }
147
+ return `${REMOTE_COMPACTION_OPEN}${V2_PREFIX}${Buffer.from(payload, 'utf8').toString('base64url')}${REMOTE_COMPACTION_CLOSE}`
148
+ }
149
+
150
+ /** Decode a V1 or V2 inner checkpoint string back into Responses input items. */
151
+ export function decodeRemoteCompactionMarker(inner: string): JsonObject[] | undefined {
152
+ if (inner.length === 0) return undefined
153
+ if (!inner.startsWith(V2_PREFIX)) {
154
+ return [{ type: 'compaction', encrypted_content: inner }]
155
+ }
156
+ const encoded = inner.slice(V2_PREFIX.length)
157
+ if (encoded.length === 0 || Buffer.byteLength(encoded, 'utf8') > Math.ceil(MAX_CHECKPOINT_PAYLOAD_BYTES / 3) * 4 + 32) {
158
+ throw new Error('Invalid Codex v2 compaction checkpoint')
159
+ }
160
+ let decoded: unknown
161
+ try {
162
+ const raw = Buffer.from(encoded, 'base64url')
163
+ if (raw.byteLength > MAX_CHECKPOINT_PAYLOAD_BYTES) throw new Error('oversized')
164
+ decoded = JSON.parse(raw.toString('utf8'))
165
+ } catch (error) {
166
+ throw new Error('Invalid Codex v2 compaction checkpoint', { cause: error })
167
+ }
168
+ if (!isJsonObject(decoded) || decoded.version !== 2 || !Array.isArray(decoded.items)) {
169
+ throw new Error('Invalid Codex v2 compaction checkpoint')
170
+ }
171
+ return validateCheckpointItems(decoded.items)
172
+ }
173
+
174
+ /** Parse either a JSON `/responses/compact` body or a V2 Responses SSE compaction stream. */
175
+ export async function parseCompactResponsePayload(
176
+ response: Response,
177
+ ): Promise<{ compactions: JsonObject[]; usage?: JsonObject }> {
178
+ const contentType = response.headers.get('content-type')?.toLowerCase() ?? ''
179
+ if (!contentType.includes('text/event-stream')) {
180
+ const body = await response.json() as JsonObject
181
+ const output = Array.isArray(body.output) ? body.output : []
182
+ const compactions: JsonObject[] = []
183
+ for (const item of output) {
184
+ if (!isJsonObject(item) || typeof item.encrypted_content !== 'string') continue
185
+ const encrypted = item.encrypted_content.trim()
186
+ if (encrypted.length === 0) continue
187
+ compactions.push({
188
+ type: 'compaction',
189
+ encrypted_content: encrypted,
190
+ ...typeof item.id === 'string' && item.id.length > 0 ? { id: item.id } : {},
191
+ })
192
+ }
193
+ return {
194
+ compactions,
195
+ ...isJsonObject(body.usage) ? { usage: body.usage } : {},
196
+ }
197
+ }
198
+
199
+ if (response.body === null) throw new Error('Codex remote compaction stream had no body')
200
+ const reader = response.body.getReader()
201
+ const decoder = new TextDecoder()
202
+ const compactions: JsonObject[] = []
203
+ let buffer = ''
204
+ let receivedBytes = 0
205
+ let completed = false
206
+ let usage: JsonObject | undefined
207
+
208
+ const consumeFrame = (frame: string): void => {
209
+ const data = frame
210
+ .split(/\r?\n/u)
211
+ .filter(line => line.startsWith('data:'))
212
+ .map(line => line.slice(5).trimStart())
213
+ .join('\n')
214
+ .trim()
215
+ if (data.length === 0 || data === '[DONE]') return
216
+ const event = JSON.parse(data) as unknown
217
+ if (!isJsonObject(event)) return
218
+ if (event.type === 'response.output_item.done') {
219
+ const item = asCompactionItem(event.item)
220
+ if (item !== undefined) compactions.push(item)
221
+ return
222
+ }
223
+ if (event.type === 'response.failed' || event.type === 'error') {
224
+ throw new Error('Codex remote compaction stream reported failure')
225
+ }
226
+ if (event.type !== 'response.completed' && event.type !== 'response.done') return
227
+ const terminal = event.response
228
+ if (completed || !isJsonObject(terminal) || terminal.status !== 'completed') {
229
+ throw new Error('Codex remote compaction stream ended without completed status')
230
+ }
231
+ if (isJsonObject(terminal.usage)) usage = terminal.usage
232
+ completed = true
233
+ }
234
+
235
+ try {
236
+ for (;;) {
237
+ const { done, value } = await reader.read()
238
+ receivedBytes += value?.byteLength ?? 0
239
+ if (receivedBytes > MAX_COMPACT_STREAM_BYTES) {
240
+ throw new Error('Codex remote compaction stream exceeded 8 MiB limit')
241
+ }
242
+ buffer += decoder.decode(value, { stream: !done })
243
+ for (;;) {
244
+ const match = /\r?\n\r?\n/u.exec(buffer)
245
+ if (match === null) break
246
+ consumeFrame(buffer.slice(0, match.index))
247
+ buffer = buffer.slice(match.index + match[0].length)
248
+ }
249
+ if (done) break
250
+ }
251
+ if (buffer.trim().length > 0) consumeFrame(buffer)
252
+ } finally {
253
+ await reader.cancel().catch(() => undefined)
254
+ reader.releaseLock()
255
+ }
256
+
257
+ if (!completed || compactions.length === 0) {
258
+ throw new Error('Codex remote compaction stream ended without a valid compaction item')
259
+ }
260
+ return {
261
+ compactions,
262
+ ...usage === undefined ? {} : { usage },
263
+ }
264
+ }
@@ -0,0 +1,290 @@
1
+ /** Scoped fetch interceptor, zstd body codec, and negative capability cache for Responses requests. */
2
+
3
+ import type { StreamChunk } from '@deepseek-ai/dsh-llm'
4
+ import { AsyncLocalStorage } from 'node:async_hooks'
5
+ import { zstdCompressSync, zstdDecompressSync } from 'node:zlib'
6
+ import { isGptModel } from '../contracts/settings.ts'
7
+ import { captureCodexErrors } from './sse-diagnostics.ts'
8
+ import {
9
+ applyRequestWireOptions,
10
+ canRewriteApplyPatchHistory,
11
+ hasFunctionApplyPatchTool,
12
+ hasRemoteCompaction,
13
+ hasWebSearchTool,
14
+ isNativeCompactionTriggerBody,
15
+ replaceRemoteCompactions,
16
+ rewriteCodexResponsesBody,
17
+ } from './wire-rewrite.ts'
18
+ import type { CodexRequestWireOptions, JsonObject } from './wire-rewrite.ts'
19
+
20
+ interface CapabilityEntry {
21
+ hostedWebSearch?: boolean
22
+ customApplyPatch?: boolean
23
+ remoteCompact?: boolean
24
+ expiresAt: number
25
+ }
26
+
27
+ const CAPABILITY_CACHE_TTL_MS = 10 * 60_000
28
+ const CAPABILITY_CACHE_MAX_ENTRIES = 64
29
+ export const CONTEXT_LIMIT_ERROR = /context_length_exceeded|maximum context length|context window|too many tokens/i
30
+ const WEB_SEARCH_ERROR = /web_search|external_web_access/i
31
+ const CUSTOM_PATCH_ERROR = /apply_patch|custom_tool|custom\s+tool|grammar|lark/i
32
+
33
+ const HOSTED_REQUESTS = new AsyncLocalStorage<CodexRequestWireOptions>()
34
+ const unsupportedCapabilities = new Map<string, CapabilityEntry>()
35
+ let hostedPatchUsers = 0
36
+ let hostedPatchRestore: (() => void) | undefined
37
+
38
+ function isResponsesRequest(url: string): boolean {
39
+ try {
40
+ const path = new URL(url).pathname.replace(/\/+$/, '')
41
+ return path.endsWith('/responses')
42
+ } catch {
43
+ return url.replace(/\/+$/, '').endsWith('/responses')
44
+ }
45
+ }
46
+
47
+ export function capabilityKey(url: string, model: unknown): string | undefined {
48
+ if (typeof model !== 'string' || model.length === 0) return undefined
49
+ try {
50
+ const parsed = new URL(url)
51
+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}\0${model}`
52
+ } catch {
53
+ return `${url.replace(/\/+$/, '')}\0${model}`
54
+ }
55
+ }
56
+
57
+ function effectiveWireOptions(key: string | undefined, options: CodexRequestWireOptions): CodexRequestWireOptions {
58
+ if (key === undefined) return options
59
+ const cached = unsupportedCapabilities.get(key)
60
+ if (cached === undefined) return options
61
+ if (cached.expiresAt <= Date.now()) {
62
+ unsupportedCapabilities.delete(key)
63
+ return options
64
+ }
65
+ return {
66
+ ...options,
67
+ ...cached.hostedWebSearch === false ? { hostedWebSearch: false } : {},
68
+ ...cached.customApplyPatch === false ? { customApplyPatch: false } : {},
69
+ }
70
+ }
71
+
72
+ export function recordUnsupportedCapability(
73
+ key: string | undefined,
74
+ flags: { hostedWebSearch?: boolean; customApplyPatch?: boolean; remoteCompact?: boolean },
75
+ ): void {
76
+ if (key === undefined) return
77
+ const now = Date.now()
78
+ const existing = unsupportedCapabilities.get(key)
79
+ const valid = existing !== undefined && existing.expiresAt > now ? existing : undefined
80
+ if (existing !== undefined) unsupportedCapabilities.delete(key)
81
+ while (unsupportedCapabilities.size >= CAPABILITY_CACHE_MAX_ENTRIES) {
82
+ const oldest = unsupportedCapabilities.keys().next().value
83
+ if (oldest === undefined) break
84
+ unsupportedCapabilities.delete(oldest)
85
+ }
86
+ unsupportedCapabilities.set(key, {
87
+ ...valid,
88
+ ...flags,
89
+ expiresAt: now + CAPABILITY_CACHE_TTL_MS,
90
+ })
91
+ }
92
+
93
+ export function isCompactUnsupported(key: string | undefined): boolean {
94
+ if (key === undefined) return false
95
+ const cached = unsupportedCapabilities.get(key)
96
+ if (cached === undefined) return false
97
+ if (cached.expiresAt <= Date.now()) {
98
+ unsupportedCapabilities.delete(key)
99
+ return false
100
+ }
101
+ return cached.remoteCompact === false
102
+ }
103
+
104
+ function shouldFallbackResponse(response: Response, errorText: string): boolean {
105
+ if (response.status !== 400
106
+ && response.status !== 404
107
+ && response.status !== 415
108
+ && response.status !== 422) {
109
+ return false
110
+ }
111
+ return !CONTEXT_LIMIT_ERROR.test(errorText)
112
+ }
113
+
114
+ function isAbortError(error: unknown, signal: AbortSignal): boolean {
115
+ if (signal.aborted) return true
116
+ return typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError'
117
+ }
118
+
119
+ function isZstdEncoded(headers: Headers): boolean {
120
+ return headers.get('content-encoding')?.split(',').some(value => value.trim().toLowerCase() === 'zstd') === true
121
+ }
122
+
123
+ async function parseResponsesBody(request: Request): Promise<JsonObject> {
124
+ if (isZstdEncoded(request.headers) && typeof zstdDecompressSync === 'function') {
125
+ const compressed = Buffer.from(await request.clone().arrayBuffer())
126
+ return JSON.parse(zstdDecompressSync(compressed).toString('utf8')) as JsonObject
127
+ }
128
+ return JSON.parse(await request.clone().text()) as JsonObject
129
+ }
130
+
131
+ function jsonRequest(request: Request, body: JsonObject): Request {
132
+ const headers = new Headers(request.headers)
133
+ headers.delete('content-length')
134
+ const serialized = JSON.stringify(body)
135
+ if (isZstdEncoded(headers)) {
136
+ if (typeof zstdCompressSync === 'function') {
137
+ return new Request(request, {
138
+ body: new Uint8Array(zstdCompressSync(Buffer.from(serialized, 'utf8'))),
139
+ headers,
140
+ })
141
+ }
142
+ headers.delete('content-encoding')
143
+ }
144
+ return new Request(request, {
145
+ body: serialized,
146
+ headers,
147
+ })
148
+ }
149
+
150
+ /**
151
+ * Install a scoped fetch shim for pi-ai's already-built Responses request.
152
+ * The generic DSH adapter remains the owner of auth, streaming, replay, and
153
+ * attachments; this shim changes only Codex's Responses tool and compaction
154
+ * representation at the wire boundary.
155
+ */
156
+ function installGlobalHostedWebSearchPatch(): () => void {
157
+ const original = globalThis.fetch
158
+ const patched: typeof fetch = async (input, init) => {
159
+ const options = HOSTED_REQUESTS.getStore()
160
+ if (options === undefined) return original(input, init)
161
+ const request = new Request(input, init)
162
+ if (!isResponsesRequest(request.url)) return original(input, init)
163
+ const requestAndCapture = async (target: RequestInfo | URL, requestInit?: RequestInit): Promise<Response> =>
164
+ captureCodexErrors(await original(target, requestInit))
165
+
166
+ let body: JsonObject
167
+ try {
168
+ body = await parseResponsesBody(request)
169
+ } catch {
170
+ return requestAndCapture(input, init)
171
+ }
172
+
173
+ if (isNativeCompactionTriggerBody(body)) return requestAndCapture(input, init)
174
+
175
+ const requestBody = applyRequestWireOptions(body, options)
176
+ const baseBody = isGptModel(requestBody.model) && hasRemoteCompaction(requestBody, options.trustedCheckpoints)
177
+ ? replaceRemoteCompactions(requestBody, options.trustedCheckpoints)
178
+ : requestBody
179
+ const key = capabilityKey(request.url, baseBody.model)
180
+ const activeOptions = effectiveWireOptions(key, options)
181
+
182
+ const usesHostedWebSearch = isGptModel(baseBody.model)
183
+ && activeOptions.hostedWebSearch !== false
184
+ && hasWebSearchTool(baseBody)
185
+ const usesCustomApplyPatch = isGptModel(baseBody.model)
186
+ && activeOptions.customApplyPatch !== false
187
+ && hasFunctionApplyPatchTool(baseBody)
188
+ && canRewriteApplyPatchHistory(baseBody)
189
+
190
+ if (!usesHostedWebSearch && !usesCustomApplyPatch) {
191
+ return baseBody === body
192
+ ? requestAndCapture(input, init)
193
+ : requestAndCapture(jsonRequest(request, baseBody))
194
+ }
195
+
196
+ const hostedBody = rewriteCodexResponsesBody(baseBody, activeOptions)
197
+ const hostedRequest = jsonRequest(request, hostedBody)
198
+ const fallbackRequest = baseBody === body ? request.clone() : jsonRequest(request, baseBody)
199
+ const sendPlainFallback = (): Promise<Response> => requestAndCapture(fallbackRequest)
200
+
201
+ let response: Response
202
+ try {
203
+ response = await requestAndCapture(hostedRequest)
204
+ } catch (error) {
205
+ if (isAbortError(error, request.signal)) throw error
206
+ // Transport failures fall back once without poisoning the capability cache.
207
+ return sendPlainFallback()
208
+ }
209
+
210
+ if (response.ok) return response
211
+ const errorText = await response.clone().text().catch(() => '')
212
+ if (!shouldFallbackResponse(response, errorText)) return response
213
+
214
+ const mentionsWebSearch = usesHostedWebSearch && WEB_SEARCH_ERROR.test(errorText)
215
+ const mentionsCustomPatch = usesCustomApplyPatch && CUSTOM_PATCH_ERROR.test(errorText)
216
+ if (usesHostedWebSearch && usesCustomApplyPatch && mentionsWebSearch !== mentionsCustomPatch) {
217
+ const reducedOptions: CodexRequestWireOptions = mentionsWebSearch
218
+ ? { ...activeOptions, hostedWebSearch: false }
219
+ : { ...activeOptions, customApplyPatch: false }
220
+ recordUnsupportedCapability(
221
+ key,
222
+ mentionsWebSearch ? { hostedWebSearch: false } : { customApplyPatch: false },
223
+ )
224
+ try {
225
+ const reducedResponse = await requestAndCapture(
226
+ jsonRequest(request, rewriteCodexResponsesBody(baseBody, reducedOptions)),
227
+ )
228
+ if (reducedResponse.ok) return reducedResponse
229
+ const secondErrorText = await reducedResponse.clone().text().catch(() => '')
230
+ if (!shouldFallbackResponse(reducedResponse, secondErrorText)) return reducedResponse
231
+ recordUnsupportedCapability(
232
+ key,
233
+ mentionsWebSearch ? { customApplyPatch: false } : { hostedWebSearch: false },
234
+ )
235
+ return sendPlainFallback()
236
+ } catch (error) {
237
+ if (isAbortError(error, request.signal)) throw error
238
+ return sendPlainFallback()
239
+ }
240
+ }
241
+
242
+ recordUnsupportedCapability(key, {
243
+ ...usesHostedWebSearch ? { hostedWebSearch: false } : {},
244
+ ...usesCustomApplyPatch ? { customApplyPatch: false } : {},
245
+ })
246
+ return sendPlainFallback()
247
+ }
248
+
249
+ globalThis.fetch = patched
250
+ return () => {
251
+ if (globalThis.fetch === patched) globalThis.fetch = original
252
+ }
253
+ }
254
+
255
+ /** Enable the transport patch for this Codex plugin scope only. */
256
+ export function installHostedWebSearch(): () => void {
257
+ hostedPatchUsers += 1
258
+ hostedPatchRestore ??= installGlobalHostedWebSearchPatch()
259
+ return () => {
260
+ hostedPatchUsers = Math.max(0, hostedPatchUsers - 1)
261
+ if (hostedPatchUsers === 0) {
262
+ hostedPatchRestore?.()
263
+ hostedPatchRestore = undefined
264
+ unsupportedCapabilities.clear()
265
+ }
266
+ }
267
+ }
268
+
269
+ /** Iterate an existing DSH stream with the hosted-request context installed. */
270
+ export function hostedWebSearchStream(
271
+ next: () => AsyncIterable<StreamChunk>,
272
+ options: CodexRequestWireOptions = {},
273
+ ): AsyncIterable<StreamChunk> {
274
+ return (async function* (): AsyncGenerator<StreamChunk> {
275
+ const iterator = HOSTED_REQUESTS.run(options, () => next()[Symbol.asyncIterator]())
276
+ let completed = false
277
+ try {
278
+ while (true) {
279
+ const item = await HOSTED_REQUESTS.run(options, () => iterator.next())
280
+ if (item.done) {
281
+ completed = true
282
+ return
283
+ }
284
+ yield item.value
285
+ }
286
+ } finally {
287
+ if (!completed) await HOSTED_REQUESTS.run(options, () => iterator.return?.())
288
+ }
289
+ })()
290
+ }