agentroam 0.2.0-preview.7 → 0.2.0-preview.70

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 (81) 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 +102 -3
  12. package/dist/cli.js +229 -33
  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 +153 -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 +170 -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/native-runtime.js +68 -0
  35. package/dist/network.js +32 -3
  36. package/dist/node-runtime-manager.js +251 -0
  37. package/dist/opencode-runtime-manager.js +239 -0
  38. package/dist/platform-packages.js +16 -5
  39. package/dist/platform.js +6 -4
  40. package/dist/power/sleep-inhibitor.js +161 -0
  41. package/dist/runtime-manager.js +129 -19
  42. package/dist/service/launcher-cleanup.js +79 -0
  43. package/dist/service/macos-launch-agent.js +288 -0
  44. package/dist/service/runtime-state.js +43 -0
  45. package/dist/service/service-command.js +219 -0
  46. package/dist/service/service-controller.js +27 -0
  47. package/dist/service/service-files.js +78 -0
  48. package/dist/service/windows-service-host.js +59 -0
  49. package/dist/service/windows-task-service.js +289 -0
  50. package/dist/startup-lock.js +81 -0
  51. package/dist/tunnel/cloudflare-provider.js +4 -1
  52. package/dist/tunnel/public-readiness.js +76 -50
  53. package/dist/tunnel/relay-orchestrator.js +29 -9
  54. package/dist/unlock-service.js +105 -0
  55. package/dist/update/update-channel.js +38 -0
  56. package/dist/update/update-command.js +96 -0
  57. package/dist/update/update-install.js +34 -0
  58. package/dist/update/update-state.js +43 -0
  59. package/dist/update/update-worker.js +80 -0
  60. package/install/README.md +55 -0
  61. package/install/codex-shared-watchdog.sh +16 -0
  62. package/install/install-agentroam.ps1 +358 -0
  63. package/install/install-agentroam.sh +457 -0
  64. package/install/install-manifest.json +15 -0
  65. package/install/start-codex-desktop-shared.sh +152 -0
  66. package/package.json +13 -10
  67. package/dist/args.test.js +0 -27
  68. package/dist/cloudflared/bundled-asset.test.js +0 -76
  69. package/dist/cloudflared/installer.test.js +0 -95
  70. package/dist/native-runtime.test.js +0 -19
  71. package/dist/network.test.js +0 -20
  72. package/dist/pairing.js +0 -2
  73. package/dist/platform-packages.test.js +0 -75
  74. package/dist/platform.test.js +0 -3
  75. package/dist/port.test.js +0 -3
  76. package/dist/process-supervisor.test.js +0 -42
  77. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  78. package/dist/tunnel/pinggy-provider.test.js +0 -40
  79. package/dist/tunnel/proxy-settings.test.js +0 -111
  80. package/dist/tunnel/public-readiness.test.js +0 -104
  81. package/dist/tunnel/relay-orchestrator.test.js +0 -72
@@ -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
+ }
@@ -0,0 +1,122 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { withDesktopRpc } from "./codex-desktop-probe.js";
4
+ import { ensureWindowsBackend, readWindowsBackend, WINDOWS_CODEX_TASK } from "./codex-windows-backend.js";
5
+ const executeFile = promisify(execFile);
6
+ export function windowsSharingEndpoint(environment) {
7
+ const endpoint = environment.AGENT_CODEX_DESKTOP_WS_URL || environment.CODEX_APP_SERVER_WS_URL;
8
+ if (!endpoint)
9
+ return null;
10
+ const url = new URL(endpoint);
11
+ if (url.protocol !== "ws:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)
12
+ || url.username || url.password || url.search || url.hash)
13
+ throw new Error("Windows 共享后端必须使用无凭据的本机 WebSocket 地址。");
14
+ return url.href;
15
+ }
16
+ export function powershellLiteral(value) { return `'${value.replaceAll("'", "''")}'`; }
17
+ export async function runWindowsCodexDesktop(options, context = {}) {
18
+ const environment = { ...(context.environment ?? process.env) };
19
+ const log = context.log ?? console.log;
20
+ const execute = context.execute ?? executeFile;
21
+ const run = (script) => execute("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `$ErrorActionPreference='Stop'; ${script}`], { env: environment, encoding: "utf8", timeout: 15_000, maxBuffer: 1024 * 1024, windowsHide: true });
22
+ const report = { state: "unsupported", configured: false, autoStart: false, daemonReachable: false,
23
+ message: "Windows 共享后台尚未就绪;已保留 Codex,不会强制重启。" };
24
+ let endpoint = windowsSharingEndpoint(environment);
25
+ if (!endpoint) {
26
+ const config = options.desktopSharingStatus || options.desktopDryRun
27
+ ? await (context.readBackend ?? readWindowsBackend)()
28
+ : await (context.backend ?? ensureWindowsBackend)(options.dataDir, { environment, execute });
29
+ if (config) {
30
+ endpoint = config.endpoint;
31
+ environment.CODEX_HOME = config.codexHome;
32
+ }
33
+ }
34
+ if (!endpoint) {
35
+ report.state = "failed";
36
+ report.message = "Windows 共享后台尚未配置,请运行安装或点击检查并修复。";
37
+ log(JSON.stringify(report));
38
+ return report;
39
+ }
40
+ environment.AGENT_CODEX_DESKTOP_WS_URL = endpoint;
41
+ let binary = environment.CODEX_DESKTOP_APP;
42
+ if (!binary) {
43
+ const { stdout } = await run(`$candidates=@(); $sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; Get-CimInstance Win32_Process | Where-Object { $_.Name -in @('Codex.exe','ChatGPT.exe') -and $_.CommandLine -notmatch '--type=' } | ForEach-Object { if ((Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid) { $candidates += $_.ExecutablePath } }; Get-AppxPackage | Where-Object { $_.Name -match 'OpenAI.*(Codex|ChatGPT)' } | ForEach-Object { $root=$_.InstallLocation; $manifest=Get-AppxPackageManifest $_; $manifest.Package.Applications.Application | ForEach-Object { if ($_.Executable) { $candidates += Join-Path $root $_.Executable } } }; $candidates += @((Join-Path $env:LOCALAPPDATA 'Programs\\Codex\\Codex.exe'),(Join-Path $env:LOCALAPPDATA 'Programs\\ChatGPT\\ChatGPT.exe')); foreach($candidate in ($candidates | Select-Object -Unique)) { if ($candidate -and (Test-Path -LiteralPath $candidate -PathType Leaf) -and [IO.Path]::GetFileName($candidate) -in @('Codex.exe','ChatGPT.exe')) { $signature=Get-AuthenticodeSignature -LiteralPath $candidate; if ($signature.Status -eq 'Valid' -and $signature.SignerCertificate.Subject -match 'OpenAI') { Write-Output $candidate; break } } }`);
44
+ binary = stdout.trim() || undefined;
45
+ }
46
+ if (!binary || !/^[A-Za-z]:\\.*\.exe$/i.test(binary)) {
47
+ report.state = "not-installed";
48
+ report.message = "未找到当前用户安装的官方 Codex 桌面端;不会结束其他程序。";
49
+ log(JSON.stringify(report));
50
+ return report;
51
+ }
52
+ const encodedBinary = powershellLiteral(binary);
53
+ const { stdout: supported } = await run(`$signature=Get-AuthenticodeSignature -LiteralPath ${encodedBinary}; if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'OpenAI') { throw 'Not an official signed Desktop executable' }; $archive=Join-Path (Split-Path ${encodedBinary}) 'resources\\app.asar'; if (Test-Path -LiteralPath $archive) { $text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($archive)); if ($text.Contains('CODEX_APP_SERVER_WS_URL')) { 'supported' } }`);
54
+ if (supported.trim() !== "supported") {
55
+ report.message = "当前 Windows 官方桌面版本未提供可确认的共享连接能力,已保留进程。";
56
+ log(JSON.stringify(report));
57
+ return report;
58
+ }
59
+ const processes = async () => {
60
+ const { stdout } = await run(`$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; @((Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq ${encodedBinary} -and $_.CommandLine -notmatch '--type=' -and (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid }) | Select-Object ProcessId,@{Name='CreationDate';Expression={$_.CreationDate.ToString('o')}},ExecutablePath) | ConvertTo-Json -Compress`);
61
+ const rows = JSON.parse(stdout.trim() || "[]");
62
+ return (Array.isArray(rows) ? rows : [rows]);
63
+ };
64
+ const initial = await processes();
65
+ if (initial.length > 1)
66
+ throw new Error("检测到多个 Codex 桌面实例,无法安全确定重启目标。");
67
+ report.backendEndpoint = endpoint;
68
+ const { stdout: task } = await run(`$task=Get-ScheduledTask -TaskName '${WINDOWS_CODEX_TASK}' -ErrorAction SilentlyContinue; if ($task -and $task.State -eq 'Running') { 'running' }`);
69
+ report.autoStart = task.trim() === "running";
70
+ report.state = initial.length ? "independent" : "stopped";
71
+ if (!options.desktopDryRun) {
72
+ await (context.probe ?? (async (url) => { await withDesktopRpc(url, async (request) => { await request("config/read", { includeLayers: false }); }); }))(endpoint);
73
+ report.daemonReachable = true;
74
+ }
75
+ const { stdout: defaults } = await run(`[Environment]::GetEnvironmentVariable('CODEX_APP_SERVER_WS_URL','User')`);
76
+ report.configured = defaults.trim() === endpoint;
77
+ if (initial.length && report.daemonReachable) {
78
+ const port = new URL(endpoint).port || "80";
79
+ const { stdout } = await run(`$listeners=@(Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue); if ($listeners.Count -eq 0 -or @($listeners | Where-Object { $_.LocalAddress -notin @('127.0.0.1','::1') -or $_.OwningProcess -eq ${initial[0].ProcessId} }).Count -gt 0) { throw 'Shared endpoint ownership unavailable' }; $ids=@(${initial[0].ProcessId}); $family=@(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq ${encodedBinary} }); do { $added=@($family | Where-Object { $_.ParentProcessId -in $ids -and $_.ProcessId -notin $ids } | ForEach-Object { $_.ProcessId }); $ids += $added } while ($added.Count -gt 0); @(Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue | Where-Object { $_.OwningProcess -in $ids -and $_.RemotePort -eq ${port} -and $_.RemoteAddress -in @('127.0.0.1','::1') }).Count`);
80
+ if (Number(stdout.trim()) > 0)
81
+ report.state = "shared";
82
+ }
83
+ report.message = report.state === "shared" ? "Codex 已连接配置的共享后台。" : report.state === "stopped" ? "共享后端可用;Codex 桌面保持关闭。" : "Codex 未连接共享后台;Windows 暂无法可靠判断桌面任务,切换前需要确认强制重启。";
84
+ if (options.desktopDryRun) {
85
+ log(JSON.stringify({ ...report, message: "Dry run: 未写配置、未启动或结束任何进程。" }));
86
+ return report;
87
+ }
88
+ if (options.desktopSharingStatus) {
89
+ log(JSON.stringify(report));
90
+ return report;
91
+ }
92
+ await run(`[Environment]::SetEnvironmentVariable('CODEX_APP_SERVER_WS_URL',${powershellLiteral(endpoint)},'User'); [Environment]::SetEnvironmentVariable('CODEX_APP_SERVER_FORCE_CLI','0','User')`);
93
+ await run(`Add-Type -Namespace AgentRoam -Name EnvironmentBroadcast -MemberDefinition '[DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint flags, uint timeout, out UIntPtr result);'; $result=[UIntPtr]::Zero; [AgentRoam.EnvironmentBroadcast]::SendMessageTimeout([IntPtr]0xffff,0x1a,[UIntPtr]::Zero,'Environment',2,3000,[ref]$result) | Out-Null`);
94
+ report.configured = true;
95
+ if (options.desktopRepair || report.state === "shared") {
96
+ log(JSON.stringify(report));
97
+ return report;
98
+ }
99
+ if (options.desktopSetup && report.state === "stopped") {
100
+ log(JSON.stringify(report));
101
+ return report;
102
+ }
103
+ if (initial.length && !options.desktopRestart) {
104
+ if (options.desktopSetup && environment.AGENTROAM_CODEX_DESKTOP_NONINTERACTIVE === "1") {
105
+ log(JSON.stringify({ codexSharingAction: "confirmation-required" }));
106
+ log(JSON.stringify(report));
107
+ return report;
108
+ }
109
+ throw new Error("Windows 桌面任务状态无法确认。请确认中断风险后使用 --restart;不会自动结束进程。");
110
+ }
111
+ if (initial.length) {
112
+ const target = initial[0];
113
+ if (!Number.isSafeInteger(target.ProcessId) || target.ProcessId <= 1)
114
+ throw new Error("无效的桌面 PID");
115
+ await run(`$target=Get-CimInstance Win32_Process -Filter 'ProcessId=${target.ProcessId}'; if (!$target -or $target.ExecutablePath -ne ${encodedBinary} -or $target.CreationDate.ToString('o') -ne ${powershellLiteral(String(target.CreationDate))}) { throw 'Desktop process identity changed' }; $sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; if ((Invoke-CimMethod -InputObject $target -MethodName GetOwnerSid).Sid -ne $sid) { throw 'Desktop user changed' }; $root=(Split-Path ${encodedBinary}) + '\\'; $private=@(Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${target.ProcessId} -and $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root,[StringComparison]::OrdinalIgnoreCase) -and $_.Name -eq 'codex.exe' -and $_.CommandLine -match '\\sapp-server(?:\\s|$)' -and $_.CommandLine -notmatch '\\s(proxy|daemon)(?:\\s|$)|--managed-daemon' }); foreach($child in $private) { $live=Get-CimInstance Win32_Process -Filter "ProcessId=$($child.ProcessId)"; if (!$live -or $live.CreationDate -ne $child.CreationDate -or $live.ParentProcessId -ne ${target.ProcessId} -or $live.ExecutablePath -ne $child.ExecutablePath) { throw 'Private backend identity changed' }; Stop-Process -Id $child.ProcessId -Force }; Stop-Process -Id ${target.ProcessId} -Force; Wait-Process -Id ${target.ProcessId} -Timeout 10 -ErrorAction SilentlyContinue; if (Get-Process -Id ${target.ProcessId} -ErrorAction SilentlyContinue) { throw 'Desktop did not exit' }`);
116
+ }
117
+ await run(`$env:CODEX_APP_SERVER_WS_URL=${powershellLiteral(endpoint)}; ${environment.CODEX_HOME ? `$env:CODEX_HOME=${powershellLiteral(environment.CODEX_HOME)}; ` : ''}$env:CODEX_APP_SERVER_FORCE_CLI='0'; Start-Process -FilePath ${encodedBinary}`);
118
+ report.state = "failed";
119
+ report.message = "已请求共享启动;请刷新并验证实际连接,尚不能确认共享成功。";
120
+ log(JSON.stringify(report));
121
+ return report;
122
+ }