codex-copilot-dx 1.4.3 → 1.4.5

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 (66) hide show
  1. package/README.md +4 -1
  2. package/bin/cli.mjs +5 -4
  3. package/docs/ARCHITECTURE.md +20 -0
  4. package/docs/REFERENCE.md +42 -8
  5. package/package.json +1 -1
  6. package/src/access-settings.mjs +5 -2
  7. package/src/adapter.mjs +9 -1
  8. package/src/antigravity-chat-bridge.mjs +4 -2
  9. package/src/antigravity-handler.mjs +51 -24
  10. package/src/antigravity-images.mjs +3 -2
  11. package/src/antigravity-runtime.mjs +13 -3
  12. package/src/application-configuration.mjs +43 -0
  13. package/src/application-control.mjs +114 -0
  14. package/src/application-evidence.mjs +42 -0
  15. package/src/application-process.mjs +114 -0
  16. package/src/claude-gateway.mjs +30 -17
  17. package/src/cli-command-spec.mjs +7 -4
  18. package/src/cli-management.mjs +37 -4
  19. package/src/client-effort.mjs +28 -0
  20. package/src/client-model-plan.mjs +2 -1
  21. package/src/codex-image-host-launch.mjs +1 -2
  22. package/src/codex-launch-control.mjs +7 -7
  23. package/src/connection-management.mjs +18 -3
  24. package/src/connection-policy.mjs +9 -1
  25. package/src/connection-routing.mjs +8 -2
  26. package/src/connection-runtime.mjs +21 -5
  27. package/src/connection-view.mjs +12 -3
  28. package/src/context-compaction-wire.mjs +7 -6
  29. package/src/context-compaction.mjs +6 -4
  30. package/src/copilot-client.mjs +17 -13
  31. package/src/copilot-responses-compat.mjs +1 -0
  32. package/src/copilot-web.mjs +6 -2
  33. package/src/dashboard/applications.js +83 -0
  34. package/src/dashboard/connections.js +71 -18
  35. package/src/dashboard/console.js +19 -9
  36. package/src/dashboard/gemini.js +8 -5
  37. package/src/dashboard/index.html +17 -0
  38. package/src/dashboard/language.js +45 -0
  39. package/src/dashboard/ui.css +9 -0
  40. package/src/dashboard-api.mjs +6 -1
  41. package/src/dashboard.mjs +1 -0
  42. package/src/gemini-app.mjs +3 -2
  43. package/src/http-transport.mjs +6 -3
  44. package/src/launcher.mjs +6 -5
  45. package/src/native-images.mjs +1 -1
  46. package/src/provider-runtime.mjs +14 -9
  47. package/src/providers/api.mjs +18 -12
  48. package/src/providers/m365.mjs +9 -5
  49. package/src/request-admission.mjs +6 -0
  50. package/src/responses-bridge.mjs +5 -2
  51. package/src/responses-handler.mjs +2 -0
  52. package/src/responses-proxy.mjs +9 -4
  53. package/src/safe-upstream-error.mjs +9 -11
  54. package/src/service-control.mjs +29 -5
  55. package/src/settings-preferences.mjs +3 -3
  56. package/src/source-admission-state.mjs +29 -0
  57. package/src/source-admission.mjs +310 -0
  58. package/src/source-discovery-probe.mjs +35 -0
  59. package/src/source-discovery.mjs +112 -0
  60. package/src/source-response.mjs +134 -0
  61. package/src/source-transport.mjs +19 -0
  62. package/src/stream-contract.mjs +3 -1
  63. package/src/stream-performance.mjs +3 -1
  64. package/src/stream.mjs +6 -4
  65. package/src/upstream-body.mjs +9 -8
  66. package/src/user-settings.mjs +2 -2
@@ -0,0 +1,112 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { execFile } from "node:child_process";
5
+ import { promisify } from "node:util";
6
+ import { fileURLToPath } from "node:url";
7
+ import { readBoundedFile } from "./bounded-file.mjs";
8
+ import { parseCodexToml } from "./config-toml.mjs";
9
+ import { previewSourceImport } from "./source-import.mjs";
10
+
11
+ const execute = promisify(execFile), pending = new Map(), tools = ["cc-switch", "magpie"];
12
+ const failure = () => new Error("ccdx_import_discovery_invalid");
13
+ const result = (tool, state) => ({ format: tool, saved: false, drafts: [], discovery: { tool, state, skipped: 0, truncated: false } });
14
+ const joinEndpoint = (base, protocol) => {
15
+ if (typeof base !== "string") throw failure();
16
+ const value = base.trim().replace(/\/+$/, ""), suffix = { messages: "messages", responses: "responses", chat: "chat/completions" }[protocol];
17
+ if (value.endsWith("/" + suffix)) return value;
18
+ return value + (value.endsWith("/v1") ? "/" : "/v1/") + suffix;
19
+ };
20
+
21
+ // Foreign credentials and executable settings never enter the returned draft.
22
+ export function discoveredProviderConfig(tool, row) {
23
+ if (tool === "magpie") {
24
+ if (row.forgot === true) return null;
25
+ const endpoints = Object.fromEntries(Object.entries({ messages: row.anthropic, responses: row.responses, chat: row.chat })
26
+ .filter(([, base]) => typeof base === "string" && base.trim()).map(([protocol, base]) => [protocol, joinEndpoint(base, protocol)]));
27
+ if (!Object.keys(endpoints).length) return null;
28
+ return { name: row.name, base_url: row.responses || row.chat || row.anthropic, endpoints,
29
+ auth_header: row.authHeader === "x-api-key" ? "x-api-key" : "bearer", models: [] };
30
+ }
31
+ const settings = row.settings, meta = row.meta || {};
32
+ if (!settings || ["codex_oauth", "xai_oauth"].includes(meta.providerType || meta.provider_type)) return null;
33
+ if (row.app_type === "codex") {
34
+ if (typeof settings.config !== "string") return null;
35
+ const config = parseCodexToml(settings.config), provider = config.model_providers?.[config.model_provider];
36
+ const protocol = { responses: "responses", chat: "chat" }[provider?.wire_api];
37
+ if (!protocol || typeof provider.base_url !== "string") return null;
38
+ return { name: row.name, base_url: provider.base_url, endpoints: { [protocol]: joinEndpoint(provider.base_url, protocol) }, auth_header: "bearer", models: [] };
39
+ }
40
+ if (!["claude", "claude-desktop"].includes(row.app_type)) return null;
41
+ const legacyChat = [true, 1, "true", "1"].includes(settings.openrouter_compat_mode);
42
+ const declared = meta.apiFormat ?? settings.api_format ?? (legacyChat ? "openai_chat" : "anthropic");
43
+ const protocol = { anthropic: "messages", openai_chat: "chat", openai_responses: "responses" }[declared];
44
+ const base = settings.env?.ANTHROPIC_BASE_URL;
45
+ if (!protocol || typeof base !== "string") return null;
46
+ const keyField = meta.apiKeyField ?? (Object.hasOwn(settings.env, "ANTHROPIC_AUTH_TOKEN") ? "ANTHROPIC_AUTH_TOKEN"
47
+ : Object.hasOwn(settings.env, "ANTHROPIC_API_KEY") ? "ANTHROPIC_API_KEY" : undefined);
48
+ return { name: row.name, base_url: base, endpoints: { [protocol]: joinEndpoint(base, protocol) },
49
+ auth_header: protocol === "messages" && keyField === "ANTHROPIC_API_KEY" ? "x-api-key" : "bearer", models: [] };
50
+ }
51
+
52
+ export function previewDiscoveredProviders(tool, rows, { truncated = false } = {}) {
53
+ const value = result(tool, "ready"), seen = new Set();value.discovery.truncated = truncated;
54
+ for (const row of rows) {
55
+ try {
56
+ const config = discoveredProviderConfig(tool, row);
57
+ if (!config) { value.discovery.skipped++;continue; }
58
+ const draft = previewSourceImport({ config }).drafts[0];
59
+ const identity = JSON.stringify([row.app_type || "", row.id || "", config.name, config.endpoints]);
60
+ if (seen.has(identity)) continue;seen.add(identity);
61
+ if (value.drafts.length === 16) { value.discovery.truncated = true;continue; }
62
+ if (tool === "magpie") {
63
+ if (row.anthropic && !["x-api-key", "bearer"].includes(row.authHeader)) draft.warnings.push("auth_header_review");
64
+ if (row.keys?.length || row.keyProtocol || row.groups || row.routing) draft.warnings.push("account_routing_omitted");
65
+ }
66
+ draft.number = value.drafts.length + 1;draft.warnings.push("model_protocols_review");value.drafts.push(draft);
67
+ } catch { value.discovery.skipped++; }
68
+ }
69
+ if (!value.drafts.length) value.discovery.state = "empty";
70
+ return value;
71
+ }
72
+
73
+ export async function sourceImportLocation(tool, { home = os.homedir(), platform = process.platform, env = process.env } = {}) {
74
+ if (!tools.includes(tool)) throw failure();
75
+ if (tool === "magpie") return path.join(path.isAbsolute(env.XDG_CONFIG_HOME || "") ? env.XDG_CONFIG_HOME : path.join(home, ".config"), "magpie", "providers.json");
76
+ const data = platform === "win32" ? env.APPDATA || path.join(home, "AppData/Roaming")
77
+ : platform === "darwin" ? path.join(home, "Library/Application Support") : env.XDG_DATA_HOME || path.join(home, ".local/share");
78
+ let directory = path.join(home, ".cc-switch");
79
+ try {
80
+ const config = JSON.parse(await readBoundedFile(path.join(data, "com.ccswitch.desktop/app_paths.json"), { encoding: "utf8", maxBytes: 65536 }));
81
+ let target = config.app_config_dir_override;
82
+ if (typeof target === "string" && (target = target.trim())) {
83
+ if (target === "~") target = home;
84
+ else if (/^~[/\\]/.test(target)) target = path.join(home, target.slice(2));
85
+ if (path.isAbsolute(target) && (await fs.stat(target).catch(() => null))?.isDirectory()) directory = target;
86
+ }
87
+ } catch (error) { if (error.code !== "ENOENT") throw failure(); }
88
+ let file = path.join(directory, "cc-switch.db");
89
+ if (platform === "win32" && directory === path.join(home, ".cc-switch") && env.HOME && path.isAbsolute(env.HOME)
90
+ && !await fs.stat(file).catch(() => null)) file = path.join(env.HOME, ".cc-switch/cc-switch.db");
91
+ return file;
92
+ }
93
+
94
+ export async function discoverSourceImport(tool, options = {}, existing = []) {
95
+ if (!tools.includes(tool)) throw failure();
96
+ let file;try { file = await sourceImportLocation(tool, options); } catch { return result(tool, "unreadable"); }
97
+ const key = tool + "\0" + file;
98
+ if (!pending.has(key)) {
99
+ if (pending.size >= 2) return result(tool, "busy");
100
+ const env = Object.fromEntries(["PATH", "SystemRoot", "WINDIR", "TEMP", "TMP"].filter(key => process.env[key] !== undefined).map(key => [key, process.env[key]]));
101
+ const operation = execute(process.execPath, [fileURLToPath(new URL("./source-discovery-probe.mjs", import.meta.url)), tool, file],
102
+ { env, encoding: "utf8", windowsHide: true, timeout: 5000, maxBuffer: 512 * 1024 }).then(({ stdout }) => JSON.parse(stdout))
103
+ .catch(() => result(tool, "unreadable")).finally(() => pending.delete(key));
104
+ pending.set(key, operation);
105
+ }
106
+ const value = structuredClone(await pending.get(key));
107
+ for (const draft of value.drafts) {
108
+ if (existing.some(source => source.name?.trim().toLowerCase() === draft.config.name.trim().toLowerCase())) draft.warnings.push("name_exists");
109
+ if (existing.some(source => source.base_url === draft.config.base_url)) draft.warnings.push("endpoint_exists");
110
+ }
111
+ return value;
112
+ }
@@ -0,0 +1,134 @@
1
+ // Internal consumers settle source ownership in their existing read/cancel
2
+ // callbacks. No second stream, reader interception or Response facade is needed.
3
+ const responses = new WeakMap(), readers = new WeakMap();
4
+ export const SOURCE_HTTP_CONTEXT = Symbol("source HTTP admission"), SOURCE_HTTP_CLIENT = Symbol("source HTTP client");
5
+
6
+ class SourceResponse {
7
+ constructor(response, lease, signal, bodyObserved, captureLimit, externalObserver, waitTimeoutMs) {
8
+ this.owner = this;this.body = response.body;this.status = response.status;this.headers = response.headers;
9
+ this.lease = lease;this.signal = signal;this.bodyObserved = bodyObserved;this.captureLimit = captureLimit;
10
+ this.externalObserver = externalObserver;
11
+ this.waitTimeoutMs = waitTimeoutMs;
12
+ this.reader = null;this.cancelled = false;this.done = false;this.failed = false;this.accepted = false;
13
+ this.branches = null;this.waiter = null;this.fragments = null;this.bytes = 0;
14
+ if (signal) { this.abort = () => { void cancelBranches(this, this.branches ? [...this.branches] : [this]).catch(() => {}); };signal.addEventListener("abort", this.abort, { once: true }); }
15
+ }
16
+ finish(success) {
17
+ if (this.done) return;this.done = true;this.signal?.removeEventListener("abort", this.abort);
18
+ this.body = null;this.reader = null;this.fragments = null;
19
+ if (this.branches) for (const branch of this.branches) { branch.body = null;branch.reader = null;branch.fragments = null; }
20
+ this.branches = null;this.lease.release(success && !this.failed && !this.signal?.aborted);this.waiter?.resolve();
21
+ }
22
+ observe(branch, value) {
23
+ if (this.done || branch.cancelled) return;
24
+ if (!value.done) {
25
+ if (this.captureLimit && !this.bodyObserved && branch.bytes <= this.captureLimit) {
26
+ branch.bytes += value.value.byteLength;
27
+ if (branch.bytes <= this.captureLimit) (branch.fragments ||= []).push(Buffer.from(value.value));else branch.fragments = null;
28
+ }
29
+ return;
30
+ }
31
+ if (!this.bodyObserved && branch.fragments?.length) {
32
+ try { this.lease.observe(this.status, this.headers, JSON.parse(Buffer.concat(branch.fragments).toString()));this.bodyObserved = true; } catch {}
33
+ }
34
+ this.finish(this.status >= 200 && this.status < 300);
35
+ }
36
+ cancelledBranch(branch) {
37
+ if (this.done) return;
38
+ branch.cancelled = true;branch.fragments = null;
39
+ if (!this.externalObserver && (!this.branches || [...this.branches].every(item => item.cancelled))) this.finish(this.accepted && !this.signal?.aborted);
40
+ }
41
+ }
42
+
43
+ export function trackSourceResponse(response, lease, { signal, bodyObserved = false, captureLimit = 0, externalObserver = false, waitTimeoutMs = 30000 } = {}) {
44
+ const state = new SourceResponse(response, lease, signal, bodyObserved, captureLimit, externalObserver, waitTimeoutMs);responses.set(response, state);
45
+ if (lease.released) state.finish(false);
46
+ else if (signal?.aborted) void cancelSourceResponse(response).catch(() => {});
47
+ return state;
48
+ }
49
+
50
+ export function sourceResponseReader(response, options) {
51
+ const reader = response?.body?.getReader?.(options), branch = responses.get(response);
52
+ if (reader && branch && !branch.owner.done) { branch.body = response.body;branch.reader = reader;readers.set(reader, branch); }
53
+ return reader;
54
+ }
55
+
56
+ export function observeSourceRead(reader, value) {
57
+ const branch = readers.get(reader);
58
+ if (branch?.reader === reader) branch.owner.observe(branch, value);
59
+ }
60
+
61
+ export function failSourceRead(reader) {
62
+ const branch = readers.get(reader);
63
+ if (branch?.reader === reader && !branch.cancelled) branch.owner.finish(false);
64
+ }
65
+
66
+ export function releaseSourceReader(reader) {
67
+ const branch = readers.get(reader);
68
+ if (branch?.reader === reader) branch.reader = null;
69
+ readers.delete(reader);
70
+ reader?.releaseLock();
71
+ }
72
+
73
+ export function cancelSourceReader(reader, reason) {
74
+ const branch = readers.get(reader);
75
+ let pending;try { pending = reader.cancel(reason); } catch (error) { return Promise.reject(error); }
76
+ if (branch?.reader === reader && !branch.owner.done) branch.owner.cancelledBranch(branch);
77
+ void Promise.resolve(pending).catch(() => {});return Promise.resolve();
78
+ }
79
+
80
+ export function cloneSourceResponse(response) {
81
+ const clone = response.clone(), original = responses.get(response);
82
+ if (original && !original.owner.done) {
83
+ original.body = response.body;const owner = original.owner;
84
+ const branch = { owner, body: clone.body, reader: null, cancelled: false, fragments: null, bytes: 0 };
85
+ (owner.branches ||= new Set([owner])).add(branch);responses.set(clone, branch);
86
+ }
87
+ return clone;
88
+ }
89
+
90
+ export function sourceResponseAccepted(response) { const state = responses.get(response)?.owner;if (state) state.accepted = true; }
91
+ export function sourceResponseStreamLimit(response, error) { const state = responses.get(response)?.owner;state?.lease.streamFailure(error, state.headers); }
92
+ export function sourceResponseFailed(response) { const state = responses.get(response)?.owner;if (state) state.failed = true; }
93
+ export function sourceResponseFeedback(response, value) {
94
+ const state = responses.get(response)?.owner;
95
+ if (state && !state.bodyObserved) { state.bodyObserved = true;state.lease.observe(state.status, state.headers, value); }
96
+ }
97
+
98
+ export function cancelSourceResponse(response, reason) {
99
+ const branch = responses.get(response), owner = branch?.owner;
100
+ if (!owner || owner.done) { try { void Promise.resolve(response?.body?.cancel?.(reason)).catch(() => {});return Promise.resolve(); } catch (error) { return Promise.reject(error); } }
101
+ // Cancellation is accepted synchronously by a valid native stream/reader.
102
+ // Its cleanup promise may remain pending (notably a tee branch); it must
103
+ // not retain a source slot after all branches have been cancelled.
104
+ branch.body = response.body;return cancelBranches(owner, [branch], reason);
105
+ }
106
+
107
+ function cancelBranches(owner, branches, reason) {
108
+ const pending = [];
109
+ for (const item of branches) {
110
+ if (item.cancelled) continue;
111
+ try {
112
+ if (item.reader) pending.push(Promise.resolve(cancelSourceReader(item.reader, reason)));
113
+ else if (!item.body?.locked) { pending.push(Promise.resolve(item.body?.cancel(reason)));owner.cancelledBranch(item); }
114
+ } catch (error) { pending.push(Promise.reject(error)); }
115
+ }
116
+ for (const operation of pending) void operation.catch(() => {});
117
+ return Promise.resolve();
118
+ }
119
+
120
+ export function hasSourceReader(reader) { return readers.has(reader); }
121
+
122
+ export function whenSourceReleased(response, { signal, timeoutMs } = {}) {
123
+ const owner = responses.get(response)?.owner;
124
+ if (!owner || owner.done) return Promise.resolve();
125
+ owner.waiter ||= (() => { let resolve;const promise = new Promise(done => { resolve = done; });return { resolve, promise }; })();
126
+ return new Promise((resolve, reject) => {
127
+ let timer;const cleanup = () => { clearTimeout(timer);signal?.removeEventListener("abort", abort); };
128
+ const abort = () => { cleanup();reject(signal.reason); };
129
+ owner.waiter.promise.then(() => { cleanup();resolve(); });
130
+ const budget = Math.min(owner.waitTimeoutMs, timeoutMs ?? Number.POSITIVE_INFINITY);
131
+ timer = setTimeout(() => { cleanup();reject(Object.assign(new Error("The previous source response did not release its slot."), { code: "ccdx_compaction_source_busy", statusCode: 503 })); }, budget);
132
+ signal?.addEventListener("abort", abort, { once: true });if (signal?.aborted) abort();
133
+ });
134
+ }
@@ -0,0 +1,19 @@
1
+ import { SOURCE_HTTP_CONTEXT } from "./source-response.mjs";
2
+ import { currentRequestContext } from "./request-context.mjs";
3
+ import { markUpstreamStarted, markRequestObservation } from "./stream-performance.mjs";
4
+
5
+ const send = input => {
6
+ input.onUpstreamStart?.();if (input.observe) { markUpstreamStarted(input.stream);if (input.evidence) markRequestObservation(input.evidence); }
7
+ return input.send.apply(input.receiver, input.args);
8
+ };
9
+
10
+ // Providers call this after final wire serialization. Queues count the exact
11
+ // retained wire text and the HTTP client reuses it; admission does not serialize.
12
+ export function sourceTransport(options, input) {
13
+ input.onUpstreamStart = options.onUpstreamStart;
14
+ const context = options[SOURCE_HTTP_CONTEXT];
15
+ if (!context || options.countTokens) return send(input);
16
+ return context.scheduler.run(context.descriptor(), send, { args: input, signal: options.signal,
17
+ model: input.model, client: currentRequestContext()?.application || "other", bodyText: input.bodyText,
18
+ sourceBodyManaged: options.sourceBodyManaged === true });
19
+ }
@@ -1,3 +1,5 @@
1
+ import { cancelSourceResponse } from "./source-response.mjs";
2
+
1
3
  const DEFAULT_BLANK_TOOL_ARGUMENT_LIMIT = 20;
2
4
 
3
5
  function streamProtocolError(message, code) {
@@ -49,7 +51,7 @@ export async function requireUpstreamEventStream(response) {
49
51
  }
50
52
 
51
53
  if (!error) return;
52
- await response?.body?.cancel?.().catch(() => {});
54
+ await cancelSourceResponse(response).catch(() => {});
53
55
  throw error;
54
56
  }
55
57
 
@@ -13,7 +13,7 @@ const TERMINAL_OUTCOMES = Object.freeze(["completed", "incomplete", "failed", "c
13
13
  const INCOMPLETE_REASONS = new Set(["max_output_tokens", "max_messages", "content_filter", "steered"]);
14
14
  const TERMINAL_ORIGINS = new Set([
15
15
  "upstream_response", "upstream_event", "chat_completion", "client_validation",
16
- "upstream_http", "transport", "privacy", "client_disconnect", "unclassified",
16
+ "upstream_http", "transport", "privacy", "source_admission", "client_disconnect", "unclassified",
17
17
  ]);
18
18
  const MAX_MODEL_OUTCOME_LABELS = 32;
19
19
  const MAX_RECENT_REQUESTS = 20;
@@ -357,6 +357,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
357
357
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
358
358
  observeContext(values) {
359
359
  if (finished || !values || typeof values !== "object") return;
360
+ if (Number.isSafeInteger(values.source_queue_ms) && values.source_queue_ms >= 0) context.source_queue_ms = values.source_queue_ms;
361
+ if (values.delivery_cancelled === 1) context.delivery_cancelled = 1;
360
362
  if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
361
363
  for (const key of [...Object.keys(context), "compaction", "requested_model", "reasoning_effort_requested", "reasoning_effort_sent", "usage_state", "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
362
364
  const value = values[key];
package/src/stream.mjs CHANGED
@@ -1,6 +1,7 @@
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
+ import { sourceResponseReader, observeSourceRead, failSourceRead, cancelSourceReader, releaseSourceReader } from "./source-response.mjs";
4
5
 
5
6
  const MAX_SSE_BUFFER_BYTES = loadRuntimeConfig().maxSseBufferBytes;
6
7
 
@@ -15,14 +16,15 @@ function appendLineFragment(parts, fragment, currentBytes, maxBufferBytes) {
15
16
  }
16
17
 
17
18
  export async function* webStreamLines(response, { onChunk, maxBufferBytes = MAX_SSE_BUFFER_BYTES } = {}) {
18
- const reader = response.body.getReader();
19
+ const reader = sourceResponseReader(response);
19
20
  const decoder = new TextDecoder();
20
21
  let lineParts = [];
21
22
  let lineBytes = 0;
22
23
  let skipLF = false, bareCR = false;
23
24
  try {
24
25
  while (true) {
25
- const { done, value } = await reader.read();
26
+ let next;try { next = await reader.read(); } catch (error) { failSourceRead(reader);throw error; }
27
+ observeSourceRead(reader, next);const { done, value } = next;
26
28
  if (done) break;
27
29
  onChunk?.(value);
28
30
  const decoded = decoder.decode(value, { stream: true });
@@ -83,7 +85,7 @@ export async function* webStreamLines(response, { onChunk, maxBufferBytes = MAX_
83
85
  yield !bareCR && line.endsWith("\r") ? line.slice(0, -1) : line;
84
86
  }
85
87
  } finally {
86
- await reader.cancel().catch(() => {});
87
- reader.releaseLock();
88
+ await cancelSourceReader(reader).catch(() => {});
89
+ releaseSourceReader(reader);
88
90
  }
89
91
  }
@@ -1,4 +1,5 @@
1
1
  import { httpError } from "./http-errors.mjs";
2
+ import { sourceResponseReader, observeSourceRead, failSourceRead, cancelSourceReader, releaseSourceReader, cancelSourceResponse, hasSourceReader } from "./source-response.mjs";
2
3
 
3
4
  export const MAX_UPSTREAM_ERROR_BODY_BYTES = 1024 * 1024;
4
5
  export const MAX_UPSTREAM_MODEL_CATALOG_BYTES = 8 * 1024 * 1024;
@@ -31,7 +32,7 @@ function unreadableUpstreamBody(label) {
31
32
  }
32
33
 
33
34
  async function cancelResponseBody(response) {
34
- try { await response?.body?.cancel?.(); } catch {}
35
+ try { await cancelSourceResponse(response); } catch {}
35
36
  }
36
37
 
37
38
  function responseAbortError(signal) {
@@ -42,7 +43,7 @@ function responseAbortError(signal) {
42
43
  }
43
44
 
44
45
  export function readResponseChunk(reader, signal) {
45
- if (!signal) return reader.read();
46
+ if (!signal) return hasSourceReader(reader) ? reader.read().then(value => { observeSourceRead(reader, value);return value; }, error => { failSourceRead(reader);throw error; }) : reader.read();
46
47
  if (signal.aborted) return Promise.reject(responseAbortError(signal));
47
48
  return new Promise((resolve, reject) => {
48
49
  let settled = false;
@@ -54,13 +55,13 @@ export function readResponseChunk(reader, signal) {
54
55
  };
55
56
  const onAbort = () => {
56
57
  const error = responseAbortError(signal);
57
- try { Promise.resolve(reader.cancel(error)).catch(() => {}); } catch {}
58
+ try { void cancelSourceReader(reader, error).catch(() => {}); } catch {}
58
59
  finish(reject, error);
59
60
  };
60
61
  signal.addEventListener("abort", onAbort, { once: true });
61
62
  reader.read().then(
62
- (value) => finish(resolve, value),
63
- (error) => finish(reject, error),
63
+ (value) => { observeSourceRead(reader, value);finish(resolve, value); },
64
+ (error) => { failSourceRead(reader);finish(reject, error); },
64
65
  );
65
66
  });
66
67
  }
@@ -96,7 +97,7 @@ export async function readBoundedResponseBuffer(response, {
96
97
  if ((responseContentLength(response) || 0) > 0) throw unreadableUpstreamBody(label);
97
98
  return Buffer.alloc(0);
98
99
  }
99
- const reader = response?.body?.getReader?.();
100
+ const reader = sourceResponseReader(response);
100
101
  if (!reader) throw unreadableUpstreamBody(label);
101
102
  const chunks = [];
102
103
  let total = 0;
@@ -107,7 +108,7 @@ export async function readBoundedResponseBuffer(response, {
107
108
  const chunk = Buffer.from(value);
108
109
  total += chunk.length;
109
110
  if (total > limit) {
110
- await reader.cancel().catch(() => {});
111
+ await cancelSourceReader(reader).catch(() => {});
111
112
  throw upstreamBodyTooLarge(label, limit);
112
113
  }
113
114
  chunks.push(chunk);
@@ -115,7 +116,7 @@ export async function readBoundedResponseBuffer(response, {
115
116
  return Buffer.concat(chunks, total);
116
117
  } finally {
117
118
  try {
118
- reader.releaseLock();
119
+ releaseSourceReader(reader);
119
120
  } catch (error) {
120
121
  if (!signal?.aborted) throw error;
121
122
  }
@@ -23,7 +23,7 @@ const AUTO_REVIEW_REASONING_KEY = "auto_review_reasoning";
23
23
  const TERMINAL_ANIMATION_KEY = "terminal_animation";
24
24
  const RESPONSE_HISTORY_MAX_MIB_KEY = "response_history_max_mib";
25
25
  const DECODED_BODY_LIMIT_MIB_KEY = "decoded_body_limit_mib";
26
- const SERVICE_FLAGS = ["terminal_animation_enabled", "open_webui", "image_enabled", "prediction_enabled", "context_compaction_enabled"];
26
+ const SERVICE_FLAGS = ["terminal_animation_enabled", "open_webui", "image_enabled", "prediction_enabled", "context_compaction_enabled", "codex_auto_launch"];
27
27
  export const DECODED_BODY_LIMIT_MIN_MIB = RUNTIME_DEFAULTS.maxDecodedBodyBytes / MIB;
28
28
  export const DECODED_BODY_LIMIT_MAX_MIB = 512;
29
29
  export { RESPONSE_HISTORY_MAX_MIB, RESPONSE_HISTORY_MIN_MIB };
@@ -138,7 +138,7 @@ export function writeNightlyUpdatePreference(enabled, options = {}) {
138
138
  return enabled;
139
139
  });
140
140
  }
141
- const serviceFlags = settings => Object.fromEntries(SERVICE_FLAGS.map(key => [key, settings[key] !== false]));
141
+ const serviceFlags = settings => Object.fromEntries(SERVICE_FLAGS.map(key => [key, key === "codex_auto_launch" ? settings[key] === true : settings[key] !== false]));
142
142
 
143
143
  // One strict read gives each status update a coherent view; no stale cache.
144
144
  export function serviceSettingsSnapshot(options = {}) {