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
@@ -22,7 +22,7 @@ import {antigravityCopilotModels} from "./antigravity-models.mjs";
22
22
  const execute=promisify(execFile),key="gemini_antigravity_enabled",modelKey="gemini_antigravity_models";
23
23
 
24
24
  export function createAntigravityRuntime({client,models=()=>[],refreshModels,privacy,home=os.homedir(),env=process.env,inspect=inspectGeminiApp,
25
- exec=execute,searchFn,imageFn,guardSource,googleFetch,acquireRequest,readToken=()=>readSavedGithubToken(home),...timeouts}={}) {
25
+ exec=execute,searchFn,imageFn,guardSource,googleFetch,acquireRequest,applicationControl,readToken=()=>readSavedGithubToken(home),...timeouts}={}) {
26
26
  const options={home,env},guard=createConversationSourceGuard(options);
27
27
  const web=searchFn?null:createCopilotWeb({client,readToken});
28
28
  let app={status:"unknown"},route=null,lastOperation=null,compactionSalt;const conversationSources=new Map();
@@ -69,7 +69,9 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
69
69
  }
70
70
  const expected=listed.filter(model=>model.selected).map(model=>model.id).sort();
71
71
  const reload=config.enabled&&sourceEnabled?(activity.catalog_models===null?null:JSON.stringify([...activity.catalog_models].sort())!==JSON.stringify(expected)):false;
72
- return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app,route_observed:handler.snapshot().observed,
72
+ const current=applicationControl?.snapshot().antigravity;
73
+ const visibleApp=current?{status:current.status,version:current.version||null,pids:current.pid?[current.pid]:[]}:app;
74
+ return {source:"gemini_antigravity",...config,source_enabled:sourceEnabled,models_reload_required:reload,app:visibleApp,application:current||null,route_observed:handler.snapshot().observed,
73
75
  model_source:"Google + GitHub Copilot",background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
74
76
  compaction_source:"Observed conversation source; existing background policy when unassigned",
75
77
  models:listed,model_groups:[...groups.values()],activity,last_operation:lastOperation};
@@ -98,10 +100,18 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
98
100
  withFileLockSync(file+".lock",()=>{const saved=readUserSettings({...options,strict:true});atomicWriteFileIfChangedSync(file,JSON.stringify({...saved,[key]:operation==="enable"},null,2)+"\n",{mode:0o600})});
99
101
  lastOperation=null;
100
102
  }
103
+ if(applicationControl){
104
+ if(operation==="open"){
105
+ const result=await applicationControl.action({id:"antigravity",operation:"open"});lastOperation={action:operation,status:result.status};
106
+ }else if(operation==="preview"){
107
+ const plan=await applicationControl.previewAntigravity();lastOperation={action:operation,status:plan.status,...(plan.status==="prepared"?{plan:{command:plan.command,args:plan.args}}:{})};
108
+ }else await applicationControl.check("antigravity",true);
109
+ return snapshot();
110
+ }
101
111
  app=await inspect();route=baseUrl+"/antigravity";
102
112
  if(["open","preview"].includes(operation)){
103
113
  const config=settings();
104
- const plan=config.enabled?planGeminiAppLaunch(app,{cloudCodeUrl:route,env}):app.status==="stopped"?{status:"prepared",command:"/usr/bin/open",args:["-a",app.app]}:{status:app.status==="running"?"needs_app_relaunch":app.status};
114
+ const plan=config.enabled?planGeminiAppLaunch(app,{cloudCodeUrl:route,env,home}):app.status==="stopped"?{status:"prepared",command:"/usr/bin/open",args:["-a",app.app]}:{status:app.status==="running"?"needs_app_relaunch":app.status};
105
115
  lastOperation={action:operation,status:plan.status};
106
116
  if(operation==="open"&&plan.status==="prepared"){
107
117
  await exec(plan.command,plan.args,{encoding:"utf8",timeout:5000,maxBuffer:4096});lastOperation.status="opened";app={...app,status:"starting"};
@@ -0,0 +1,43 @@
1
+ import { createHash } from "node:crypto";
2
+ import { claudeClientPaths, M365_CLAUDE_PROFILE_ID } from "./claude-client-config.mjs";
3
+ import { codexPaths } from "./codex-paths.mjs";
4
+ import { parseCodexToml } from "./config-toml.mjs";
5
+ import { readBoundedFile } from "./bounded-file.mjs";
6
+ import { userSettingsPath } from "./user-settings.mjs";
7
+
8
+ const read = async file => JSON.parse(await readBoundedFile(file, { maxBytes: 1024 * 1024, encoding: "utf8" }));
9
+ const sameUrl = (actual, expected) => { try { return new URL(actual).href.replace(/\/$/, "") === new URL(expected).href.replace(/\/$/, ""); } catch { return false; } };
10
+ const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object"
11
+ ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
12
+ const digest = value => createHash("sha256").update(JSON.stringify(canonical(value))).digest("hex");
13
+
14
+ // Inspect only integration fields; fingerprints stay in process memory.
15
+ export async function inspectApplicationConfiguration(id, { port = 2026, host = "127.0.0.1", ...options } = {}) {
16
+ let value, state;
17
+ try {
18
+ if (id === "claude_app") {
19
+ const paths = claudeClientPaths(options), [profile, meta, mode] = await Promise.all([read(paths.profile), read(paths.meta), read(paths.threep).catch(error => { if (error.code === "ENOENT") return {};throw error; })]);
20
+ value = { provider: profile.inferenceProvider, address: profile.inferenceGatewayBaseUrl, key: profile.inferenceGatewayApiKey,
21
+ models: typeof profile.inferenceModels === "string" ? JSON.parse(profile.inferenceModels) : profile.inferenceModels,
22
+ discovery: profile.modelDiscoveryEnabled, profile: meta.appliedId, hybrid: meta.hybridPointer,
23
+ mode: profile.disableDeploymentModeChooser === true || mode.deploymentMode !== "1p" ? "3p" : "1p" };
24
+ state = value.provider === "gateway" && value.profile === M365_CLAUDE_PROFILE_ID && !value.hybrid && value.mode === "3p" && typeof value.key === "string" && Boolean(value.key)
25
+ && sameUrl(value.address, `http://${host}:${port}/anthropic`) ? "configured" : "preserved";
26
+ } else if (id === "codex") {
27
+ const file = codexPaths(options).config;
28
+ const config = parseCodexToml(await readBoundedFile(file, { maxBytes: 2 * 1024 * 1024, encoding: "utf8" }));
29
+ value = { provider: config.model_provider, address: config.openai_base_url, models: config.model_catalog_json, gateway: config.model_providers?.ccdx_gateway,
30
+ model: config.model };
31
+ state = ((!value.provider || value.provider === "openai") && sameUrl(value.address, `http://${host}:${port}/v1`))
32
+ || (value.provider === "ccdx_gateway" && sameUrl(value.gateway?.base_url, `http://${host}:${port}/v1`)) ? "configured" : "preserved";
33
+ } else {
34
+ let settings;try { settings = await read(userSettingsPath(options)); } catch (error) { if (error.code !== "ENOENT") throw error;settings = {}; }
35
+ value = { enabled: settings.gemini_antigravity_enabled === true, models: settings.gemini_antigravity_models || null, port, host };
36
+ state = value.enabled ? "configured" : "native";
37
+ }
38
+ const reload = { ...value };delete reload.key;
39
+ return { state, revision: digest(value), reloadRevision: digest(reload) };
40
+ } catch (error) {
41
+ return { state: error.code === "ENOENT" ? "not_configured" : "unavailable", revision: "unknown" };
42
+ }
43
+ }
@@ -0,0 +1,114 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { setTimeout as sleep } from "node:timers/promises";
4
+ import { inspectApplicationProcesses, processFamily, applicationConnections, controlApplicationProcess } from "./application-process.mjs";
5
+ import { inspectApplicationConfiguration } from "./application-configuration.mjs";
6
+ import { createApplicationEvidence } from "./application-evidence.mjs";
7
+ import { planGeminiAppLaunch, inspectGeminiApp } from "./gemini-app.mjs";
8
+ import { readUserSettings } from "./user-settings.mjs";
9
+
10
+ const execute = promisify(execFile), ids = ["codex", "claude_app", "antigravity"];
11
+ export function createApplicationControl({ providerRuntime, clientIntegration, imageHostState, env = process.env, home,
12
+ platform = process.platform, port = 2026, host = "127.0.0.1", now = Date.now, exec = execute, wait = sleep,
13
+ inspect = inspectApplicationProcesses, connections = applicationConnections, control = controlApplicationProcess,
14
+ inspectGemini = inspectGeminiApp,
15
+ configuration = inspectApplicationConfiguration, openCodexApp, evidence = providerRuntime?.applicationEvidence || createApplicationEvidence({ now }) } = {}) {
16
+ const options = { env, home, platform, exec };
17
+ const states = Object.fromEntries(ids.map(id => [id, { status: "unknown", connection: "pending" }]));
18
+ const configurations = new Map(), starting = new Map();
19
+ let cached, at = 0, pending, pendingAt = 0, serial = Promise.resolve(), inspection = 0, operations = 0;
20
+ const snapshot = () => structuredClone(states);
21
+ const inventory = async fresh => {
22
+ if (!fresh && cached && now() >= at && now() - at < 3000) return cached;
23
+ if (!pending) { pendingAt = now();pending = inspect(options).then(value => { cached = value;at = now();return value; }).finally(() => { pending = null; }); }
24
+ const remaining = Math.min(5000, 5000 - (now() - pendingAt));
25
+ if (remaining <= 0) throw new Error("Application inspection is still pending");
26
+ let timer;try { return await Promise.race([pending, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("Application inspection timed out")), remaining); })]); }
27
+ finally { clearTimeout(timer); }
28
+ };
29
+ async function check(id, fresh = false) {
30
+ if (!ids.includes(id)) throw new Error("Unknown application");
31
+ let data;try { data = await inventory(fresh); } catch { states[id] = { status: "unknown", connection: "pending", inspection: ++inspection };return states[id]; }
32
+ const app = data.apps[id] || { status: "unknown" }, config = await configuration(id, { ...options, port, host });
33
+ const old = configurations.get(id);
34
+ if (!old || old.revision !== config.revision) configurations.set(id, { ...config,
35
+ evidenceAt: old ? now() : 0,
36
+ changed: old && (old.reloadRevision || old.revision) !== (config.reloadRevision || config.revision) ? now() : old?.changed || 0 });
37
+ let connection = { state: "pending" };
38
+ if (app.status === "running") {
39
+ const family = processFamily(data.processes, app.pid).map(row => row.pid);
40
+ let sockets = [];try { sockets = await connections(family, port, options); } catch { /* Missing process access is unconfirmed, not disconnected. */ }
41
+ connection = evidence.inspect(id, app, sockets, config.revision, configurations.get(id)?.evidenceAt || 0);
42
+ } else evidence.clear(id);
43
+ const changed = configurations.get(id)?.changed || 0;
44
+ const needsReload = app.status === "running" && (config.state === "configured" || id === "antigravity" && config.state === "native") && changed > Date.parse(app.started) && connection.state !== "observed";
45
+ const status = app.status === "stopped" && (starting.get(id) || 0) > now() ? "starting" : app.status;
46
+ states[id] = { status, inspection: ++inspection, connection: connection.state, scope: connection.scope || null, observed_at: connection.at || null,
47
+ configuration: config.state, needs_reload: needsReload, ...(app.pid ? { pid: app.pid, started: app.started } : {}), ...(app.version ? { version: app.version } : {}) };
48
+ return states[id];
49
+ }
50
+ async function action(input) {
51
+ const { id, operation, confirmed, fresh = false, expected_pid: expectedPid, expected_started: expectedStarted } = input;
52
+ if (!ids.includes(id) || !["check", "open", "focus", "restart"].includes(operation)) throw new Error("Unknown application action");
53
+ if (operation === "check") return { status: "checked", app: await check(id, fresh) };
54
+ if (operation === "restart" && confirmed !== true) throw new Error("Confirm that reopening may interrupt this application's tasks");
55
+ let state = await check(id, true), app = cached?.apps[id];
56
+ if (operation === "restart" && expectedPid !== undefined && (expectedPid !== app?.pid || expectedStarted !== app?.started)) return { status: "app_changed", app: state };
57
+ if (["unknown", "multiple", "unsupported", "not_installed"].includes(state.status)) return { status: state.status, app: state };
58
+ if (state.status === "starting") return { status: "opening", app: state };
59
+ if (state.status === "running" && operation !== "restart") {
60
+ if (state.needs_reload && operation !== "focus") return { status: "needs_app_relaunch", app: state };
61
+ const result = await control(app, "focus", options);
62
+ return { status: result === "sent" ? "focused" : "focus_unavailable", app: state };
63
+ }
64
+ if (operation === "focus") return { status: "app_not_running", app: state };
65
+ if (state.status === "running") {
66
+ const pid = app.pid, started = app.started;
67
+ const result = await control(app, "quit", options);
68
+ if (!["sent", "absent"].includes(result)) return { status: "quit_refused", app: state };
69
+ const deadline = now() + 10000;
70
+ do {
71
+ await wait(250);await check(id, true);app = cached?.apps[id];
72
+ if (app?.status === "stopped") break;
73
+ if (app?.pid !== pid || app?.started !== started) return { status: "app_changed", app: states[id] };
74
+ } while (now() < deadline);
75
+ if (app?.status !== "stopped") return { status: "quit_timeout", app: states[id] };
76
+ }
77
+ if (id !== "antigravity") await providerRuntime?.prepareApplication?.(id);
78
+ let opened = true, handled = false;
79
+ if (id === "codex" && openCodexApp) {
80
+ const result = await openCodexApp();
81
+ if (result) {
82
+ if (result.status === "already_connected") return { status: "focused", app: await check(id, true) };
83
+ if (!["opened_new_chat_required", "opened_with_pending", "opened"].includes(result.status)) return { ...result, app: states[id] };
84
+ handled = true;
85
+ }
86
+ }
87
+ if (!handled && platform === "darwin") {
88
+ const plan = id === "antigravity" ? await antigravityPlan(app) : { status: "prepared", command: "/usr/bin/open", args: ["-a", app.app] };
89
+ if (plan.status !== "prepared") return { status: plan.status, app: states[id] };
90
+ await exec(plan.command, plan.args, { encoding: "utf8", timeout: 5000, maxBuffer: 4096 });
91
+ } else if (!handled && platform === "win32") {
92
+ if (app.target.startsWith("shell:AppsFolder\\")) await exec("explorer.exe", [app.target], { encoding: "utf8", timeout: 5000, maxBuffer: 4096, windowsHide: true });
93
+ else await exec(app.target, [], { encoding: "utf8", timeout: 5000, maxBuffer: 4096, windowsHide: true });
94
+ } else if (!handled) opened = false;
95
+ if (!opened) return { status: "open_failed", app: states[id] };
96
+ evidence.clear(id);starting.set(id, now() + 10000);states[id] = { ...states[id], inspection: ++inspection, status: "starting", connection: "pending", needs_reload: false };
97
+ return { status: "opened", app: states[id] };
98
+ }
99
+ async function antigravityPlan(app) {
100
+ const config = readUserSettings({ env, home, strict: true });
101
+ if (config.gemini_antigravity_enabled !== true) return { status: "prepared", command: "/usr/bin/open", args: ["-a", app.app] };
102
+ const verified = await inspectGemini({ ...options, app: app.app });
103
+ if (verified.status !== "stopped") return { status: verified.status === "running" ? "app_changed" : verified.status };
104
+ if (readUserSettings({ env, home, strict: true }).gemini_antigravity_enabled !== true) return { status: "prepared", command: "/usr/bin/open", args: ["-a", app.app] };
105
+ return planGeminiAppLaunch(verified, { cloudCodeUrl: `http://${host}:${port}/antigravity`, env, home });
106
+ }
107
+ return { snapshot, evidence, check, busy: () => operations > 0,
108
+ async previewAntigravity() {
109
+ const state = await check("antigravity", true);
110
+ if (state.status !== "stopped") return { status: state.status === "running" ? "needs_app_relaunch" : state.status };
111
+ return antigravityPlan(cached.apps.antigravity);
112
+ },
113
+ action(input) { operations++;const result = serial.then(() => action(input)).finally(() => { operations--; });serial = result.catch(() => {});return result; } };
114
+ }
@@ -0,0 +1,42 @@
1
+ const APPS = new Set(["codex", "claude_app", "antigravity"]);
2
+
3
+ // Only accepted protocol metadata. No bodies, tokens, headers or raw chat IDs.
4
+ export function createApplicationEvidence({ now = Date.now } = {}) {
5
+ const candidates = new Map(), confirmed = new Map();
6
+ const accept = (req, app, scope, at = now()) => {
7
+ if (!APPS.has(app) || !["catalog", "inference", "control"].includes(scope)) return;
8
+ const peerPort = req?.socket?.remotePort, port = req?.socket?.localPort;
9
+ if (!Number.isInteger(peerPort) || !Number.isInteger(port)) return;
10
+ const key = `${port}:${peerPort}`;candidates.delete(key);candidates.set(key, { app, scope, peerPort, port, at });
11
+ while (candidates.size > 256) candidates.delete(candidates.keys().next().value);
12
+ };
13
+ return {
14
+ accept,
15
+ notice(req, res, app, scope) {
16
+ if (!APPS.has(app) || !["catalog", "inference", "control"].includes(scope)) return;
17
+ const peerPort = req.socket?.remotePort, port = req.socket?.localPort;
18
+ if (!Number.isInteger(peerPort) || !Number.isInteger(port)) return;
19
+ const event = { app, scope, peerPort, port, at: now() };
20
+ res.once("finish", () => {
21
+ if (!Number.isInteger(res.statusCode) || res.statusCode < 200 || res.statusCode >= 300) return;
22
+ const key = `${port}:${peerPort}`;candidates.delete(key);candidates.set(key, event);
23
+ while (candidates.size > 256) candidates.delete(candidates.keys().next().value);
24
+ });
25
+ },
26
+ inspect(app, process, connections, revision, since = 0) {
27
+ if (!process?.pid || !process.started) { confirmed.delete(app);return { state: "pending" }; }
28
+ const identity = `${process.pid}:${process.started}`;
29
+ const previous = confirmed.get(app);
30
+ if (previous?.identity === identity && previous.revision === revision && previous.at >= since && now() - previous.at < 300000) return { state: "observed", scope: previous.scope, at: new Date(previous.at).toISOString() };
31
+ confirmed.delete(app);
32
+ for (const [key, event] of candidates) {
33
+ if (now() - event.at > 300000) { candidates.delete(key);continue; }
34
+ if (event.app !== app || event.at < Math.max(since, Date.parse(process.started))) continue;
35
+ if (!connections.some(connection => connection.port === event.port && connection.peerPort === event.peerPort)) continue;
36
+ confirmed.set(app, { ...event, identity, revision });return { state: "observed", scope: event.scope, at: new Date(event.at).toISOString() };
37
+ }
38
+ return { state: "pending" };
39
+ },
40
+ clear(app) { confirmed.delete(app);for (const [key, event] of candidates) if (event.app === app) candidates.delete(key); },
41
+ };
42
+ }
@@ -0,0 +1,114 @@
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 { installedWindowsPredictionAppAsync } from "./native-prediction-windows.mjs";
7
+
8
+ const execute = promisify(execFile);
9
+ const definitions = {
10
+ codex: { bundles: ["Codex.app", "ChatGPT.app"], id: "com.openai.codex", executables: ["Codex", "ChatGPT"] },
11
+ claude_app: { bundles: ["Claude.app"], id: "com.anthropic.claudefordesktop", executables: ["Claude"] },
12
+ antigravity: { bundles: ["Gemini.app"], id: "com.google.GeminiMacOS", executables: ["Gemini"] },
13
+ };
14
+ const runOptions = { encoding: "utf8", timeout: 3000, maxBuffer: 4 * 1024 * 1024, windowsHide: true };
15
+ const metadataEnvironment = env => ({ ...Object.fromEntries(["PATH", "SystemRoot", "WINDIR", "TEMP", "TMP", "LOCALAPPDATA", "APPDATA", "USERPROFILE", "HOME", "TZ"]
16
+ .filter(key => env[key] !== undefined || process.env[key] !== undefined).map(key => [key, env[key] ?? process.env[key]])), LC_ALL: "C", LANG: "C" });
17
+ const windowsInventory = `[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);$ErrorActionPreference='Stop';$claude=$null;
18
+ $p=@(Get-AppxPackage -Name '*Claude*' | Where-Object { $_.Publisher -match 'Anthropic' -and [int]$_.Status -eq 0 });
19
+ if($p.Count -eq 1){$m=Get-AppxPackageManifest -Package $p[0].PackageFullName;$a=@($m.Package.Applications.Application | Where-Object { [IO.Path]::GetFileName($_.Executable) -eq 'Claude.exe' });if($a.Count -eq 1){$claude=@{app=(Join-Path $p[0].InstallLocation $a[0].Executable);target=('shell:AppsFolder\\'+$p[0].PackageFamilyName+'!'+$a[0].Id)}}}
20
+ if(!$claude){$f=Join-Path $env:LOCALAPPDATA 'AnthropicClaude\\Claude.exe';if(Test-Path -LiteralPath $f){$v=[Diagnostics.FileVersionInfo]::GetVersionInfo($f);if($v.CompanyName -match 'Anthropic' -and $v.ProductName -in @('Claude','Claude Desktop')){$claude=@{app=$f;target=$f}}}}
21
+ $rows=@(Get-CimInstance Win32_Process | ForEach-Object { if($_.CreationDate -and $_.ExecutablePath){@{pid=[int]$_.ProcessId;parent=[int]$_.ParentProcessId;command=[string]$_.ExecutablePath;started=$_.CreationDate.ToUniversalTime().ToString('o')}} });
22
+ @{claude=$claude;processes=$rows} | ConvertTo-Json -Depth 5 -Compress`;
23
+
24
+ export function processFamily(processes, root) {
25
+ const rows = new Map(processes.map(row => [row.pid, row]));
26
+ return processes.filter(row => {
27
+ let node = row;const visited = new Set();
28
+ while (node && !visited.has(node.pid)) { if (node.pid === root) return true;visited.add(node.pid);node = rows.get(node.parent); }
29
+ return false;
30
+ });
31
+ }
32
+
33
+ export async function inspectApplicationProcesses({ platform = process.platform, home = os.homedir(), env = process.env,
34
+ exec = execute, discoverWindows = installedWindowsPredictionAppAsync, applicationsRoot = "/Applications" } = {}) {
35
+ if (!["darwin", "win32"].includes(platform)) return { apps: Object.fromEntries(Object.keys(definitions).map(id => [id, { status: "unsupported" }])), processes: [] };
36
+ const apps = {}, processes = [];
37
+ if (platform === "darwin") {
38
+ const listing = await exec("/bin/ps", ["-ww", "-axo", "pid=,ppid=,lstart=,comm="], { ...runOptions, env: metadataEnvironment(env) });
39
+ for (const line of String(listing.stdout).split("\n")) {
40
+ const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s+(\/.*?)\s*$/.exec(line);
41
+ if (match) processes.push({ pid: Number(match[1]), parent: Number(match[2]), started: Number.isFinite(Date.parse(match[3])) ? new Date(match[3]).toISOString() : null, command: match[4] });
42
+ }
43
+ for (const [id, definition] of Object.entries(definitions)) {
44
+ const installed = [];
45
+ for (const directory of [applicationsRoot, path.join(home, "Applications")]) for (const bundle of definition.bundles) {
46
+ const app = path.join(directory, bundle), file = path.join(app, "Contents/Info.plist");
47
+ try { await fs.access(file); } catch { continue; }
48
+ const result = await exec("/usr/bin/plutil", ["-convert", "json", "-o", "-", file], { ...runOptions, maxBuffer: 65536 });
49
+ const info = JSON.parse(result.stdout);
50
+ if (info.CFBundleIdentifier !== definition.id || !definition.executables.includes(info.CFBundleExecutable)) continue;
51
+ installed.push({ app, target: app, identity: definition.id, executable: path.join(app, "Contents/MacOS", info.CFBundleExecutable), version: info.CFBundleShortVersionString });
52
+ }
53
+ const running = installed.filter(info => processes.some(row => row.command === info.executable));
54
+ apps[id] = running.length > 1 ? { status: "multiple" } : running[0] || installed[0] || { status: "not_installed" };
55
+ }
56
+ } else {
57
+ const result = await exec("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", windowsInventory], { ...runOptions, env: metadataEnvironment(env) });
58
+ const inventory = JSON.parse(result.stdout);
59
+ for (const row of inventory.processes || []) if (Number.isSafeInteger(row.pid) && row.pid > 0 && Number.isFinite(Date.parse(row.started))) processes.push(row);
60
+ let codex;try { codex = await discoverWindows({ env }); } catch {}
61
+ apps.codex = codex ? { app: codex.app, target: codex.app, executable: codex.app } : { status: "not_installed" };
62
+ const claude = inventory.claude;
63
+ apps.claude_app = claude && path.win32.isAbsolute(claude.app) && path.win32.basename(claude.app).toLowerCase() === "claude.exe"
64
+ && (claude.target === claude.app || /^shell:AppsFolder\\[A-Za-z0-9._-]+![A-Za-z0-9._-]+$/.test(claude.target))
65
+ ? { app: claude.app, target: claude.target, executable: claude.app } : { status: "not_installed" };
66
+ apps.antigravity = { status: "unsupported" };
67
+ }
68
+ for (const info of Object.values(apps)) if (info.executable) {
69
+ const same = command => platform === "win32" ? command?.toLowerCase() === info.executable.toLowerCase() : command === info.executable;
70
+ const candidates = processes.filter(row => same(row.command));
71
+ const matches = candidates.filter(row => !candidates.some(other => other.pid !== row.pid && processFamily(processes, other.pid).some(child => child.pid === row.pid)));
72
+ Object.assign(info, { status: matches.length > 1 ? "multiple" : matches.length ? matches[0].started ? "running" : "unknown" : "stopped" });
73
+ if (matches.length === 1) Object.assign(info, { pid: matches[0].pid, started: matches[0].started });
74
+ }
75
+ return { apps, processes };
76
+ }
77
+
78
+ export async function applicationConnections(pids, port, { platform = process.platform, exec = execute, env = process.env } = {}) {
79
+ if (!pids.length || pids.length > 128 || pids.some(pid => !Number.isSafeInteger(pid) || pid <= 0) || !Number.isInteger(port) || port < 1 || port > 65535) return [];
80
+ if (platform === "darwin") {
81
+ let out;
82
+ try { out = await exec("/usr/sbin/lsof", ["-nP", "-a", "-p", pids.join(","), `-iTCP:${port}`, "-sTCP:ESTABLISHED", "-Fpn"], { ...runOptions, maxBuffer: 256 * 1024 }); }
83
+ catch (error) { if (error.code === 1 && !String(error.stderr || "").trim()) return [];throw error; }
84
+ let pid;const connections = [];
85
+ for (const line of out.stdout.split("\n")) {
86
+ if (/^p\d+$/.test(line)) pid = Number(line.slice(1));
87
+ const match = /^n(?:127\.0\.0\.1|\[::1\]):(\d+)->(?:127\.0\.0\.1|\[::1\]):(\d+)$/.exec(line);
88
+ if (match && pids.includes(pid) && Number(match[2]) === port) connections.push({ pid, peerPort: Number(match[1]), port });
89
+ }
90
+ return connections;
91
+ }
92
+ if (platform === "win32") {
93
+ const script = `$ids=@(${pids.join(",")});@(Get-NetTCPConnection -State Established -RemotePort ${port} -ErrorAction SilentlyContinue | Where-Object { $_.OwningProcess -in $ids -and $_.RemoteAddress -in @('127.0.0.1','::1') } | ForEach-Object { @{pid=[int]$_.OwningProcess;peerPort=[int]$_.LocalPort;port=[int]$_.RemotePort} }) | ConvertTo-Json -Compress`;
94
+ const result = await exec("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], { ...runOptions, env });
95
+ const value = JSON.parse(result.stdout || "[]");return Array.isArray(value) ? value : [value];
96
+ }
97
+ return [];
98
+ }
99
+
100
+ export async function controlApplicationProcess(info, action, { platform = process.platform, exec = execute, env = process.env } = {}) {
101
+ if (!Number.isSafeInteger(info.pid) || !["focus", "quit"].includes(action)) throw new Error("Invalid application control");
102
+ if (platform === "darwin") {
103
+ const script = `ObjC.import('AppKit');function run(a){var p=$.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(a[0]));if(p.isNil())return 'absent';if(ObjC.unwrap(p.bundleIdentifier)!==a[1]||ObjC.unwrap(p.bundleURL.path)!==a[2])return 'different';return (a[3]==='quit'?p.terminate:p.activateWithOptions($.NSApplicationActivateIgnoringOtherApps))?'sent':'refused';}`;
104
+ const result = await exec("/usr/bin/osascript", ["-l", "JavaScript", "-e", script, String(info.pid), info.identity, info.app, action], { ...runOptions, timeout: 5000, maxBuffer: 4096 });
105
+ return String(result.stdout).trim();
106
+ }
107
+ if (platform === "win32") {
108
+ const script = action === "focus" ? `$w=New-Object -ComObject WScript.Shell;if($w.AppActivate(${info.pid})){'sent'}else{'refused'}`
109
+ : `$p=Get-Process -Id ${info.pid} -ErrorAction SilentlyContinue;if(!$p){'absent'}elseif($p.CloseMainWindow()){'sent'}else{'refused'}`;
110
+ const result = await exec("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], { ...runOptions, env });
111
+ return String(result.stdout).trim();
112
+ }
113
+ return "unsupported";
114
+ }
@@ -14,6 +14,7 @@ import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
14
14
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
15
15
  import { decodedBodyLimitPreference } from "./user-settings.mjs";
16
16
  import { operationErrorDetails, transportErrorDetails } from "./operation-error.mjs";
17
+ import { observeSourceStreamFailure } from "./source-admission.mjs";
17
18
  import { requestApplication } from "./request-application.mjs";
18
19
  import { observeContextSession } from "./context-metrics.mjs";
19
20
  import { catalogCapabilities } from "./model-capabilities.mjs";
@@ -23,6 +24,8 @@ import { MESSAGES_TOOL_GUARD } from "./messages-tool-schema.mjs";
23
24
  import { isCompactionRequest, compactionScope } from "./context-compaction.mjs";
24
25
  import { compactionSummarizer } from "./context-compaction-wire.mjs";
25
26
  import { requestPurpose } from "./request-context.mjs";
27
+ import { messagesWithEffortDefault } from "./client-effort.mjs";
28
+ import { sourceResponseReader, observeSourceRead, failSourceRead, cancelSourceReader, releaseSourceReader, cancelSourceResponse, sourceResponseAccepted } from "./source-response.mjs";
26
29
 
27
30
  function observeMessagesWindow(provider, model, capability, entry) {
28
31
  try {
@@ -47,11 +50,12 @@ const MAX_TERMINAL_DRAIN_BYTES = 64 * 1024;
47
50
  const TERMINAL_DRAIN_TIMEOUT_MS = 1000;
48
51
  async function drainAfterMessageStop(reader) {
49
52
  let bytes = 0, ended = false;
50
- const cancel = () => { try { void reader.cancel().catch(() => {}); } catch {} };
53
+ const cancel = () => { try { void cancelSourceReader(reader).catch(() => {}); } catch {} };
51
54
  const timer = setTimeout(cancel, TERMINAL_DRAIN_TIMEOUT_MS);timer.unref?.();
52
55
  try {
53
56
  while (true) {
54
- const { done, value } = await reader.read();
57
+ let next;try { next = await reader.read(); } catch (error) { failSourceRead(reader);throw error; }
58
+ observeSourceRead(reader, next);const { done, value } = next;
55
59
  if (done) { ended = true;break; }
56
60
  bytes += value.byteLength;
57
61
  if (bytes > MAX_TERMINAL_DRAIN_BYTES) break;
@@ -59,7 +63,7 @@ async function drainAfterMessageStop(reader) {
59
63
  } catch { /* The response has already ended for the client. */ }
60
64
  finally {
61
65
  clearTimeout(timer);if (!ended) cancel();
62
- try { reader.releaseLock(); } catch {}
66
+ try { releaseSourceReader(reader); } catch {}
63
67
  }
64
68
  }
65
69
  const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
@@ -233,8 +237,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
233
237
  const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, purpose, application: requestApplication(req.headers, "claude") });
234
238
  if (!resolveRequest) tracker?.setProvider(provider.id);
235
239
  const abort = createRequestAbort(req, res);
236
- let release = () => {}, conversation, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
237
- let selectedModel, selectedCapability;
240
+ let release = () => {}, conversation, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false, deliveryCancelled = false;
241
+ let selectedModel, selectedCapability, selectedEffortDefault;
238
242
  let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
239
243
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
240
244
  const context = parent || { requestId, purpose: req.headers["x-ccdx-purpose"] };
@@ -259,6 +263,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
259
263
  selectedProvider = resolved.provider;finishProvider = resolved.finish || finishProvider;
260
264
  configuredModel = resolved.model;clientModel = body.model === configuredModel ? null : body.model;
261
265
  selectedCapability = resolved.capability;
266
+ selectedEffortDefault = resolved.effortDefault;
262
267
  body = { ...body, model: configuredModel };tracker?.setProvider(selectedProvider.id);
263
268
  const context = currentRequestContext();if (context) context.provider = selectedProvider.id;
264
269
  }
@@ -271,10 +276,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
271
276
  }
272
277
  if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
273
278
  if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
279
+ const requestedEffort = body.output_config?.effort;
280
+ if (!countTokens) body = messagesWithEffortDefault(body, selectedEffortDefault, selectedCapability);
274
281
  stats.last_model = model;
275
282
  context.model = configuredModel || model;
276
283
  if (!countTokens) {
277
- markRequestObservation({ max_output_tokens_requested: body.max_tokens, reasoning_effort_requested: body.output_config?.effort });
284
+ markRequestObservation({ max_output_tokens_requested: body.max_tokens, reasoning_effort_requested: requestedEffort });
278
285
  observeMessagesWindow(selectedProvider, configuredModel || model, selectedCapability, selectedModel);
279
286
  }
280
287
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
@@ -291,7 +298,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
291
298
  } : selectedProvider.client.messages;
292
299
  const call = privacy?.wrap(sourceCall, { res, protocol: "messages", client: privacyClient }) || sourceCall;
293
300
  let upstreamHeadersObserved = false;
294
- const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
301
+ const callOptions = { headers: req.headers, countTokens, signal: abort.signal, sourceBodyManaged: true,
295
302
  onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
296
303
  onCountObservation(value) {
297
304
  context.countObservation = { ...context.countObservation, ...value };
@@ -318,7 +325,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
318
325
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
319
326
  if (!upstreamHeadersObserved) tracker?.upstreamHeaders(upstream.status);
320
327
  release();release = () => {};
321
- try { onRequest({ client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude" }); } catch {}
328
+ try { onRequest({ client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude" }, req); } catch {}
322
329
  const headers = safeUpstreamResponseHeaders(upstream.headers);
323
330
  for (const [name, value] of upstream.headers) if (/^anthropic-ratelimit-[a-z0-9-]+$/.test(name)) headers[name] = value;
324
331
  if (!upstream.ok || !streamed) {
@@ -331,6 +338,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
331
338
  && ["code", "type", "message"].some(key => typeof value.error[key] === "string" && value.error[key].trim())
332
339
  && !["content", "output", "choices", "candidates"].some(key => Array.isArray(value[key]) && value[key].length);
333
340
  if (modelFailure) {
341
+ observeSourceStreamFailure(upstream, value.error);
334
342
  const evidence = upstreamErrorEvidence(raw);
335
343
  context.onHttpError?.({ ...evidence, code: evidence.code || evidence.error_type || "upstream_error", model_error: true, origin: "upstream_response", headers: upstream.headers });
336
344
  }
@@ -346,7 +354,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
346
354
  const outgoing = clientModel && !countTokens && upstream.ok && value?.type === "message" ? JSON.stringify({ ...value, model: clientModel }) : raw;
347
355
  if (!res.destroyed && !res.writableEnded) { res.writeHead(upstream.status, headers);res.end(outgoing); }
348
356
  } else {
349
- if (!/^text\/event-stream(?:\s*;|$)/i.test(upstream.headers.get("content-type") || "")) throw new Error("Expected a Claude event stream");
357
+ if (!/^text\/event-stream(?:\s*;|$)/i.test(upstream.headers.get("content-type") || "")) { await cancelSourceResponse(upstream).catch(() => {});throw new Error("Expected a Claude event stream"); }
350
358
  abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
351
359
  res.writeHead(upstream.status, { ...headers, "Cache-Control": "no-cache" });
352
360
  let commitState = null, conversationCommitted = false;
@@ -359,6 +367,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
359
367
  };
360
368
  const observe = event => {
361
369
  if (event.type === "error") {
370
+ observeSourceStreamFailure(upstream, event.error);
362
371
  failedEvent = true;outcome = "failed";
363
372
  const evidence = upstreamErrorEvidence(JSON.stringify(event));
364
373
  context.onHttpError?.({ ...evidence, code: evidence.code || evidence.error_type || "upstream_error", model_error: true, origin: "upstream_event", headers: upstream.headers });return;
@@ -375,16 +384,17 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
375
384
  usage = { ...usage, ...Object.fromEntries(Object.entries(event.usage || {}).filter(([, value]) => value != null)) };
376
385
  stopReason = event.delta?.stop_reason || stopReason;
377
386
  }
378
- if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
387
+ if (event.type === "message_stop") { sawStop = true;sourceResponseAccepted(upstream);outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
379
388
  };
380
389
  const observer = toolGuard
381
390
  ? createGuardedMessagesObserver(observe, config.maxSseBufferBytes, clientModel, toolGuard, restoreToolInput)
382
391
  : createMessagesObserver(observe, config.maxSseBufferBytes, clientModel);
383
- const reader = upstream.body.getReader();
392
+ const reader = sourceResponseReader(upstream);
384
393
  let draining = false;
385
394
  try {
386
395
  while (true) {
387
- const { value, done } = await reader.read();if (done) break;
396
+ let next;try { next = await reader.read(); } catch (error) { failSourceRead(reader);throw error; }
397
+ observeSourceRead(reader, next);const { value, done } = next;if (done) break;
388
398
  tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
389
399
  const frames = observer.write(value);
390
400
  await commitOutput();
@@ -401,23 +411,26 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
401
411
  draining = true;void drainAfterMessageStop(reader);
402
412
  }
403
413
  } finally {
404
- if (!draining) { await reader.cancel().catch(() => {});reader.releaseLock(); }
414
+ if (!draining) { await cancelSourceReader(reader).catch(() => {});releaseSourceReader(reader); }
405
415
  }
406
416
  }
407
417
  } catch (error) {
408
418
  rejectionReason = error.jsonBody?.error?.reason || (error.code === "ccdx_client_source_disabled" ? error.code : undefined);
409
419
  const detail = operationErrorDetails(error, { reason: abort.reason });
410
- outcome = detail.source === "cancelled" ? "cancelled" : "failed";
420
+ deliveryCancelled = detail.source === "cancelled";
421
+ if (deliveryCancelled) markRequestObservation({ delivery_cancelled: 1 });
422
+ if (!deliveryCancelled || !sawStop || failedEvent) outcome = deliveryCancelled ? "cancelled" : "failed";
411
423
  const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
412
- failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : error.origin === "privacy" ? "privacy" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
424
+ failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : ["privacy", "source_admission"].includes(error.origin) ? error.origin : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
413
425
  context.errorOrigin = terminalOrigin;
414
426
  const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
415
427
  const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
416
428
  log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
417
429
  tracker?.setErrorOrigin(terminalOrigin);
418
430
  context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
419
- if (outcome === "cancelled") return;
431
+ if (deliveryCancelled) return;
420
432
  if (!res.headersSent) {
433
+ if (Number.isFinite(error.retryAfterMs) && error.retryAfterMs > 0) res.setHeader("Retry-After", String(Math.ceil(error.retryAfterMs / 1000)));
421
434
  if (typeof error.code === "string" && error.code.startsWith("ccdx_compaction_")) res.setHeader("x-should-retry", "false");
422
435
  if (error.origin === "privacy" && Number.isInteger(error.retryAfter) && error.retryAfter > 0) res.setHeader("Retry-After", String(error.retryAfter));
423
436
  const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
@@ -436,7 +449,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
436
449
  cached_input_tokens: usageRecord?.usage?.cached_input_tokens });
437
450
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
438
451
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, stopReason, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
439
- tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode, rejectionReason });
452
+ tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled" || deliveryCancelled, aborted: deliveryCancelled, statusCode: failureStatus || res.statusCode, rejectionReason });
440
453
  try { void Promise.resolve(record(usageRecord)).catch(() => {}); } catch {}
441
454
  }
442
455
  }
@@ -57,7 +57,7 @@ export const MANAGED_COMMANDS = [
57
57
  ),
58
58
  command("source list", "List registered model sources", read),
59
59
  command("source import", "Preview supplied CCDX, CC Switch or Magpie API metadata; apply one explicitly", {
60
- ...read, "--file": "value", "--select": "integer", "--apply": "flag", "--key-stdin": "flag", ...confirm,
60
+ ...read, "--file": "value", "--from": "value", "--select": "integer", "--apply": "flag", "--key-stdin": "flag", ...confirm,
61
61
  }),
62
62
  command("source add", "Save an API and read its model catalog", {
63
63
  "--file": "value",
@@ -70,6 +70,7 @@ export const MANAGED_COMMANDS = [
70
70
  "--refresh": "flag",
71
71
  }),
72
72
  command("source <source> check", "Check source access without inference", read),
73
+ command("source <source> limits", "Read adaptive source concurrency or set a ceiling", { ...read, ...confirm, "--max": "value", "--edit": "flag" }),
73
74
  command("source <source> edit", "Edit API configuration and model selection", {
74
75
  "--file": "value",
75
76
  "--key-stdin": "flag",
@@ -112,6 +113,8 @@ export const MANAGED_COMMANDS = [
112
113
  ...["gemini", "antigravity"].flatMap(app => ["status", "models", "enable", "disable", "open"].map(action => command(`app ${app} ${action}`,
113
114
  ({status:"Inspect Gemini App and Antigravity setup",models:"List compatible Copilot models for Antigravity",enable:"Enable Antigravity routing and Copilot background requests",disable:"Pause Antigravity Copilot access; reopen Gemini for native routing",open:"Open the original Gemini App with its prepared route"})[action], {...read,...confirm,...(action==="models"?{"--edit":"flag","--file":"value","--refresh":"flag"}:{})}))),
114
115
  command("app <app> status", "Show configuration, not process liveness", { ...read, "--details": "flag" }),
116
+ ...["open", "focus", "restart", "check"].map(action => command(`app <app> ${action}`, ({ open: "Open the native app or focus its current process", focus: "Focus the current app without relaunching", restart: "Confirm and gracefully reopen the app", check: "Inspect the current app without inference or writes" })[action], { ...read, ...confirm })),
117
+ ...["focus", "restart", "check"].map(action => command(`app antigravity ${action}`, "Control or inspect the current Antigravity app", { ...read, ...confirm })),
115
118
  command("app <app> models", "Show or edit the client's selected model plan", {
116
119
  ...read,
117
120
  "--edit": "flag",
@@ -287,8 +290,8 @@ export function parseManagedCommand(args) {
287
290
 
288
291
  const extras = {
289
292
  source:
290
- "Status reads local/cached evidence. check/--refresh may contact the source; no inference.\nsource import --file FILE previews supplied metadata. --select N --apply saves one source using private key input; no client access is granted.\nSource access grants do not select client models. Disable previews affected clients.\nGitHub login and company-account selection are source-specific.\nChoose visible models and defaults with app <app> models --edit.",
291
- app: "Configured is not App adoption or process liveness. Unknown stays unknown.\nmodels shows the selected plan; Antigravity lists compatible Copilot models and their selection.\napp antigravity models --refresh reads the GitHub catalog without inference or changing saved choices.\nsource <id> models shows the upstream catalog.\nsetup/remove changes integration setup; pause/resume retains credentials.\nsync --preview shows the model/configuration plan, not a byte-level file diff.\nNo client program is force-restarted.",
293
+ "Status reads local/cached evidence. check/--refresh may contact the source; no inference.\nsource import --file FILE previews supplied metadata; --from cc-switch|magpie reads known local configuration on demand.\n--select N --apply saves one source using private key input; no client access is granted.\nSource access grants do not select client models. Disable previews affected clients.\nGitHub login and company-account selection are source-specific.\nChoose visible models and defaults with app <app> models --edit.",
294
+ app: "Configured is not App adoption or process liveness. Unknown stays unknown.\nmodels shows the selected plan; Antigravity lists compatible Copilot models and their selection.\napp antigravity models --refresh reads the GitHub catalog without inference or changing saved choices.\nsource <id> models shows the upstream catalog.\nsetup/remove changes integration setup; pause/resume retains credentials.\nsync --preview shows the model/configuration plan, not a byte-level file diff.\nopen focuses an already-running app; check is read-only and sends no inference.\nrestart asks before a graceful reopen. No client program is force-restarted.",
292
295
  config:
293
296
  "Only service and terminal preferences are in scope. Browser appearance stays in WebUI.\nReset keeps accounts, keys, model plans and chats and stores a pre-reset backup.\nSaved and effective values can differ; restart requirements remain explicit.",
294
297
  requests:
@@ -336,5 +339,5 @@ export function managedCommandHelp(parts) {
336
339
  );
337
340
  }
338
341
  export function rootCommandHelp() {
339
- return `Usage:\n ccdx [start] [--show-request-id] [--no-browser] [--verbose]\n\nCommon:\n status Show service state; --details expands diagnostics\n web Open local management tools\n requests Show retained model requests and failures\n usage Show recorded token usage\n compact Inspect and control context compression\n doctor Check local setup; deeper checks are explicit\n\nManage:\n source Accounts, APIs, catalogs and client authorization\n app Client model plans, sync and app-specific features\n config Service and terminal preferences\n\nUpdate:\n update check Check without installing\n update github|npm Install; restart the service normally afterward\n version Show installed package version\n\nHelp:\n ccdx <command> --help\n ccdx help app codex prediction\n\nStart keeps the existing configured-client setup and launch behavior.\nCLI output stays in English. Read-only commands do not start a service.`;
342
+ return `Usage:\n ccdx [start] [--show-request-id] [--no-browser] [--verbose]\n\nCommon:\n status Show service state; --details expands diagnostics\n web Open local management tools\n requests Show retained model requests and failures\n usage Show recorded token usage\n compact Inspect and control context compression\n doctor Check local setup; deeper checks are explicit\n\nManage:\n source Accounts, APIs, catalogs and client authorization\n app Client model plans, sync and app-specific features\n config Service and terminal preferences\n\nUpdate:\n update check Check without installing\n update github|npm Install; restart the service normally afterward\n version Show installed package version\n\nHelp:\n ccdx <command> --help\n ccdx help app codex prediction\n\nStart preserves owned client setup. Automatic Codex opening is off by default; enable it on the Codex page or with config set codex_auto_launch true.\nCLI output stays in English. Read-only commands do not start a service.`;
340
343
  }