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
@@ -1,4 +1,6 @@
1
1
  import { markToolActivity } from "./stream-performance.mjs";
2
+ import { observeSourceStreamFailure } from "./source-admission.mjs";
3
+ import { sourceResponseReader, cancelSourceReader, releaseSourceReader, sourceResponseAccepted } from "./source-response.mjs";
2
4
  import { responses as copilotResponses } from "./copilot.mjs";
3
5
  import {
4
6
  logRequestFailure,
@@ -163,6 +165,7 @@ function inspectResponseSseEvent(state, eventName, data) {
163
165
  }
164
166
  if (!RESPONSES_TERMINAL_EVENT_TYPES.has(eventType)) return changed ? event : null;
165
167
  if (eventType === "error" || eventType === "response.failed") {
168
+ observeSourceStreamFailure(state.sourceResponse, event.response?.error ?? event.error ?? event);
166
169
  const response = { ...(event.response && typeof event.response === "object" ? event.response : {}), ...state.response };
167
170
  const sequenceNumber = Number.isSafeInteger(state.lastSequence) && state.lastSequence > previousSequence
168
171
  ? state.lastSequence : Number.isSafeInteger(previousSequence) ? previousSequence + 1 : 0;
@@ -184,6 +187,7 @@ function inspectResponseSseEvent(state, eventName, data) {
184
187
  );
185
188
  }
186
189
  state.sawTerminal = true;
190
+ sourceResponseAccepted(state.sourceResponse);
187
191
  if (eventType === "response.completed") {
188
192
  const response = event.response;
189
193
  state.completed = { response, event };
@@ -502,8 +506,9 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
502
506
  headersSent = true;
503
507
  res.writeHead(resp.status, headers);
504
508
  };
505
- const reader = resp.body.getReader();
509
+ const reader = sourceResponseReader(resp);
506
510
  const streamState = {
511
+ sourceResponse: resp,
507
512
  completed: null,
508
513
  incomplete: null,
509
514
  failure: null,
@@ -621,7 +626,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
621
626
  if (!res.writableEnded) res.end();
622
627
  return { successful: Boolean(streamState.completed), compacted: false };
623
628
  } catch (error) {
624
- markResponseErrorOrigin(error.origin === "privacy" ? "privacy" : "transport");
629
+ markResponseErrorOrigin(["privacy", "source_admission"].includes(error.origin) ? error.origin : "transport");
625
630
  markStreamFailure();
626
631
  logRequestFailure("Responses", error, options.abort);
627
632
  writeHeaders();
@@ -631,8 +636,8 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
631
636
  return { successful: false, compacted: false };
632
637
  } finally {
633
638
  keepalive.stop();
634
- await reader.cancel().catch(() => {});
635
- reader.releaseLock();
639
+ await cancelSourceReader(reader).catch(() => {});
640
+ releaseSourceReader(reader);
636
641
  }
637
642
  }
638
643
  }
@@ -1,6 +1,7 @@
1
1
  import { isMissingCallIdError } from "./responses-tool-output.mjs";
2
2
  import { isRootToolSchemaError } from "./messages-tool-schema.mjs";
3
3
  import { redactDiagnosticText, boundedDiagnosticText } from "./diagnostic-text.mjs";
4
+ import { sourceResponseReader, observeSourceRead, failSourceRead, cancelSourceReader, releaseSourceReader, cancelSourceResponse } from "./source-response.mjs";
4
5
 
5
6
  // Default evidence contains only fixed categories. A separately authorized
6
7
  // one-shot capture can retain a bounded, redacted technical message.
@@ -26,10 +27,6 @@ const reasons = new Map([
26
27
  const MAX_ACTIVE_READS = 4;
27
28
  let activeReads = 0;
28
29
 
29
- function cancelBody(body) {
30
- try { void Promise.resolve(body?.cancel()).catch(() => {}); } catch {}
31
- }
32
-
33
30
  export function safeUpstreamReason(code, status) {
34
31
  const reason = typeof code === "string" ? reasons.get(code) : null;
35
32
  return reason?.statuses.includes(status) ? { code, message: reason.message } : null;
@@ -78,20 +75,20 @@ function readChunk(reader, signal) {
78
75
  const finish = (fn, value) => { if (settled) return;settled = true;signal.removeEventListener("abort", onAbort);fn(value); };
79
76
  const onAbort = () => finish(reject, signal.reason);
80
77
  signal.addEventListener("abort", onAbort, { once: true });
81
- reader.read().then(value => finish(resolve, value), error => finish(reject, error));
78
+ reader.read().then(value => { observeSourceRead(reader, value);finish(resolve, value); }, error => { failSourceRead(reader);finish(reject, error); });
82
79
  if (signal.aborted) onAbort();
83
80
  });
84
81
  }
85
82
 
86
83
  // Failure responses only. A stalled body or a stalled cancellation cannot delay
87
84
  // the caller beyond the budget. The original request's cancellation wins.
88
- export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024, missingCallId = false, rootToolSchema = false, diagnosticRedact } = {}) {
85
+ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024, missingCallId = false, rootToolSchema = false, diagnosticRedact, onSourceLimit } = {}) {
89
86
  if (signal?.aborted) {
90
- cancelBody(response?.body);
87
+ void cancelSourceResponse(response).catch(() => {});
91
88
  signal.throwIfAborted();
92
89
  }
93
90
  if (!response?.body) return null;
94
- if (activeReads >= MAX_ACTIVE_READS) { cancelBody(response.body);return null; }
91
+ if (activeReads >= MAX_ACTIVE_READS) { void cancelSourceResponse(response).catch(() => {});return null; }
95
92
  activeReads++;
96
93
  const deadline = performance.now() + timeoutMs;
97
94
  const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -100,7 +97,7 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
100
97
  try {
101
98
  const length = Number(response.headers?.get?.("content-length"));
102
99
  if (Number.isFinite(length) && length > maxBytes) return null;
103
- reader = response.body.getReader();const chunks = [];let bytes = 0;
100
+ reader = sourceResponseReader(response);const chunks = [];let bytes = 0;
104
101
  while (true) {
105
102
  if (performance.now() >= deadline) controller.abort();
106
103
  const { done, value } = await readChunk(reader, readSignal);
@@ -112,6 +109,7 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
112
109
  }
113
110
  const text = Buffer.concat(chunks, bytes).toString("utf8");
114
111
  let value;try { value = JSON.parse(text); } catch { value=text; }
112
+ if (response.status === 429) try { onSourceLimit?.(value); } catch { /* Optional classification never alters the public error. */ }
115
113
  const reason = missingCallId && isMissingCallIdError(response.status, text)
116
114
  ? { code: "ccdx_missing_call_id", message: "The source requires a tool call ID." }
117
115
  : rootToolSchema && isRootToolSchemaError(response.status, text)
@@ -127,9 +125,9 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
127
125
  } finally {
128
126
  clearTimeout(timer);
129
127
  if (!finished) {
130
- try { void Promise.resolve(reader ? reader.cancel() : response.body.cancel()).catch(() => {}); } catch {}
128
+ try { void (reader ? cancelSourceReader(reader) : cancelSourceResponse(response)).catch(() => {}); } catch {}
131
129
  }
132
- try { reader?.releaseLock(); } catch {}
130
+ try { releaseSourceReader(reader); } catch {}
133
131
  activeReads--;
134
132
  }
135
133
  }
@@ -10,15 +10,29 @@ import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
10
10
  import { settingsPreferencesSnapshot, writeSettingsPreferences } from "./settings-preferences.mjs";
11
11
  import { predictionControlSnapshot, controlPrediction } from "./prediction-control.mjs";
12
12
  import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
13
+ import { createApplicationControl } from "./application-control.mjs";
14
+ import { openCodex, autoLaunchEnabled } from "./launcher.mjs";
13
15
 
14
- export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
16
+ export function createServiceControl({ env = process.env, home, platform = process.platform, providerRuntime, clientIntegration, terminal,
15
17
  nightlyStatus = () => null, nightlyChanged = () => {},
16
18
  manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage, codexLaunchControl = controlCodexLaunch,
17
- clientVersions,
19
+ clientVersions, applicationControlFactory = createApplicationControl,
18
20
  adapterPort = 2026, adapterHost = "127.0.0.1",
19
21
  readImages = () => imageSetupSummary({ env, home }).configured, readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
20
- const options = { env, home };
22
+ const options = { env, home, platform };
21
23
  const imageHostState = createImageHostState();
24
+ const applicationControl = applicationControlFactory({ ...options, providerRuntime, clientIntegration, imageHostState, port: adapterPort, host: adapterHost,
25
+ async openCodexApp() {
26
+ if (platform === "win32") {
27
+ const native = await clientIntegration?.start({ autoSetup: false });
28
+ if (!native?.pacUrl) return null;
29
+ const opened = await openCodex({ env: { ...env, CCDX_AUTO_LAUNCH: "1" }, platform, predictionPacUrl: native.pacUrl,
30
+ predictionApp: native.app, predictionProfile: native.profile, preparePredictionRoute: () => native.prepareRoute?.() });
31
+ return { status: opened ? "opened" : "open_failed" };
32
+ }
33
+ return codexLaunchControl("open", { ...options, intent: "app", configureClient: false, host: adapterHost, port: adapterPort,
34
+ integration: clientIntegration, state: imageHostState, models: providerRuntime?.imageModels?.().models || [] });
35
+ } });
22
36
  let serial = Promise.resolve(), lastOperation = null, pending = 0;
23
37
  const featureSnapshot = read => { try { return read(options); } catch { return { status: "unavailable" }; } };
24
38
  function snapshot() {
@@ -30,6 +44,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
30
44
  const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
31
45
  const localPrivacy = providerRuntime?.privacy?.snapshot();
32
46
  return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
47
+ applications: applicationControl.snapshot(),
33
48
  features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: { ...image, runtime: imageHostState.snapshot() } },
34
49
  decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
35
50
  ...(providerRuntime?.errorCaptureSnapshot ? { error_capture: providerRuntime.errorCaptureSnapshot() } : {}),
@@ -41,6 +56,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
41
56
  terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
42
57
  state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
43
58
  open_webui: { value: saved.open_webui, state: "next_start" },
59
+ codex_auto_launch: { value: env.CCDX_AUTO_LAUNCH ? autoLaunchEnabled(env, options) : saved.codex_auto_launch, state: "next_start", locked: Boolean(env.CCDX_AUTO_LAUNCH) },
44
60
  image_enabled: { value: saved.image_enabled && imageConfigured && image.selected_available === true, state: !imageConfigured ? "needs_github_access" : image.selected_available ? "next_call" : "image_model_unavailable", configured: imageConfigured },
45
61
  prediction_enabled: { value: prediction?.active === true, state: !predictionConfigured ? "needs_setup"
46
62
  : prediction?.environment?.status === "needs_app_relaunch" ? "needs_app_relaunch" : prediction?.bridge !== "running" ? "needs_service_restart" : "next_config_request", configured: predictionConfigured },
@@ -53,13 +69,18 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
53
69
  history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
54
70
  prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence", "confirmed"],
55
71
  codex_app: ["action", "operation", "intent", "confirmed"],
72
+ application: ["action", "id", "operation", "confirmed", "fresh", "expected_pid", "expected_started"],
56
73
  update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
57
74
  error_capture: ["action", "operation", "source", "model"],
58
75
  preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
59
76
  provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
60
77
  if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
61
78
  lastOperation = null;
62
- if (input.action === "error_capture") {
79
+ if (input.action === "application") {
80
+ if (input.fresh !== undefined && typeof input.fresh !== "boolean") throw new Error("Invalid application check");
81
+ if (input.expected_pid !== undefined && (!Number.isSafeInteger(input.expected_pid) || input.expected_pid <= 0 || !Number.isFinite(Date.parse(input.expected_started)))) throw new Error("Invalid application identity");
82
+ lastOperation = { feature: "application", result: await applicationControl.action(input) };
83
+ } else if (input.action === "error_capture") {
63
84
  if (!providerRuntime?.captureUpstreamError) throw new Error("This service cannot capture upstream errors.");
64
85
  lastOperation = { feature: "error_capture", result: providerRuntime.captureUpstreamError(input) };
65
86
  } else if (input.action === "codex_app") {
@@ -92,6 +113,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
92
113
  } else if (input.action === "nightly_update") {
93
114
  writeNightlyUpdatePreference(input.enabled, options);nightlyChanged(input.enabled);
94
115
  } else if (input.action === "preference") {
116
+ if (input.key === "codex_auto_launch" && env.CCDX_AUTO_LAUNCH) throw new Error("Automatic Codex launch is controlled by CCDX_AUTO_LAUNCH");
95
117
  if (input.key === "prediction_enabled") await predictionControl(input.value ? "enable" : "disable", { ...options, integration: clientIntegration });
96
118
  else writeServicePreference(input.key, input.value, options);
97
119
  terminal?.apply?.({ ...servicePreferences(options) });
@@ -119,7 +141,9 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
119
141
  }
120
142
  return snapshot();
121
143
  }
122
- return { snapshot, busy: () => pending > 0, action(input) {
144
+ return { snapshot, applicationControl, busy: () => pending > 0 || applicationControl.busy?.() === true,
145
+ async inspectApplication(id, fresh = false) { await applicationControl.check(id, fresh);return snapshot(); },
146
+ action(input) {
123
147
  if (input?.action === "client_versions") {
124
148
  if (Object.keys(input).some(key => key !== "action")) return Promise.reject(new Error("Unknown setting action or field"));
125
149
  if (clientVersions?.refresh) void Promise.resolve().then(() => clientVersions.refresh()).catch(() => {});
@@ -9,7 +9,7 @@ import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-
9
9
  import { withFileLockSync } from "./lock.mjs";
10
10
 
11
11
  export const SETTINGS_DEFAULTS = Object.freeze({ terminal_color_theme: "green", terminal_animation: DEFAULT_TERMINAL_ANIMATION_THEME,
12
- terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true });
12
+ terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true, codex_auto_launch: false });
13
13
  const keys = Object.keys(SETTINGS_DEFAULTS);
14
14
  const fail = (code, message, statusCode = 409) => Object.assign(new Error(message), { code, statusCode });
15
15
  const idValid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
@@ -30,8 +30,8 @@ function readBackup(options) {
30
30
  const value = JSON.parse(readBoundedFileSync(settingsBackupPath(options), { encoding: "utf8", maxBytes: 8192 }));
31
31
  if (value?.version !== 1 || !idValid(value.id) || typeof value.created_at !== "string" || !Number.isFinite(Date.parse(value.created_at))
32
32
  || Object.keys(value).some(key => !["version", "id", "created_at", "values"].includes(key))
33
- || keys.filter(key => !key.startsWith("privacy_") && key !== "context_compaction_enabled").some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
34
- value.values = { privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true, ...value.values };
33
+ || keys.filter(key => !key.startsWith("privacy_") && !["context_compaction_enabled", "codex_auto_launch"].includes(key)).some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
34
+ value.values = { privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true, codex_auto_launch: false, ...value.values };
35
35
  checkedPreferenceValues(value.values);return value;
36
36
  } catch (error) {
37
37
  if (error.code === "ENOENT") return null;
@@ -0,0 +1,29 @@
1
+ import path from "node:path";
2
+ import { createSourceAdmission } from "./source-admission.mjs";
3
+ import { userSettingsPath } from "./user-settings.mjs";
4
+ import { readBoundedFileSync } from "./bounded-file.mjs";
5
+ import { atomicWriteFile } from "./atomic-file.mjs";
6
+
7
+ export function createRuntimeSourceAdmission({ persistSourceState = false, ...options } = {}) {
8
+ if (!persistSourceState) return createSourceAdmission();
9
+ const file = path.join(path.dirname(userSettingsPath(options)), "source-capacity.json");
10
+ let learned = {}, dirty = false, timer, writing = Promise.resolve();
11
+ try {
12
+ const saved = JSON.parse(readBoundedFileSync(file, { maxBytes: 16384, encoding: "utf8" }));
13
+ if (saved.version === 1 && saved.entries && Object.keys(saved.entries).length <= 64) learned = Object.fromEntries(Object.entries(saved.entries)
14
+ .filter(([key, value]) => /^[a-f0-9]{64}$/.test(key) && Number.isSafeInteger(value.limit) && value.limit > 0 && value.limit <= 128 && Number.isFinite(value.at)));
15
+ } catch { /* Disposable capacity metadata is relearned; source configuration is never rewritten. */ }
16
+ const flush = () => {
17
+ clearTimeout(timer);timer = null;
18
+ if (!dirty) return writing;
19
+ dirty = false;const text = JSON.stringify({ version: 1, entries: learned }) + "\n";
20
+ writing = writing.catch(() => {}).then(() => atomicWriteFile(file, text)).catch(() => {});
21
+ return writing;
22
+ };
23
+ const scheduler = createSourceAdmission({ learned, onStable(key, limit) {
24
+ delete learned[key];learned[key] = { limit, at: Date.now() };
25
+ while (Object.keys(learned).length > 64) delete learned[Object.keys(learned)[0]];
26
+ dirty = true;if (!timer) { timer = setTimeout(flush, 1000);timer.unref?.(); }
27
+ } });
28
+ return { ...scheduler, async close() { scheduler.close();await flush(); } };
29
+ }
@@ -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));