@shuind/dsh-codex-harness 0.3.1 → 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.
- package/CHANGELOG.md +29 -0
- package/README.md +21 -43
- package/docs/preset-library.md +2 -2
- package/docs/tool-policy.md +1 -1
- package/lib/client.js +1738 -327
- package/lib/compact-command.js +7 -1
- package/lib/compaction.js +7 -1
- package/lib/hybrid-executor.js +23 -12
- package/lib/index.js +1266 -36
- package/lib/preferences.js +21 -2
- package/lib/tool-policy.js +11 -2
- package/lib/typert.js +42 -1
- package/lib/types/client/desktop.d.ts +20 -42
- package/lib/types/client/desktop.js +191 -126
- package/lib/types/client/index.d.ts +104 -28
- package/lib/types/client/index.js +97 -15
- package/lib/types/client/policy-drafts.d.ts +18 -0
- package/lib/types/client/policy-drafts.js +27 -0
- package/lib/types/client/policy-locale.d.ts +80 -20
- package/lib/types/client/policy-locale.js +197 -80
- package/lib/types/client/preset-manager.d.ts +25 -2
- package/lib/types/client/preset-manager.js +89 -5
- package/lib/types/client/preset-requests.d.ts +44 -1
- package/lib/types/client/preset-requests.js +150 -0
- package/lib/types/client/tool-policy.d.ts +7 -2
- package/lib/types/client/tool-policy.js +48 -6
- package/lib/types/contracts/preset-editor-schema.d.ts +35 -0
- package/lib/types/contracts/preset-editor-schema.js +39 -0
- package/lib/types/contracts/settings.d.ts +12 -0
- package/lib/types/contracts/settings.js +10 -1
- package/lib/types/contracts/ui-contracts.d.ts +52 -0
- package/lib/types/contracts/ui-contracts.js +58 -0
- package/lib/types/contracts/update.d.ts +73 -0
- package/lib/types/contracts/update.js +291 -0
- package/lib/types/entries/index.js +20 -2
- package/lib/types/entries/preferences.d.ts +2 -0
- package/lib/types/entries/preferences.js +9 -0
- package/lib/types/hybrid/hybrid-sdk.d.ts +1 -1
- package/lib/types/hybrid/hybrid-sdk.js +27 -13
- package/lib/types/presets/preset-editor.d.ts +13 -1
- package/lib/types/presets/preset-editor.js +24 -1
- package/lib/types/presets/pro-mode-store.d.ts +13 -0
- package/lib/types/presets/pro-mode-store.js +69 -0
- package/lib/types/responses/background-sse-codec.d.ts +23 -0
- package/lib/types/responses/background-sse-codec.js +230 -0
- package/lib/types/responses/background-stream.d.ts +28 -0
- package/lib/types/responses/background-stream.js +351 -0
- package/lib/types/responses/compact-checkpoint.js +3 -10
- package/lib/types/responses/fetch-transport.js +24 -9
- package/lib/types/responses/remote-compact.js +39 -11
- package/lib/types/responses/wire-rewrite.d.ts +4 -0
- package/lib/types/responses/wire-rewrite.js +30 -4
- package/lib/types/tools/codex-subagent.d.ts +14 -0
- package/lib/types/tools/codex-subagent.js +269 -0
- package/lib/types/update/checker.d.ts +14 -0
- package/lib/types/update/checker.js +166 -0
- package/locale/en.json +1 -1
- package/locale/hybrid-executor/en.json +1 -1
- package/locale/hybrid-executor/zh.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +6 -2
- package/src/client/desktop.tsx +370 -153
- package/src/client/index.tsx +122 -22
- package/src/client/policy-drafts.ts +45 -0
- package/src/client/policy-locale.ts +197 -80
- package/src/client/preset-manager.tsx +125 -4
- package/src/client/preset-requests.ts +185 -1
- package/src/client/tool-policy.tsx +63 -9
- package/src/contracts/preset-editor-schema.ts +44 -0
- package/src/contracts/settings.ts +20 -1
- package/src/contracts/ui-contracts.ts +91 -0
- package/src/contracts/update.ts +307 -0
- package/src/entries/index.ts +25 -2
- package/src/entries/preferences.ts +9 -0
- package/src/hybrid/hybrid-sdk.ts +28 -12
- package/src/presets/preset-editor.ts +31 -3
- package/src/presets/pro-mode-store.ts +80 -0
- package/src/responses/background-sse-codec.ts +237 -0
- package/src/responses/background-stream.ts +371 -0
- package/src/responses/compact-checkpoint.ts +2 -8
- package/src/responses/fetch-transport.ts +28 -9
- package/src/responses/remote-compact.ts +41 -11
- package/src/responses/wire-rewrite.ts +34 -3
- package/src/tools/codex-subagent.ts +290 -0
- package/src/update/checker.ts +193 -0
- 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
|
|
@@ -165,16 +165,9 @@ export async function parseCompactResponsePayload(response) {
|
|
|
165
165
|
const output = Array.isArray(body.output) ? body.output : [];
|
|
166
166
|
const compactions = [];
|
|
167
167
|
for (const item of output) {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
if (encrypted.length === 0)
|
|
172
|
-
continue;
|
|
173
|
-
compactions.push({
|
|
174
|
-
type: 'compaction',
|
|
175
|
-
encrypted_content: encrypted,
|
|
176
|
-
...typeof item.id === 'string' && item.id.length > 0 ? { id: item.id } : {},
|
|
177
|
-
});
|
|
168
|
+
const compaction = asCompactionItem(item);
|
|
169
|
+
if (compaction !== undefined)
|
|
170
|
+
compactions.push(compaction);
|
|
178
171
|
}
|
|
179
172
|
return {
|
|
180
173
|
compactions,
|
|
@@ -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
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
?
|
|
167
|
-
:
|
|
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 = () =>
|
|
187
|
+
const sendPlainFallback = () => sendResponsesRequest(fallbackRequest);
|
|
173
188
|
let response;
|
|
174
189
|
try {
|
|
175
|
-
response = await
|
|
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
|
|
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(() => '');
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** OpenAI Responses `/responses/compact` and V2 `/responses` transport with local compaction fallback. */
|
|
2
2
|
import { credentialRef } from '@deepseek-ai/dsh-credentials';
|
|
3
|
+
import { offloadedImageText, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm';
|
|
3
4
|
import { isGptModel, readHostSettings } from "../contracts/settings.js";
|
|
4
5
|
import { collectTrustedCompactionMarkers, encodeRemoteCompactionCheckpoint, parseCompactResponsePayload, retainedUserMessagesFromInput, } from "./compact-checkpoint.js";
|
|
5
6
|
import { capabilityKey, CONTEXT_LIMIT_ERROR, hostedWebSearchStream, isCompactUnsupported, recordUnsupportedCapability, } from "./fetch-transport.js";
|
|
@@ -45,9 +46,36 @@ async function apiHeaders(ctx, profile, isV2Responses) {
|
|
|
45
46
|
}
|
|
46
47
|
return headers;
|
|
47
48
|
}
|
|
48
|
-
|
|
49
|
+
const VALID_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
|
|
50
|
+
function hasValidImageRef(attachment) {
|
|
51
|
+
if (typeof attachment !== 'object' || attachment === null)
|
|
52
|
+
return false;
|
|
53
|
+
const record = attachment;
|
|
54
|
+
return typeof record.attachmentId === 'string' && record.attachmentId.length > 0
|
|
55
|
+
&& typeof record.mediaType === 'string' && VALID_IMAGE_MEDIA_TYPES.has(record.mediaType)
|
|
56
|
+
&& typeof record.width === 'number' && typeof record.height === 'number';
|
|
57
|
+
}
|
|
58
|
+
function formatOffloadedImage(ctx, block) {
|
|
59
|
+
const attachments = ctx.get('attachments');
|
|
60
|
+
const fs = ctx.get('fs');
|
|
61
|
+
const access = typeof attachments?.imageHostPath === 'function' && typeof fs?.processPathFromHostPath === 'function'
|
|
62
|
+
? resolveImageAttachmentAccess(attachments, hostPath => fs.processPathFromHostPath(hostPath), block.attachment)
|
|
63
|
+
: undefined;
|
|
64
|
+
return offloadedImageText(block.attachment, access);
|
|
65
|
+
}
|
|
66
|
+
function textOf(ctx, message) {
|
|
49
67
|
return message.content
|
|
50
|
-
.map(block =>
|
|
68
|
+
.map(block => {
|
|
69
|
+
if (block.type === 'text')
|
|
70
|
+
return block.text;
|
|
71
|
+
if (block.type === 'image') {
|
|
72
|
+
if (block.offloaded !== true || !hasValidImageRef(block.attachment)) {
|
|
73
|
+
throw new Error('Codex remote compaction requires the DSH adapter for image attachments');
|
|
74
|
+
}
|
|
75
|
+
return formatOffloadedImage(ctx, block);
|
|
76
|
+
}
|
|
77
|
+
return '';
|
|
78
|
+
})
|
|
51
79
|
.join('');
|
|
52
80
|
}
|
|
53
81
|
function stripCompactionPrompt(messages) {
|
|
@@ -57,19 +85,19 @@ function stripCompactionPrompt(messages) {
|
|
|
57
85
|
}
|
|
58
86
|
return messages;
|
|
59
87
|
}
|
|
60
|
-
function extractInstructions(options, messages) {
|
|
88
|
+
function extractInstructions(ctx, options, messages) {
|
|
61
89
|
if (options.system !== undefined)
|
|
62
90
|
return options.system;
|
|
63
91
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
64
92
|
const message = messages[index];
|
|
65
93
|
if (message.role !== 'system')
|
|
66
94
|
continue;
|
|
67
|
-
const text = textOf(message);
|
|
95
|
+
const text = textOf(ctx, message);
|
|
68
96
|
return text.length > 0 ? text : undefined;
|
|
69
97
|
}
|
|
70
98
|
return undefined;
|
|
71
99
|
}
|
|
72
|
-
function responsesInput(messages) {
|
|
100
|
+
function responsesInput(ctx, messages) {
|
|
73
101
|
const result = [];
|
|
74
102
|
for (const message of messages) {
|
|
75
103
|
// This compact transport cannot serialize attachment file references losslessly.
|
|
@@ -78,7 +106,7 @@ function responsesInput(messages) {
|
|
|
78
106
|
}
|
|
79
107
|
if (message.role === 'system')
|
|
80
108
|
continue;
|
|
81
|
-
const text = textOf(message);
|
|
109
|
+
const text = textOf(ctx, message);
|
|
82
110
|
if (message.role === 'tool') {
|
|
83
111
|
result.push({ type: 'function_call_output', call_id: message.toolCallId.split('|')[0], output: text });
|
|
84
112
|
continue;
|
|
@@ -122,14 +150,14 @@ function responsesTools(tools) {
|
|
|
122
150
|
parameters: tool.parameters,
|
|
123
151
|
}));
|
|
124
152
|
}
|
|
125
|
-
function compactBody(options, wireOptions, isV2Responses) {
|
|
153
|
+
function compactBody(ctx, options, wireOptions, isV2Responses) {
|
|
126
154
|
const messages = stripCompactionPrompt(options.messages);
|
|
127
|
-
const instructions = extractInstructions(options, messages);
|
|
155
|
+
const instructions = extractInstructions(ctx, options, messages);
|
|
128
156
|
const tools = responsesTools(options.tools);
|
|
129
157
|
const serviceTier = wireOptions.serviceTier ?? serviceTierOf(options);
|
|
130
158
|
const body = {
|
|
131
159
|
model: options.model,
|
|
132
|
-
input: responsesInput(messages),
|
|
160
|
+
input: responsesInput(ctx, messages),
|
|
133
161
|
...instructions !== undefined ? { instructions } : isV2Responses ? { instructions: '' } : {},
|
|
134
162
|
...tools === undefined ? {} : { tools },
|
|
135
163
|
...typeof options.sessionId === 'string' && options.sessionId.length > 0
|
|
@@ -256,7 +284,7 @@ async function remoteCompact(ctx, options, wireOptions = {}) {
|
|
|
256
284
|
...wireOptions,
|
|
257
285
|
trustedCheckpoints: wireOptions.trustedCheckpoints ?? collectTrustedCompactionMarkers(options.messages),
|
|
258
286
|
};
|
|
259
|
-
const initial = compactBody(options, compactWireOptions, isV2Responses);
|
|
287
|
+
const initial = compactBody(ctx, options, compactWireOptions, isV2Responses);
|
|
260
288
|
let preCompactInput = initial.preCompactInput;
|
|
261
289
|
let response = await sendWithRetry(endpoint, headers, initial.body, options.signal);
|
|
262
290
|
if (!response.ok
|
|
@@ -264,7 +292,7 @@ async function remoteCompact(ctx, options, wireOptions = {}) {
|
|
|
264
292
|
&& canRewriteCompactTools(options, wireOptions)) {
|
|
265
293
|
const errorText = await response.clone().text().catch(() => '');
|
|
266
294
|
if (!CONTEXT_LIMIT_ERROR.test(errorText)) {
|
|
267
|
-
const reduced = compactBody(options, {
|
|
295
|
+
const reduced = compactBody(ctx, options, {
|
|
268
296
|
...compactWireOptions,
|
|
269
297
|
hostedWebSearch: false,
|
|
270
298
|
customApplyPatch: false,
|
|
@@ -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
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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
|