@shuind/dsh-codex-harness 0.3.2 → 0.3.3

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 (82) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +21 -41
  3. package/docs/preset-library.md +2 -2
  4. package/docs/tool-policy.md +1 -1
  5. package/lib/client.js +1826 -545
  6. package/lib/compact-command.js +7 -1
  7. package/lib/compaction.js +7 -1
  8. package/lib/hybrid-executor.js +23 -12
  9. package/lib/index.js +1229 -17
  10. package/lib/preferences.js +21 -2
  11. package/lib/tool-policy.js +11 -2
  12. package/lib/typert.js +42 -1
  13. package/lib/types/client/desktop.d.ts +20 -42
  14. package/lib/types/client/desktop.js +184 -127
  15. package/lib/types/client/index.d.ts +104 -39
  16. package/lib/types/client/index.js +97 -15
  17. package/lib/types/client/policy-drafts.d.ts +18 -0
  18. package/lib/types/client/policy-drafts.js +27 -0
  19. package/lib/types/client/policy-locale.d.ts +81 -32
  20. package/lib/types/client/policy-locale.js +197 -107
  21. package/lib/types/client/preset-manager.d.ts +25 -2
  22. package/lib/types/client/preset-manager.js +89 -5
  23. package/lib/types/client/preset-requests.d.ts +44 -1
  24. package/lib/types/client/preset-requests.js +150 -0
  25. package/lib/types/client/tool-policy.d.ts +6 -15
  26. package/lib/types/client/tool-policy.js +24 -39
  27. package/lib/types/contracts/preset-editor-schema.d.ts +35 -0
  28. package/lib/types/contracts/preset-editor-schema.js +39 -0
  29. package/lib/types/contracts/settings.d.ts +12 -0
  30. package/lib/types/contracts/settings.js +10 -1
  31. package/lib/types/contracts/ui-contracts.d.ts +48 -0
  32. package/lib/types/contracts/ui-contracts.js +58 -0
  33. package/lib/types/contracts/update.d.ts +73 -0
  34. package/lib/types/contracts/update.js +291 -0
  35. package/lib/types/entries/index.js +20 -2
  36. package/lib/types/entries/preferences.d.ts +2 -0
  37. package/lib/types/entries/preferences.js +9 -0
  38. package/lib/types/hybrid/hybrid-sdk.d.ts +1 -1
  39. package/lib/types/hybrid/hybrid-sdk.js +27 -13
  40. package/lib/types/presets/preset-editor.d.ts +13 -1
  41. package/lib/types/presets/preset-editor.js +24 -1
  42. package/lib/types/presets/pro-mode-store.d.ts +13 -0
  43. package/lib/types/presets/pro-mode-store.js +69 -0
  44. package/lib/types/responses/background-sse-codec.d.ts +23 -0
  45. package/lib/types/responses/background-sse-codec.js +230 -0
  46. package/lib/types/responses/background-stream.d.ts +28 -0
  47. package/lib/types/responses/background-stream.js +351 -0
  48. package/lib/types/responses/fetch-transport.js +24 -9
  49. package/lib/types/responses/wire-rewrite.d.ts +4 -0
  50. package/lib/types/responses/wire-rewrite.js +30 -4
  51. package/lib/types/tools/codex-subagent.d.ts +14 -0
  52. package/lib/types/tools/codex-subagent.js +269 -0
  53. package/lib/types/update/checker.d.ts +14 -0
  54. package/lib/types/update/checker.js +166 -0
  55. package/locale/en.json +1 -1
  56. package/locale/hybrid-executor/en.json +1 -1
  57. package/locale/hybrid-executor/zh.json +1 -1
  58. package/locale/zh.json +1 -1
  59. package/package.json +6 -2
  60. package/src/client/desktop.tsx +359 -160
  61. package/src/client/index.tsx +122 -22
  62. package/src/client/policy-drafts.ts +45 -0
  63. package/src/client/policy-locale.ts +198 -106
  64. package/src/client/preset-manager.tsx +125 -4
  65. package/src/client/preset-requests.ts +185 -1
  66. package/src/client/tool-policy.tsx +29 -63
  67. package/src/contracts/preset-editor-schema.ts +44 -0
  68. package/src/contracts/settings.ts +20 -1
  69. package/src/contracts/ui-contracts.ts +87 -0
  70. package/src/contracts/update.ts +307 -0
  71. package/src/entries/index.ts +25 -2
  72. package/src/entries/preferences.ts +9 -0
  73. package/src/hybrid/hybrid-sdk.ts +28 -12
  74. package/src/presets/preset-editor.ts +31 -3
  75. package/src/presets/pro-mode-store.ts +80 -0
  76. package/src/responses/background-sse-codec.ts +237 -0
  77. package/src/responses/background-stream.ts +371 -0
  78. package/src/responses/fetch-transport.ts +28 -9
  79. package/src/responses/wire-rewrite.ts +34 -3
  80. package/src/tools/codex-subagent.ts +290 -0
  81. package/src/update/checker.ts +193 -0
  82. package/tsdown.config.ts +4 -0
@@ -0,0 +1,237 @@
1
+ /** Pure OpenAI Responses background SSE helpers: URL/body predicates, frame parsing, and poll synthesis. */
2
+
3
+ import type { JsonObject } from './wire-rewrite.ts'
4
+
5
+ export const ENCODER = new TextEncoder()
6
+ export const KEEPALIVE_WIRE_CHUNK = ENCODER.encode(': keepalive\n\n')
7
+ export const SYNTHETIC_KEEPALIVE_OUTPUT_INDEX = 999_999
8
+
9
+ const STREAM_EXPIRED_PATTERN = /no longer be streamed|more than 5 minutes|cannot be streamed|not streamable|stream.*expired/i
10
+
11
+ const HOP_BY_HOP_OR_BODY_HEADERS = new Set([
12
+ 'accept',
13
+ 'connection',
14
+ 'content-encoding',
15
+ 'content-length',
16
+ 'content-type',
17
+ 'host',
18
+ 'transfer-encoding',
19
+ ])
20
+
21
+ export const PIAI_VISIBLE_EVENT_TYPES = new Set([
22
+ 'response.output_item.added',
23
+ 'response.reasoning_summary_text.delta',
24
+ 'response.reasoning_summary_part.done',
25
+ 'response.reasoning_text.delta',
26
+ 'response.output_text.delta',
27
+ 'response.refusal.delta',
28
+ 'response.function_call_arguments.delta',
29
+ 'response.function_call_arguments.done',
30
+ 'response.custom_tool_call_input.delta',
31
+ 'response.custom_tool_call_input.done',
32
+ 'response.output_item.done',
33
+ 'response.completed',
34
+ 'response.incomplete',
35
+ 'response.failed',
36
+ 'error',
37
+ ])
38
+
39
+ export const TERMINAL_EVENT_TYPES = new Set([
40
+ 'response.completed',
41
+ 'response.incomplete',
42
+ 'response.failed',
43
+ 'response.cancelled',
44
+ 'error',
45
+ ])
46
+
47
+ /** True only for the official OpenAI Platform Responses API over HTTPS. */
48
+ export function isOfficialOpenAiResponsesUrl(url: string): boolean {
49
+ try {
50
+ const parsed = new URL(url)
51
+ return parsed.protocol === 'https:'
52
+ && parsed.hostname.toLowerCase() === 'api.openai.com'
53
+ && parsed.pathname.replace(/\/+$/, '').endsWith('/responses')
54
+ } catch {
55
+ return false
56
+ }
57
+ }
58
+
59
+ /** Enable background+store alongside streaming on eligible OpenAI Pro bodies. */
60
+ export function applyBackgroundStreamBody(body: JsonObject): JsonObject {
61
+ if (body.stream !== true || body.background === false) return body
62
+ return { ...body, background: true, store: true, stream: true }
63
+ }
64
+
65
+ export function normalizeResponsesBaseUrl(url: string): string {
66
+ const parsed = new URL(url)
67
+ parsed.search = ''
68
+ parsed.hash = ''
69
+ parsed.pathname = parsed.pathname.replace(/\/+$/, '')
70
+ return parsed.toString()
71
+ }
72
+
73
+ export function buildBackgroundControlHeaders(source: Headers, accept: string): Headers {
74
+ const headers = new Headers()
75
+ source.forEach((value, key) => {
76
+ if (!HOP_BY_HOP_OR_BODY_HEADERS.has(key.toLowerCase())) headers.set(key, value)
77
+ })
78
+ headers.set('accept', accept)
79
+ return headers
80
+ }
81
+
82
+ export function encodeSseEvent(eventType: string, payload: unknown): Uint8Array {
83
+ return ENCODER.encode(`event: ${eventType}\ndata: ${JSON.stringify(payload)}\n\n`)
84
+ }
85
+
86
+ export function asObject(value: unknown): JsonObject | undefined {
87
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
88
+ ? value as JsonObject
89
+ : undefined
90
+ }
91
+
92
+ export function parseSseEventJson(frame: string): JsonObject | undefined {
93
+ const dataLines: string[] = []
94
+ for (const rawLine of frame.split(/\r?\n/)) {
95
+ if (rawLine.startsWith('data:')) {
96
+ const rest = rawLine.slice(5)
97
+ dataLines.push(rest.startsWith(' ') ? rest.slice(1) : rest)
98
+ }
99
+ }
100
+ if (dataLines.length === 0) return undefined
101
+ const data = dataLines.join('\n')
102
+ if (data === '' || data === '[DONE]') return undefined
103
+ try {
104
+ return asObject(JSON.parse(data))
105
+ } catch {
106
+ return undefined
107
+ }
108
+ }
109
+
110
+ export function isSseContentType(headers: Headers): boolean {
111
+ const contentType = headers.get('content-type')
112
+ return contentType === null || contentType.toLowerCase().includes('text/event-stream')
113
+ }
114
+
115
+ export function shouldFallbackToPolling(status: number, errorText: string): boolean {
116
+ if (status === 410) return true
117
+ if ((status === 400 || status === 422) && STREAM_EXPIRED_PATTERN.test(errorText)) return true
118
+ return status === 400 && errorText.trim().length > 0
119
+ }
120
+
121
+ export function isRetryableStatus(status: number): boolean {
122
+ return status === 408 || status === 429 || status >= 500
123
+ }
124
+
125
+ export function cancelledFailureEvent(response: unknown): JsonObject {
126
+ const record = asObject(response) ?? {}
127
+ const existingError = asObject(record.error)
128
+ return {
129
+ type: 'response.failed',
130
+ response: {
131
+ ...record,
132
+ status: 'cancelled',
133
+ error: existingError ?? { code: 'cancelled', message: 'Response was cancelled' },
134
+ },
135
+ }
136
+ }
137
+
138
+ function skeletonForAddedItem(item: JsonObject): JsonObject {
139
+ switch (item.type) {
140
+ case 'reasoning': return { ...item, summary: [], content: [] }
141
+ case 'message': return { ...item, content: [] }
142
+ case 'function_call': return { ...item, arguments: '' }
143
+ case 'custom_tool_call': return { ...item, input: '' }
144
+ default: return item
145
+ }
146
+ }
147
+
148
+ function deltaFramesForNewItem(index: number, item: JsonObject): Uint8Array[] {
149
+ const frames: Uint8Array[] = []
150
+ if (item.type === 'reasoning') {
151
+ const summaries = Array.isArray(item.summary)
152
+ ? item.summary.map(part => asObject(part)?.text).filter((text): text is string => typeof text === 'string' && text.length > 0)
153
+ : []
154
+ const contents = Array.isArray(item.content)
155
+ ? item.content.map(part => asObject(part)?.text).filter((text): text is string => typeof text === 'string' && text.length > 0)
156
+ : []
157
+ const text = summaries.length > 0 ? summaries.join('\n\n') : contents.join('\n\n')
158
+ if (text.length > 0) {
159
+ frames.push(encodeSseEvent('response.reasoning_summary_text.delta', {
160
+ type: 'response.reasoning_summary_text.delta',
161
+ output_index: index,
162
+ delta: text,
163
+ }))
164
+ }
165
+ } else if (item.type === 'message' && Array.isArray(item.content)) {
166
+ for (const rawPart of item.content) {
167
+ const part = asObject(rawPart)
168
+ if (part === undefined) continue
169
+ if (part.type === 'output_text' && typeof part.text === 'string' && part.text.length > 0) {
170
+ frames.push(encodeSseEvent('response.output_text.delta', {
171
+ type: 'response.output_text.delta',
172
+ output_index: index,
173
+ delta: part.text,
174
+ }))
175
+ } else if (part.type === 'refusal' && typeof part.refusal === 'string' && part.refusal.length > 0) {
176
+ frames.push(encodeSseEvent('response.refusal.delta', {
177
+ type: 'response.refusal.delta',
178
+ output_index: index,
179
+ delta: part.refusal,
180
+ }))
181
+ }
182
+ }
183
+ } else if (item.type === 'function_call' && typeof item.arguments === 'string' && item.arguments.length > 0) {
184
+ frames.push(encodeSseEvent('response.function_call_arguments.delta', {
185
+ type: 'response.function_call_arguments.delta',
186
+ output_index: index,
187
+ delta: item.arguments,
188
+ }))
189
+ } else if (item.type === 'custom_tool_call' && typeof item.input === 'string' && item.input.length > 0) {
190
+ frames.push(encodeSseEvent('response.custom_tool_call_input.delta', {
191
+ type: 'response.custom_tool_call_input.delta',
192
+ output_index: index,
193
+ delta: item.input,
194
+ }))
195
+ }
196
+ return frames
197
+ }
198
+
199
+ /** Synthesize SSE events for a polled terminal Responses object without duplicating completed items. */
200
+ export function synthesizePolledResponseSseFrames(
201
+ polled: JsonObject,
202
+ openedOutputIndices: ReadonlySet<number>,
203
+ completedOutputIndices: ReadonlySet<number>,
204
+ ): Uint8Array[] {
205
+ const frames: Uint8Array[] = []
206
+ const output = Array.isArray(polled.output) ? polled.output : []
207
+ for (let index = 0; index < output.length; index++) {
208
+ if (completedOutputIndices.has(index)) continue
209
+ const item = asObject(output[index])
210
+ if (item === undefined) continue
211
+ if (!openedOutputIndices.has(index)) {
212
+ frames.push(encodeSseEvent('response.output_item.added', {
213
+ type: 'response.output_item.added',
214
+ output_index: index,
215
+ item: skeletonForAddedItem(item),
216
+ }))
217
+ frames.push(...deltaFramesForNewItem(index, item))
218
+ }
219
+ frames.push(encodeSseEvent('response.output_item.done', {
220
+ type: 'response.output_item.done',
221
+ output_index: index,
222
+ item,
223
+ }))
224
+ }
225
+
226
+ const status = typeof polled.status === 'string' ? polled.status : 'completed'
227
+ if (status === 'completed') {
228
+ frames.push(encodeSseEvent('response.completed', { type: 'response.completed', response: polled }))
229
+ } else if (status === 'incomplete') {
230
+ frames.push(encodeSseEvent('response.incomplete', { type: 'response.incomplete', response: polled }))
231
+ } else if (status === 'cancelled') {
232
+ frames.push(encodeSseEvent('response.failed', cancelledFailureEvent(polled)))
233
+ } else {
234
+ frames.push(encodeSseEvent('response.failed', { type: 'response.failed', response: polled }))
235
+ }
236
+ return frames
237
+ }
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Resilient OpenAI Responses background+streaming transport for API Pro mode.
3
+ *
4
+ * Wraps official `api.openai.com/v1/responses` SSE streams with:
5
+ * 1. Mid-stream SSE resume via `GET /responses/{id}?stream=true&starting_after={seq}`;
6
+ * 2. Seamless fallback to `GET /responses/{id}` polling after OpenAI's 5-minute
7
+ * streaming replay window expires, synthesizing only missing SSE events;
8
+ * 3. Wire (`: keepalive`) + DSH watchdog keepalives so 5-minute idle timeouts
9
+ * do not abort active Pro reasoning;
10
+ * 4. Best-effort `POST /responses/{id}/cancel` on user abort before completion.
11
+ */
12
+
13
+ import {
14
+ applyBackgroundStreamBody,
15
+ asObject,
16
+ buildBackgroundControlHeaders,
17
+ cancelledFailureEvent,
18
+ ENCODER,
19
+ encodeSseEvent,
20
+ isOfficialOpenAiResponsesUrl,
21
+ isRetryableStatus,
22
+ isSseContentType,
23
+ KEEPALIVE_WIRE_CHUNK,
24
+ normalizeResponsesBaseUrl,
25
+ parseSseEventJson,
26
+ PIAI_VISIBLE_EVENT_TYPES,
27
+ shouldFallbackToPolling,
28
+ SYNTHETIC_KEEPALIVE_OUTPUT_INDEX,
29
+ synthesizePolledResponseSseFrames,
30
+ TERMINAL_EVENT_TYPES,
31
+ } from './background-sse-codec.ts'
32
+
33
+ export { applyBackgroundStreamBody, isOfficialOpenAiResponsesUrl, synthesizePolledResponseSseFrames }
34
+
35
+ const DEFAULT_WIRE_KEEPALIVE_MS = 25_000
36
+ const DEFAULT_WATCHDOG_KEEPALIVE_MS = 120_000
37
+ const DEFAULT_POLL_INTERVAL_MS = 3_000
38
+ const DEFAULT_RECONNECT_BASE_DELAY_MS = 500
39
+ const DEFAULT_MAX_RECONNECT_DELAY_MS = 5_000
40
+ const DEFAULT_MAX_TRANSIENT_ERRORS = 5
41
+ const DEFAULT_CANCEL_TIMEOUT_MS = 5_000
42
+
43
+ export interface BackgroundStreamTimingOptions {
44
+ wireKeepaliveIntervalMs?: number
45
+ watchdogKeepaliveIntervalMs?: number
46
+ pollIntervalMs?: number
47
+ reconnectBaseDelayMs?: number
48
+ maxReconnectDelayMs?: number
49
+ maxTransientErrors?: number
50
+ cancelTimeoutMs?: number
51
+ }
52
+
53
+ function sleepWithSignal(ms: number, signal: AbortSignal): Promise<void> {
54
+ if (ms <= 0) return Promise.resolve()
55
+ if (signal.aborted) return Promise.reject(signal.reason ?? new DOMException('Aborted', 'AbortError'))
56
+ return new Promise((resolve, reject) => {
57
+ const onAbort = (): void => {
58
+ clearTimeout(timer)
59
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'))
60
+ }
61
+ const timer = setTimeout(() => {
62
+ signal.removeEventListener('abort', onAbort)
63
+ resolve()
64
+ }, ms)
65
+ signal.addEventListener('abort', onAbort, { once: true })
66
+ })
67
+ }
68
+
69
+ /**
70
+ * Wrap an initial 200 SSE `POST /v1/responses` response with transparent
71
+ * sequence-tracked SSE resume, >5-minute poll fallback, keepalives, and cancel.
72
+ */
73
+ export function wrapResilientBackgroundSseResponse(
74
+ initialResponse: Response,
75
+ request: Request,
76
+ fetchImpl: typeof fetch,
77
+ timing: BackgroundStreamTimingOptions = {},
78
+ ): Response {
79
+ if (!initialResponse.ok || initialResponse.body === null || !isSseContentType(initialResponse.headers)) {
80
+ return initialResponse
81
+ }
82
+
83
+ const baseUrl = normalizeResponsesBaseUrl(request.url)
84
+ const wireKeepaliveIntervalMs = timing.wireKeepaliveIntervalMs ?? DEFAULT_WIRE_KEEPALIVE_MS
85
+ const watchdogKeepaliveIntervalMs = timing.watchdogKeepaliveIntervalMs ?? DEFAULT_WATCHDOG_KEEPALIVE_MS
86
+ const pollIntervalMs = timing.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS
87
+ const reconnectBaseDelayMs = timing.reconnectBaseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS
88
+ const maxReconnectDelayMs = timing.maxReconnectDelayMs ?? DEFAULT_MAX_RECONNECT_DELAY_MS
89
+ const maxTransientErrors = timing.maxTransientErrors ?? DEFAULT_MAX_TRANSIENT_ERRORS
90
+ const cancelTimeoutMs = timing.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS
91
+
92
+ let responseId: string | undefined
93
+ let lastSequenceNumber: number | undefined
94
+ const openedOutputIndices = new Set<number>()
95
+ const completedOutputIndices = new Set<number>()
96
+ let openReasoningOutputIndex: number | undefined
97
+ let syntheticKeepaliveSlotOpened = false
98
+ let sawTerminal = false
99
+ let closed = false
100
+ let cancelRequested = false
101
+ let activeReader: ReadableStreamDefaultReader<Uint8Array> | undefined
102
+
103
+ const internalAbort = new AbortController()
104
+ const signal = request.signal
105
+ ? AbortSignal.any([request.signal, internalAbort.signal])
106
+ : internalAbort.signal
107
+
108
+ const fireServerCancel = (): void => {
109
+ if (sawTerminal || cancelRequested || responseId === undefined) return
110
+ cancelRequested = true
111
+ const cancelUrl = `${baseUrl}/${encodeURIComponent(responseId)}/cancel`
112
+ const init: RequestInit = {
113
+ method: 'POST',
114
+ headers: buildBackgroundControlHeaders(request.headers, 'application/json'),
115
+ ...(typeof AbortSignal.timeout === 'function' ? { signal: AbortSignal.timeout(cancelTimeoutMs) } : {}),
116
+ }
117
+ void fetchImpl(cancelUrl, init).then(res => res.body?.cancel?.().catch(() => {})).catch(() => {})
118
+ }
119
+
120
+ const onRequestAbort = (): void => {
121
+ fireServerCancel()
122
+ void activeReader?.cancel?.().catch(() => {})
123
+ }
124
+ request.signal?.addEventListener('abort', onRequestAbort, { once: true })
125
+
126
+ const backoffDelay = (attempt: number): number =>
127
+ Math.min(reconnectBaseDelayMs * (2 ** (attempt - 1)), maxReconnectDelayMs)
128
+
129
+ const stream = new ReadableStream<Uint8Array>({
130
+ async start(controller) {
131
+ let lastFrameSentAt = Date.now()
132
+ let lastPiAiEventAt = Date.now()
133
+
134
+ const safeEnqueue = (chunk: Uint8Array): void => {
135
+ if (closed) return
136
+ controller.enqueue(chunk)
137
+ lastFrameSentAt = Date.now()
138
+ }
139
+ const safeClose = (): void => { if (!closed) { closed = true; controller.close() } }
140
+ const safeError = (error: unknown): void => { if (!closed) { closed = true; controller.error(error) } }
141
+
142
+ const emitWatchdogKeepalive = (): void => {
143
+ if (closed || sawTerminal) return
144
+ const targetIndex = openReasoningOutputIndex ?? SYNTHETIC_KEEPALIVE_OUTPUT_INDEX
145
+ if (openReasoningOutputIndex === undefined && !syntheticKeepaliveSlotOpened) {
146
+ syntheticKeepaliveSlotOpened = true
147
+ safeEnqueue(encodeSseEvent('response.output_item.added', {
148
+ type: 'response.output_item.added',
149
+ output_index: SYNTHETIC_KEEPALIVE_OUTPUT_INDEX,
150
+ item: { type: 'reasoning', id: 'rs_codex_keepalive', summary: [] },
151
+ }))
152
+ }
153
+ safeEnqueue(encodeSseEvent('response.reasoning_summary_text.delta', {
154
+ type: 'response.reasoning_summary_text.delta',
155
+ output_index: targetIndex,
156
+ delta: '',
157
+ }))
158
+ lastPiAiEventAt = Date.now()
159
+ }
160
+
161
+ const tickIntervalMs = Math.max(5, Math.min(wireKeepaliveIntervalMs, watchdogKeepaliveIntervalMs))
162
+ const keepaliveTimer = setInterval(() => {
163
+ if (closed || sawTerminal || signal.aborted) return
164
+ const now = Date.now()
165
+ if (now - lastPiAiEventAt >= watchdogKeepaliveIntervalMs) {
166
+ emitWatchdogKeepalive()
167
+ return
168
+ }
169
+ if (now - lastFrameSentAt >= wireKeepaliveIntervalMs) safeEnqueue(KEEPALIVE_WIRE_CHUNK)
170
+ }, tickIntervalMs)
171
+ keepaliveTimer.unref?.()
172
+
173
+ const processFrame = (rawFrame: string, deduplicate: boolean): void => {
174
+ if (closed || rawFrame.trim().length === 0) return
175
+ const event = parseSseEventJson(rawFrame)
176
+ if (event === undefined) {
177
+ safeEnqueue(ENCODER.encode(`${rawFrame}\n\n`))
178
+ return
179
+ }
180
+
181
+ const seq = typeof event.sequence_number === 'number' ? event.sequence_number : undefined
182
+ if (deduplicate && seq !== undefined && lastSequenceNumber !== undefined && seq <= lastSequenceNumber) return
183
+ if (seq !== undefined) {
184
+ lastSequenceNumber = lastSequenceNumber === undefined ? seq : Math.max(lastSequenceNumber, seq)
185
+ }
186
+
187
+ const responseObj = asObject(event.response)
188
+ if (typeof responseObj?.id === 'string' && responseObj.id.length > 0) responseId = responseObj.id
189
+
190
+ const type = typeof event.type === 'string' ? event.type : ''
191
+ const outputIndex = typeof event.output_index === 'number' ? event.output_index : undefined
192
+ const item = asObject(event.item)
193
+ if (type === 'response.output_item.added' && outputIndex !== undefined) {
194
+ openedOutputIndices.add(outputIndex)
195
+ if (item?.type === 'reasoning') openReasoningOutputIndex = outputIndex
196
+ } else if (type === 'response.output_item.done' && outputIndex !== undefined) {
197
+ completedOutputIndices.add(outputIndex)
198
+ if (openReasoningOutputIndex === outputIndex) openReasoningOutputIndex = undefined
199
+ }
200
+
201
+ if (PIAI_VISIBLE_EVENT_TYPES.has(type)) lastPiAiEventAt = Date.now()
202
+ if (TERMINAL_EVENT_TYPES.has(type)) {
203
+ sawTerminal = true
204
+ if (type === 'response.cancelled') {
205
+ safeEnqueue(encodeSseEvent('response.failed', cancelledFailureEvent(event.response)))
206
+ return
207
+ }
208
+ }
209
+ safeEnqueue(ENCODER.encode(`${rawFrame}\n\n`))
210
+ }
211
+
212
+ const pumpSseBody = async (body: ReadableStream<Uint8Array>, deduplicate: boolean): Promise<void> => {
213
+ const reader = body.getReader()
214
+ activeReader = reader
215
+ const decoder = new TextDecoder()
216
+ let buffer = ''
217
+ try {
218
+ while (!closed && !signal.aborted) {
219
+ const { done, value } = await reader.read()
220
+ if (done) break
221
+ buffer += decoder.decode(value, { stream: true })
222
+ let match = /\r?\n\r?\n/.exec(buffer)
223
+ while (match !== null) {
224
+ const frame = buffer.slice(0, match.index)
225
+ buffer = buffer.slice(match.index + match[0].length)
226
+ processFrame(frame, deduplicate)
227
+ if (sawTerminal || closed) return
228
+ match = /\r?\n\r?\n/.exec(buffer)
229
+ }
230
+ }
231
+ buffer += decoder.decode()
232
+ if (!sawTerminal && !closed && buffer.trim().length > 0 && parseSseEventJson(buffer) !== undefined) {
233
+ processFrame(buffer, deduplicate)
234
+ }
235
+ } finally {
236
+ activeReader = undefined
237
+ await reader.cancel().catch(() => {})
238
+ reader.releaseLock()
239
+ }
240
+ }
241
+
242
+ const pollUntilTerminal = async (): Promise<void> => {
243
+ if (responseId === undefined) throw new Error('Cannot poll OpenAI background response without response_id')
244
+ const pollUrl = `${baseUrl}/${encodeURIComponent(responseId)}`
245
+ let transientErrors = 0
246
+ while (!sawTerminal && !closed && !signal.aborted) {
247
+ let pollResponse: Response
248
+ try {
249
+ pollResponse = await fetchImpl(pollUrl, {
250
+ method: 'GET',
251
+ headers: buildBackgroundControlHeaders(request.headers, 'application/json'),
252
+ signal,
253
+ })
254
+ } catch (error) {
255
+ if (signal.aborted || ++transientErrors > maxTransientErrors) throw error
256
+ await sleepWithSignal(backoffDelay(transientErrors), signal)
257
+ continue
258
+ }
259
+ if (!pollResponse.ok) {
260
+ const errorText = await pollResponse.text().catch(() => '')
261
+ if (isRetryableStatus(pollResponse.status) && ++transientErrors <= maxTransientErrors) {
262
+ await sleepWithSignal(backoffDelay(transientErrors), signal)
263
+ continue
264
+ }
265
+ throw new Error(`OpenAI background poll failed (${pollResponse.status}): ${errorText || pollResponse.statusText}`)
266
+ }
267
+ transientErrors = 0
268
+ const polled = asObject(await pollResponse.json())
269
+ if (polled === undefined) throw new Error('OpenAI background poll returned a non-object JSON payload')
270
+ const status = typeof polled.status === 'string' ? polled.status : undefined
271
+ if (status === 'queued' || status === 'in_progress') {
272
+ await sleepWithSignal(pollIntervalMs, signal)
273
+ continue
274
+ }
275
+ if (status === 'completed' || status === 'incomplete' || status === 'failed' || status === 'cancelled') {
276
+ const syntheticFrames = synthesizePolledResponseSseFrames(polled, openedOutputIndices, completedOutputIndices)
277
+ sawTerminal = true
278
+ for (const frame of syntheticFrames) safeEnqueue(frame)
279
+ return
280
+ }
281
+ throw new Error(`Unexpected OpenAI background response status: ${String(status)}`)
282
+ }
283
+ }
284
+
285
+ const resumeOrPoll = async (): Promise<void> => {
286
+ let transientErrors = 0
287
+ let usePolling = false
288
+ while (!sawTerminal && !closed && !signal.aborted) {
289
+ if (usePolling) {
290
+ await pollUntilTerminal()
291
+ return
292
+ }
293
+ if (responseId === undefined) return
294
+ const query = lastSequenceNumber === undefined ? 'stream=true' : `stream=true&starting_after=${lastSequenceNumber}`
295
+ const resumeUrl = `${baseUrl}/${encodeURIComponent(responseId)}?${query}`
296
+ let resumeResponse: Response
297
+ try {
298
+ resumeResponse = await fetchImpl(resumeUrl, {
299
+ method: 'GET',
300
+ headers: buildBackgroundControlHeaders(request.headers, 'text/event-stream'),
301
+ signal,
302
+ })
303
+ } catch (error) {
304
+ if (signal.aborted || ++transientErrors > maxTransientErrors) throw error
305
+ await sleepWithSignal(backoffDelay(transientErrors), signal)
306
+ continue
307
+ }
308
+ if (!resumeResponse.ok) {
309
+ const errorText = await resumeResponse.text().catch(() => '')
310
+ if (shouldFallbackToPolling(resumeResponse.status, errorText)) {
311
+ usePolling = true
312
+ continue
313
+ }
314
+ if (isRetryableStatus(resumeResponse.status) && ++transientErrors <= maxTransientErrors) {
315
+ await sleepWithSignal(backoffDelay(transientErrors), signal)
316
+ continue
317
+ }
318
+ throw new Error(`OpenAI background stream resume failed (${resumeResponse.status}): ${errorText || resumeResponse.statusText}`)
319
+ }
320
+ if (resumeResponse.body === null) {
321
+ usePolling = true
322
+ continue
323
+ }
324
+ transientErrors = 0
325
+ try {
326
+ await pumpSseBody(resumeResponse.body, true)
327
+ } catch (error) {
328
+ if (signal.aborted || ++transientErrors > maxTransientErrors) throw error
329
+ await sleepWithSignal(backoffDelay(transientErrors), signal)
330
+ }
331
+ }
332
+ }
333
+
334
+ try {
335
+ try {
336
+ await pumpSseBody(initialResponse.body!, false)
337
+ } catch (error) {
338
+ if (signal.aborted || responseId === undefined) throw error
339
+ }
340
+ if (!sawTerminal && !closed && !signal.aborted && responseId !== undefined) await resumeOrPoll()
341
+ if (signal.aborted) {
342
+ fireServerCancel()
343
+ safeError(signal.reason ?? new DOMException('Aborted', 'AbortError'))
344
+ return
345
+ }
346
+ safeClose()
347
+ } catch (error) {
348
+ if (signal.aborted) fireServerCancel()
349
+ safeError(error)
350
+ } finally {
351
+ clearInterval(keepaliveTimer)
352
+ request.signal?.removeEventListener('abort', onRequestAbort)
353
+ }
354
+ },
355
+
356
+ cancel() {
357
+ closed = true
358
+ fireServerCancel()
359
+ internalAbort.abort(new DOMException('Stream cancelled', 'AbortError'))
360
+ void activeReader?.cancel?.().catch(() => {})
361
+ },
362
+ })
363
+
364
+ const headers = new Headers(initialResponse.headers)
365
+ headers.delete('content-length')
366
+ return new Response(stream, {
367
+ status: initialResponse.status,
368
+ statusText: initialResponse.statusText,
369
+ headers,
370
+ })
371
+ }
@@ -4,6 +4,11 @@ import type { StreamChunk } from '@deepseek-ai/dsh-llm'
4
4
  import { AsyncLocalStorage } from 'node:async_hooks'
5
5
  import { zstdCompressSync, zstdDecompressSync } from 'node:zlib'
6
6
  import { isGptModel } from '../contracts/settings.ts'
7
+ import {
8
+ applyBackgroundStreamBody,
9
+ isOfficialOpenAiResponsesUrl,
10
+ wrapResilientBackgroundSseResponse,
11
+ } from './background-stream.ts'
7
12
  import { captureCodexErrors } from './sse-diagnostics.ts'
8
13
  import {
9
14
  applyRequestWireOptions,
@@ -27,6 +32,7 @@ interface CapabilityEntry {
27
32
  const CAPABILITY_CACHE_TTL_MS = 10 * 60_000
28
33
  const CAPABILITY_CACHE_MAX_ENTRIES = 64
29
34
  export const CONTEXT_LIMIT_ERROR = /context_length_exceeded|maximum context length|context window|too many tokens/i
35
+ const REASONING_MODE_ERROR = /reasoning\.mode|reasoning_mode|['"`]mode['"`].*\bpro\b/i
30
36
  const WEB_SEARCH_ERROR = /web_search|external_web_access/i
31
37
  const CUSTOM_PATCH_ERROR = /apply_patch|custom_tool|custom\s+tool|grammar|lark/i
32
38
 
@@ -108,7 +114,7 @@ function shouldFallbackResponse(response: Response, errorText: string): boolean
108
114
  && response.status !== 422) {
109
115
  return false
110
116
  }
111
- return !CONTEXT_LIMIT_ERROR.test(errorText)
117
+ return !CONTEXT_LIMIT_ERROR.test(errorText) && !REASONING_MODE_ERROR.test(errorText)
112
118
  }
113
119
 
114
120
  function isAbortError(error: unknown, signal: AbortSignal): boolean {
@@ -173,9 +179,22 @@ function installGlobalHostedWebSearchPatch(): () => void {
173
179
  if (isNativeCompactionTriggerBody(body)) return requestAndCapture(input, init)
174
180
 
175
181
  const requestBody = applyRequestWireOptions(body, options)
176
- const baseBody = isGptModel(requestBody.model) && hasRemoteCompaction(requestBody, options.trustedCheckpoints)
177
- ? replaceRemoteCompactions(requestBody, options.trustedCheckpoints)
178
- : requestBody
182
+ const useBackgroundStream = options.reasoningMode === 'pro'
183
+ && options.backgroundStream === true
184
+ && isOfficialOpenAiResponsesUrl(request.url)
185
+ && requestBody.stream === true
186
+ && requestBody.background !== false
187
+ const transportBody = useBackgroundStream ? applyBackgroundStreamBody(requestBody) : requestBody
188
+ const sendResponsesRequest = async (target: RequestInfo | URL, requestInit?: RequestInit): Promise<Response> => {
189
+ const response = await original(target, requestInit)
190
+ const wrapped = useBackgroundStream
191
+ ? wrapResilientBackgroundSseResponse(response, request, original)
192
+ : response
193
+ return captureCodexErrors(wrapped)
194
+ }
195
+ const baseBody = isGptModel(transportBody.model) && hasRemoteCompaction(transportBody, options.trustedCheckpoints)
196
+ ? replaceRemoteCompactions(transportBody, options.trustedCheckpoints)
197
+ : transportBody
179
198
  const key = capabilityKey(request.url, baseBody.model)
180
199
  const activeOptions = effectiveWireOptions(key, options)
181
200
 
@@ -189,18 +208,18 @@ function installGlobalHostedWebSearchPatch(): () => void {
189
208
 
190
209
  if (!usesHostedWebSearch && !usesCustomApplyPatch) {
191
210
  return baseBody === body
192
- ? requestAndCapture(input, init)
193
- : requestAndCapture(jsonRequest(request, baseBody))
211
+ ? sendResponsesRequest(input, init)
212
+ : sendResponsesRequest(jsonRequest(request, baseBody))
194
213
  }
195
214
 
196
215
  const hostedBody = rewriteCodexResponsesBody(baseBody, activeOptions)
197
216
  const hostedRequest = jsonRequest(request, hostedBody)
198
217
  const fallbackRequest = baseBody === body ? request.clone() : jsonRequest(request, baseBody)
199
- const sendPlainFallback = (): Promise<Response> => requestAndCapture(fallbackRequest)
218
+ const sendPlainFallback = (): Promise<Response> => sendResponsesRequest(fallbackRequest)
200
219
 
201
220
  let response: Response
202
221
  try {
203
- response = await requestAndCapture(hostedRequest)
222
+ response = await sendResponsesRequest(hostedRequest)
204
223
  } catch (error) {
205
224
  if (isAbortError(error, request.signal)) throw error
206
225
  // Transport failures fall back once without poisoning the capability cache.
@@ -222,7 +241,7 @@ function installGlobalHostedWebSearchPatch(): () => void {
222
241
  mentionsWebSearch ? { hostedWebSearch: false } : { customApplyPatch: false },
223
242
  )
224
243
  try {
225
- const reducedResponse = await requestAndCapture(
244
+ const reducedResponse = await sendResponsesRequest(
226
245
  jsonRequest(request, rewriteCodexResponsesBody(baseBody, reducedOptions)),
227
246
  )
228
247
  if (reducedResponse.ok) return reducedResponse