codex-copilot-dx 1.4.4 → 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 (64) hide show
  1. package/README.md +2 -1
  2. package/bin/cli.mjs +5 -4
  3. package/docs/ARCHITECTURE.md +16 -0
  4. package/docs/REFERENCE.md +34 -8
  5. package/package.json +1 -1
  6. package/src/access-settings.mjs +3 -1
  7. package/src/adapter.mjs +9 -1
  8. package/src/antigravity-chat-bridge.mjs +4 -2
  9. package/src/antigravity-handler.mjs +28 -16
  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 +24 -15
  17. package/src/cli-command-spec.mjs +7 -4
  18. package/src/cli-management.mjs +27 -2
  19. package/src/codex-image-host-launch.mjs +1 -2
  20. package/src/codex-launch-control.mjs +7 -7
  21. package/src/connection-management.mjs +18 -3
  22. package/src/connection-policy.mjs +3 -1
  23. package/src/connection-routing.mjs +7 -2
  24. package/src/connection-runtime.mjs +21 -5
  25. package/src/connection-view.mjs +9 -3
  26. package/src/context-compaction-wire.mjs +7 -6
  27. package/src/context-compaction.mjs +6 -4
  28. package/src/copilot-client.mjs +17 -13
  29. package/src/copilot-responses-compat.mjs +1 -0
  30. package/src/copilot-web.mjs +6 -2
  31. package/src/dashboard/applications.js +83 -0
  32. package/src/dashboard/connections.js +52 -14
  33. package/src/dashboard/console.js +19 -9
  34. package/src/dashboard/gemini.js +8 -5
  35. package/src/dashboard/index.html +16 -0
  36. package/src/dashboard/language.js +41 -0
  37. package/src/dashboard/ui.css +9 -0
  38. package/src/dashboard-api.mjs +6 -1
  39. package/src/dashboard.mjs +1 -0
  40. package/src/gemini-app.mjs +3 -2
  41. package/src/http-transport.mjs +5 -2
  42. package/src/launcher.mjs +6 -5
  43. package/src/native-images.mjs +1 -1
  44. package/src/provider-runtime.mjs +14 -9
  45. package/src/providers/api.mjs +18 -12
  46. package/src/providers/m365.mjs +9 -5
  47. package/src/request-admission.mjs +6 -0
  48. package/src/responses-bridge.mjs +5 -2
  49. package/src/responses-handler.mjs +2 -0
  50. package/src/responses-proxy.mjs +9 -4
  51. package/src/safe-upstream-error.mjs +9 -11
  52. package/src/service-control.mjs +29 -5
  53. package/src/settings-preferences.mjs +3 -3
  54. package/src/source-admission-state.mjs +29 -0
  55. package/src/source-admission.mjs +310 -0
  56. package/src/source-discovery-probe.mjs +35 -0
  57. package/src/source-discovery.mjs +112 -0
  58. package/src/source-response.mjs +134 -0
  59. package/src/source-transport.mjs +19 -0
  60. package/src/stream-contract.mjs +3 -1
  61. package/src/stream-performance.mjs +3 -1
  62. package/src/stream.mjs +6 -4
  63. package/src/upstream-body.mjs +9 -8
  64. package/src/user-settings.mjs +2 -2
@@ -0,0 +1,310 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isDisturbed } from "node:stream";
3
+ import { currentRequestContext } from "./request-context.mjs";
4
+ import { readSafeUpstreamReason } from "./safe-upstream-error.mjs";
5
+ import { trackSourceResponse, sourceResponseFailed, sourceResponseStreamLimit, SOURCE_HTTP_CONTEXT, SOURCE_HTTP_CLIENT } from "./source-response.mjs";
6
+
7
+ const MAX_LIMIT = 128;
8
+ const MAX_QUEUE_BYTES = 8 * 1024 * 1024;
9
+ const MAX_ERROR_BYTES = 4096;
10
+ const BODY_METHODS = new Set(["arrayBuffer", "blob", "bytes", "formData", "json", "text", "clone"]);
11
+ const immediate = value => value;
12
+ const abortError = signal => signal?.reason || Object.assign(new Error("Request cancelled"), { name: "AbortError" });
13
+ const failure = (code, message, retryAfterMs = 1000, statusCode = 503) => Object.assign(new Error(message), { code, statusCode, retryAfterMs,
14
+ sourceQueue: true, origin: "source_admission", jsonBody: { type: "error", error: { type: statusCode === 429 ? "rate_limit_error" : "api_error", code, message } } });
15
+ const fingerprint = value => createHash("sha256").update(value).digest("hex");
16
+ const validLimit = value => value === null || Number.isSafeInteger(value) && value >= 1 && value <= MAX_LIMIT;
17
+ export const SOURCE_ADMISSION = Symbol("source admission");
18
+ export const SOURCE_LIMIT_EVIDENCE = Symbol("source limit evidence");
19
+ const SOURCE_STREAM_LIMIT = Symbol("source stream limit");
20
+ export function observeSourceStreamFailure(response, error) {
21
+ sourceResponseFailed(response);
22
+ const code = error?.details?.error_code || error?.upstream_code || error?.code || error?.type;
23
+ if (["rate_limit_error", "rate_limit_exceeded", "ramp_limit_exceeded", "concurrency_limit", "concurrency_limit_exceeded", "too_many_concurrent_requests",
24
+ "insufficient_quota", "credit_balance_exhausted", "quota_exceeded", "model_quota_exceeded", "enforced_spend_limit_reached"].includes(code)) {
25
+ if (response?.[SOURCE_STREAM_LIMIT]) response[SOURCE_STREAM_LIMIT](error);
26
+ else sourceResponseStreamLimit(response, error);
27
+ }
28
+ }
29
+ export function admittedSource(source, scheduler) {
30
+ return source?.client && scheduler ? { ...source, client: scheduler.wrap(source.client, () => ({ source: source.id, account: source.profileId() })) } : source;
31
+ }
32
+
33
+ export function sourceLimitFeedback(status, headers, body, now = Date.now()) {
34
+ if (status !== 429) return null;
35
+ const retry = headers?.get?.("retry-after");
36
+ let delay = /^\d{1,8}$/.test(retry || "") ? Number(retry) * 1000 : Math.max(0, Date.parse(retry) - now);
37
+ if (!Number.isFinite(delay)) delay = 0;
38
+ const error = body?.error;
39
+ const code = String(error?.details?.error_code || error?.upstream_code || error?.code || error?.type || "");
40
+ const message = typeof error?.message === "string" ? error.message.slice(0, MAX_ERROR_BYTES) : "";
41
+ const modelScoped = error?.details?.scope === "model" || error?.param === "model" || /^model_.*quota/.test(code);
42
+ if (/insufficient_quota|credit_balance_exhausted|quota_exceeded|quota_exhausted|enforced_spend_limit_reached/.test(code)
43
+ || /\b(?:individual quota reached|exhausted your capacity on this model)\b/i.test(message)) {
44
+ const reset = /\b(?:quota will reset after|resets in)\s+((?:\d+h)?(?:\d+m)?(?:\d+(?:\.\d+)?s)?)/i.exec(message)?.[1];
45
+ if (reset) {
46
+ const duration = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?$/.exec(reset);
47
+ if (duration) delay = Math.max(delay, (Number(duration[1] || 0) * 3600 + Number(duration[2] || 0) * 60 + Number(duration[3] || 0)) * 1000);
48
+ }
49
+ const accountQuota = /insufficient_quota|credit_balance_exhausted|enforced_spend_limit_reached/.test(code)
50
+ || ["source", "account", "organization", "project"].includes(error?.details?.scope);
51
+ return { kind: "quota", scope: modelScoped || /on this model/i.test(message) || !accountQuota ? "model" : "source", delay: delay || 300000 };
52
+ }
53
+ if (/concurr|parallel_requests/.test(code) || /\b(?:concurrent requests|concurrency limit|too many parallel)\b/i.test(message)) {
54
+ const limit = error?.limit;
55
+ return { kind: "concurrency", scope: modelScoped ? "model" : "source", delay: delay || 1000,
56
+ ...(Number.isSafeInteger(limit) && limit >= 1 && limit <= MAX_LIMIT ? { limit } : {}) };
57
+ }
58
+ const knownRate = /rate_limit|ramp_limit/.test(code);
59
+ const sourceScoped = ["source", "account", "organization", "project"].includes(error?.details?.scope);
60
+ return { kind: knownRate ? "rate" : "unknown", scope: sourceScoped ? "source" : "model", delay: delay || 1000 };
61
+ }
62
+
63
+ // Request-body reservations and source slots have different owners. A source
64
+ // slot ends when its actual upstream body ends/cancels, never at its headers.
65
+ export function createSourceAdmission({ now = Date.now, initialLimit = MAX_LIMIT, maxQueued = 16,
66
+ maxQueuedBytes = MAX_QUEUE_BYTES, waitTimeoutMs = 30000, stableMs = 60000, onStable = () => {}, learned = {} } = {}) {
67
+ const groups = new Map(), limits = new Map(), clients = new WeakMap();
68
+ let closed = false, queuedBytes = 0;
69
+ const groupFor = ({ source, account = source }) => {
70
+ const identity = source + "\0" + account;
71
+ let group = groups.get(identity);
72
+ if (!group) {
73
+ if (groups.size >= 64) {
74
+ const idle = [...groups].find(([, value]) => !value.active && !value.queue.length);
75
+ if (!idle) throw failure("ccdx_source_capacity", "Source scheduler is busy. Retry shortly.");
76
+ clearTimeout(idle[1].timer);groups.delete(idle[0]);
77
+ }
78
+ const key = fingerprint(identity), saved = learned[key], restored = validLimit(saved?.limit) && saved?.limit !== null && now() >= saved.at && now() - saved.at < 86400000;
79
+ group = { source, key, limit: restored ? saved.limit : initialLimit, active: 0, queue: [], models: new Map(), lastClient: null,
80
+ epoch: 0, stableAt: now(), successes: 0, readyToGrow: false, lastStableNotice: now(), pausedUntil: 0, reason: null, timer: null, completed: 0, rejected: 0 };
81
+ groups.set(identity, group);
82
+ }
83
+ return group;
84
+ };
85
+ const capacity = group => Math.min(group.limit, limits.get(group.source) || MAX_LIMIT);
86
+ const modelState = (group, model) => {
87
+ if (!group.models.has(model)) {
88
+ if (group.models.size >= 128) {
89
+ const idle = [...group.models].find(([id, value]) => !value.active && value.until <= now() && !group.queue.some(entry => entry.model === id));
90
+ if (!idle) return null;
91
+ group.models.delete(idle[0]);
92
+ }
93
+ group.models.set(model, { active: 0, limit: MAX_LIMIT, maximum: MAX_LIMIT, maximumUntil: 0, until: 0, reason: null, epoch: 0, successes: 0, stableAt: now() });
94
+ }
95
+ return group.models.get(model);
96
+ };
97
+ const readyAt = (group, entry) => Math.max(group.pausedUntil, group.models.get(entry.model)?.until || 0);
98
+ const fits = (group, entry) => group.active < capacity(group)
99
+ && (group.models.get(entry.model)?.active || 0) < (group.models.get(entry.model)?.limit || MAX_LIMIT)
100
+ && readyAt(group, entry) <= now();
101
+ function arm(group) {
102
+ clearTimeout(group.timer);group.timer = null;
103
+ if (!group.queue.length) return;
104
+ const times = group.queue.map(entry => readyAt(group, entry)).filter(at => at > now());
105
+ if (times.length) { group.timer = setTimeout(() => drain(group), Math.max(1, Math.min(...times) - now()));group.timer.unref?.(); }
106
+ }
107
+ function drain(group) {
108
+ if (closed) return;
109
+ if (!group.queue.length) { if (group.timer) { clearTimeout(group.timer);group.timer = null; }return; }
110
+ while (group.queue.length && group.active < capacity(group)) {
111
+ let index = group.queue.findIndex(entry => entry.client !== group.lastClient && fits(group, entry));
112
+ if (index < 0) index = group.queue.findIndex(entry => fits(group, entry));
113
+ if (index < 0) break;
114
+ const [entry] = group.queue.splice(index, 1);queuedBytes -= entry.bytes;entry.cleanup();activate(group, entry);
115
+ }
116
+ arm(group);
117
+ }
118
+ function feedback(group, entry, value) {
119
+ if (!value) return;
120
+ const until = now() + Math.min(7 * 86400000, value.delay);
121
+ const model = modelState(group, entry.model);
122
+ if (value.scope === "source") { group.pausedUntil = Math.max(group.pausedUntil, until);group.reason = value.kind; }
123
+ else if (model) { model.until = Math.max(model.until, until);model.reason = value.kind; }
124
+ // Unknown 429s briefly space the account, without inventing a permanent
125
+ // account-wide quota rejection from one model's response.
126
+ if (value.scope === "model") group.pausedUntil = Math.max(group.pausedUntil, Math.min(until, now() + 1000));
127
+ if (value.kind === "concurrency" && (value.scope === "model" ? model && entry.modelEpoch === model.epoch : entry.epoch === group.epoch)) {
128
+ const next = value.limit || Math.max(1, Math.floor((value.scope === "model" ? entry.modelInflight : entry.inflight) / 2));
129
+ if (value.scope === "model" && model) {
130
+ model.limit = Math.min(model.limit, next);if (value.limit) { model.maximum = value.limit;model.maximumUntil = now() + stableMs; }
131
+ model.epoch++;model.successes = 0;model.stableAt = now();
132
+ } else {
133
+ group.limit = Math.min(group.limit, next);if (value.limit) { group.advertised = value.limit;group.advertisedUntil = now() + stableMs; }
134
+ group.epoch++;group.successes = 0;group.readyToGrow = false;group.stableAt = now();
135
+ }
136
+ }
137
+ arm(group);
138
+ }
139
+ class Lease {
140
+ constructor(group, model, client) { this.group = group;this.model = model;this.client = client;this.epoch = group.epoch;this.bytes = 0;this.released = false;this.observed = false; }
141
+ limit(value) { this.observed = true;feedback(this.group, this, value); }
142
+ streamFailure(error, headers) { const value = sourceLimitFeedback(429, headers, { error }, now());if (value?.kind !== "unknown") this.limit(value); }
143
+ observe(status, headers, body) {
144
+ const group = this.group, entry = this;
145
+ this.responseAt ??= now();
146
+ const declared = headers?.get?.("x-ratelimit-concurrency-limit");
147
+ if (!this.headersObserved && /^\d{1,3}$/.test(declared || "") && validLimit(Number(declared))) {
148
+ group.advertised = Number(declared);group.advertisedUntil = now() + stableMs;group.limit = Math.min(group.limit, group.advertised);
149
+ }
150
+ this.headersObserved = true;this.observed ||= status === 429;
151
+ const value = sourceLimitFeedback(status, headers, body, this.responseAt);
152
+ if (value) value.delay = Math.max(0, this.responseAt + value.delay - now());
153
+ feedback(group, entry, value);
154
+ }
155
+ release(success = false) {
156
+ if (this.released) return;this.released = true;
157
+ const group = this.group, entry = this, model = this.modelState;group.active--;if (model) model.active--;group.completed++;
158
+ if (success && !this.observed) {
159
+ group.successes = Math.min(8, group.successes + 1);
160
+ const mature = group.successes >= 8 && now() - group.stableAt >= stableMs;
161
+ group.readyToGrow ||= mature;
162
+ if (group.readyToGrow) {
163
+ const ceiling = limits.get(group.source) || MAX_LIMIT;
164
+ if (group.queue.length && group.limit < ceiling) {
165
+ group.limit = Math.min(group.advertisedUntil > now() ? group.advertised : MAX_LIMIT, group.limit + 1);
166
+ group.readyToGrow = false;group.stableAt = now();group.successes = 0;
167
+ } else if (group.limit >= ceiling) { group.readyToGrow = false;group.stableAt = now();group.successes = 0; }
168
+ if (mature && now() - group.lastStableNotice >= stableMs && group.limit <= ceiling && (group.epoch || group.limit !== initialLimit)) {
169
+ group.lastStableNotice = now();try { onStable(group.key, group.limit); } catch { /* Metadata persistence cannot fail inference. */ }
170
+ }
171
+ }
172
+ if (model) {
173
+ model.successes = Math.min(8, model.successes + 1);
174
+ if (group.queue.some(waiter => waiter.model === entry.model) && model.limit < capacity(group) && model.successes >= 8 && now() - model.stableAt >= stableMs) {
175
+ model.limit = Math.min(model.maximumUntil > now() ? model.maximum : MAX_LIMIT, model.limit + 1);model.stableAt = now();model.successes = 0;
176
+ }
177
+ }
178
+ }
179
+ drain(group);
180
+ }
181
+ }
182
+ function activate(group, entry) {
183
+ group.active++;group.lastClient = entry.client;
184
+ const model = modelState(group, entry.model);if (model) model.active++;
185
+ entry.epoch = group.epoch;entry.modelEpoch = model?.epoch;entry.inflight = group.active;entry.modelInflight = model?.active || 1;
186
+ entry.modelState = model;return entry.resolve(entry);
187
+ }
188
+ function acquire(descriptor, { signal, model = "unknown", client = "other", bytes, bodyText } = {}) {
189
+ if (closed) throw failure("ccdx_source_closed", "The source scheduler is stopping.");
190
+ if (signal?.aborted) throw abortError(signal);
191
+ const group = groupFor(descriptor), entry = new Lease(group, model, client);
192
+ if (!group.queue.length && fits(group, entry)) { entry.resolve = immediate;return activate(group, entry); }
193
+ const delay = Math.max(0, readyAt(group, entry) - now());
194
+ if (delay >= waitTimeoutMs) throw failure("ccdx_source_limited", "The source is limited. Retry after its recovery time.", delay, 429);
195
+ const size = bytes === undefined ? typeof bodyText === "string" ? Math.max(1, Buffer.byteLength(bodyText)) : 1 : typeof bytes === "function" ? bytes() : bytes;
196
+ entry.bytes = Number.isSafeInteger(size) && size > 0 ? size : maxQueuedBytes + 1;
197
+ if (group.queue.length >= maxQueued || entry.bytes + queuedBytes > maxQueuedBytes) {
198
+ group.rejected++;throw failure("ccdx_source_queue_full", "The source is busy and its waiting queue is full. Retry shortly.", Math.max(1000, delay));
199
+ }
200
+ const started = now(), tracker = currentRequestContext()?.streamPerformance;
201
+ return new Promise((resolve, reject) => {
202
+ const remove = () => { const index = group.queue.indexOf(entry);if (index >= 0) { group.queue.splice(index, 1);queuedBytes -= entry.bytes; } };
203
+ const fail = error => { remove();entry.cleanup();reject(error);drain(group); };
204
+ const cancelled = () => fail(Object.assign(new Error("Waiting for the source was cancelled."), { name: "AbortError", code: "ccdx_source_queue_cancelled", sourceQueue: true, origin: "source_admission" }));
205
+ const timer = setTimeout(() => fail(failure("ccdx_source_queue_timeout", "Waiting for the source timed out. Retry shortly.")), waitTimeoutMs);
206
+ timer.unref?.();
207
+ entry.cleanup = () => { clearTimeout(timer);signal?.removeEventListener("abort", cancelled); };
208
+ entry.resolve = value => { tracker?.observeContext?.({ source_queue_ms: Math.max(0, Math.round(now() - started)) });resolve(value); };
209
+ entry.reject = fail;queuedBytes += entry.bytes;group.queue.push(entry);
210
+ signal?.addEventListener("abort", cancelled, { once: true });
211
+ if (signal?.aborted) cancelled();else drain(group);
212
+ });
213
+ }
214
+ async function run(descriptor, perform, options = {}) {
215
+ const acquired = acquire(descriptor, options), lease = acquired instanceof Promise ? await acquired : acquired;
216
+ let response;
217
+ try { if (options.signal?.aborted) throw abortError(options.signal);response = await perform(options.args); }
218
+ catch (error) { lease.release();throw error; }
219
+ if (!(response instanceof Response)) { lease.release();return response; }
220
+ lease.observe(response.status, response.headers);
221
+ const observedLimit = response[SOURCE_LIMIT_EVIDENCE];let bodyObserved = Boolean(observedLimit);
222
+ if (observedLimit) { lease.limit(observedLimit);lease.release(false); }
223
+ if (!response.body) { lease.release(response.ok);return response; }
224
+ if (response.status === 429 && !observedLimit) {
225
+ try { await readSafeUpstreamReason(response.clone(), { signal: options.signal, maxBytes: MAX_ERROR_BYTES,
226
+ onSourceLimit: value => { bodyObserved = true;lease.observe(response.status, response.headers, value);lease.release(false); } }); }
227
+ catch (error) { lease.release(false);throw error; }
228
+ }
229
+ if (options.sourceBodyManaged) {
230
+ trackSourceResponse(response, lease, { signal: options.signal, bodyObserved, waitTimeoutMs, captureLimit: response.status === 429 && !bodyObserved ? MAX_ERROR_BYTES : 0 });
231
+ return response;
232
+ }
233
+ let state;
234
+ const reader = response.body.getReader();let ended = false, errorBytes = 0, fragments = [];
235
+ const finish = success => {
236
+ if (ended) return;ended = true;options.signal?.removeEventListener("abort", cancel);
237
+ if (fragments.length) { try { lease.observe(response.status, response.headers, JSON.parse(Buffer.concat(fragments).toString())); } catch {}fragments = []; }
238
+ try { reader.releaseLock(); } catch {}if (state) state.finish(success);else lease.release(success);
239
+ };
240
+ const cancel = () => { void reader.cancel(options.signal?.reason).catch(() => {}).finally(() => finish(false)); };
241
+ options.signal?.addEventListener("abort", cancel, { once: true });
242
+ const body = new ReadableStream({
243
+ async pull(controller) {
244
+ try {
245
+ const next = await reader.read();
246
+ if (next.done) { finish(response.ok);controller.close();return; }
247
+ if (response.status === 429 && !bodyObserved && errorBytes <= MAX_ERROR_BYTES) {
248
+ errorBytes += next.value.byteLength;
249
+ if (errorBytes <= MAX_ERROR_BYTES) fragments.push(Buffer.from(next.value));else fragments = [];
250
+ }
251
+ controller.enqueue(next.value);
252
+ } catch (error) { finish(false);controller.error(error); }
253
+ },
254
+ async cancel(reason) { try { await reader.cancel(reason); } finally { finish(false); } },
255
+ });
256
+ if (options.signal?.aborted) cancel();
257
+ // Streaming callers need only the observed body. Keep native metadata and
258
+ // policy markers without rebuilding Headers for every stream. Native body
259
+ // convenience methods and clone share one lazily created consumption view.
260
+ let consumption;
261
+ const result = new Proxy(response, { get(target, key) {
262
+ if (key === "body") return consumption ? consumption.body : body;
263
+ if (key === "bodyUsed") return consumption ? consumption.bodyUsed : isDisturbed(body);
264
+ if (BODY_METHODS.has(key) && typeof target[key] === "function") return (...args) => {
265
+ consumption ||= new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
266
+ return consumption[key](...args);
267
+ };
268
+ return Reflect.get(target, key, target);
269
+ } });
270
+ Object.defineProperty(result, SOURCE_STREAM_LIMIT, { value: error => {
271
+ const value = sourceLimitFeedback(429, response.headers, { error }, now());if (value?.kind !== "unknown") lease.limit(value);
272
+ } });
273
+ state = trackSourceResponse(result, lease, { externalObserver: true, waitTimeoutMs });
274
+ return result;
275
+ }
276
+ return {
277
+ run,
278
+ wrap(client, descriptor) {
279
+ if (!client || clients.has(client) || client[SOURCE_ADMISSION]?.scheduler === this) return clients.get(client) || client;
280
+ const wrapped = { ...client };
281
+ const sourceContext = { scheduler: this, descriptor };
282
+ for (const method of ["responses", "responsesCompact", "messages", "chatCompletions", "images"]) {
283
+ if (typeof client[method] !== "function") continue;
284
+ const perform = args => client[method](...args);
285
+ wrapped[method] = (...args) => {
286
+ const index = method === "images" ? 1 : 0, body = args[index], options = args[index + 1] || {};
287
+ if (options.countTokens) return client[method](...args);
288
+ if (client[SOURCE_HTTP_CLIENT]) { args[index + 1] = { ...options, [SOURCE_HTTP_CONTEXT]: sourceContext };return client[method](...args); }
289
+ return run(descriptor(), perform, { args, signal: options.signal, model: body?.model, sourceBodyManaged: options.sourceBodyManaged === true,
290
+ client: currentRequestContext()?.application || "other", bytes: () => Buffer.byteLength(options.bodyText || JSON.stringify(body || {})) });
291
+ };
292
+ }
293
+ wrapped[SOURCE_ADMISSION] = { scheduler: this, descriptor };
294
+ clients.set(client, wrapped);return wrapped;
295
+ },
296
+ configure(source, limit) {
297
+ if (!validLimit(limit)) throw failure("ccdx_source_limit_invalid", "Choose Auto or a maximum concurrency from 1 to 128.", 0, 400);
298
+ if (limit === null) limits.delete(source);else limits.set(source, limit);
299
+ for (const group of groups.values()) if (group.source === source) drain(group);
300
+ },
301
+ snapshot() {
302
+ return [...groups.values()].map(group => ({ source: group.source, active: group.active, queued: group.queue.length,
303
+ limit: capacity(group), maximum: limits.get(group.source) || null, mode: "auto", retry_after_ms: Math.max(0, group.pausedUntil - now()),
304
+ reason: group.pausedUntil > now() ? group.reason : null, completed: group.completed, rejected: group.rejected,
305
+ model_limits: [...group.models].filter(([, state]) => state.until > now() || state.limit < MAX_LIMIT)
306
+ .map(([model, state]) => ({ model, limit: state.limit, retry_after_ms: Math.max(0, state.until - now()), reason: state.until > now() ? state.reason : null })) }));
307
+ },
308
+ close() { closed = true;for (const group of groups.values()) { clearTimeout(group.timer);for (const entry of [...group.queue]) entry.reject(failure("ccdx_source_closed", "The source scheduler is stopping.")); } },
309
+ };
310
+ }
@@ -0,0 +1,35 @@
1
+ // Explicit local import only. Read and parse outside the inference event loop.
2
+ import fs from "node:fs";
3
+ import { readBoundedFileSync } from "./bounded-file.mjs";
4
+ import { previewDiscoveredProviders } from "./source-discovery.mjs";
5
+
6
+ const [tool, file] = process.argv.slice(2);
7
+ const result = state => ({ format: tool, saved: false, drafts: [], discovery: { tool, state, skipped: 0, truncated: false } });
8
+ let db, value;
9
+ try {
10
+ if (!["cc-switch", "magpie"].includes(tool) || !fs.statSync(file).isFile()) throw Error("unsupported");
11
+ if (tool === "magpie") {
12
+ const input = JSON.parse(readBoundedFileSync(file, { maxBytes: 2 * 1024 * 1024, encoding: "utf8" }));
13
+ if (!Array.isArray(input.providers)) throw Error("unsupported");
14
+ value = previewDiscoveredProviders(tool, input.providers.slice(0, 64), { truncated: input.providers.length > 64 });
15
+ } else {
16
+ // An orphaned WAL needs the owning application to recover it. Do not
17
+ // create sidecars or copy a database containing foreign credentials.
18
+ if (fs.existsSync(file + "-wal") && !fs.existsSync(file + "-shm")) throw Error("busy");
19
+ const { DatabaseSync } = await import("node:sqlite");db = new DatabaseSync(file, { readOnly: true });db.exec("PRAGMA busy_timeout=500");
20
+ const columns = db.prepare("PRAGMA table_info(providers)").all().map(row => row.name);
21
+ if (!["id", "app_type", "name", "settings_config"].every(key => columns.includes(key))) throw Error("unsupported");
22
+ const meta = columns.includes("meta") ? "CASE WHEN length(meta)<=65536 THEN meta ELSE '{}' END" : "'{}'";
23
+ const rows = db.prepare(`SELECT id, app_type, substr(name,1,160) AS name,
24
+ CASE WHEN length(settings_config)<=262144 THEN settings_config ELSE NULL END AS settings,
25
+ ${meta} AS meta FROM providers WHERE app_type IN ('claude','claude-desktop','codex') ORDER BY app_type,id LIMIT 65`).all();
26
+ value = previewDiscoveredProviders(tool, rows.slice(0, 64).map(row => {
27
+ try { return { ...row, settings: JSON.parse(row.settings), meta: JSON.parse(row.meta) }; } catch { return { app_type: row.app_type }; }
28
+ }), { truncated: rows.length > 64 });
29
+ }
30
+ } catch (error) {
31
+ const state = error.code === "ENOENT" ? "not_found" : [5, 6].includes(error.errcode) || error.message === "busy" ? "busy"
32
+ : error.message === "unsupported" ? "unsupported" : "unreadable";
33
+ value = result(state);
34
+ } finally { db?.close(); }
35
+ process.stdout.write(JSON.stringify(value));
@@ -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