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
@@ -1,16 +1,27 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname } from "node:path";
4
- export const AGENTROAM_VERSION = "0.2.0-preview.8";
4
+ import { MINIMUM_NODE_VERSION, assertSupportedNodeVersion } from "../bin/runtime-policy.mjs";
5
+ const CLI_PACKAGE_JSON = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
6
+ /**
7
+ * CLI 自身版本。
8
+ *
9
+ * **唯一源头是 packages/cli/package.json 的 version** —— 发版时只改那一处,
10
+ * 本文件、bin/node-preflight.mjs、tunnel/public-readiness.ts 全部自动跟随。
11
+ */
12
+ export const AGENTROAM_VERSION = CLI_PACKAGE_JSON.version;
13
+ export const PLATFORM_DEPENDENCY_VERSIONS = CLI_PACKAGE_JSON.optionalDependencies;
5
14
  export const PLATFORM_PACKAGES = {
6
15
  "darwin-arm64": {
7
16
  runtime: "agentroam-runtime-darwin-arm64",
8
17
  cloudflared: "agentroam-cloudflared-darwin-arm64",
18
+ tailscale: "agentroam-tailscale-darwin-arm64",
9
19
  tui: "agentroam-tui-darwin-arm64",
10
20
  },
11
21
  "windows-amd64": {
12
22
  runtime: "agentroam-runtime-win32-x64",
13
23
  cloudflared: "agentroam-cloudflared-win32-x64",
24
+ tailscale: "agentroam-tailscale-win32-x64",
14
25
  tui: "@caoqu/agentroam-tui-win32-x64",
15
26
  },
16
27
  };
@@ -35,14 +46,16 @@ export function resolvePlatformRuntime(target, requireFromCli = createRequire(im
35
46
  throw error;
36
47
  }
37
48
  const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
38
- if (manifest.packageVersion !== AGENTROAM_VERSION
49
+ if (manifest.packageVersion !== PLATFORM_DEPENDENCY_VERSIONS[packageName]
39
50
  || manifest.target !== target
40
- || manifest.nodeMajor !== 22
41
- || manifest.nodeModuleAbi !== 127
51
+ || manifest.schemaVersion !== 2
52
+ || manifest.minimumNodeVersion !== MINIMUM_NODE_VERSION
42
53
  || !manifest.nativeFiles
43
- || typeof manifest.nativeFiles !== "object") {
54
+ || typeof manifest.nativeFiles !== "object"
55
+ || Array.isArray(manifest.nativeFiles)) {
44
56
  throw new Error(`invalid AgentRoam runtime manifest: ${manifestPath}`);
45
57
  }
58
+ assertSupportedNodeVersion();
46
59
  return {
47
60
  packageName,
48
61
  runtimeRoot: dirname(runtimePackageJson),
package/dist/platform.js CHANGED
@@ -1,7 +1,5 @@
1
- export function detectPlatform(platform = process.platform, arch = process.arch, nodeVersion = process.versions.node) {
2
- const major = Number(nodeVersion.split(".")[0]);
3
- if (major !== 22)
4
- throw Object.assign(new Error(`Node.js 22 required (current ${nodeVersion})`), { exitCode: 2 });
1
+ import { assertSupportedNodeVersion } from "../bin/runtime-policy.mjs";
2
+ export function detectPlatformTarget(platform = process.platform, arch = process.arch) {
5
3
  if (platform === "darwin" && arch === "arm64")
6
4
  return "darwin-arm64";
7
5
  if (platform === "darwin" && arch === "x64")
@@ -10,3 +8,7 @@ export function detectPlatform(platform = process.platform, arch = process.arch,
10
8
  return "windows-amd64";
11
9
  throw Object.assign(new Error(`unsupported platform: ${platform}-${arch}`), { exitCode: 2 });
12
10
  }
11
+ export function detectPlatform(platform = process.platform, arch = process.arch, nodeVersion = process.versions.node) {
12
+ assertSupportedNodeVersion(nodeVersion);
13
+ return detectPlatformTarget(platform, arch);
14
+ }
@@ -0,0 +1,161 @@
1
+ import { spawn } from "node:child_process";
2
+ export async function acquireSleepInhibitor(options = {}) {
3
+ const platform = options.platform ?? process.platform;
4
+ const pid = options.pid ?? process.pid;
5
+ const spawnProcess = options.spawnProcess ?? spawn;
6
+ // Windows PowerShell compiles the P/Invoke helper on first use. Cold startup
7
+ // and antivirus scanning can take longer than five seconds.
8
+ const readyTimeoutMs = options.readyTimeoutMs ?? (platform === "win32" ? 30_000 : 5_000);
9
+ const stopTimeoutMs = options.stopTimeoutMs ?? 2_000;
10
+ if (platform === "darwin") {
11
+ const child = spawnProcess("/usr/bin/caffeinate", ["-i", "-w", String(pid)], {
12
+ stdio: "ignore",
13
+ windowsHide: true,
14
+ });
15
+ await waitForSpawn(child, readyTimeoutMs, "macOS idle-sleep inhibitor");
16
+ return monitorChild(child, stopTimeoutMs, "macOS idle-sleep inhibitor");
17
+ }
18
+ if (platform === "win32") {
19
+ const script = buildWindowsSleepInhibitorScript(pid);
20
+ const child = spawnProcess("powershell.exe", [
21
+ "-NoProfile",
22
+ "-NonInteractive",
23
+ "-ExecutionPolicy", "Bypass",
24
+ "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64"),
25
+ ], {
26
+ stdio: ["ignore", "pipe", "pipe"],
27
+ windowsHide: true,
28
+ });
29
+ try {
30
+ await waitForReadyLine(child, readyTimeoutMs);
31
+ }
32
+ catch (error) {
33
+ // A timed-out child otherwise keeps Node alive after startup has failed.
34
+ if (child.exitCode === null && child.signalCode === null)
35
+ child.kill("SIGKILL");
36
+ throw error;
37
+ }
38
+ return monitorChild(child, stopTimeoutMs, "Windows idle-sleep inhibitor");
39
+ }
40
+ throw new Error(`idle-sleep prevention is unsupported on ${platform}`);
41
+ }
42
+ export function buildWindowsSleepInhibitorScript(parentPid) {
43
+ return String.raw `
44
+ $ErrorActionPreference = "Stop"
45
+ $source = @'
46
+ using System;
47
+ using System.Runtime.InteropServices;
48
+ public static class AgentRoamPower {
49
+ [DllImport("kernel32.dll", SetLastError = true)]
50
+ public static extern uint SetThreadExecutionState(uint esFlags);
51
+ }
52
+ '@
53
+ Add-Type -TypeDefinition $source
54
+ $continuous = [uint32]::Parse("80000000", [Globalization.NumberStyles]::HexNumber)
55
+ $systemRequired = [uint32]1
56
+ $result = [AgentRoamPower]::SetThreadExecutionState($continuous -bor $systemRequired)
57
+ if ($result -eq 0) { throw "SetThreadExecutionState failed" }
58
+ [Console]::Out.WriteLine("AGENTROAM_SLEEP_INHIBITOR_READY")
59
+ try {
60
+ Wait-Process -Id ${parentPid}
61
+ } finally {
62
+ [void][AgentRoamPower]::SetThreadExecutionState($continuous)
63
+ }
64
+ `;
65
+ }
66
+ function waitForSpawn(child, timeoutMs, label) {
67
+ return new Promise((resolveReady, rejectReady) => {
68
+ const timeout = setTimeout(() => finish(new Error(`${label} did not start within ${timeoutMs}ms`)), timeoutMs);
69
+ const onError = (error) => finish(error);
70
+ const onExit = (code, signal) => {
71
+ finish(new Error(`${label} exited before readiness (${formatExit(code, signal)})`));
72
+ };
73
+ const onSpawn = () => finish();
74
+ const finish = (error) => {
75
+ clearTimeout(timeout);
76
+ child.removeListener("error", onError);
77
+ child.removeListener("exit", onExit);
78
+ child.removeListener("spawn", onSpawn);
79
+ if (error)
80
+ rejectReady(error);
81
+ else
82
+ resolveReady();
83
+ };
84
+ child.once("error", onError);
85
+ child.once("exit", onExit);
86
+ child.once("spawn", onSpawn);
87
+ });
88
+ }
89
+ function waitForReadyLine(child, timeoutMs) {
90
+ return new Promise((resolveReady, rejectReady) => {
91
+ let stdout = "";
92
+ let stderr = "";
93
+ const timeout = setTimeout(() => {
94
+ finish(new Error(`Windows idle-sleep inhibitor did not become ready within ${timeoutMs}ms`));
95
+ }, timeoutMs);
96
+ const onStdout = (chunk) => {
97
+ stdout += chunk.toString();
98
+ if (stdout.includes("AGENTROAM_SLEEP_INHIBITOR_READY"))
99
+ finish();
100
+ };
101
+ const onStderr = (chunk) => { stderr += chunk.toString(); };
102
+ const onError = (error) => finish(error);
103
+ const onExit = (code, signal) => {
104
+ const detail = stderr.trim();
105
+ finish(new Error(`Windows idle-sleep inhibitor exited before readiness (${formatExit(code, signal)})${detail ? `: ${detail}` : ""}`));
106
+ };
107
+ const finish = (error) => {
108
+ clearTimeout(timeout);
109
+ child.stdout?.removeListener("data", onStdout);
110
+ child.stderr?.removeListener("data", onStderr);
111
+ child.removeListener("error", onError);
112
+ child.removeListener("exit", onExit);
113
+ if (error)
114
+ rejectReady(error);
115
+ else
116
+ resolveReady();
117
+ };
118
+ child.stdout?.on("data", onStdout);
119
+ child.stderr?.on("data", onStderr);
120
+ child.once("error", onError);
121
+ child.once("exit", onExit);
122
+ });
123
+ }
124
+ function monitorChild(child, stopTimeoutMs, label) {
125
+ let releasing = false;
126
+ let released = false;
127
+ let resolveLost;
128
+ const lost = new Promise((resolvePromise) => { resolveLost = resolvePromise; });
129
+ const exited = new Promise((resolveExit) => {
130
+ child.once("exit", (code, signal) => {
131
+ if (!releasing)
132
+ resolveLost(new Error(`${label} stopped unexpectedly (${formatExit(code, signal)})`));
133
+ resolveExit();
134
+ });
135
+ child.once("error", (error) => {
136
+ if (!releasing)
137
+ resolveLost(error);
138
+ });
139
+ });
140
+ return {
141
+ lost,
142
+ async release() {
143
+ if (released)
144
+ return;
145
+ released = true;
146
+ releasing = true;
147
+ if (child.exitCode !== null || child.signalCode !== null)
148
+ return;
149
+ child.kill("SIGTERM");
150
+ await Promise.race([exited, delay(stopTimeoutMs)]);
151
+ if (child.exitCode === null && child.signalCode === null)
152
+ child.kill("SIGKILL");
153
+ },
154
+ };
155
+ }
156
+ function formatExit(code, signal) {
157
+ return signal ? `signal ${signal}` : `exit ${code ?? 1}`;
158
+ }
159
+ function delay(timeoutMs) {
160
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, timeoutMs));
161
+ }
@@ -1,34 +1,82 @@
1
+ import { loadMeshEnvironment } from "./mesh/mesh-config.js";
1
2
  import { mkdir } from "node:fs/promises";
2
3
  import { delimiter, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { resolveCodexRuntime, } from "./codex-runtime-manager.js";
3
6
  import { repairNativeRuntimePermissions } from "./native-runtime.js";
7
+ import { resolveOpenCodeRuntime, } from "./opencode-runtime-manager.js";
4
8
  import { resolvePlatformRuntime } from "./platform-packages.js";
5
9
  import { findAvailablePort } from "./port.js";
6
10
  import { ProcessSupervisor } from "./process-supervisor.js";
11
+ import { ensureWindowsBackend } from "./codex-windows-backend.js";
12
+ import { configureCodexSharing } from "./codex-sharing.js";
13
+ import { withCliProgress } from "../bin/cli-progress.mjs";
14
+ import { withAbortSignal, withTimeout } from "./abort.js";
15
+ export const CODEX_PREPARATION_TIMEOUT_MS = 180_000;
16
+ const OPTIONAL_RUNTIME_CHECK_TIMEOUT_MS = 60_000;
17
+ const CODEX_SHARING_TIMEOUT_MS = 10_000;
7
18
  export class RuntimeManager {
8
19
  supervisor;
9
- constructor(supervisor = new ProcessSupervisor()) {
20
+ codexResolver;
21
+ report;
22
+ opencodeResolver;
23
+ constructor(supervisor = new ProcessSupervisor(), codexResolver = resolveCodexRuntime, report = (message) => process.stderr.write(`${message}\n`), opencodeResolver = resolveOpenCodeRuntime) {
10
24
  this.supervisor = supervisor;
25
+ this.codexResolver = codexResolver;
26
+ this.report = report;
27
+ this.opencodeResolver = opencodeResolver;
11
28
  }
12
- async start(options, pairing, target) {
29
+ async start(options, target) {
13
30
  const port = await findAvailablePort(options.port);
14
31
  const dataDir = resolve(options.dataDir);
15
32
  await Promise.all(["data", "bin", "cache", "logs"].map((name) => mkdir(resolve(dataDir, name), { recursive: true })));
33
+ const { AGENTROAM_MESH_ACTIVATION_CODE: _, ...runtimeEnvironment } = process.env;
34
+ const childEnvironment = await withCliProgress("正在检查 Agent 组件;缺少 Codex 时自动安装最新版,最多等待 180 秒", () => prepareAgentRuntimeEnvironment(runtimeEnvironment, { dataDir, target }, this.codexResolver, this.report, this.opencodeResolver));
35
+ if (process.platform === "darwin" && childEnvironment.AGENT_CODEX_BIN) {
36
+ try {
37
+ await withTimeout(signal => configureCodexSharing(options, { environment: childEnvironment, signal }), CODEX_SHARING_TIMEOUT_MS, "Codex 共享后台配置超时(10 秒)");
38
+ }
39
+ catch (error) {
40
+ this.report(`Codex 共享启动配置未完成,可在电脑菜单中修复:${error instanceof Error ? error.message : error}`);
41
+ }
42
+ }
43
+ if (process.platform === "win32" && childEnvironment.AGENT_CODEX_BIN) {
44
+ try {
45
+ const backend = await ensureWindowsBackend(dataDir, { environment: childEnvironment });
46
+ childEnvironment.AGENT_CODEX_DESKTOP_WS_URL = backend.endpoint;
47
+ }
48
+ catch (error) {
49
+ this.report(`Codex 共享后台未就绪,可在头像菜单重试:${error instanceof Error ? error.message : error}`);
50
+ }
51
+ }
16
52
  const { runtimeRoot } = resolvePlatformRuntime(target);
17
53
  await repairNativeRuntimePermissions(runtimeRoot);
18
54
  const gateway = resolve(runtimeRoot, "ws-server.mjs");
19
- const child = this.supervisor.spawn(process.execPath, [gateway], {
55
+ const meshEnvironment = await loadMeshEnvironment(dataDir, process.env).catch(error => {
56
+ if (process.env.AGENTROAM_MESH_ACTIVATION_CODE?.trim())
57
+ throw error;
58
+ this.report(`组网配置未加载:${error.message}`);
59
+ return {};
60
+ });
61
+ const child = this.supervisor.spawn(process.execPath, [gateway, ...(options.testNoPairing ? ["--test-no-pairing"] : [])], {
62
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
20
63
  cwd: runtimeRoot,
21
64
  env: {
22
- ...process.env,
65
+ ...childEnvironment,
66
+ ...meshEnvironment,
23
67
  NODE_ENV: "production",
24
68
  NEXT_DIST_DIR: ".next",
25
69
  PORT: String(port),
26
- HOST: "127.0.0.1",
70
+ HOST: "0.0.0.0",
27
71
  AGENT_DATA_DIR: resolve(dataDir, "data"),
72
+ // 应用日志收口到 <dataDir>/logs,与 launchd 的 service.stdout/stderr.log
73
+ // 及 CLI 自身的错误日志同一个目录,用户排障时只需打包这一处。
74
+ AGENT_LOG_DIR: resolve(dataDir, "logs"),
28
75
  AGENT_WEB_ROOTS: options.roots.join(delimiter),
29
76
  AGENT_TRUST_TUNNEL_PROXY: "1",
30
- AGENT_PAIRING_HASH: pairing?.hashHex || "",
31
- AGENT_PAIRING_EXPIRES_AT: pairing?.expiresAt || "",
77
+ AGENTROAM_VERSION: resolvePlatformRuntime(target).manifest.packageVersion,
78
+ AGENTROAM_DATA_DIR: dataDir,
79
+ AGENTROAM_CLI_PATH: fileURLToPath(new URL("../bin/agentroam.mjs", import.meta.url)),
32
80
  },
33
81
  });
34
82
  const log = (stream) => stream?.on("data", (chunk) => process.stderr.write(chunk));
@@ -38,7 +86,14 @@ export class RuntimeManager {
38
86
  child.once("exit", (code, signal) => resolveExit({ code, signal }));
39
87
  });
40
88
  const localUrl = `http://127.0.0.1:${port}`;
41
- const status = await waitForHealth(`${localUrl}/api/web-auth/status`, child, 20_000);
89
+ let status;
90
+ try {
91
+ status = await withCliProgress("正在等待本机服务就绪", () => waitForHealth(`${localUrl}/api/web-auth/status`, child, 20_000));
92
+ }
93
+ catch (error) {
94
+ await this.supervisor.stopAll();
95
+ throw error;
96
+ }
42
97
  return {
43
98
  port,
44
99
  localUrl,
@@ -50,18 +105,83 @@ export class RuntimeManager {
50
105
  };
51
106
  }
52
107
  }
108
+ export async function prepareAgentRuntimeEnvironment(environment, options, codexResolver = resolveCodexRuntime, report = (message) => process.stderr.write(`${message}\n`), opencodeResolver = resolveOpenCodeRuntime) {
109
+ const [codex, opencode] = await Promise.all([
110
+ prepareCodexRuntimeEnvironment(environment, options, codexResolver, report),
111
+ prepareOpenCodeRuntimeEnvironment(environment, options, opencodeResolver, report),
112
+ ]);
113
+ return {
114
+ ...codex,
115
+ AGENT_OPENCODE_BIN: opencode.AGENT_OPENCODE_BIN,
116
+ AGENT_OPENCODE_RUNTIME_ERROR: opencode.AGENT_OPENCODE_RUNTIME_ERROR,
117
+ };
118
+ }
119
+ export async function prepareCodexRuntimeEnvironment(environment, options, resolver = resolveCodexRuntime, report = (message) => process.stderr.write(`${message}\n`)) {
120
+ const childEnvironment = { ...environment };
121
+ const timeoutMs = options.timeoutMs ?? CODEX_PREPARATION_TIMEOUT_MS;
122
+ report(`Checking Codex ${options.target} runtime...`);
123
+ try {
124
+ const resolution = await withTimeout(signal => resolver({
125
+ dataDir: options.dataDir,
126
+ target: options.target,
127
+ signal,
128
+ environment,
129
+ onProgress: report,
130
+ }), timeoutMs, `Codex 组件准备超时(${timeoutMs / 1000} 秒);请检查网络后运行 agentroam doctor 重试。`);
131
+ childEnvironment.AGENT_CODEX_BIN = resolution.executable;
132
+ delete childEnvironment.AGENT_CODEX_RUNTIME_ERROR;
133
+ report(`Codex ${resolution.version} (${resolution.source}): ${resolution.executable}`);
134
+ }
135
+ catch (error) {
136
+ delete childEnvironment.AGENT_CODEX_BIN;
137
+ const message = error instanceof Error ? error.message : String(error);
138
+ childEnvironment.AGENT_CODEX_RUNTIME_ERROR = message;
139
+ report(`⚠ Codex 会话功能未就绪,局域网服务将继续启动;运行 agentroam doctor 修复后重启服务:${message}`);
140
+ }
141
+ return childEnvironment;
142
+ }
143
+ export async function prepareOpenCodeRuntimeEnvironment(environment, options, resolver = resolveOpenCodeRuntime, report = (message) => process.stderr.write(`${message}\n`)) {
144
+ const childEnvironment = { ...environment };
145
+ report(`Checking OpenCode ${options.target} runtime...`);
146
+ try {
147
+ const resolution = await withTimeout(signal => resolver({
148
+ dataDir: options.dataDir, target: options.target, environment, signal, installIfMissing: false, onProgress: report,
149
+ }), options.timeoutMs ?? OPTIONAL_RUNTIME_CHECK_TIMEOUT_MS, "OpenCode 组件检查超时;已跳过,不下载安装。");
150
+ childEnvironment.AGENT_OPENCODE_BIN = resolution.executable;
151
+ delete childEnvironment.AGENT_OPENCODE_RUNTIME_ERROR;
152
+ report(`OpenCode ${resolution.version} (${resolution.source}): ${resolution.executable}`);
153
+ }
154
+ catch (error) {
155
+ delete childEnvironment.AGENT_OPENCODE_BIN;
156
+ const message = error instanceof Error ? error.message : String(error);
157
+ childEnvironment.AGENT_OPENCODE_RUNTIME_ERROR = message;
158
+ report(`OpenCode 不可用,已跳过(不自动安装):${message}`);
159
+ }
160
+ return childEnvironment;
161
+ }
53
162
  async function waitForHealth(url, child, timeoutMs) {
54
163
  const end = Date.now() + timeoutMs;
55
- while (Date.now() < end) {
56
- if (child.exitCode !== null)
57
- throw new Error(`local server exited with ${child.exitCode}`);
58
- try {
59
- const response = await fetch(url);
60
- if (response.ok)
61
- return response.json();
62
- }
63
- catch { }
64
- await new Promise((resolveWait) => setTimeout(resolveWait, 250));
164
+ const controller = new AbortController();
165
+ const timer = setTimeout(() => controller.abort(new Error("local server health check timed out")), timeoutMs);
166
+ try {
167
+ return await withAbortSignal(async () => {
168
+ while (Date.now() < end) {
169
+ controller.signal.throwIfAborted();
170
+ if (child.exitCode !== null)
171
+ throw new Error(`local server exited with ${child.exitCode}`);
172
+ try {
173
+ const response = await fetch(url, { signal: controller.signal });
174
+ if (response.ok)
175
+ return response.json();
176
+ void response.body?.cancel().catch(() => { });
177
+ }
178
+ catch { }
179
+ await new Promise((resolveWait) => setTimeout(resolveWait, 250));
180
+ }
181
+ throw new Error("local server health check timed out");
182
+ }, controller.signal);
183
+ }
184
+ finally {
185
+ clearTimeout(timer);
65
186
  }
66
- throw new Error("local server health check timed out");
67
187
  }
@@ -0,0 +1 @@
1
+ {"url":"https://connect.kaiwuyouwei.com"}
@@ -0,0 +1,79 @@
1
+ import { lstat, readFile, readdir, realpath, rm } from "node:fs/promises";
2
+ import { relative, resolve, sep } from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ const execFileAsync = promisify(execFile);
6
+ async function processPathsInUse() {
7
+ // Windows has no reliable cwd inventory here: retain old installs instead.
8
+ if (process.platform === "win32")
9
+ throw new Error("Process paths unavailable");
10
+ const { stdout } = await execFileAsync(process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof", ["-nP", "-d", "cwd,txt", "-Fn"], { timeout: 5_000, maxBuffer: 16 * 1024 * 1024 });
11
+ const paths = stdout.split("\n").filter(line => line.startsWith("n/")).map(line => line.slice(1));
12
+ if (!paths.length)
13
+ throw new Error("Incomplete process paths");
14
+ return [process.cwd(), ...paths];
15
+ }
16
+ function versionParts(version) {
17
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-preview\.(0|[1-9]\d*))?$/.exec(version);
18
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3]), match[4] === undefined ? Infinity : Number(match[4])] : null;
19
+ }
20
+ function older(candidate, current) {
21
+ const left = versionParts(candidate), right = versionParts(current);
22
+ if (!left || !right)
23
+ return false;
24
+ for (let i = 0; i < left.length; i++)
25
+ if (left[i] !== right[i])
26
+ return left[i] < right[i];
27
+ return false;
28
+ }
29
+ function contains(parent, child) {
30
+ const path = relative(parent, child);
31
+ return path === "" || (!path.startsWith(`..${sep}`) && path !== ".." && !path.startsWith(sep));
32
+ }
33
+ /** Remove only recognized managed launcher versions after the replacement service is ready. */
34
+ export async function cleanupOldLaunchers(config, log, context = {}) {
35
+ try {
36
+ const dataDir = await realpath(config.dataDir);
37
+ const launcherDir = resolve(dataDir, "launcher");
38
+ if (!(await lstat(launcherDir)).isDirectory() || (await lstat(launcherDir)).isSymbolicLink())
39
+ return;
40
+ const currentDir = resolve(launcherDir, config.version);
41
+ const expectedEntry = resolve(currentDir, "node_modules/agentroam/bin/agentroam.mjs");
42
+ if (await realpath(config.cliPath) !== expectedEntry)
43
+ return;
44
+ const roots = await Promise.all(config.roots.map(async (root) => realpath(root).catch(() => resolve(root))));
45
+ for (const entry of await readdir(launcherDir, { withFileTypes: true })) {
46
+ if (!entry.isDirectory() || !older(entry.name, config.version))
47
+ continue;
48
+ const candidate = resolve(launcherDir, entry.name);
49
+ try {
50
+ if (await lstat(`${candidate}.lock`).then(() => true, () => false))
51
+ continue;
52
+ if (roots.some(root => contains(candidate, root)))
53
+ continue;
54
+ const files = await readdir(candidate);
55
+ if (files.some(file => !["node_modules", "package.json", "package-lock.json"].includes(file)))
56
+ continue;
57
+ const manifestPath = resolve(candidate, "node_modules/agentroam/package.json");
58
+ if (await realpath(manifestPath) !== manifestPath)
59
+ continue;
60
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
61
+ if (manifest.name !== "agentroam" || manifest.version !== entry.name)
62
+ continue;
63
+ const usedPaths = await (context.pathsInUse ?? processPathsInUse)();
64
+ if (usedPaths.some(path => contains(candidate, path))) {
65
+ log(`旧版 CLI ${entry.name} 仍被进程使用,已保留。`);
66
+ continue;
67
+ }
68
+ await rm(candidate, { recursive: true });
69
+ log(`✓ 已清理旧版 CLI ${entry.name},配置和数据已保留`);
70
+ }
71
+ catch {
72
+ log(`旧版 CLI ${entry.name} 暂未清理,将在下次安装时重试。`);
73
+ }
74
+ }
75
+ }
76
+ catch {
77
+ log("旧版 CLI 清理已跳过,新版服务不受影响。");
78
+ }
79
+ }