agentroam 0.2.0-preview.8 → 0.2.0-preview.80

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 (95) hide show
  1. package/README.md +61 -15
  2. package/bin/agentroam.mjs +10 -1
  3. package/bin/cli-progress.d.mts +9 -0
  4. package/bin/cli-progress.mjs +65 -0
  5. package/bin/desktop-download.mjs +69 -0
  6. package/bin/node-preflight.mjs +171 -0
  7. package/bin/node-runtime-policy.json +4 -0
  8. package/bin/runtime-policy.d.mts +5 -0
  9. package/bin/runtime-policy.mjs +37 -0
  10. package/dist/abort.js +25 -0
  11. package/dist/args.js +136 -5
  12. package/dist/cli.js +295 -44
  13. package/dist/cloudflared/bundled-asset.js +3 -2
  14. package/dist/cloudflared/manifest.js +2 -2
  15. package/dist/codex-desktop-command.js +70 -0
  16. package/dist/codex-desktop-force-stop.js +46 -0
  17. package/dist/codex-desktop-idle-guard.js +15 -0
  18. package/dist/codex-desktop-preflight.js +63 -0
  19. package/dist/codex-desktop-probe.js +152 -0
  20. package/dist/codex-desktop-setup.js +154 -0
  21. package/dist/codex-desktop-status.js +85 -0
  22. package/dist/codex-desktop-windows.js +122 -0
  23. package/dist/codex-runtime-manager.js +368 -0
  24. package/dist/codex-sharing.js +155 -0
  25. package/dist/codex-windows-backend-host.js +59 -0
  26. package/dist/codex-windows-backend.js +120 -0
  27. package/dist/desktop-authorization-prompt.js +84 -0
  28. package/dist/desktop-authorization.js +161 -0
  29. package/dist/device-pairing.js +228 -0
  30. package/dist/error-log.js +113 -0
  31. package/dist/instance-takeover.js +143 -0
  32. package/dist/local-desktop-url.js +8 -0
  33. package/dist/local-service-request.js +69 -0
  34. package/dist/mesh/mesh-command.js +51 -0
  35. package/dist/mesh/mesh-config.js +95 -0
  36. package/dist/mesh/mesh-payload.js +20 -0
  37. package/dist/mesh/mesh-runtime.js +101 -0
  38. package/dist/native-runtime.js +68 -0
  39. package/dist/network.js +46 -3
  40. package/dist/node-runtime-manager.js +251 -0
  41. package/dist/opencode-runtime-manager.js +260 -0
  42. package/dist/platform-packages.js +18 -5
  43. package/dist/platform.js +6 -4
  44. package/dist/power/sleep-inhibitor.js +161 -0
  45. package/dist/runtime-manager.js +139 -19
  46. package/dist/self-hosted-relay.json +1 -0
  47. package/dist/service/launcher-cleanup.js +79 -0
  48. package/dist/service/macos-launch-agent.js +288 -0
  49. package/dist/service/runtime-state.js +43 -0
  50. package/dist/service/service-command.js +226 -0
  51. package/dist/service/service-controller.js +29 -0
  52. package/dist/service/service-files.js +78 -0
  53. package/dist/service/windows-service-host.js +59 -0
  54. package/dist/service/windows-task-service.js +289 -0
  55. package/dist/startup-lock.js +81 -0
  56. package/dist/tailscale/bundled-asset.js +43 -0
  57. package/dist/tailscale/daemon-manager.js +112 -0
  58. package/dist/tailscale/installer.js +131 -0
  59. package/dist/tailscale/manifest.js +15 -0
  60. package/dist/tailscale/tailnet-cli.js +101 -0
  61. package/dist/todo-mcp-command.js +27 -0
  62. package/dist/tunnel/cloudflare-provider.js +4 -1
  63. package/dist/tunnel/public-readiness.js +76 -50
  64. package/dist/tunnel/relay-orchestrator.js +53 -19
  65. package/dist/tunnel/self-hosted-provider.js +147 -0
  66. package/dist/tunnel/tunnel-controller.js +232 -0
  67. package/dist/unlock-service.js +105 -0
  68. package/dist/update/update-channel.js +38 -0
  69. package/dist/update/update-command.js +97 -0
  70. package/dist/update/update-install.js +34 -0
  71. package/dist/update/update-state.js +43 -0
  72. package/dist/update/update-worker.js +82 -0
  73. package/install/README.md +55 -0
  74. package/install/codex-shared-watchdog.sh +16 -0
  75. package/install/install-agentroam.ps1 +358 -0
  76. package/install/install-agentroam.sh +457 -0
  77. package/install/install-manifest.json +15 -0
  78. package/install/start-codex-desktop-shared.sh +152 -0
  79. package/install/write-relay-default.mjs +6 -0
  80. package/package.json +15 -10
  81. package/dist/args.test.js +0 -27
  82. package/dist/cloudflared/bundled-asset.test.js +0 -76
  83. package/dist/cloudflared/installer.test.js +0 -95
  84. package/dist/native-runtime.test.js +0 -19
  85. package/dist/network.test.js +0 -20
  86. package/dist/pairing.js +0 -2
  87. package/dist/platform-packages.test.js +0 -75
  88. package/dist/platform.test.js +0 -3
  89. package/dist/port.test.js +0 -3
  90. package/dist/process-supervisor.test.js +0 -42
  91. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  92. package/dist/tunnel/pinggy-provider.test.js +0 -40
  93. package/dist/tunnel/proxy-settings.test.js +0 -111
  94. package/dist/tunnel/public-readiness.test.js +0 -104
  95. package/dist/tunnel/relay-orchestrator.test.js +0 -72
@@ -0,0 +1,70 @@
1
+ import { execFile } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import { promisify } from "node:util";
4
+ import { resolveCodexRuntime } from "./codex-runtime-manager.js";
5
+ import { readServiceConfig, resolveServicePaths } from "./service/service-files.js";
6
+ import { detectPlatform } from "./platform.js";
7
+ import { configureCodexSharing, inspectCodexSharing } from "./codex-sharing.js";
8
+ import { runWindowsCodexDesktop } from "./codex-desktop-windows.js";
9
+ const execFileAsync = promisify(execFile);
10
+ const scriptPath = fileURLToPath(new URL("../install/start-codex-desktop-shared.sh", import.meta.url));
11
+ export async function runCodexDesktopCommand(options, context = {}) {
12
+ const platform = context.platform ?? process.platform;
13
+ if (platform === "win32") {
14
+ await runWindowsCodexDesktop(options, context);
15
+ return;
16
+ }
17
+ if (platform !== "darwin")
18
+ throw new Error("当前系统不支持官方 Codex 桌面共享后端入口");
19
+ const log = context.log ?? console.log;
20
+ const environment = { ...(context.environment ?? process.env) };
21
+ const service = await (context.readConfig ?? (() => readServiceConfig(resolveServicePaths())))();
22
+ if (service?.dataDir === options.dataDir) {
23
+ if (!environment.AGENT_CODEX_BIN && service.codexPath)
24
+ environment.AGENT_CODEX_BIN = service.codexPath;
25
+ if (!environment.CODEX_HOME && service.codexHome)
26
+ environment.CODEX_HOME = service.codexHome;
27
+ }
28
+ if (options.desktopSharingStatus || options.desktopRepair) {
29
+ if (options.desktopRepair)
30
+ await (context.configureSharing ?? configureCodexSharing)(options, { platform, environment });
31
+ log(JSON.stringify(await (context.inspectSharing ?? inspectCodexSharing)({ platform, environment })));
32
+ return;
33
+ }
34
+ // A dry run reads the installed configuration and never installs a runtime.
35
+ if (!options.desktopDryRun) {
36
+ const codex = await (context.codexResolver ?? resolveCodexRuntime)({
37
+ dataDir: options.dataDir,
38
+ target: detectPlatform(platform, process.arch, process.versions.node),
39
+ environment: { ...environment },
40
+ platform,
41
+ nodeExecutable: process.execPath,
42
+ onProgress: (message) => log(`… ${message}`),
43
+ });
44
+ environment.AGENT_CODEX_BIN = codex.executable;
45
+ await (context.configureSharing ?? configureCodexSharing)(options, { platform, environment });
46
+ }
47
+ const args = [scriptPath];
48
+ if (!options.desktopDryRun) {
49
+ environment.AGENTROAM_CODEX_DESKTOP_PREFLIGHT_NODE = process.execPath;
50
+ environment.AGENTROAM_CODEX_DESKTOP_PREFLIGHT = fileURLToPath(new URL("./codex-desktop-preflight.js", import.meta.url));
51
+ environment.AGENTROAM_CODEX_DESKTOP_FORCE_STOP = fileURLToPath(new URL("./codex-desktop-force-stop.js", import.meta.url));
52
+ }
53
+ if (options.desktopRestart)
54
+ args.push("--restart");
55
+ if (options.desktopDryRun)
56
+ args.push("--dry-run");
57
+ try {
58
+ const { stdout, stderr } = await (context.execute ?? execFileAsync)("/bin/bash", args, {
59
+ env: environment, encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024,
60
+ });
61
+ if (stdout.trim())
62
+ log(stdout.trimEnd());
63
+ if (stderr.trim())
64
+ log(stderr.trimEnd());
65
+ }
66
+ catch (error) {
67
+ const detail = error;
68
+ throw new Error(detail.stderr?.trim() || detail.message, { cause: error });
69
+ }
70
+ }
@@ -0,0 +1,46 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { pathToFileURL } from "node:url";
3
+ function snapshot() {
4
+ return execFileSync("/bin/ps", ["-axo", "pid=,ppid=,lstart=,args="], { encoding: "utf8" }).split("\n").flatMap(line => {
5
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\S+\s+\d+)\s+(.+)$/.exec(line);
6
+ return match ? [{ pid: Number(match[1]), parent: Number(match[2]), started: match[3], command: match[4] }] : [];
7
+ });
8
+ }
9
+ export function forceStopCodexDesktop(pid, binary, context = {}) {
10
+ const read = context.snapshot ?? snapshot;
11
+ const initial = read();
12
+ const desktop = initial.find(row => row.pid === pid && (row.command === binary || row.command.startsWith(`${binary} `)));
13
+ if (!desktop)
14
+ throw new Error("Desktop process changed; no forced restart attempted.");
15
+ const appRoot = binary.slice(0, binary.lastIndexOf("/Contents/MacOS/"));
16
+ const backends = initial.filter(row => row.parent === pid && row.command.startsWith(`${appRoot}/Contents/`)
17
+ && /\/codex\s.*\bapp-server(?:\s|$)/.test(row.command) && !/\bapp-server\s+(?:proxy|daemon)\b/.test(row.command));
18
+ for (const target of [...backends, desktop]) {
19
+ const current = read().find(row => row.pid === target.pid);
20
+ if (!current)
21
+ continue;
22
+ if (current.started !== target.started || current.command !== target.command || current.parent !== target.parent) {
23
+ throw new Error("Desktop process identity changed; forced restart stopped.");
24
+ }
25
+ try {
26
+ (context.kill ?? (targetPid => process.kill(targetPid, "SIGKILL")))(target.pid);
27
+ }
28
+ catch (error) {
29
+ if (error.code !== "ESRCH")
30
+ throw error;
31
+ }
32
+ }
33
+ }
34
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
35
+ try {
36
+ const pid = Number(process.argv[2]);
37
+ const binary = process.argv[3];
38
+ if (!Number.isSafeInteger(pid) || pid <= 1 || !binary?.includes("/Contents/MacOS/"))
39
+ throw new Error("Invalid Desktop process identity");
40
+ forceStopCodexDesktop(pid, binary);
41
+ }
42
+ catch (error) {
43
+ console.error(error instanceof Error ? error.message : error);
44
+ process.exitCode = 1;
45
+ }
46
+ }
@@ -0,0 +1,15 @@
1
+ import { inspectCodexDesktop } from "./codex-desktop-status.js";
2
+ // Invoked only by the packaged launcher, after daemon preflight and immediately
3
+ // before graceful quit. Runtime installation may have taken minutes since setup.
4
+ try {
5
+ const snapshot = await inspectCodexDesktop(process.env);
6
+ if (snapshot.status !== "running" || String(snapshot.pid) !== process.env.AGENTROAM_CODEX_DESKTOP_EXPECTED_PID
7
+ || snapshot.activity.state !== "idle") {
8
+ console.error("Desktop is no longer confirmed idle; no automatic restart attempted. Run agentroam codex-desktop --setup to choose again.");
9
+ process.exitCode = 1;
10
+ }
11
+ }
12
+ catch {
13
+ console.error("Desktop idle check failed; no automatic restart attempted.");
14
+ process.exitCode = 1;
15
+ }
@@ -0,0 +1,63 @@
1
+ import { execFile } from "node:child_process";
2
+ import { homedir } from "node:os";
3
+ import { promisify } from "node:util";
4
+ import { pathToFileURL } from "node:url";
5
+ import { DesktopProbeRpcError, readDesktopActivity, withDesktopRpc } from "./codex-desktop-probe.js";
6
+ const execFileAsync = promisify(execFile);
7
+ function isUnsupportedGatewayMethod(error) {
8
+ if (!(error instanceof DesktopProbeRpcError))
9
+ return false;
10
+ return error.code === -32601 || (error.code === -32600
11
+ && error.message.startsWith("Invalid request: unknown variant `account/gatewayOAuth/read`, expected one of "));
12
+ }
13
+ async function inspectBackend(endpoint) {
14
+ return withDesktopRpc(endpoint, async (request, becameActive) => {
15
+ try {
16
+ await request("config/read", {});
17
+ try {
18
+ await request("account/gatewayOAuth/read", {});
19
+ }
20
+ catch (error) {
21
+ // Older servers may not have the Desktop gateway RPC.
22
+ if (!isUnsupportedGatewayMethod(error))
23
+ throw error;
24
+ }
25
+ return true;
26
+ }
27
+ catch (error) {
28
+ if (!(error instanceof DesktopProbeRpcError) || !/No such file or directory|os error 2/.test(error.message))
29
+ throw error;
30
+ const activity = await readDesktopActivity(request);
31
+ if (activity.state !== "idle" || becameActive())
32
+ throw new Error("共享后端配置失效,但任务忙碌或状态无法确认;已保留桌面和共享后端");
33
+ return false;
34
+ }
35
+ });
36
+ }
37
+ /** Repair only a missing-directory backend after two complete idle snapshots. */
38
+ export async function preflightCodexDesktop(endpoint, executable, context = {}) {
39
+ if (await inspectBackend(endpoint))
40
+ return;
41
+ if (await inspectBackend(endpoint))
42
+ return;
43
+ (context.log ?? console.log)("共享后端的工作目录已失效,已确认全部任务空闲,正在从稳定目录重建…");
44
+ await (context.restart ?? (async () => {
45
+ await execFileAsync(executable, ["app-server", "daemon", "restart"], {
46
+ cwd: homedir(), env: process.env, timeout: 15_000, maxBuffer: 1024 * 1024,
47
+ });
48
+ }))();
49
+ if (!await inspectBackend(endpoint))
50
+ throw new Error("共享后端重建后仍无法读取配置;已保留桌面");
51
+ }
52
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
53
+ const [endpoint, executable] = process.argv.slice(2);
54
+ if (!endpoint || !executable) {
55
+ console.error("Missing shared backend endpoint or Codex executable");
56
+ process.exitCode = 1;
57
+ }
58
+ else
59
+ preflightCodexDesktop(endpoint, executable).catch(error => {
60
+ console.error(`共享后端检查失败:${error instanceof Error ? error.message : error}`);
61
+ process.exitCode = 1;
62
+ });
63
+ }
@@ -0,0 +1,152 @@
1
+ import { createConnection } from "node:net";
2
+ import WebSocket from "ws";
3
+ export class DesktopProbeRpcError extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.code = code;
8
+ }
9
+ }
10
+ /** Read live state only. Never resume, subscribe, interrupt or unload a thread. */
11
+ export async function probeDesktopActivity(endpoint, timeoutMs = 5_000) {
12
+ try {
13
+ return await withDesktopRpc(endpoint, async (request, becameActive) => {
14
+ const activity = await readDesktopActivity(request);
15
+ return becameActive() && activity.state === "idle" ? { state: "busy", activeCount: 1 } : activity;
16
+ }, timeoutMs);
17
+ }
18
+ catch {
19
+ return { state: "unknown", reason: "无法完整查询桌面端的实时任务状态" };
20
+ }
21
+ }
22
+ export async function withDesktopRpc(endpoint, operation, timeoutMs = 5_000) {
23
+ let socket;
24
+ let timer;
25
+ let rejectPending;
26
+ try {
27
+ const address = new URL(endpoint);
28
+ let url = endpoint;
29
+ let socketPath;
30
+ if (address.protocol === "ws+unix:") {
31
+ const separator = address.pathname.indexOf(":");
32
+ if (address.hostname !== "localhost" || separator < 1)
33
+ throw new Error("invalid local socket");
34
+ socketPath = decodeURIComponent(address.pathname.slice(0, separator));
35
+ url = `ws://localhost${address.pathname.slice(separator + 1)}`;
36
+ }
37
+ else if (!(["ws:", "wss:"].includes(address.protocol)
38
+ && ["127.0.0.1", "localhost", "[::1]"].includes(address.hostname))) {
39
+ throw new Error("not a local Desktop endpoint");
40
+ }
41
+ if (address.username || address.password || address.search || address.hash)
42
+ throw new Error("invalid endpoint");
43
+ socket = new WebSocket(url, {
44
+ ...(socketPath ? { createConnection: () => createConnection({ path: socketPath }) } : {}),
45
+ handshakeTimeout: timeoutMs,
46
+ // Older Codex backends reject a Sec-WebSocket-Extensions offer.
47
+ perMessageDeflate: false,
48
+ });
49
+ const connection = socket;
50
+ let nextId = 0;
51
+ let changedToActive = false;
52
+ const pending = new Map();
53
+ const fail = (error = new Error("Desktop probe disconnected")) => {
54
+ for (const item of pending.values())
55
+ item.reject(error);
56
+ pending.clear();
57
+ };
58
+ rejectPending = fail;
59
+ const opened = new Promise((resolve, reject) => {
60
+ connection.once("open", () => resolve());
61
+ connection.once("error", (error) => reject(new Error(`Desktop probe connection failed: ${error.message}`, { cause: error })));
62
+ connection.once("close", () => reject(new Error("Desktop probe disconnected")));
63
+ });
64
+ connection.on("error", fail);
65
+ connection.on("close", () => fail());
66
+ connection.on("message", (data) => {
67
+ try {
68
+ const message = JSON.parse(String(data));
69
+ if (message.method === "thread/status/changed" && message.params?.status?.type === "active")
70
+ changedToActive = true;
71
+ const item = pending.get(message.id);
72
+ if (!item)
73
+ return;
74
+ pending.delete(message.id);
75
+ if (message.error)
76
+ item.reject(new DesktopProbeRpcError(message.error.code, String(message.error.message ?? "Desktop probe RPC failed")));
77
+ else
78
+ item.resolve(message.result);
79
+ }
80
+ catch {
81
+ fail();
82
+ }
83
+ });
84
+ const request = (method, params) => new Promise((resolve, reject) => {
85
+ const id = ++nextId;
86
+ pending.set(id, { resolve, reject });
87
+ try {
88
+ connection.send(JSON.stringify({ id, method, params }));
89
+ }
90
+ catch (error) {
91
+ pending.delete(id);
92
+ reject(error);
93
+ }
94
+ });
95
+ const run = async () => {
96
+ await opened;
97
+ await request("initialize", { clientInfo: { name: "agentroam_desktop_setup", version: "1" }, capabilities: { experimentalApi: true } });
98
+ connection.send(JSON.stringify({ method: "initialized", params: {} }));
99
+ return operation(request, () => changedToActive);
100
+ };
101
+ return await Promise.race([
102
+ run(),
103
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("Desktop probe timed out")), timeoutMs); }),
104
+ ]);
105
+ }
106
+ finally {
107
+ if (timer)
108
+ clearTimeout(timer);
109
+ rejectPending?.();
110
+ socket?.terminate();
111
+ }
112
+ }
113
+ export async function readDesktopActivity(request) {
114
+ const listLoaded = async () => {
115
+ const ids = new Set();
116
+ const cursors = new Set();
117
+ let cursor = null;
118
+ for (let pageIndex = 0; pageIndex < 20; pageIndex++) {
119
+ const page = await request("thread/loaded/list", { cursor, limit: 100 });
120
+ if (!Array.isArray(page?.data) || page.data.some((id) => typeof id !== "string" || !id))
121
+ throw new Error("incomplete loaded thread list");
122
+ for (const id of page.data)
123
+ ids.add(id);
124
+ if (page.nextCursor === null || page.nextCursor === undefined)
125
+ return [...ids].sort();
126
+ if (typeof page.nextCursor !== "string" || !page.nextCursor || cursors.has(page.nextCursor))
127
+ throw new Error("invalid cursor");
128
+ cursors.add(page.nextCursor);
129
+ cursor = page.nextCursor;
130
+ }
131
+ throw new Error("Desktop thread list exceeded probe limit");
132
+ };
133
+ const ids = await listLoaded();
134
+ let activeCount = 0;
135
+ let hasUnknownStatus = false;
136
+ for (const threadId of ids) {
137
+ const result = await request("thread/read", { threadId, includeTurns: false });
138
+ if (result?.thread?.id !== threadId)
139
+ throw new Error("Desktop thread identity changed");
140
+ const status = result.thread.status?.type;
141
+ if (status === "active")
142
+ activeCount++;
143
+ else if (status !== "idle")
144
+ hasUnknownStatus = true;
145
+ }
146
+ if (activeCount)
147
+ return { state: "busy", activeCount };
148
+ if (hasUnknownStatus || JSON.stringify(ids) !== JSON.stringify(await listLoaded())) {
149
+ return { state: "unknown", reason: "桌面任务列表发生变化或包含无法确认的状态" };
150
+ }
151
+ return { state: "idle" };
152
+ }
@@ -0,0 +1,154 @@
1
+ import { openSync, closeSync } from "node:fs";
2
+ import { createInterface } from "node:readline";
3
+ import { ReadStream, WriteStream } from "node:tty";
4
+ import { fileURLToPath } from "node:url";
5
+ import { runCodexDesktopCommand } from "./codex-desktop-command.js";
6
+ import { inspectCodexDesktop } from "./codex-desktop-status.js";
7
+ import { configureCodexSharing, inspectCodexSharing } from "./codex-sharing.js";
8
+ import { withoutCliProgress } from "../bin/cli-progress.mjs";
9
+ import { runWindowsCodexDesktop } from "./codex-desktop-windows.js";
10
+ export async function setupCodexDesktop(options, context = {}) {
11
+ if ((context.platform ?? process.platform) === "win32") {
12
+ const inherited = context.environment ?? process.env;
13
+ const environment = { ...inherited, AGENTROAM_CODEX_DESKTOP_NONINTERACTIVE: "1" };
14
+ if (context.service?.dataDir === options.dataDir) {
15
+ if (!environment.CODEX_HOME && context.service.codexHome)
16
+ environment.CODEX_HOME = context.service.codexHome;
17
+ if (!environment.AGENT_CODEX_BIN && context.service.codexPath)
18
+ environment.AGENT_CODEX_BIN = context.service.codexPath;
19
+ }
20
+ const result = await runWindowsCodexDesktop(options, { environment, log: context.log });
21
+ if (result.state === "independent" && inherited.AGENTROAM_CODEX_DESKTOP_NONINTERACTIVE !== "1") {
22
+ const answer = await withoutCliProgress(() => (context.confirm ?? confirmDesktopRestart)("Force restart Codex Desktop? Running tasks and unsent input may be lost [y/N]: "));
23
+ if (/^(y|yes)$/i.test(answer?.trim() ?? ""))
24
+ await runWindowsCodexDesktop({ ...options, desktopSetup: false, desktopRestart: true }, { environment, log: context.log });
25
+ }
26
+ return;
27
+ }
28
+ if ((context.platform ?? process.platform) !== "darwin")
29
+ return;
30
+ const log = context.log ?? console.log;
31
+ const environment = { ...(context.environment ?? process.env) };
32
+ if (context.service?.dataDir === options.dataDir) {
33
+ if (!environment.CODEX_HOME && context.service.codexHome)
34
+ environment.CODEX_HOME = context.service.codexHome;
35
+ if (!environment.AGENT_CODEX_BIN && context.service.codexPath)
36
+ environment.AGENT_CODEX_BIN = context.service.codexPath;
37
+ }
38
+ const inspect = context.inspect ?? inspectCodexDesktop;
39
+ const deferred = () => log("Current Codex Desktop preserved. Scan to connect to AgentRoam; existing desktop sessions are not shared yet. Run agentroam codex-desktop --setup later.");
40
+ try {
41
+ await (context.configureSharing ?? configureCodexSharing)(options, { environment });
42
+ log("Saved shared backend and background recovery settings. Use the avatar menu to switch if Desktop starts independently.");
43
+ if ((await (context.inspectSharing ?? inspectCodexSharing)({ environment })).state === "shared") {
44
+ log("Codex Desktop already uses the shared backend; no restart needed.");
45
+ return;
46
+ }
47
+ let snapshot = await inspect(environment);
48
+ if (snapshot.status === "not-installed") {
49
+ log("Codex Desktop is not installed. Continuing with phone pairing.");
50
+ return;
51
+ }
52
+ if (snapshot.status === "stopped") {
53
+ log("Shared backend configured. Codex Desktop remains closed; open it normally when needed.");
54
+ return;
55
+ }
56
+ const original = snapshot;
57
+ let restartConfirmed = false;
58
+ if (snapshot.status === "running" && snapshot.activity.state === "idle") {
59
+ // Read every loaded thread again immediately before choosing automatic restart.
60
+ snapshot = await inspect(environment);
61
+ if (!sameDesktop(original, snapshot)) {
62
+ log("Desktop process changed. Preserving Desktop.");
63
+ deferred();
64
+ return;
65
+ }
66
+ }
67
+ if (snapshot.status === "running" && snapshot.activity.state !== "idle") {
68
+ const reason = snapshot.activity.state === "busy"
69
+ ? `Codex Desktop has ${snapshot.activity.activeCount} active sessions.`
70
+ : "Cannot reliably confirm that all Codex Desktop tasks have finished.";
71
+ log(reason);
72
+ if (environment.AGENTROAM_CODEX_DESKTOP_NONINTERACTIVE === "1") {
73
+ log(JSON.stringify({ codexSharingAction: "confirmation-required" }));
74
+ deferred();
75
+ return;
76
+ }
77
+ const answer = await withoutCliProgress(() => (context.confirm ?? confirmDesktopRestart)("Force restart Desktop now to share sessions? This will interrupt all running desktop tasks and may lose unsent input. No Codex quit dialog will appear. Continue [y/N]: "));
78
+ if (!answer || !/^(?:y|yes)$/i.test(answer.trim())) {
79
+ deferred();
80
+ return;
81
+ }
82
+ restartConfirmed = true;
83
+ const checked = await inspect(environment);
84
+ if (!sameDesktop(snapshot, checked)) {
85
+ log("Desktop process changed after confirmation. Preserving Desktop.");
86
+ deferred();
87
+ return;
88
+ }
89
+ snapshot = checked;
90
+ }
91
+ if (snapshot.status !== "running" && snapshot.status !== "stopped")
92
+ return;
93
+ environment.CODEX_DESKTOP_APP = snapshot.appPath;
94
+ environment.AGENTROAM_CODEX_DESKTOP_EXPECTED_PID = snapshot.status === "running" ? String(snapshot.pid) : "0";
95
+ if (snapshot.status === "running" && !restartConfirmed) {
96
+ environment.AGENTROAM_CODEX_DESKTOP_IDLE_GUARD = fileURLToPath(new URL("./codex-desktop-idle-guard.js", import.meta.url));
97
+ environment.AGENTROAM_CODEX_DESKTOP_GUARD_NODE = process.execPath;
98
+ }
99
+ else {
100
+ delete environment.AGENTROAM_CODEX_DESKTOP_IDLE_GUARD;
101
+ delete environment.AGENTROAM_CODEX_DESKTOP_GUARD_NODE;
102
+ }
103
+ const launchOptions = { ...options, command: "codex-desktop", desktopSetup: false,
104
+ desktopDryRun: false, desktopRestart: snapshot.status === "running" };
105
+ log(snapshot.status === "stopped" ? "Starting Codex Desktop and connecting to the shared backend..." : "Reconnecting Codex Desktop to the shared backend...");
106
+ await (context.launch ?? ((args, env) => runCodexDesktopCommand(args, { environment: env, log })))(launchOptions, environment);
107
+ log("Desktop connection attempted. Pairing follows. AgentRoam selects the desktop, shared, or standalone backend based on actual connectivity.");
108
+ }
109
+ catch (error) {
110
+ log(`Desktop sharing connection incomplete: ${error instanceof Error ? error.message : error}`);
111
+ log("AgentRoam installation continues; scan to connect. Backend fallback: desktop -> shared -> standalone. Existing desktop sharing is unconfirmed. Retry later with agentroam codex-desktop --setup.");
112
+ }
113
+ }
114
+ function sameDesktop(previous, current) {
115
+ return previous.status === "running" && current.status === "running"
116
+ && previous.pid === current.pid && previous.appPath === current.appPath;
117
+ }
118
+ /** curl | sh owns stdin. Only the controlling terminal can authorize restart. */
119
+ export async function confirmDesktopRestart(question) {
120
+ let inputFd;
121
+ let outputFd;
122
+ let input;
123
+ let output;
124
+ let reader;
125
+ try {
126
+ inputFd = openSync("/dev/tty", "r");
127
+ outputFd = openSync("/dev/tty", "w");
128
+ input = new ReadStream(inputFd);
129
+ output = new WriteStream(outputFd);
130
+ reader = createInterface({ input, output, terminal: true });
131
+ const prompt = reader;
132
+ return await new Promise((resolve) => {
133
+ prompt.once("close", () => resolve(null));
134
+ prompt.once("SIGINT", () => resolve(null));
135
+ input.once("error", () => resolve(null));
136
+ output.once("error", () => resolve(null));
137
+ prompt.question(question, resolve);
138
+ });
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ finally {
144
+ reader?.close();
145
+ if (input)
146
+ input.destroy();
147
+ else if (inputFd !== undefined)
148
+ closeSync(inputFd);
149
+ if (output)
150
+ output.destroy();
151
+ else if (outputFd !== undefined)
152
+ closeSync(outputFd);
153
+ }
154
+ }
@@ -0,0 +1,85 @@
1
+ import { execFile } from "node:child_process";
2
+ import { access } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ import { basename, join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { probeDesktopActivity } from "./codex-desktop-probe.js";
7
+ const execFileAsync = promisify(execFile);
8
+ export async function inspectCodexDesktop(environment, context = {}) {
9
+ const executableExists = context.executableExists ?? (async (path) => {
10
+ try {
11
+ await access(path, constants.X_OK);
12
+ return true;
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ });
18
+ let appPath = environment.CODEX_DESKTOP_APP;
19
+ if (!appPath)
20
+ appPath = await executableExists("/Applications/ChatGPT.app") ? "/Applications/ChatGPT.app" : "/Applications/Codex.app";
21
+ const binary = join(appPath, "Contents/MacOS", basename(appPath, ".app"));
22
+ if (!await executableExists(binary))
23
+ return { status: "not-installed" };
24
+ const execute = context.execute ?? execFileAsync;
25
+ const commandOptions = { encoding: "utf8", timeout: 1_500, maxBuffer: 2 * 1024 * 1024 };
26
+ const { stdout } = await execute("/bin/ps", ["-axo", "pid=,ppid=,args="], commandOptions);
27
+ const processes = String(stdout).split("\n").flatMap((line) => {
28
+ const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
29
+ return match ? [{ pid: Number(match[1]), parentPid: Number(match[2]), command: match[3] }] : [];
30
+ });
31
+ const desktops = processes.filter(({ command }) => command === binary || command.startsWith(`${binary} `));
32
+ if (!desktops.length)
33
+ return { status: "stopped", appPath };
34
+ const pid = desktops[0].pid;
35
+ const unknown = (reason) => ({ status: "running", appPath, pid, activity: { state: "unknown", reason } });
36
+ if (desktops.length !== 1)
37
+ return unknown("检测到多个官方桌面进程,无法完整确认任务状态");
38
+ const servers = processes.filter((process) => process.parentPid === pid && /^(?:.*\/)?codex\s.*\bapp-server(?:\s|$)/.test(process.command));
39
+ if (servers.length !== 1)
40
+ return unknown("桌面端未提供可完整查询的独立后端");
41
+ const server = servers[0];
42
+ const listenUrl = /(?:^|\s)--listen(?:=|\s+)(unix:\/\/.*?|ws:\/\/\S+)(?=\s+-|$)/.exec(server.command)?.[1];
43
+ if (!listenUrl || /\bapp-server\s+(?:proxy|daemon)\b/.test(server.command)) {
44
+ return unknown("桌面端使用私有后端,无法可靠判断全部会话是否空闲");
45
+ }
46
+ let endpoint = null;
47
+ try {
48
+ if (listenUrl.startsWith("ws://")) {
49
+ const address = new URL(listenUrl);
50
+ if (["0.0.0.0", "[::]"].includes(address.hostname))
51
+ address.hostname = "localhost";
52
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(address.hostname) || address.port === "0")
53
+ throw new Error("not local");
54
+ const result = await execute("/usr/sbin/lsof", ["-nP", "-a", "-p", String(server.pid), "-iTCP", "-sTCP:LISTEN", "-Ftn"], commandOptions);
55
+ const port = address.port || "80";
56
+ if (String(result.stdout).split("\n").some((line) => /^n(?:127\.0\.0\.1|localhost|\[::1\]|\*|0\.0\.0\.0|\[::\]):(\d+)$/.exec(line)?.[1] === port))
57
+ endpoint = address.href;
58
+ }
59
+ else {
60
+ const result = await execute("/usr/sbin/lsof", ["-nP", "-a", "-p", String(server.pid), "-U", "-Ftn"], commandOptions);
61
+ const requested = listenUrl.slice("unix://".length);
62
+ const paths = [];
63
+ let unix = false;
64
+ for (const line of String(result.stdout).split("\n")) {
65
+ if (line.startsWith("t"))
66
+ unix = line === "tunix";
67
+ if (!unix || !line.startsWith("n/"))
68
+ continue;
69
+ const path = line.slice(1).split(" type=")[0];
70
+ if (path.includes(" -> ") || path.includes(":"))
71
+ continue;
72
+ if (!requested || path === requested)
73
+ paths.push(path);
74
+ }
75
+ if (paths.length === 1)
76
+ endpoint = `ws+unix://localhost${encodeURI(paths[0])}:/rpc`;
77
+ }
78
+ if (!endpoint)
79
+ return unknown("未找到归属桌面端的可连接监听地址");
80
+ return { status: "running", appPath, pid, activity: await (context.probe ?? probeDesktopActivity)(endpoint) };
81
+ }
82
+ catch {
83
+ return unknown("无法完整查询桌面端的实时任务状态");
84
+ }
85
+ }