@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,351 @@
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
+ import { applyBackgroundStreamBody, asObject, buildBackgroundControlHeaders, cancelledFailureEvent, ENCODER, encodeSseEvent, isOfficialOpenAiResponsesUrl, isRetryableStatus, isSseContentType, KEEPALIVE_WIRE_CHUNK, normalizeResponsesBaseUrl, parseSseEventJson, PIAI_VISIBLE_EVENT_TYPES, shouldFallbackToPolling, SYNTHETIC_KEEPALIVE_OUTPUT_INDEX, synthesizePolledResponseSseFrames, TERMINAL_EVENT_TYPES, } from "./background-sse-codec.js";
13
+ export { applyBackgroundStreamBody, isOfficialOpenAiResponsesUrl, synthesizePolledResponseSseFrames };
14
+ const DEFAULT_WIRE_KEEPALIVE_MS = 25_000;
15
+ const DEFAULT_WATCHDOG_KEEPALIVE_MS = 120_000;
16
+ const DEFAULT_POLL_INTERVAL_MS = 3_000;
17
+ const DEFAULT_RECONNECT_BASE_DELAY_MS = 500;
18
+ const DEFAULT_MAX_RECONNECT_DELAY_MS = 5_000;
19
+ const DEFAULT_MAX_TRANSIENT_ERRORS = 5;
20
+ const DEFAULT_CANCEL_TIMEOUT_MS = 5_000;
21
+ function sleepWithSignal(ms, signal) {
22
+ if (ms <= 0)
23
+ return Promise.resolve();
24
+ if (signal.aborted)
25
+ return Promise.reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
26
+ return new Promise((resolve, reject) => {
27
+ const onAbort = () => {
28
+ clearTimeout(timer);
29
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
30
+ };
31
+ const timer = setTimeout(() => {
32
+ signal.removeEventListener('abort', onAbort);
33
+ resolve();
34
+ }, ms);
35
+ signal.addEventListener('abort', onAbort, { once: true });
36
+ });
37
+ }
38
+ /**
39
+ * Wrap an initial 200 SSE `POST /v1/responses` response with transparent
40
+ * sequence-tracked SSE resume, >5-minute poll fallback, keepalives, and cancel.
41
+ */
42
+ export function wrapResilientBackgroundSseResponse(initialResponse, request, fetchImpl, timing = {}) {
43
+ if (!initialResponse.ok || initialResponse.body === null || !isSseContentType(initialResponse.headers)) {
44
+ return initialResponse;
45
+ }
46
+ const baseUrl = normalizeResponsesBaseUrl(request.url);
47
+ const wireKeepaliveIntervalMs = timing.wireKeepaliveIntervalMs ?? DEFAULT_WIRE_KEEPALIVE_MS;
48
+ const watchdogKeepaliveIntervalMs = timing.watchdogKeepaliveIntervalMs ?? DEFAULT_WATCHDOG_KEEPALIVE_MS;
49
+ const pollIntervalMs = timing.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
50
+ const reconnectBaseDelayMs = timing.reconnectBaseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS;
51
+ const maxReconnectDelayMs = timing.maxReconnectDelayMs ?? DEFAULT_MAX_RECONNECT_DELAY_MS;
52
+ const maxTransientErrors = timing.maxTransientErrors ?? DEFAULT_MAX_TRANSIENT_ERRORS;
53
+ const cancelTimeoutMs = timing.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS;
54
+ let responseId;
55
+ let lastSequenceNumber;
56
+ const openedOutputIndices = new Set();
57
+ const completedOutputIndices = new Set();
58
+ let openReasoningOutputIndex;
59
+ let syntheticKeepaliveSlotOpened = false;
60
+ let sawTerminal = false;
61
+ let closed = false;
62
+ let cancelRequested = false;
63
+ let activeReader;
64
+ const internalAbort = new AbortController();
65
+ const signal = request.signal
66
+ ? AbortSignal.any([request.signal, internalAbort.signal])
67
+ : internalAbort.signal;
68
+ const fireServerCancel = () => {
69
+ if (sawTerminal || cancelRequested || responseId === undefined)
70
+ return;
71
+ cancelRequested = true;
72
+ const cancelUrl = `${baseUrl}/${encodeURIComponent(responseId)}/cancel`;
73
+ const init = {
74
+ method: 'POST',
75
+ headers: buildBackgroundControlHeaders(request.headers, 'application/json'),
76
+ ...(typeof AbortSignal.timeout === 'function' ? { signal: AbortSignal.timeout(cancelTimeoutMs) } : {}),
77
+ };
78
+ void fetchImpl(cancelUrl, init).then(res => res.body?.cancel?.().catch(() => { })).catch(() => { });
79
+ };
80
+ const onRequestAbort = () => {
81
+ fireServerCancel();
82
+ void activeReader?.cancel?.().catch(() => { });
83
+ };
84
+ request.signal?.addEventListener('abort', onRequestAbort, { once: true });
85
+ const backoffDelay = (attempt) => Math.min(reconnectBaseDelayMs * (2 ** (attempt - 1)), maxReconnectDelayMs);
86
+ const stream = new ReadableStream({
87
+ async start(controller) {
88
+ let lastFrameSentAt = Date.now();
89
+ let lastPiAiEventAt = Date.now();
90
+ const safeEnqueue = (chunk) => {
91
+ if (closed)
92
+ return;
93
+ controller.enqueue(chunk);
94
+ lastFrameSentAt = Date.now();
95
+ };
96
+ const safeClose = () => { if (!closed) {
97
+ closed = true;
98
+ controller.close();
99
+ } };
100
+ const safeError = (error) => { if (!closed) {
101
+ closed = true;
102
+ controller.error(error);
103
+ } };
104
+ const emitWatchdogKeepalive = () => {
105
+ if (closed || sawTerminal)
106
+ return;
107
+ const targetIndex = openReasoningOutputIndex ?? SYNTHETIC_KEEPALIVE_OUTPUT_INDEX;
108
+ if (openReasoningOutputIndex === undefined && !syntheticKeepaliveSlotOpened) {
109
+ syntheticKeepaliveSlotOpened = true;
110
+ safeEnqueue(encodeSseEvent('response.output_item.added', {
111
+ type: 'response.output_item.added',
112
+ output_index: SYNTHETIC_KEEPALIVE_OUTPUT_INDEX,
113
+ item: { type: 'reasoning', id: 'rs_codex_keepalive', summary: [] },
114
+ }));
115
+ }
116
+ safeEnqueue(encodeSseEvent('response.reasoning_summary_text.delta', {
117
+ type: 'response.reasoning_summary_text.delta',
118
+ output_index: targetIndex,
119
+ delta: '',
120
+ }));
121
+ lastPiAiEventAt = Date.now();
122
+ };
123
+ const tickIntervalMs = Math.max(5, Math.min(wireKeepaliveIntervalMs, watchdogKeepaliveIntervalMs));
124
+ const keepaliveTimer = setInterval(() => {
125
+ if (closed || sawTerminal || signal.aborted)
126
+ return;
127
+ const now = Date.now();
128
+ if (now - lastPiAiEventAt >= watchdogKeepaliveIntervalMs) {
129
+ emitWatchdogKeepalive();
130
+ return;
131
+ }
132
+ if (now - lastFrameSentAt >= wireKeepaliveIntervalMs)
133
+ safeEnqueue(KEEPALIVE_WIRE_CHUNK);
134
+ }, tickIntervalMs);
135
+ keepaliveTimer.unref?.();
136
+ const processFrame = (rawFrame, deduplicate) => {
137
+ if (closed || rawFrame.trim().length === 0)
138
+ return;
139
+ const event = parseSseEventJson(rawFrame);
140
+ if (event === undefined) {
141
+ safeEnqueue(ENCODER.encode(`${rawFrame}\n\n`));
142
+ return;
143
+ }
144
+ const seq = typeof event.sequence_number === 'number' ? event.sequence_number : undefined;
145
+ if (deduplicate && seq !== undefined && lastSequenceNumber !== undefined && seq <= lastSequenceNumber)
146
+ return;
147
+ if (seq !== undefined) {
148
+ lastSequenceNumber = lastSequenceNumber === undefined ? seq : Math.max(lastSequenceNumber, seq);
149
+ }
150
+ const responseObj = asObject(event.response);
151
+ if (typeof responseObj?.id === 'string' && responseObj.id.length > 0)
152
+ responseId = responseObj.id;
153
+ const type = typeof event.type === 'string' ? event.type : '';
154
+ const outputIndex = typeof event.output_index === 'number' ? event.output_index : undefined;
155
+ const item = asObject(event.item);
156
+ if (type === 'response.output_item.added' && outputIndex !== undefined) {
157
+ openedOutputIndices.add(outputIndex);
158
+ if (item?.type === 'reasoning')
159
+ openReasoningOutputIndex = outputIndex;
160
+ }
161
+ else if (type === 'response.output_item.done' && outputIndex !== undefined) {
162
+ completedOutputIndices.add(outputIndex);
163
+ if (openReasoningOutputIndex === outputIndex)
164
+ openReasoningOutputIndex = undefined;
165
+ }
166
+ if (PIAI_VISIBLE_EVENT_TYPES.has(type))
167
+ lastPiAiEventAt = Date.now();
168
+ if (TERMINAL_EVENT_TYPES.has(type)) {
169
+ sawTerminal = true;
170
+ if (type === 'response.cancelled') {
171
+ safeEnqueue(encodeSseEvent('response.failed', cancelledFailureEvent(event.response)));
172
+ return;
173
+ }
174
+ }
175
+ safeEnqueue(ENCODER.encode(`${rawFrame}\n\n`));
176
+ };
177
+ const pumpSseBody = async (body, deduplicate) => {
178
+ const reader = body.getReader();
179
+ activeReader = reader;
180
+ const decoder = new TextDecoder();
181
+ let buffer = '';
182
+ try {
183
+ while (!closed && !signal.aborted) {
184
+ const { done, value } = await reader.read();
185
+ if (done)
186
+ break;
187
+ buffer += decoder.decode(value, { stream: true });
188
+ let match = /\r?\n\r?\n/.exec(buffer);
189
+ while (match !== null) {
190
+ const frame = buffer.slice(0, match.index);
191
+ buffer = buffer.slice(match.index + match[0].length);
192
+ processFrame(frame, deduplicate);
193
+ if (sawTerminal || closed)
194
+ return;
195
+ match = /\r?\n\r?\n/.exec(buffer);
196
+ }
197
+ }
198
+ buffer += decoder.decode();
199
+ if (!sawTerminal && !closed && buffer.trim().length > 0 && parseSseEventJson(buffer) !== undefined) {
200
+ processFrame(buffer, deduplicate);
201
+ }
202
+ }
203
+ finally {
204
+ activeReader = undefined;
205
+ await reader.cancel().catch(() => { });
206
+ reader.releaseLock();
207
+ }
208
+ };
209
+ const pollUntilTerminal = async () => {
210
+ if (responseId === undefined)
211
+ throw new Error('Cannot poll OpenAI background response without response_id');
212
+ const pollUrl = `${baseUrl}/${encodeURIComponent(responseId)}`;
213
+ let transientErrors = 0;
214
+ while (!sawTerminal && !closed && !signal.aborted) {
215
+ let pollResponse;
216
+ try {
217
+ pollResponse = await fetchImpl(pollUrl, {
218
+ method: 'GET',
219
+ headers: buildBackgroundControlHeaders(request.headers, 'application/json'),
220
+ signal,
221
+ });
222
+ }
223
+ catch (error) {
224
+ if (signal.aborted || ++transientErrors > maxTransientErrors)
225
+ throw error;
226
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
227
+ continue;
228
+ }
229
+ if (!pollResponse.ok) {
230
+ const errorText = await pollResponse.text().catch(() => '');
231
+ if (isRetryableStatus(pollResponse.status) && ++transientErrors <= maxTransientErrors) {
232
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
233
+ continue;
234
+ }
235
+ throw new Error(`OpenAI background poll failed (${pollResponse.status}): ${errorText || pollResponse.statusText}`);
236
+ }
237
+ transientErrors = 0;
238
+ const polled = asObject(await pollResponse.json());
239
+ if (polled === undefined)
240
+ throw new Error('OpenAI background poll returned a non-object JSON payload');
241
+ const status = typeof polled.status === 'string' ? polled.status : undefined;
242
+ if (status === 'queued' || status === 'in_progress') {
243
+ await sleepWithSignal(pollIntervalMs, signal);
244
+ continue;
245
+ }
246
+ if (status === 'completed' || status === 'incomplete' || status === 'failed' || status === 'cancelled') {
247
+ const syntheticFrames = synthesizePolledResponseSseFrames(polled, openedOutputIndices, completedOutputIndices);
248
+ sawTerminal = true;
249
+ for (const frame of syntheticFrames)
250
+ safeEnqueue(frame);
251
+ return;
252
+ }
253
+ throw new Error(`Unexpected OpenAI background response status: ${String(status)}`);
254
+ }
255
+ };
256
+ const resumeOrPoll = async () => {
257
+ let transientErrors = 0;
258
+ let usePolling = false;
259
+ while (!sawTerminal && !closed && !signal.aborted) {
260
+ if (usePolling) {
261
+ await pollUntilTerminal();
262
+ return;
263
+ }
264
+ if (responseId === undefined)
265
+ return;
266
+ const query = lastSequenceNumber === undefined ? 'stream=true' : `stream=true&starting_after=${lastSequenceNumber}`;
267
+ const resumeUrl = `${baseUrl}/${encodeURIComponent(responseId)}?${query}`;
268
+ let resumeResponse;
269
+ try {
270
+ resumeResponse = await fetchImpl(resumeUrl, {
271
+ method: 'GET',
272
+ headers: buildBackgroundControlHeaders(request.headers, 'text/event-stream'),
273
+ signal,
274
+ });
275
+ }
276
+ catch (error) {
277
+ if (signal.aborted || ++transientErrors > maxTransientErrors)
278
+ throw error;
279
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
280
+ continue;
281
+ }
282
+ if (!resumeResponse.ok) {
283
+ const errorText = await resumeResponse.text().catch(() => '');
284
+ if (shouldFallbackToPolling(resumeResponse.status, errorText)) {
285
+ usePolling = true;
286
+ continue;
287
+ }
288
+ if (isRetryableStatus(resumeResponse.status) && ++transientErrors <= maxTransientErrors) {
289
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
290
+ continue;
291
+ }
292
+ throw new Error(`OpenAI background stream resume failed (${resumeResponse.status}): ${errorText || resumeResponse.statusText}`);
293
+ }
294
+ if (resumeResponse.body === null) {
295
+ usePolling = true;
296
+ continue;
297
+ }
298
+ transientErrors = 0;
299
+ try {
300
+ await pumpSseBody(resumeResponse.body, true);
301
+ }
302
+ catch (error) {
303
+ if (signal.aborted || ++transientErrors > maxTransientErrors)
304
+ throw error;
305
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
306
+ }
307
+ }
308
+ };
309
+ try {
310
+ try {
311
+ await pumpSseBody(initialResponse.body, false);
312
+ }
313
+ catch (error) {
314
+ if (signal.aborted || responseId === undefined)
315
+ throw error;
316
+ }
317
+ if (!sawTerminal && !closed && !signal.aborted && responseId !== undefined)
318
+ await resumeOrPoll();
319
+ if (signal.aborted) {
320
+ fireServerCancel();
321
+ safeError(signal.reason ?? new DOMException('Aborted', 'AbortError'));
322
+ return;
323
+ }
324
+ safeClose();
325
+ }
326
+ catch (error) {
327
+ if (signal.aborted)
328
+ fireServerCancel();
329
+ safeError(error);
330
+ }
331
+ finally {
332
+ clearInterval(keepaliveTimer);
333
+ request.signal?.removeEventListener('abort', onRequestAbort);
334
+ }
335
+ },
336
+ cancel() {
337
+ closed = true;
338
+ fireServerCancel();
339
+ internalAbort.abort(new DOMException('Stream cancelled', 'AbortError'));
340
+ void activeReader?.cancel?.().catch(() => { });
341
+ },
342
+ });
343
+ const headers = new Headers(initialResponse.headers);
344
+ headers.delete('content-length');
345
+ return new Response(stream, {
346
+ status: initialResponse.status,
347
+ statusText: initialResponse.statusText,
348
+ headers,
349
+ });
350
+ }
351
+ //# sourceMappingURL=background-stream.js.map
@@ -2,11 +2,13 @@
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
3
  import { zstdCompressSync, zstdDecompressSync } from 'node:zlib';
4
4
  import { isGptModel } from "../contracts/settings.js";
5
+ import { applyBackgroundStreamBody, isOfficialOpenAiResponsesUrl, wrapResilientBackgroundSseResponse, } from "./background-stream.js";
5
6
  import { captureCodexErrors } from "./sse-diagnostics.js";
6
7
  import { applyRequestWireOptions, canRewriteApplyPatchHistory, hasFunctionApplyPatchTool, hasRemoteCompaction, hasWebSearchTool, isNativeCompactionTriggerBody, replaceRemoteCompactions, rewriteCodexResponsesBody, } from "./wire-rewrite.js";
7
8
  const CAPABILITY_CACHE_TTL_MS = 10 * 60_000;
8
9
  const CAPABILITY_CACHE_MAX_ENTRIES = 64;
9
10
  export const CONTEXT_LIMIT_ERROR = /context_length_exceeded|maximum context length|context window|too many tokens/i;
11
+ const REASONING_MODE_ERROR = /reasoning\.mode|reasoning_mode|['"`]mode['"`].*\bpro\b/i;
10
12
  const WEB_SEARCH_ERROR = /web_search|external_web_access/i;
11
13
  const CUSTOM_PATCH_ERROR = /apply_patch|custom_tool|custom\s+tool|grammar|lark/i;
12
14
  const HOSTED_REQUESTS = new AsyncLocalStorage();
@@ -88,7 +90,7 @@ function shouldFallbackResponse(response, errorText) {
88
90
  && response.status !== 422) {
89
91
  return false;
90
92
  }
91
- return !CONTEXT_LIMIT_ERROR.test(errorText);
93
+ return !CONTEXT_LIMIT_ERROR.test(errorText) && !REASONING_MODE_ERROR.test(errorText);
92
94
  }
93
95
  function isAbortError(error, signal) {
94
96
  if (signal.aborted)
@@ -149,9 +151,22 @@ function installGlobalHostedWebSearchPatch() {
149
151
  if (isNativeCompactionTriggerBody(body))
150
152
  return requestAndCapture(input, init);
151
153
  const requestBody = applyRequestWireOptions(body, options);
152
- const baseBody = isGptModel(requestBody.model) && hasRemoteCompaction(requestBody, options.trustedCheckpoints)
153
- ? replaceRemoteCompactions(requestBody, options.trustedCheckpoints)
154
- : requestBody;
154
+ const useBackgroundStream = options.reasoningMode === 'pro'
155
+ && options.backgroundStream === true
156
+ && isOfficialOpenAiResponsesUrl(request.url)
157
+ && requestBody.stream === true
158
+ && requestBody.background !== false;
159
+ const transportBody = useBackgroundStream ? applyBackgroundStreamBody(requestBody) : requestBody;
160
+ const sendResponsesRequest = async (target, requestInit) => {
161
+ const response = await original(target, requestInit);
162
+ const wrapped = useBackgroundStream
163
+ ? wrapResilientBackgroundSseResponse(response, request, original)
164
+ : response;
165
+ return captureCodexErrors(wrapped);
166
+ };
167
+ const baseBody = isGptModel(transportBody.model) && hasRemoteCompaction(transportBody, options.trustedCheckpoints)
168
+ ? replaceRemoteCompactions(transportBody, options.trustedCheckpoints)
169
+ : transportBody;
155
170
  const key = capabilityKey(request.url, baseBody.model);
156
171
  const activeOptions = effectiveWireOptions(key, options);
157
172
  const usesHostedWebSearch = isGptModel(baseBody.model)
@@ -163,16 +178,16 @@ function installGlobalHostedWebSearchPatch() {
163
178
  && canRewriteApplyPatchHistory(baseBody);
164
179
  if (!usesHostedWebSearch && !usesCustomApplyPatch) {
165
180
  return baseBody === body
166
- ? requestAndCapture(input, init)
167
- : requestAndCapture(jsonRequest(request, baseBody));
181
+ ? sendResponsesRequest(input, init)
182
+ : sendResponsesRequest(jsonRequest(request, baseBody));
168
183
  }
169
184
  const hostedBody = rewriteCodexResponsesBody(baseBody, activeOptions);
170
185
  const hostedRequest = jsonRequest(request, hostedBody);
171
186
  const fallbackRequest = baseBody === body ? request.clone() : jsonRequest(request, baseBody);
172
- const sendPlainFallback = () => requestAndCapture(fallbackRequest);
187
+ const sendPlainFallback = () => sendResponsesRequest(fallbackRequest);
173
188
  let response;
174
189
  try {
175
- response = await requestAndCapture(hostedRequest);
190
+ response = await sendResponsesRequest(hostedRequest);
176
191
  }
177
192
  catch (error) {
178
193
  if (isAbortError(error, request.signal))
@@ -193,7 +208,7 @@ function installGlobalHostedWebSearchPatch() {
193
208
  : { ...activeOptions, customApplyPatch: false };
194
209
  recordUnsupportedCapability(key, mentionsWebSearch ? { hostedWebSearch: false } : { customApplyPatch: false });
195
210
  try {
196
- const reducedResponse = await requestAndCapture(jsonRequest(request, rewriteCodexResponsesBody(baseBody, reducedOptions)));
211
+ const reducedResponse = await sendResponsesRequest(jsonRequest(request, rewriteCodexResponsesBody(baseBody, reducedOptions)));
197
212
  if (reducedResponse.ok)
198
213
  return reducedResponse;
199
214
  const secondErrorText = await reducedResponse.clone().text().catch(() => '');
@@ -6,6 +6,10 @@ export type { JsonObject };
6
6
  export interface CodexRequestWireOptions {
7
7
  /** Provider-facing request option preserved by older DSH LLM adapters. */
8
8
  serviceTier?: string;
9
+ /** Optional Responses reasoning mode override (e.g. 'pro' for GPT-5.6/6+). */
10
+ reasoningMode?: 'standard' | 'pro';
11
+ /** Enable background+stream resilient execution on the official OpenAI Responses API. */
12
+ backgroundStream?: boolean;
9
13
  /** Whether local web_search should become the hosted Responses tool. */
10
14
  hostedWebSearch?: boolean;
11
15
  /** Whether apply_patch should use the Responses custom grammar tool. */
@@ -1,5 +1,5 @@
1
1
  /** Pure Responses wire transformations for hosted search, custom `apply_patch`, and compaction items. */
2
- import { isGptModel } from "../contracts/settings.js";
2
+ import { isGptModel, supportsApiProMode } from "../contracts/settings.js";
3
3
  import { APPLY_PATCH_DESCRIPTION, APPLY_PATCH_GRAMMAR } from "../tools/patch.js";
4
4
  import { REMOTE_COMPACTION_OPEN, REMOTE_COMPACTION_CLOSE, decodeRemoteCompactionMarker, extractMarkerBody, } from "./compact-checkpoint.js";
5
5
  export { REMOTE_COMPACTION_OPEN, REMOTE_COMPACTION_CLOSE, decodeRemoteCompactionMarker, extractMarkerBody };
@@ -229,9 +229,35 @@ export function hasRemoteCompaction(body, trustedCheckpoints) {
229
229
  return false;
230
230
  return body.input.some(item => trustedMarkerInInputItem(item, trustedCheckpoints) !== undefined);
231
231
  }
232
+ function withEncryptedReasoningInclude(include) {
233
+ if (!Array.isArray(include))
234
+ return ['reasoning.encrypted_content'];
235
+ return include.includes('reasoning.encrypted_content')
236
+ ? include
237
+ : [...include, 'reasoning.encrypted_content'];
238
+ }
232
239
  export function applyRequestWireOptions(body, options) {
233
- if (options.serviceTier === undefined || !isGptModel(body.model) || body.service_tier !== undefined)
234
- return body;
235
- return { ...body, service_tier: options.serviceTier };
240
+ let next = body;
241
+ if (options.serviceTier !== undefined && isGptModel(next.model) && next.service_tier === undefined) {
242
+ next = { ...next, service_tier: options.serviceTier };
243
+ }
244
+ if (options.reasoningMode === 'pro' && supportsApiProMode(next.model)) {
245
+ const existing = typeof next.reasoning === 'object' && next.reasoning !== null && !Array.isArray(next.reasoning)
246
+ ? next.reasoning
247
+ : undefined;
248
+ if (existing?.mode === undefined) {
249
+ const reasoning = {
250
+ ...existing,
251
+ mode: 'pro',
252
+ ...(existing?.summary === undefined ? { summary: 'auto' } : {}),
253
+ };
254
+ next = {
255
+ ...next,
256
+ reasoning,
257
+ include: withEncryptedReasoningInclude(next.include),
258
+ };
259
+ }
260
+ }
261
+ return next;
236
262
  }
237
263
  //# sourceMappingURL=wire-rewrite.js.map
@@ -0,0 +1,14 @@
1
+ /** Opt-in global `codex_subagent` tool backed by Codex Connect (`openai-codex`) + DSH `spawn`. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import type { CodexSettings } from '../contracts/settings.ts';
4
+ import { CODEX_SUBAGENT_DEFAULT_PRESET, CODEX_SUBAGENT_PRESET_INHERIT, CODEX_SUBAGENT_TOOL_NAME } from '../contracts/ui-contracts.ts';
5
+ import type { CodexSubagentModelCatalog } from '../contracts/ui-contracts.ts';
6
+ export { CODEX_SUBAGENT_DEFAULT_PRESET, CODEX_SUBAGENT_PRESET_INHERIT, CODEX_SUBAGENT_TOOL_NAME, };
7
+ /** Query live `openai-codex` models and advertised reasoning efforts from the Host LLM registry. */
8
+ export declare function readCodexSubagentModels(ctx: Context): Promise<CodexSubagentModelCatalog>;
9
+ /**
10
+ * Mount a reactive global registration controller for `codex_subagent`.
11
+ * Registers immediately when enabled + `spawn` + `openai-codex` are ready, and unregisters on disable.
12
+ */
13
+ export declare function installCodexSubagent(ctx: Context, currentSettings: () => CodexSettings): void;
14
+ //# sourceMappingURL=codex-subagent.d.ts.map