codex-copilot-dx 1.4.4 → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +2 -1
  2. package/bin/cli.mjs +5 -4
  3. package/docs/ARCHITECTURE.md +16 -0
  4. package/docs/REFERENCE.md +34 -8
  5. package/package.json +1 -1
  6. package/src/access-settings.mjs +3 -1
  7. package/src/adapter.mjs +9 -1
  8. package/src/antigravity-chat-bridge.mjs +4 -2
  9. package/src/antigravity-handler.mjs +28 -16
  10. package/src/antigravity-images.mjs +3 -2
  11. package/src/antigravity-runtime.mjs +13 -3
  12. package/src/application-configuration.mjs +43 -0
  13. package/src/application-control.mjs +114 -0
  14. package/src/application-evidence.mjs +42 -0
  15. package/src/application-process.mjs +114 -0
  16. package/src/claude-gateway.mjs +24 -15
  17. package/src/cli-command-spec.mjs +7 -4
  18. package/src/cli-management.mjs +27 -2
  19. package/src/codex-image-host-launch.mjs +1 -2
  20. package/src/codex-launch-control.mjs +7 -7
  21. package/src/connection-management.mjs +18 -3
  22. package/src/connection-policy.mjs +3 -1
  23. package/src/connection-routing.mjs +7 -2
  24. package/src/connection-runtime.mjs +21 -5
  25. package/src/connection-view.mjs +9 -3
  26. package/src/context-compaction-wire.mjs +7 -6
  27. package/src/context-compaction.mjs +6 -4
  28. package/src/copilot-client.mjs +17 -13
  29. package/src/copilot-responses-compat.mjs +1 -0
  30. package/src/copilot-web.mjs +6 -2
  31. package/src/dashboard/applications.js +83 -0
  32. package/src/dashboard/connections.js +52 -14
  33. package/src/dashboard/console.js +19 -9
  34. package/src/dashboard/gemini.js +8 -5
  35. package/src/dashboard/index.html +16 -0
  36. package/src/dashboard/language.js +41 -0
  37. package/src/dashboard/ui.css +9 -0
  38. package/src/dashboard-api.mjs +6 -1
  39. package/src/dashboard.mjs +1 -0
  40. package/src/gemini-app.mjs +3 -2
  41. package/src/http-transport.mjs +5 -2
  42. package/src/launcher.mjs +6 -5
  43. package/src/native-images.mjs +1 -1
  44. package/src/provider-runtime.mjs +14 -9
  45. package/src/providers/api.mjs +18 -12
  46. package/src/providers/m365.mjs +9 -5
  47. package/src/request-admission.mjs +6 -0
  48. package/src/responses-bridge.mjs +5 -2
  49. package/src/responses-handler.mjs +2 -0
  50. package/src/responses-proxy.mjs +9 -4
  51. package/src/safe-upstream-error.mjs +9 -11
  52. package/src/service-control.mjs +29 -5
  53. package/src/settings-preferences.mjs +3 -3
  54. package/src/source-admission-state.mjs +29 -0
  55. package/src/source-admission.mjs +310 -0
  56. package/src/source-discovery-probe.mjs +35 -0
  57. package/src/source-discovery.mjs +112 -0
  58. package/src/source-response.mjs +134 -0
  59. package/src/source-transport.mjs +19 -0
  60. package/src/stream-contract.mjs +3 -1
  61. package/src/stream-performance.mjs +3 -1
  62. package/src/stream.mjs +6 -4
  63. package/src/upstream-body.mjs +9 -8
  64. package/src/user-settings.mjs +2 -2
@@ -0,0 +1,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";
@@ -24,6 +25,7 @@ import { isCompactionRequest, compactionScope } from "./context-compaction.mjs";
24
25
  import { compactionSummarizer } from "./context-compaction-wire.mjs";
25
26
  import { requestPurpose } from "./request-context.mjs";
26
27
  import { messagesWithEffortDefault } from "./client-effort.mjs";
28
+ import { sourceResponseReader, observeSourceRead, failSourceRead, cancelSourceReader, releaseSourceReader, cancelSourceResponse, sourceResponseAccepted } from "./source-response.mjs";
27
29
 
28
30
  function observeMessagesWindow(provider, model, capability, entry) {
29
31
  try {
@@ -48,11 +50,12 @@ const MAX_TERMINAL_DRAIN_BYTES = 64 * 1024;
48
50
  const TERMINAL_DRAIN_TIMEOUT_MS = 1000;
49
51
  async function drainAfterMessageStop(reader) {
50
52
  let bytes = 0, ended = false;
51
- const cancel = () => { try { void reader.cancel().catch(() => {}); } catch {} };
53
+ const cancel = () => { try { void cancelSourceReader(reader).catch(() => {}); } catch {} };
52
54
  const timer = setTimeout(cancel, TERMINAL_DRAIN_TIMEOUT_MS);timer.unref?.();
53
55
  try {
54
56
  while (true) {
55
- 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;
56
59
  if (done) { ended = true;break; }
57
60
  bytes += value.byteLength;
58
61
  if (bytes > MAX_TERMINAL_DRAIN_BYTES) break;
@@ -60,7 +63,7 @@ async function drainAfterMessageStop(reader) {
60
63
  } catch { /* The response has already ended for the client. */ }
61
64
  finally {
62
65
  clearTimeout(timer);if (!ended) cancel();
63
- try { reader.releaseLock(); } catch {}
66
+ try { releaseSourceReader(reader); } catch {}
64
67
  }
65
68
  }
66
69
  const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
@@ -234,7 +237,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
234
237
  const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, purpose, application: requestApplication(req.headers, "claude") });
235
238
  if (!resolveRequest) tracker?.setProvider(provider.id);
236
239
  const abort = createRequestAbort(req, res);
237
- let release = () => {}, conversation, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
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;
238
241
  let selectedModel, selectedCapability, selectedEffortDefault;
239
242
  let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
240
243
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
@@ -295,7 +298,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
295
298
  } : selectedProvider.client.messages;
296
299
  const call = privacy?.wrap(sourceCall, { res, protocol: "messages", client: privacyClient }) || sourceCall;
297
300
  let upstreamHeadersObserved = false;
298
- const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
301
+ const callOptions = { headers: req.headers, countTokens, signal: abort.signal, sourceBodyManaged: true,
299
302
  onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
300
303
  onCountObservation(value) {
301
304
  context.countObservation = { ...context.countObservation, ...value };
@@ -322,7 +325,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
322
325
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
323
326
  if (!upstreamHeadersObserved) tracker?.upstreamHeaders(upstream.status);
324
327
  release();release = () => {};
325
- 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 {}
326
329
  const headers = safeUpstreamResponseHeaders(upstream.headers);
327
330
  for (const [name, value] of upstream.headers) if (/^anthropic-ratelimit-[a-z0-9-]+$/.test(name)) headers[name] = value;
328
331
  if (!upstream.ok || !streamed) {
@@ -335,6 +338,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
335
338
  && ["code", "type", "message"].some(key => typeof value.error[key] === "string" && value.error[key].trim())
336
339
  && !["content", "output", "choices", "candidates"].some(key => Array.isArray(value[key]) && value[key].length);
337
340
  if (modelFailure) {
341
+ observeSourceStreamFailure(upstream, value.error);
338
342
  const evidence = upstreamErrorEvidence(raw);
339
343
  context.onHttpError?.({ ...evidence, code: evidence.code || evidence.error_type || "upstream_error", model_error: true, origin: "upstream_response", headers: upstream.headers });
340
344
  }
@@ -350,7 +354,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
350
354
  const outgoing = clientModel && !countTokens && upstream.ok && value?.type === "message" ? JSON.stringify({ ...value, model: clientModel }) : raw;
351
355
  if (!res.destroyed && !res.writableEnded) { res.writeHead(upstream.status, headers);res.end(outgoing); }
352
356
  } else {
353
- 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"); }
354
358
  abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
355
359
  res.writeHead(upstream.status, { ...headers, "Cache-Control": "no-cache" });
356
360
  let commitState = null, conversationCommitted = false;
@@ -363,6 +367,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
363
367
  };
364
368
  const observe = event => {
365
369
  if (event.type === "error") {
370
+ observeSourceStreamFailure(upstream, event.error);
366
371
  failedEvent = true;outcome = "failed";
367
372
  const evidence = upstreamErrorEvidence(JSON.stringify(event));
368
373
  context.onHttpError?.({ ...evidence, code: evidence.code || evidence.error_type || "upstream_error", model_error: true, origin: "upstream_event", headers: upstream.headers });return;
@@ -379,16 +384,17 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
379
384
  usage = { ...usage, ...Object.fromEntries(Object.entries(event.usage || {}).filter(([, value]) => value != null)) };
380
385
  stopReason = event.delta?.stop_reason || stopReason;
381
386
  }
382
- 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"; }
383
388
  };
384
389
  const observer = toolGuard
385
390
  ? createGuardedMessagesObserver(observe, config.maxSseBufferBytes, clientModel, toolGuard, restoreToolInput)
386
391
  : createMessagesObserver(observe, config.maxSseBufferBytes, clientModel);
387
- const reader = upstream.body.getReader();
392
+ const reader = sourceResponseReader(upstream);
388
393
  let draining = false;
389
394
  try {
390
395
  while (true) {
391
- 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;
392
398
  tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
393
399
  const frames = observer.write(value);
394
400
  await commitOutput();
@@ -405,23 +411,26 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
405
411
  draining = true;void drainAfterMessageStop(reader);
406
412
  }
407
413
  } finally {
408
- if (!draining) { await reader.cancel().catch(() => {});reader.releaseLock(); }
414
+ if (!draining) { await cancelSourceReader(reader).catch(() => {});releaseSourceReader(reader); }
409
415
  }
410
416
  }
411
417
  } catch (error) {
412
418
  rejectionReason = error.jsonBody?.error?.reason || (error.code === "ccdx_client_source_disabled" ? error.code : undefined);
413
419
  const detail = operationErrorDetails(error, { reason: abort.reason });
414
- 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";
415
423
  const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
416
- 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";
417
425
  context.errorOrigin = terminalOrigin;
418
426
  const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
419
427
  const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
420
428
  log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
421
429
  tracker?.setErrorOrigin(terminalOrigin);
422
430
  context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
423
- if (outcome === "cancelled") return;
431
+ if (deliveryCancelled) return;
424
432
  if (!res.headersSent) {
433
+ if (Number.isFinite(error.retryAfterMs) && error.retryAfterMs > 0) res.setHeader("Retry-After", String(Math.ceil(error.retryAfterMs / 1000)));
425
434
  if (typeof error.code === "string" && error.code.startsWith("ccdx_compaction_")) res.setHeader("x-should-retry", "false");
426
435
  if (error.origin === "privacy" && Number.isInteger(error.retryAfter) && error.retryAfter > 0) res.setHeader("Retry-After", String(error.retryAfter));
427
436
  const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
@@ -440,7 +449,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
440
449
  cached_input_tokens: usageRecord?.usage?.cached_input_tokens });
441
450
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
442
451
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, stopReason, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
443
- 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 });
444
453
  try { void Promise.resolve(record(usageRecord)).catch(() => {}); } catch {}
445
454
  }
446
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
  }
@@ -218,6 +218,17 @@ export async function runManagementCommand(command, options = {}) {
218
218
  writeSettingsPreferences(body, preferenceOptions);return print({ saved: settingsPreferencesSnapshot(preferenceOptions).values, effect: "Saved for the next CCDX start; no service was started" });
219
219
  }
220
220
  if (group === "app") {
221
+ if (path.length === 3 && ["open", "focus", "restart", "check"].includes(action)) {
222
+ const id = ["antigravity", "gemini"].includes(path[1]) ? "antigravity" : CLI_CLIENTS[ids.app || path[1]];
223
+ if (!["codex", "claude_app", "antigravity"].includes(id)) throw new Error("This command opens desktop apps. Run Claude Code in your terminal.");
224
+ const settings = await request({ path: "settings?application=" + id + "&fresh=1", timeoutMs: 15000 }), app = settings.applications?.[id];
225
+ if (!app) throw new Error("This command needs the updated running service; no app was changed.");
226
+ if (action === "check" || flags.preview) return print({ id, ...app, ...(flags.preview ? { action, performed: false } : {}) });
227
+ if (action === "restart") await confirm("Reopen " + path[1] + "? This may interrupt its current tasks.");
228
+ const result = await request({ path: "settings", body: { action: "application", id, operation: action,
229
+ ...(action === "restart" ? { confirmed: true, ...(app.pid ? { expected_pid: app.pid, expected_started: app.started } : {}) } : {}) }, timeoutMs: 65000 });
230
+ return print(result.last_operation?.result || result.applications?.[id]);
231
+ }
221
232
  if (["gemini", "antigravity"].includes(path[1])) {
222
233
  if (["enable", "disable"].includes(action)) {
223
234
  const preview = { action, background_source: "GitHub Copilot (all Antigravity summaries, searches and image generation)", ordinary_Gemini_chat: "Google; no routing change" };
@@ -352,8 +363,11 @@ export async function runManagementCommand(command, options = {}) {
352
363
  }
353
364
  if (group !== "source") throw new Error("Unknown management command.");
354
365
  if (action === "import") {
355
- if (!flags.file) throw new Error("Supply one explicit JSON file with --file.");
356
- const preview = previewSourceImport(readFile(), readAccessSettings(options).apis);
366
+ if (Boolean(flags.file) === Boolean(flags.from)) throw new Error("Use --file FILE or --from cc-switch|magpie.");
367
+ if (flags.from && !["cc-switch", "magpie"].includes(flags.from)) throw new Error("Choose --from cc-switch or --from magpie.");
368
+ const existing = readAccessSettings(options).apis;
369
+ const preview = flags.from ? await (await import("./source-discovery.mjs")).discoverSourceImport(flags.from, options, existing)
370
+ : previewSourceImport(readFile(), existing);
357
371
  if (!flags.apply || flags.preview) return print(preview);
358
372
  const selected = preview.drafts[(flags.select || 0) - 1];
359
373
  if (!selected) throw new Error("Review the preview, then use --select NUMBER --apply for one source.");
@@ -373,6 +387,17 @@ export async function runManagementCommand(command, options = {}) {
373
387
  if (!flags.preview && (flags.edit || ["add", "edit", "enable", "disable", "remove"].includes(action))) requireManagement();
374
388
  if (action === "list") return print(graph.providers.map(source => ({ id: source.id, name: source.name, enabled: source.enabled, key_saved: source.builtin ? undefined : source.key_saved })), [["id", "ID"], ["name", "Source"], ["enabled", "Enabled"]]);
375
389
  const id = ids.source, source = id ? getSource(graph, id) : null;
390
+ if (action === "limits") {
391
+ let value = flags.max;
392
+ if (flags.edit && value === undefined) value = (await ask("Maximum concurrency (auto, or 1–128; Enter keeps selection): ")).trim() || (source.concurrency?.maximum ?? "auto");
393
+ if (value === undefined) return print(source.concurrency || { mode: "auto", maximum: null });
394
+ const maximum = value === "auto" ? null : Number(value);
395
+ if (maximum !== null && (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 128)) throw new Error("Choose auto or an integer from 1 to 128.");
396
+ if (flags.preview) return print({ id, mode: "auto", maximum, saved: false });
397
+ await confirm("Save this source's adaptive concurrency ceiling?");
398
+ const next = await save({ operation: "source_limits", id, maximum, impact_revision: graph.source_impacts?.[id]?.revision });
399
+ return print(getSource(next, id).concurrency);
400
+ }
376
401
  if (action === "status" || action === "models" && !flags.refresh) {
377
402
  if (action === "models" && source.builtin) {
378
403
  return print(await save({ operation: "source_catalog", id }));
@@ -6,7 +6,6 @@ import { fileURLToPath } from "node:url";
6
6
  import { userSettingsPath, servicePreferences } from "./user-settings.mjs";
7
7
  import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
8
8
  import { installedPredictionApp } from "./native-prediction-app.mjs";
9
- import { autoLaunchEnabled } from "./launcher.mjs";
10
9
  import { adapterBaseUrl } from "./running-adapter.mjs";
11
10
 
12
11
  const execute = promisify(execFile);
@@ -20,7 +19,7 @@ export function imageHostLauncherPath(options = {}) {
20
19
  export async function prepareImageHostLaunch({ env = process.env, home, platform = process.platform, host = "127.0.0.1", port = 2026,
21
20
  discoverApp = installedPredictionApp, exec = execute, node = process.execPath,
22
21
  entry = fileURLToPath(new URL("../bin/codex-image-host.mjs", import.meta.url)) } = {}) {
23
- if (platform !== "darwin" || !autoLaunchEnabled(env) || !servicePreferences({ env, home }).image_enabled) return null;
22
+ if (platform !== "darwin" || !servicePreferences({ env, home }).image_enabled) return null;
24
23
  const wrapper = imageHostLauncherPath({ env, home });
25
24
  if (env.CODEX_CLI_PATH?.trim() && path.resolve(env.CODEX_CLI_PATH) !== wrapper) throw new Error("A custom Codex CLI route is already configured; image host setup was preserved");
26
25
  const app = await discoverApp({ env, platform });
@@ -34,8 +34,8 @@ export async function controlCodexLaunch(operation, { intent = "image", integrat
34
34
  prepare = prepareImageHostLaunch, launch = openCodex, readSummary = imageSetupSummary,
35
35
  readPrediction = predictionControlSnapshot, nativeOperation = runPredictionOperation,
36
36
  discover = installedPredictionApp, inspect = inspectCodexApp, appControl = controlCodexApp,
37
- confirmed = false, wait = sleep, now = Date.now, quitTimeoutMs = 10000, ...options } = {}) {
38
- if (!["check", "repair", "open", "focus", "restart"].includes(operation) || !["image", "prediction"].includes(intent)) throw new Error("Unknown Codex App control");
37
+ confirmed = false, configureClient = true, wait = sleep, now = Date.now, quitTimeoutMs = 10000, ...options } = {}) {
38
+ if (!["check", "repair", "open", "focus", "restart"].includes(operation) || !["image", "prediction", "app"].includes(intent)) throw new Error("Unknown Codex App control");
39
39
  if (operation === "restart" && confirmed !== true) throw new Error("Confirm that restarting Codex can interrupt its running tasks");
40
40
  const platform = options.platform || process.platform;
41
41
  let image, prediction;
@@ -73,9 +73,9 @@ export async function controlCodexLaunch(operation, { intent = "image", integrat
73
73
  if (intent === "image" && !image.enabled) throw new Error("Enable images before repairing image access");
74
74
  if (intent === "prediction" && !prediction.configured && !prediction.display_pending) throw new Error("Enable predictions before opening Codex");
75
75
  const env = { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" };
76
- await integration.configure();
76
+ if (configureClient) await integration.configure();
77
77
  let imageHost = null, imagePrepFailed = false, imageWarning = intent === "prediction" && image.enabled && (!image.configured || !image.selected_available);
78
- if (image.enabled) {
78
+ if (image.enabled && (intent !== "app" || image.configured && image.selected_available)) {
79
79
  try { imageHost = await prepare({ ...options, env, host, port }); }
80
80
  catch (error) { if (intent === "image") throw error;imageWarning = true;imagePrepFailed = true; }
81
81
  if (!imageHost) { if (intent === "image") return { status: "unsupported", prepared: false };imageWarning = true;imagePrepFailed = true; }
@@ -94,9 +94,9 @@ export async function controlCodexLaunch(operation, { intent = "image", integrat
94
94
  if (operation === "restart" && current.status === "running" && !current.needs_restart) return { status: "already_connected", prepared: true, app: publicAppState(current) };
95
95
  // Never lose a currently connected image host due to a failed preparation.
96
96
  if (imagePrepFailed && current.status === "running" && current.host === "connected") return { status: "image_unavailable", prepared: true, app: publicAppState(current) };
97
- const native = await integration.start();
98
- if (prediction.status === "unavailable") return { status: "prediction_unavailable", prepared: true, app: publicAppState(current) };
99
- if (!native && prediction.configured && prediction.enabled) return { status: "prediction_unavailable", prepared: true, app: publicAppState(current) };
97
+ const native = await integration.start({ autoSetup: intent !== "app" });
98
+ if (intent !== "app" && prediction.status === "unavailable") return { status: "prediction_unavailable", prepared: true, app: publicAppState(current) };
99
+ if (intent !== "app" && !native && prediction.configured && prediction.enabled) return { status: "prediction_unavailable", prepared: true, app: publicAppState(current) };
100
100
  await native?.prepareRoute?.();
101
101
  if (native?.pacUrl && native.app && native.app !== app) return { status: "app_route_conflict", prepared: true };
102
102
  if (operation === "restart") {