codex-copilot-dx 1.3.18 → 1.3.20
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/README.md +1 -0
- package/bin/cli.mjs +22 -2
- package/docs/ARCHITECTURE.md +16 -0
- package/docs/REFERENCE.md +16 -4
- package/package.json +1 -1
- package/src/adapter.mjs +3 -3
- package/src/claude-capability-config.mjs +6 -0
- package/src/claude-gateway.mjs +56 -9
- package/src/client-versions.mjs +139 -0
- package/src/clients/codex-models.mjs +17 -6
- package/src/codex-app-control.mjs +67 -0
- package/src/codex-client-doctor.mjs +3 -1
- package/src/codex-launch-control.mjs +132 -0
- package/src/codex-model-catalog.mjs +33 -10
- package/src/connection-runtime.mjs +11 -3
- package/src/dashboard/console.js +18 -4
- package/src/dashboard/context.js +2 -1
- package/src/dashboard/features.js +61 -12
- package/src/dashboard/index.html +8 -2
- package/src/dashboard/language.js +33 -1
- package/src/dashboard/status.js +5 -1
- package/src/dashboard/tools.js +1 -0
- package/src/doctor.mjs +8 -0
- package/src/http-transport.mjs +1 -1
- package/src/image-control.mjs +11 -24
- package/src/image-host-state.mjs +3 -1
- package/src/local-tools.mjs +6 -3
- package/src/native-images.mjs +12 -7
- package/src/native-prediction-windows.mjs +8 -0
- package/src/observability.mjs +2 -1
- package/src/privacy-stream.mjs +10 -7
- package/src/providers/api-token-count.mjs +12 -2
- package/src/providers/api.mjs +9 -4
- package/src/response-failures.mjs +8 -3
- package/src/responses-proxy.mjs +95 -27
- package/src/safe-upstream-error.mjs +79 -0
- package/src/service-control.mjs +25 -6
- package/src/stream.mjs +42 -5
package/src/responses-proxy.mjs
CHANGED
|
@@ -172,6 +172,7 @@ function createResponseSseTransformer(state) {
|
|
|
172
172
|
let previous1 = -1;
|
|
173
173
|
let previous2 = -1;
|
|
174
174
|
let previous3 = -1;
|
|
175
|
+
let bareCR = false;
|
|
175
176
|
|
|
176
177
|
const ensureCapacity = (required) => {
|
|
177
178
|
if (required > MAX_SSE_BUFFER_BYTES + 4) {
|
|
@@ -198,7 +199,7 @@ function createResponseSseTransformer(state) {
|
|
|
198
199
|
throw httpError(`Upstream SSE buffer exceeds ${MAX_SSE_BUFFER_BYTES} bytes`, 502);
|
|
199
200
|
}
|
|
200
201
|
const chunk = frame.subarray(0, contentLength).toString("utf8");
|
|
201
|
-
const lines = chunk.split(/\r?\n/);
|
|
202
|
+
const lines = bareCR ? chunk.split(/\r\n|\r|\n/) : chunk.split(/\r?\n/);
|
|
202
203
|
const eventName = lines
|
|
203
204
|
.find((line) => line.startsWith("event:"))
|
|
204
205
|
?.slice(6)
|
|
@@ -216,7 +217,8 @@ function createResponseSseTransformer(state) {
|
|
|
216
217
|
wroteData = true;
|
|
217
218
|
return true;
|
|
218
219
|
}).map((line) => line.startsWith("data:") ? `data: ${JSON.stringify(changed)}` : line);
|
|
219
|
-
|
|
220
|
+
const newline = bareCR ? chunk.match(/\r\n|\r|\n/)?.[0] || "\n" : chunk.includes("\r\n") ? "\r\n" : "\n";
|
|
221
|
+
return Buffer.from(rewritten.join(newline)
|
|
220
222
|
+ frame.subarray(contentLength).toString("ascii"));
|
|
221
223
|
};
|
|
222
224
|
|
|
@@ -233,40 +235,97 @@ function createResponseSseTransformer(state) {
|
|
|
233
235
|
return output;
|
|
234
236
|
};
|
|
235
237
|
let segmentStart = 0;
|
|
238
|
+
if (!bareCR) {
|
|
239
|
+
if (previous1 === 0x0d && value.length && value[0] !== 0x0a) bareCR = true;
|
|
240
|
+
for (let at = value.indexOf(0x0d); !bareCR && at >= 0; at = value.indexOf(0x0d, at + 1)) {
|
|
241
|
+
if (at + 1 < value.length && value[at + 1] !== 0x0a) bareCR = true;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (!bareCR) {
|
|
245
|
+
// The common LF/CRLF path searches newline bytes in native code;
|
|
246
|
+
// the three-byte carry keeps delimiters split across reads intact.
|
|
247
|
+
for (let index = value.indexOf(0x0a); index >= 0; index = value.indexOf(0x0a, index + 1)) {
|
|
248
|
+
const available = index - segmentStart;
|
|
249
|
+
const p1 = available >= 1 ? value[index - 1] : segmentStart === 0 ? previous1 : -1;
|
|
250
|
+
const p2 = available >= 2 ? value[index - 2] : segmentStart === 0 ? available === 1 ? previous1 : previous2 : -1;
|
|
251
|
+
const p3 = available >= 3 ? value[index - 3] : segmentStart === 0 ? available === 2 ? previous1 : available === 1 ? previous2 : previous3 : -1;
|
|
252
|
+
let delimiterLength = 0;
|
|
253
|
+
if (p1 === 0x0a) {
|
|
254
|
+
delimiterLength = p2 === 0x0d ? 3 : 2;
|
|
255
|
+
} else if (p1 === 0x0d && p2 === 0x0a) {
|
|
256
|
+
delimiterLength = p3 === 0x0d ? 4 : 3;
|
|
257
|
+
}
|
|
258
|
+
if (delimiterLength) {
|
|
259
|
+
let frame = value.subarray(segmentStart, index + 1);
|
|
260
|
+
if (eventLength > 0) {
|
|
261
|
+
append(frame);
|
|
262
|
+
if (eventLength > SSE_WRITE_BATCH_BYTES) {
|
|
263
|
+
frame = eventBuffer.subarray(0, eventLength);
|
|
264
|
+
eventBuffer = Buffer.allocUnsafe(Math.min(4096, MAX_SSE_BUFFER_BYTES + 4));
|
|
265
|
+
} else frame = Buffer.from(eventBuffer.subarray(0, eventLength));
|
|
266
|
+
}
|
|
267
|
+
eventLength = 0;previous1 = -1;previous2 = -1;previous3 = -1;segmentStart = index + 1;
|
|
268
|
+
const forwarded = inspectEvent(frame, delimiterLength), last = pending.at(-1);
|
|
269
|
+
if (last && last.buffer === forwarded.buffer && last.byteOffset + last.byteLength === forwarded.byteOffset)
|
|
270
|
+
pending[pending.length - 1] = Buffer.from(last.buffer, last.byteOffset, last.byteLength + forwarded.byteLength);
|
|
271
|
+
else pending.push(forwarded);
|
|
272
|
+
pendingBytes += forwarded.byteLength;
|
|
273
|
+
if (state.sawTerminal) return flush();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
for (let index = Math.max(segmentStart, value.byteLength - 3); index < value.byteLength; index++) {
|
|
277
|
+
previous3 = previous2;previous2 = previous1;previous1 = value[index];
|
|
278
|
+
}
|
|
279
|
+
append(value.subarray(segmentStart));
|
|
280
|
+
if (eventLength > MAX_SSE_BUFFER_BYTES + 3) throw httpError(`Upstream SSE buffer exceeds ${MAX_SSE_BUFFER_BYTES} bytes`, 502);
|
|
281
|
+
return pendingBytes > 0 ? flush() : null;
|
|
282
|
+
}
|
|
283
|
+
const forward = (end, delimiterLength) => {
|
|
284
|
+
let frame = value.subarray(segmentStart, end);
|
|
285
|
+
if (eventLength > 0) {
|
|
286
|
+
append(frame);
|
|
287
|
+
// Writes may retain a Buffer after returning; never expose the reusable buffer.
|
|
288
|
+
if (eventLength > SSE_WRITE_BATCH_BYTES) {
|
|
289
|
+
frame = eventBuffer.subarray(0, eventLength);
|
|
290
|
+
eventBuffer = Buffer.allocUnsafe(Math.min(4096, MAX_SSE_BUFFER_BYTES + 4));
|
|
291
|
+
} else {
|
|
292
|
+
frame = Buffer.from(eventBuffer.subarray(0, eventLength));
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
eventLength = 0;
|
|
296
|
+
previous1 = -1;
|
|
297
|
+
previous2 = -1;
|
|
298
|
+
previous3 = -1;
|
|
299
|
+
segmentStart = end;
|
|
300
|
+
const forwarded = inspectEvent(frame, delimiterLength);
|
|
301
|
+
const last = pending.at(-1);
|
|
302
|
+
if (last && last.buffer === forwarded.buffer
|
|
303
|
+
&& last.byteOffset + last.byteLength === forwarded.byteOffset) {
|
|
304
|
+
pending[pending.length - 1] = Buffer.from(last.buffer, last.byteOffset, last.byteLength + forwarded.byteLength);
|
|
305
|
+
} else {
|
|
306
|
+
pending.push(forwarded);
|
|
307
|
+
}
|
|
308
|
+
pendingBytes += forwarded.byteLength;
|
|
309
|
+
};
|
|
236
310
|
for (let index = 0; index < value.byteLength; index += 1) {
|
|
237
311
|
const byte = value[index];
|
|
312
|
+
// A CR after an LF may be the last byte of a blank line. Wait for
|
|
313
|
+
// the next byte so split CRLF frames retain their original bytes.
|
|
314
|
+
if (previous1 === 0x0d && previous2 === 0x0a && byte !== 0x0a) {
|
|
315
|
+
forward(index, previous3 === 0x0d ? 3 : 2);
|
|
316
|
+
if (state.sawTerminal) return flush();
|
|
317
|
+
}
|
|
238
318
|
let delimiterLength = 0;
|
|
239
319
|
if (byte === 0x0a && previous1 === 0x0a) {
|
|
240
320
|
delimiterLength = previous2 === 0x0d ? 3 : 2;
|
|
241
321
|
} else if (byte === 0x0a && previous1 === 0x0d && previous2 === 0x0a) {
|
|
242
322
|
delimiterLength = previous3 === 0x0d ? 4 : 3;
|
|
323
|
+
} else if (byte === 0x0d && previous1 === 0x0d) {
|
|
324
|
+
delimiterLength = 2;
|
|
325
|
+
if (value[index + 1] === 0x0a) { index += 1;delimiterLength += 1; }
|
|
243
326
|
}
|
|
244
327
|
if (delimiterLength) {
|
|
245
|
-
|
|
246
|
-
if (eventLength > 0) {
|
|
247
|
-
append(frame);
|
|
248
|
-
// Writes may retain a Buffer after returning; never expose the reusable buffer.
|
|
249
|
-
if (eventLength > SSE_WRITE_BATCH_BYTES) {
|
|
250
|
-
frame = eventBuffer.subarray(0, eventLength);
|
|
251
|
-
eventBuffer = Buffer.allocUnsafe(Math.min(4096, MAX_SSE_BUFFER_BYTES + 4));
|
|
252
|
-
} else {
|
|
253
|
-
frame = Buffer.from(eventBuffer.subarray(0, eventLength));
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
eventLength = 0;
|
|
257
|
-
previous1 = -1;
|
|
258
|
-
previous2 = -1;
|
|
259
|
-
previous3 = -1;
|
|
260
|
-
segmentStart = index + 1;
|
|
261
|
-
const forwarded = inspectEvent(frame, delimiterLength);
|
|
262
|
-
const last = pending.at(-1);
|
|
263
|
-
if (last && last.buffer === forwarded.buffer
|
|
264
|
-
&& last.byteOffset + last.byteLength === forwarded.byteOffset) {
|
|
265
|
-
pending[pending.length - 1] = Buffer.from(last.buffer, last.byteOffset, last.byteLength + forwarded.byteLength);
|
|
266
|
-
} else {
|
|
267
|
-
pending.push(forwarded);
|
|
268
|
-
}
|
|
269
|
-
pendingBytes += forwarded.byteLength;
|
|
328
|
+
forward(index + 1, delimiterLength);
|
|
270
329
|
if (state.sawTerminal) return flush();
|
|
271
330
|
continue;
|
|
272
331
|
}
|
|
@@ -280,6 +339,14 @@ function createResponseSseTransformer(state) {
|
|
|
280
339
|
}
|
|
281
340
|
return pendingBytes > 0 ? flush() : null;
|
|
282
341
|
},
|
|
342
|
+
finish() {
|
|
343
|
+
if (previous1 !== 0x0d || previous2 !== 0x0a || !eventLength) return null;
|
|
344
|
+
bareCR = true;
|
|
345
|
+
const delimiterLength = previous3 === 0x0d ? 3 : 2;
|
|
346
|
+
const frame = Buffer.from(eventBuffer.subarray(0, eventLength));
|
|
347
|
+
eventLength = 0;previous1 = -1;previous2 = -1;previous3 = -1;
|
|
348
|
+
return inspectEvent(frame, delimiterLength);
|
|
349
|
+
},
|
|
283
350
|
};
|
|
284
351
|
}
|
|
285
352
|
|
|
@@ -452,6 +519,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
452
519
|
while (true) {
|
|
453
520
|
const { done, value } = await reader.read();
|
|
454
521
|
if (done) {
|
|
522
|
+
if (!await forwardFrame(transformer.finish())) return { successful: false, compacted: false };
|
|
455
523
|
if (!streamState.sawTerminal) throw incompleteUpstreamStream("a terminal Responses event");
|
|
456
524
|
break;
|
|
457
525
|
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Only fixed, documented-shaped codes leave this module; vendor messages and
|
|
2
|
+
// request data are never returned or logged.
|
|
3
|
+
const reasons = new Map([
|
|
4
|
+
["credit_balance_exhausted", { statuses: [429], message: "The source account has no remaining credits." }],
|
|
5
|
+
["insufficient_quota", { statuses: [429], message: "The source account has insufficient quota." }],
|
|
6
|
+
["quota_exceeded", { statuses: [429], message: "The source account has exceeded its quota." }],
|
|
7
|
+
["rate_limit_exceeded", { statuses: [429], message: "The source request rate limit was reached." }],
|
|
8
|
+
["rate_limit_error", { statuses: [429], message: "The source request rate limit was reached." }],
|
|
9
|
+
["context_length_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
|
|
10
|
+
["context_window_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
|
|
11
|
+
["content_policy_violation", { statuses: [400, 403, 422], message: "The source rejected the request under its content policy." }],
|
|
12
|
+
]);
|
|
13
|
+
const MAX_ACTIVE_READS = 4;
|
|
14
|
+
let activeReads = 0;
|
|
15
|
+
|
|
16
|
+
function cancelBody(body) {
|
|
17
|
+
try { void Promise.resolve(body?.cancel()).catch(() => {}); } catch {}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function safeUpstreamReason(code, status) {
|
|
21
|
+
const reason = typeof code === "string" ? reasons.get(code) : null;
|
|
22
|
+
return reason?.statuses.includes(status) ? { code, message: reason.message } : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readChunk(reader, signal) {
|
|
26
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
let settled = false;
|
|
29
|
+
const finish = (fn, value) => { if (settled) return;settled = true;signal.removeEventListener("abort", onAbort);fn(value); };
|
|
30
|
+
const onAbort = () => finish(reject, signal.reason);
|
|
31
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
32
|
+
reader.read().then(value => finish(resolve, value), error => finish(reject, error));
|
|
33
|
+
if (signal.aborted) onAbort();
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Failure responses only. A stalled body or a stalled cancellation cannot delay
|
|
38
|
+
// the caller beyond the budget. The original request's cancellation wins.
|
|
39
|
+
export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024 } = {}) {
|
|
40
|
+
if (signal?.aborted) {
|
|
41
|
+
cancelBody(response?.body);
|
|
42
|
+
signal.throwIfAborted();
|
|
43
|
+
}
|
|
44
|
+
if (!response?.body) return null;
|
|
45
|
+
if (activeReads >= MAX_ACTIVE_READS) { cancelBody(response.body);return null; }
|
|
46
|
+
activeReads++;
|
|
47
|
+
const deadline = performance.now() + timeoutMs;
|
|
48
|
+
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
49
|
+
const readSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
50
|
+
let reader, finished = false;
|
|
51
|
+
try {
|
|
52
|
+
const length = Number(response.headers?.get?.("content-length"));
|
|
53
|
+
if (Number.isFinite(length) && length > maxBytes) return null;
|
|
54
|
+
reader = response.body.getReader();const chunks = [];let bytes = 0;
|
|
55
|
+
while (true) {
|
|
56
|
+
if (performance.now() >= deadline) controller.abort();
|
|
57
|
+
const { done, value } = await readChunk(reader, readSignal);
|
|
58
|
+
if (done) { finished = true;break; }
|
|
59
|
+
if (Number.isFinite(value?.byteLength) && bytes + value.byteLength > maxBytes) return null;
|
|
60
|
+
const chunk = Buffer.from(value);bytes += chunk.length;
|
|
61
|
+
if (bytes > maxBytes) return null;
|
|
62
|
+
chunks.push(chunk);
|
|
63
|
+
}
|
|
64
|
+
let value;try { value = JSON.parse(Buffer.concat(chunks, bytes).toString("utf8")); } catch { return null; }
|
|
65
|
+
const error = value?.error;
|
|
66
|
+
if (!error || typeof error !== "object" || Array.isArray(error)) return null;
|
|
67
|
+
return safeUpstreamReason(error.code, response.status) || safeUpstreamReason(error.type, response.status);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (signal?.aborted) signal.throwIfAborted();
|
|
70
|
+
return null;
|
|
71
|
+
} finally {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
if (!finished) {
|
|
74
|
+
try { void Promise.resolve(reader ? reader.cancel() : response.body.cancel()).catch(() => {}); } catch {}
|
|
75
|
+
}
|
|
76
|
+
try { reader?.releaseLock(); } catch {}
|
|
77
|
+
activeReads--;
|
|
78
|
+
}
|
|
79
|
+
}
|
package/src/service-control.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createImageHostState } from "./image-host-state.mjs";
|
|
2
2
|
import { controlImage } from "./image-control.mjs";
|
|
3
|
+
import { controlCodexLaunch } from "./codex-launch-control.mjs";
|
|
3
4
|
import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
|
|
4
5
|
writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
|
|
5
6
|
nightlyUpdatePreference, writeNightlyUpdatePreference, decodedBodyLimitPreference, writeDecodedBodyLimitMib } from "./user-settings.mjs";
|
|
@@ -12,7 +13,8 @@ import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
|
|
|
12
13
|
|
|
13
14
|
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
14
15
|
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
15
|
-
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage,
|
|
16
|
+
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage, codexLaunchControl = controlCodexLaunch,
|
|
17
|
+
clientVersions,
|
|
16
18
|
adapterPort = 2026, adapterHost = "127.0.0.1",
|
|
17
19
|
readImages = () => imageSetupSummary({ env, home }).configured, readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
18
20
|
const options = { env, home };
|
|
@@ -40,23 +42,26 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
40
42
|
prediction_enabled: { value: prediction?.active === true, state: !predictionConfigured ? "needs_setup"
|
|
41
43
|
: prediction?.environment?.status === "needs_app_relaunch" ? "needs_app_relaunch" : prediction?.bridge !== "running" ? "needs_service_restart" : "next_config_request", configured: predictionConfigured },
|
|
42
44
|
}, history: { ...historyLimit, ...cacheRuntimeSnapshot().response_history },
|
|
43
|
-
providers: providerRuntime?.snapshot() || null, terminal: terminal?.snapshot?.() || null };
|
|
45
|
+
providers: providerRuntime?.snapshot() || null, terminal: terminal?.snapshot?.() || null, client_versions: featureSnapshot(() => clientVersions?.snapshot?.() || null) };
|
|
44
46
|
}
|
|
45
47
|
async function apply(input) {
|
|
46
48
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
47
49
|
const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
|
|
48
50
|
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
49
|
-
prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence"],
|
|
51
|
+
prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence", "confirmed"],
|
|
52
|
+
codex_app: ["action", "operation", "intent", "confirmed"],
|
|
50
53
|
update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
|
|
51
54
|
preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
|
|
52
55
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
53
56
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
54
57
|
lastOperation = null;
|
|
55
|
-
if (input.action === "
|
|
58
|
+
if (input.action === "codex_app") {
|
|
59
|
+
lastOperation = { feature: "codex_app", result: await codexLaunchControl(input.operation, { ...options, host: adapterHost, port: adapterPort,
|
|
60
|
+
integration: clientIntegration, state: imageHostState, intent: input.intent, confirmed: input.confirmed, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
61
|
+
} else if (input.action === "prediction") {
|
|
56
62
|
lastOperation = { feature: "prediction", result: await predictionControl(input.operation, { ...options, integration: clientIntegration }) };
|
|
57
63
|
} else if (input.action === "image") {
|
|
58
|
-
if (input.operation
|
|
59
|
-
else if (["check", "repair", "open"].includes(input.operation)) lastOperation = { feature: "image", result: await imageHostControl(input.operation, { ...options, host: adapterHost, port: adapterPort, integration: clientIntegration, state: imageHostState, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
64
|
+
if (["check", "repair", "open", "focus", "restart"].includes(input.operation)) lastOperation = { feature: "image", result: await imageHostControl(input.operation, { ...options, host: adapterHost, port: adapterPort, integration: clientIntegration, state: imageHostState, confirmed: input.confirmed, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
60
65
|
else if (["pause", "resume"].includes(input.operation)) writeServicePreference("image_enabled", input.operation === "resume", options);
|
|
61
66
|
else lastOperation = { feature: "image", result: await imageControl(input, { ...options, providerRuntime, adapterPort, adapterHost }) };
|
|
62
67
|
} else if (input.action === "update") {
|
|
@@ -108,6 +113,20 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
108
113
|
return snapshot();
|
|
109
114
|
}
|
|
110
115
|
return { snapshot, busy: () => pending > 0, action(input) {
|
|
116
|
+
if (input?.action === "client_versions") {
|
|
117
|
+
if (Object.keys(input).some(key => key !== "action")) return Promise.reject(new Error("Unknown setting action or field"));
|
|
118
|
+
if (clientVersions?.refresh) void Promise.resolve().then(() => clientVersions.refresh()).catch(() => {});
|
|
119
|
+
return Promise.resolve({ source: "client_versions", scheduled: Boolean(clientVersions) });
|
|
120
|
+
}
|
|
121
|
+
// Image-host evidence must not wait behind a user-initiated App restart:
|
|
122
|
+
// the host sends it with a short deadline as the new App starts.
|
|
123
|
+
if (input?.action === "image" && input.operation === "report") {
|
|
124
|
+
try {
|
|
125
|
+
if (Object.keys(input).some(key => !["action", "operation", "evidence"].includes(key))) throw new Error("Unknown setting action or field");
|
|
126
|
+
imageHostState.report(input.evidence);terminal?.image?.(imageHostState.snapshot());
|
|
127
|
+
return Promise.resolve(snapshot());
|
|
128
|
+
} catch (error) { return Promise.reject(error); }
|
|
129
|
+
}
|
|
111
130
|
const counted = input?.action !== "update";if (counted) pending++;
|
|
112
131
|
const operation = serial.then(() => apply(input)).finally(() => { if (counted) pending--; });serial = operation.catch(() => {});return operation;
|
|
113
132
|
} };
|
package/src/stream.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Yield fetch Response body lines while preserving SSE semantics for callers.
|
|
2
|
-
//
|
|
2
|
+
// Handle LF, CRLF and CR endings, and release the reader if iteration stops early.
|
|
3
3
|
import { loadRuntimeConfig } from "./runtime-config.mjs";
|
|
4
4
|
|
|
5
5
|
const MAX_SSE_BUFFER_BYTES = loadRuntimeConfig().maxSseBufferBytes;
|
|
@@ -19,6 +19,7 @@ export async function* webStreamLines(response, { onChunk, maxBufferBytes = MAX_
|
|
|
19
19
|
const decoder = new TextDecoder();
|
|
20
20
|
let lineParts = [];
|
|
21
21
|
let lineBytes = 0;
|
|
22
|
+
let skipLF = false, bareCR = false;
|
|
22
23
|
try {
|
|
23
24
|
while (true) {
|
|
24
25
|
const { done, value } = await reader.read();
|
|
@@ -26,24 +27,60 @@ export async function* webStreamLines(response, { onChunk, maxBufferBytes = MAX_
|
|
|
26
27
|
onChunk?.(value);
|
|
27
28
|
const decoded = decoder.decode(value, { stream: true });
|
|
28
29
|
let start = 0;
|
|
30
|
+
if (!bareCR && decoded.length) {
|
|
31
|
+
const tailCR = lineParts.at(-1)?.endsWith("\r") === true;
|
|
32
|
+
if (tailCR && decoded[0] !== "\n") {
|
|
33
|
+
bareCR = true;
|
|
34
|
+
lineParts[lineParts.length - 1] = lineParts.at(-1).slice(0, -1);lineBytes--;
|
|
35
|
+
yield lineParts.length > 1 ? lineParts.join("") : lineParts[0];
|
|
36
|
+
lineParts = [];lineBytes = 0;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (!bareCR) {
|
|
40
|
+
let nextCR = decoded.indexOf("\r", start);
|
|
41
|
+
while (start < decoded.length) {
|
|
42
|
+
const newline = decoded.indexOf("\n", start), end = newline < 0 ? decoded.length : newline;
|
|
43
|
+
if (nextCR >= 0 && nextCR < end - 1) { bareCR = true;break; }
|
|
44
|
+
const part = decoded.slice(start, end);
|
|
45
|
+
if (newline < 0) { lineBytes = appendLineFragment(lineParts, part, lineBytes, maxBufferBytes);break; }
|
|
46
|
+
let line;
|
|
47
|
+
if (!lineParts.length) {
|
|
48
|
+
if (Buffer.byteLength(part) > maxBufferBytes) throw new Error(`Upstream SSE buffer exceeds ${maxBufferBytes} bytes`);
|
|
49
|
+
line = part;
|
|
50
|
+
} else {
|
|
51
|
+
lineBytes = appendLineFragment(lineParts, part, lineBytes, maxBufferBytes);
|
|
52
|
+
line = lineParts.length > 1 ? lineParts.join("") : lineParts[0];
|
|
53
|
+
}
|
|
54
|
+
lineParts = [];lineBytes = 0;start = newline + 1;
|
|
55
|
+
if (nextCR >= 0 && nextCR === end - 1) nextCR = decoded.indexOf("\r", start);
|
|
56
|
+
yield line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
57
|
+
}
|
|
58
|
+
if (!bareCR) continue;
|
|
59
|
+
}
|
|
60
|
+
if (skipLF && decoded.length) { if (decoded[0] === "\n") start = 1;skipLF = false; }
|
|
29
61
|
while (start < decoded.length) {
|
|
30
|
-
const
|
|
31
|
-
|
|
62
|
+
const lf = decoded.indexOf("\n", start), cr = decoded.indexOf("\r", start);
|
|
63
|
+
const newline = lf < 0 ? cr : cr < 0 ? lf : Math.min(lf, cr);
|
|
64
|
+
if (newline < 0) {
|
|
32
65
|
lineBytes = appendLineFragment(lineParts, decoded.slice(start), lineBytes, maxBufferBytes);
|
|
33
66
|
break;
|
|
34
67
|
}
|
|
35
68
|
lineBytes = appendLineFragment(lineParts, decoded.slice(start, newline), lineBytes, maxBufferBytes);
|
|
36
69
|
const line = lineParts.length > 1 ? lineParts.join("") : (lineParts[0] || "");
|
|
37
|
-
yield line
|
|
70
|
+
yield line;
|
|
38
71
|
lineParts = [];
|
|
39
72
|
lineBytes = 0;
|
|
40
73
|
start = newline + 1;
|
|
74
|
+
if (decoded[newline] === "\r") {
|
|
75
|
+
if (start === decoded.length) skipLF = true;
|
|
76
|
+
else if (decoded[start] === "\n") start++;
|
|
77
|
+
}
|
|
41
78
|
}
|
|
42
79
|
}
|
|
43
80
|
lineBytes = appendLineFragment(lineParts, decoder.decode(), lineBytes, maxBufferBytes);
|
|
44
81
|
if (lineParts.length > 0) {
|
|
45
82
|
const line = lineParts.length > 1 ? lineParts.join("") : lineParts[0];
|
|
46
|
-
yield line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
83
|
+
yield !bareCR && line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
47
84
|
}
|
|
48
85
|
} finally {
|
|
49
86
|
await reader.cancel().catch(() => {});
|