@shuind/dsh-codex-harness 0.2.21 → 0.2.32-dsh-v0.2.2-rc.1

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