agentroam 0.2.0-preview.8 → 0.2.0-preview.81

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 +177 -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,105 @@
1
+ import { execFile } from "node:child_process";
2
+ import { resolve } from "node:path";
3
+ const SERVICE_NAME = "AgentRoamUnlock";
4
+ const DISPLAY_NAME = "AgentRoam Remote Unlock";
5
+ // Keep the event loop free while PowerShell waits for UAC or service control.
6
+ const runFile = (file, args, options) => new Promise((resolveResult) => {
7
+ execFile(file, [...args], options, (error, stdout, stderr) => {
8
+ resolveResult({ stdout, stderr, status: error ? 1 : 0,
9
+ ...(error && typeof error.code !== "number" ? { error } : {}),
10
+ });
11
+ });
12
+ });
13
+ function psQuote(value) {
14
+ return `'${value.replaceAll("'", "''")}'`;
15
+ }
16
+ export function encodePowerShell(script) {
17
+ return Buffer.from(script, "utf16le").toString("base64");
18
+ }
19
+ export function unlockServiceExecutable(runtimeRoot) {
20
+ return resolve(runtimeRoot, "native", "agentroam-remote-unlock.exe");
21
+ }
22
+ export function buildUnlockServiceAdminScript(action, executable) {
23
+ const common = `$ErrorActionPreference = 'Stop'\n$serviceName = '${SERVICE_NAME}'`;
24
+ if (action === "uninstall") {
25
+ return `${common}
26
+ $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
27
+ if ($service) {
28
+ if ($service.Status -ne 'Stopped') { Stop-Service -Name $serviceName -Force -ErrorAction Stop }
29
+ & "$env:SystemRoot\\System32\\sc.exe" delete $serviceName | Out-Null
30
+ if ($LASTEXITCODE -ne 0) { throw "sc.exe delete failed: $LASTEXITCODE" }
31
+ }
32
+ `;
33
+ }
34
+ const binaryPath = `\"${executable}\" --service`;
35
+ return `${common}
36
+ $binary = ${psQuote(executable)}
37
+ if (-not (Test-Path -LiteralPath $binary -PathType Leaf)) { throw "Remote unlock helper is missing: $binary" }
38
+ $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
39
+ if ($service) {
40
+ if ($service.Status -ne 'Stopped') { Stop-Service -Name $serviceName -Force -ErrorAction Stop }
41
+ & "$env:SystemRoot\\System32\\sc.exe" delete $serviceName | Out-Null
42
+ if ($LASTEXITCODE -ne 0) { throw "sc.exe delete failed: $LASTEXITCODE" }
43
+ for ($attempt = 0; $attempt -lt 50 -and (Get-Service -Name $serviceName -ErrorAction SilentlyContinue); $attempt++) { Start-Sleep -Milliseconds 100 }
44
+ }
45
+ New-Service -Name $serviceName -BinaryPathName ${psQuote(binaryPath)} -DisplayName '${DISPLAY_NAME}' -StartupType Automatic | Out-Null
46
+ & "$env:SystemRoot\\System32\\sc.exe" description $serviceName "Allows an authorized AgentRoam session to wake and unlock the Windows secure desktop." | Out-Null
47
+ Start-Service -Name $serviceName -ErrorAction Stop
48
+ `;
49
+ }
50
+ export function buildElevatedPowerShell(adminScript) {
51
+ const payload = encodePowerShell(adminScript);
52
+ return `$ErrorActionPreference = 'Stop'
53
+ $powershell = Join-Path $PSHOME 'powershell.exe'
54
+ $process = Start-Process -FilePath $powershell -Verb RunAs -Wait -PassThru -ArgumentList @('-NoLogo','-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','${payload}')
55
+ exit $process.ExitCode
56
+ `;
57
+ }
58
+ export function parseUnlockServiceStatus(output) {
59
+ const value = output.trim().split(/\r?\n/).at(-1)?.trim().toLowerCase();
60
+ if (value === "running" || value === "stopped" || value === "missing")
61
+ return value;
62
+ throw new Error("无法读取远程解锁服务状态");
63
+ }
64
+ function runPowerShell(script, runner) {
65
+ return runner("powershell.exe", [
66
+ "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
67
+ "-EncodedCommand", encodePowerShell(script),
68
+ ], { encoding: "utf8", windowsHide: true });
69
+ }
70
+ export async function queryUnlockServiceStatus(runner = runFile) {
71
+ const script = `$service = Get-Service -Name '${SERVICE_NAME}' -ErrorAction SilentlyContinue
72
+ if (-not $service) { Write-Output 'missing' } elseif ($service.Status -eq 'Running') { Write-Output 'running' } else { Write-Output 'stopped' }
73
+ `;
74
+ const result = await runPowerShell(script, runner);
75
+ if (result.error)
76
+ throw result.error;
77
+ if (result.status !== 0)
78
+ throw new Error((result.stderr || "远程解锁服务状态查询失败").trim());
79
+ return parseUnlockServiceStatus(result.stdout || "");
80
+ }
81
+ export async function runUnlockServiceCommand(action, runtimeRoot, options = {}) {
82
+ const platform = options.platform ?? process.platform;
83
+ const runner = options.runner ?? runFile;
84
+ const log = options.log ?? console.log;
85
+ if (platform !== "win32")
86
+ throw new Error("远程解锁服务仅支持 Windows 10/11 x64");
87
+ if (action === "status") {
88
+ const status = await queryUnlockServiceStatus(runner);
89
+ log(status === "running" ? "远程解锁服务正在运行" : status === "stopped" ? "远程解锁服务已安装但未运行" : "远程解锁服务未安装");
90
+ return;
91
+ }
92
+ const executable = unlockServiceExecutable(runtimeRoot);
93
+ const result = await runPowerShell(buildElevatedPowerShell(buildUnlockServiceAdminScript(action, executable)), runner);
94
+ if (result.error)
95
+ throw result.error;
96
+ if (result.status !== 0) {
97
+ throw new Error((result.stderr || (action === "install" ? "远程解锁服务安装失败或已取消管理员授权" : "远程解锁服务卸载失败或已取消管理员授权")).trim());
98
+ }
99
+ const status = await queryUnlockServiceStatus(runner);
100
+ if (action === "install" && status !== "running")
101
+ throw new Error("远程解锁服务安装后未能启动");
102
+ if (action === "uninstall" && status !== "missing")
103
+ throw new Error("远程解锁服务卸载后仍然存在");
104
+ log(action === "install" ? "远程解锁服务已安装并启动" : "远程解锁服务已卸载");
105
+ }
@@ -0,0 +1,38 @@
1
+ const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-preview\.(0|[1-9]\d*))?$/;
2
+ export function parseAgentRoamVersion(value) {
3
+ const match = VERSION.exec(value);
4
+ if (!match)
5
+ return null;
6
+ return {
7
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
8
+ preview: match[4] === undefined ? null : Number(match[4]),
9
+ };
10
+ }
11
+ // A prerelease installation follows the preview channel; a stable installation
12
+ // follows latest. Preview users are also offered a newer stable release so they
13
+ // can migrate to the stable track without reinstalling.
14
+ export function resolveUpdateChannel(currentVersion) {
15
+ const parsed = parseAgentRoamVersion(currentVersion);
16
+ if (!parsed)
17
+ throw new Error("invalid AgentRoam version");
18
+ return parsed.preview === null ? "latest" : "preview";
19
+ }
20
+ export function resolveReleaseChannel(version) {
21
+ const parsed = parseAgentRoamVersion(version);
22
+ if (!parsed)
23
+ throw new Error("invalid AgentRoam version");
24
+ return parsed.preview === null ? "latest" : "preview";
25
+ }
26
+ export function registryUrlsForChannel(channel, registryBase) {
27
+ return channel === "preview" ? [`${registryBase}/latest`, `${registryBase}/preview`] : [`${registryBase}/latest`];
28
+ }
29
+ export function parseChannelVersion(value, channel) {
30
+ if (typeof value !== "string")
31
+ return null;
32
+ const parsed = parseAgentRoamVersion(value);
33
+ if (!parsed)
34
+ return null;
35
+ if (parsed.preview === null)
36
+ return value;
37
+ return channel === "preview" ? value : null;
38
+ }
@@ -0,0 +1,97 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { fileURLToPath } from "node:url";
5
+ import { resolve } from "node:path";
6
+ import { updatePaths, writeUpdateState } from "./update-state.js";
7
+ import { parseChannelVersion, registryUrlsForChannel, resolveUpdateChannel, } from "./update-channel.js";
8
+ import { buildCliInstallManifestUrl, validateCliInstallManifest } from "./update-install.js";
9
+ const REGISTRY_BASE = "https://registry.npmjs.org/agentroam";
10
+ export async function resolveUpdate(options, fetchImpl = fetch) {
11
+ const channel = resolveUpdateChannel(options.currentVersion);
12
+ const target = await readRegistryCandidate(fetchImpl, channel);
13
+ if (!target)
14
+ throw new Error("unable to check the npm release channel");
15
+ if (options.requestedVersion && options.requestedVersion !== target)
16
+ throw new Error("requested version is not the current npm candidate");
17
+ if (compare(target, options.currentVersion) <= 0)
18
+ throw new Error("AgentRoam is already up to date");
19
+ const response = await fetchWithTimeout(fetchImpl, buildCliInstallManifestUrl());
20
+ if (!response.ok)
21
+ throw new Error("CLI install manifest is unavailable");
22
+ const asset = validateCliInstallManifest(await response.json(), options.target);
23
+ return { targetVersion: target, fileName: asset.fileName, sha256: asset.sha256 };
24
+ }
25
+ // Preview installations follow the higher of the preview and latest npm
26
+ // dist-tags so a newer stable release can move them onto the stable track.
27
+ async function readRegistryCandidate(fetchImpl, channel) {
28
+ let best = null;
29
+ for (const url of registryUrlsForChannel(channel, REGISTRY_BASE)) {
30
+ const response = await fetchWithTimeout(fetchImpl, url).catch(() => null);
31
+ if (!response?.ok)
32
+ continue;
33
+ const candidate = parseChannelVersion((await response.json()).version, channel);
34
+ if (!candidate)
35
+ continue;
36
+ if (!best || compare(candidate, best) > 0)
37
+ best = candidate;
38
+ }
39
+ return best;
40
+ }
41
+ export async function startUpdate(options) {
42
+ const release = await resolveUpdate(options);
43
+ const paths = updatePaths(options.dataDir);
44
+ const service = await readServiceConfig();
45
+ const state = {
46
+ schemaVersion: 1,
47
+ phase: "downloading",
48
+ currentVersion: options.currentVersion,
49
+ ...release,
50
+ dataDir: resolve(options.dataDir),
51
+ roots: service?.roots?.length ? service.roots : [process.cwd()],
52
+ port: service?.port ?? null,
53
+ relay: service?.relay ?? "auto",
54
+ tunnelCommand: service?.tunnelCommand ?? null,
55
+ ...(service?.relayUrl ? { relayUrl: service.relayUrl } : {}),
56
+ localOnly: service?.localOnly ?? false,
57
+ cliPath: resolve(options.cliPath),
58
+ updatedAt: Date.now(),
59
+ };
60
+ await writeUpdateState(paths.stateFile, state);
61
+ const child = spawn(process.execPath, [options.cliPath, "update-worker", paths.stateFile], { detached: true, stdio: "ignore", windowsHide: true });
62
+ child.unref();
63
+ return state;
64
+ }
65
+ async function readServiceConfig() {
66
+ try {
67
+ return JSON.parse(await readFile(resolve(homedir(), ".agentroam", "service", "config.json"), "utf8"));
68
+ }
69
+ catch { }
70
+ return null;
71
+ }
72
+ async function fetchWithTimeout(fetchImpl, url) {
73
+ const controller = new AbortController();
74
+ const timer = setTimeout(() => controller.abort(), 4_000);
75
+ timer.unref?.();
76
+ try {
77
+ return await fetchImpl(url, { headers: { accept: "application/json" }, signal: controller.signal });
78
+ }
79
+ finally {
80
+ clearTimeout(timer);
81
+ }
82
+ }
83
+ function compare(left, right) {
84
+ const parse = (value) => {
85
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-preview\.(\d+))?$/.exec(value);
86
+ if (!match)
87
+ throw new Error("invalid AgentRoam version");
88
+ return [...match.slice(1, 4).map(Number), match[4] === undefined ? Number.MAX_SAFE_INTEGER : Number(match[4])];
89
+ };
90
+ const a = parse(left);
91
+ const b = parse(right);
92
+ for (let i = 0; i < a.length; i += 1)
93
+ if (a[i] !== b[i])
94
+ return a[i] > b[i] ? 1 : -1;
95
+ return 0;
96
+ }
97
+ export const currentCliPath = () => fileURLToPath(new URL("../../bin/agentroam.mjs", import.meta.url));
@@ -0,0 +1,34 @@
1
+ const REPOSITORY_BASE = "https://github.com/tclxqu-cao/team-agent";
2
+ const REPOSITORY_BRANCH = "main";
3
+ const INSTALL_BASE = `${REPOSITORY_BASE}/raw/${REPOSITORY_BRANCH}/packages/cli/install`;
4
+ export const CLI_INSTALL_FILE_NAMES = {
5
+ "darwin-arm64": "install-agentroam.sh",
6
+ "windows-amd64": "install-agentroam.ps1",
7
+ };
8
+ export function buildCliInstallManifestUrl() {
9
+ return `${INSTALL_BASE}/install-manifest.json`;
10
+ }
11
+ export function buildCliInstallScriptUrl(fileName) {
12
+ if (!Object.values(CLI_INSTALL_FILE_NAMES).includes(fileName))
13
+ throw new Error("invalid CLI installer file name");
14
+ return `${INSTALL_BASE}/${fileName}`;
15
+ }
16
+ export function validateCliInstallManifest(value, platform) {
17
+ const expected = CLI_INSTALL_FILE_NAMES[platform];
18
+ if (!expected)
19
+ throw new Error("CLI install manifest does not support this platform");
20
+ if (typeof value !== "object" || value === null)
21
+ throw new Error("invalid CLI install manifest identity");
22
+ const manifest = value;
23
+ if (manifest.schemaVersion !== 1 || typeof manifest.installers !== "object" || manifest.installers === null) {
24
+ throw new Error("invalid CLI install manifest identity");
25
+ }
26
+ const asset = manifest.installers[platform];
27
+ if (!asset || asset.fileName !== expected || typeof asset.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(asset.sha256)) {
28
+ throw new Error("invalid CLI installer metadata");
29
+ }
30
+ if (asset.size !== undefined && (!Number.isSafeInteger(asset.size) || asset.size <= 0)) {
31
+ throw new Error("invalid CLI installer size");
32
+ }
33
+ return { fileName: expected, sha256: asset.sha256, ...(asset.size === undefined ? {} : { size: asset.size }) };
34
+ }
@@ -0,0 +1,43 @@
1
+ import { mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ export function updatePaths(dataDir) {
4
+ const directory = resolve(dataDir, "updates");
5
+ return { directory, stateFile: resolve(directory, "state.json"), lockFile: resolve(directory, "update.lock") };
6
+ }
7
+ export async function readUpdateState(path) {
8
+ try {
9
+ const value = JSON.parse(await readFile(path, "utf8"));
10
+ return value?.schemaVersion === 1 ? value : null;
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ export async function writeUpdateState(path, state) {
17
+ await mkdir(dirname(path), { recursive: true });
18
+ const temp = `${path}.${process.pid}.tmp`;
19
+ await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
20
+ await rename(temp, path);
21
+ }
22
+ export async function acquireUpdateLock(path, now = Date.now()) {
23
+ await mkdir(dirname(path), { recursive: true });
24
+ try {
25
+ const handle = await open(path, "wx", 0o600);
26
+ await handle.writeFile(`${process.pid}\n${now}\n`);
27
+ await handle.close();
28
+ }
29
+ catch (error) {
30
+ if (error.code !== "EEXIST")
31
+ throw error;
32
+ const age = now - (await stat(path)).mtimeMs;
33
+ if (age <= 30 * 60 * 1_000)
34
+ throw new Error("an AgentRoam update is already running");
35
+ await unlink(path);
36
+ return acquireUpdateLock(path, now);
37
+ }
38
+ return async () => { await unlink(path).catch(() => undefined); };
39
+ }
40
+ export function sanitizeUpdateError(error) {
41
+ const value = error instanceof Error ? error.message : String(error);
42
+ return value.replace(/[A-Za-z]:\\[^\s]+|\/(?:Users|home|var|tmp)\/[^\s]+/g, "<path>").slice(0, 300);
43
+ }
@@ -0,0 +1,82 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createWriteStream } from "node:fs";
3
+ import { chmod, readFile, unlink } from "node:fs/promises";
4
+ import { basename, resolve } from "node:path";
5
+ import { pipeline } from "node:stream/promises";
6
+ import { Readable } from "node:stream";
7
+ import { spawn } from "node:child_process";
8
+ import { acquireUpdateLock, readUpdateState, sanitizeUpdateError, updatePaths, writeUpdateState } from "./update-state.js";
9
+ import { buildCliInstallScriptUrl } from "./update-install.js";
10
+ export async function runUpdateWorker(stateFile, fetchImpl = fetch) {
11
+ const initial = await readUpdateState(stateFile);
12
+ if (!initial)
13
+ throw new Error("update state is missing");
14
+ const paths = updatePaths(initial.dataDir);
15
+ if (resolve(stateFile) !== paths.stateFile)
16
+ throw new Error("update state is outside the data directory");
17
+ const releaseLock = await acquireUpdateLock(paths.lockFile);
18
+ const partial = resolve(paths.directory, `${basename(initial.fileName)}.partial`);
19
+ let state = initial;
20
+ const update = async (next) => {
21
+ state = { ...state, ...next, updatedAt: Date.now() };
22
+ await writeUpdateState(stateFile, state);
23
+ };
24
+ try {
25
+ const response = await fetchImpl(buildCliInstallScriptUrl(state.fileName));
26
+ if (!response.ok || !response.body)
27
+ throw new Error("installer download failed");
28
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(partial, { mode: 0o700 }));
29
+ const actual = createHash("sha256").update(await readFile(partial)).digest("hex");
30
+ if (actual !== state.sha256)
31
+ throw new Error("installer checksum mismatch");
32
+ await chmod(partial, 0o700).catch(() => undefined);
33
+ await update({ phase: "installing" });
34
+ const command = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
35
+ const args = process.platform === "win32" ? ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", partial] : [partial];
36
+ // 用 AGENTROAM_VERSION 钉住版本,而不是让安装脚本自己解析 dist-tag:
37
+ // 一是装的必须正是检查阶段向用户承诺的那一版,二是下一步要按
38
+ // launcher/<targetVersion> 定位入口,版本漂了就找不到。
39
+ const code = await run(command, args, {
40
+ ...process.env,
41
+ AGENTROAM_VERSION: state.targetVersion,
42
+ AGENTROAM_DATA_DIR: state.dataDir,
43
+ AGENTROAM_ROOT: state.roots[0],
44
+ AGENTROAM_INSTALL_SKIP_SERVICE: "1",
45
+ });
46
+ if (code !== 0)
47
+ throw new Error(`installer exited with code ${code}`);
48
+ const nextEntry = resolve(state.dataDir, "launcher", state.targetVersion, "node_modules", "agentroam", "bin", "agentroam.mjs");
49
+ const serviceArgs = [nextEntry, "service", "install"];
50
+ for (const root of state.roots)
51
+ serviceArgs.push("--root", root);
52
+ serviceArgs.push("--data-dir", state.dataDir, "--relay", state.relay, "--no-qr");
53
+ if (state.port)
54
+ serviceArgs.push("--port", String(state.port));
55
+ if (state.tunnelCommand)
56
+ serviceArgs.push("--tunnel-command", state.tunnelCommand);
57
+ if (state.relayUrl)
58
+ serviceArgs.push("--relay-url", state.relayUrl);
59
+ if (state.localOnly)
60
+ serviceArgs.push("--local-only");
61
+ await update({ phase: "reconnecting" });
62
+ const serviceCode = await run(process.execPath, serviceArgs, process.env);
63
+ if (serviceCode !== 0)
64
+ throw new Error(`service activation exited with code ${serviceCode}`);
65
+ await update({ phase: "complete", message: `AgentRoam ${state.targetVersion} installed` });
66
+ }
67
+ catch (error) {
68
+ await update({ phase: "failed", message: sanitizeUpdateError(error) });
69
+ throw error;
70
+ }
71
+ finally {
72
+ await unlink(partial).catch(() => undefined);
73
+ await releaseLock();
74
+ }
75
+ }
76
+ function run(command, args, env) {
77
+ return new Promise((resolveRun, reject) => {
78
+ const child = spawn(command, args, { env, stdio: "ignore", windowsHide: true });
79
+ child.once("error", reject);
80
+ child.once("exit", resolveRun);
81
+ });
82
+ }
@@ -0,0 +1,55 @@
1
+ # AgentRoam bootstrap installers
2
+
3
+ These installers support macOS Apple Silicon and Windows x64. They install the newest published `preview` release by default (resolved from the npm dist-tag); pin an exact release with `AGENTROAM_VERSION=<x.y.z-preview.N>`. They reuse the active Node.js installation when it meets `>=22.22.0`, with no upper version bound. Otherwise they search NVM for the highest compatible version, then fall back to the verified private Node.js `22.22.0` runtime under the AgentRoam data directory. They then register and start the current-user AgentRoam background service. They never modify, replace, or uninstall system Node.js or global power settings.
4
+
5
+ ## macOS Apple Silicon
6
+
7
+ ```sh
8
+ curl -fsSL https://github.com/tclxqu-cao/team-agent/raw/main/packages/cli/install/install-agentroam.sh | sh
9
+ ```
10
+
11
+ The command installs the wrapper at `~/.local/bin/agentroam`. If that directory is not already in `PATH`, the installer prints the required shell setting without editing shell profiles.
12
+
13
+ ## Windows x64
14
+
15
+ ```powershell
16
+ irm https://github.com/tclxqu-cao/team-agent/raw/main/packages/cli/install/install-agentroam.ps1 | iex
17
+ ```
18
+
19
+ The command installs `%USERPROFILE%\.agentroam\bin\agentroam.cmd` and adds only that user directory to the user-level `PATH`. It does not require administrator access or change the machine-level `PATH`.
20
+
21
+ ## Service behavior
22
+
23
+ Run the installer from the project directory AgentRoam should expose, or set `AGENTROAM_ROOT` explicitly. The current directory is accepted even when it is the home directory.
24
+
25
+ The installer registers and starts the service after Node, CLI, and `doctor` validation. When a previous AgentRoam user service is installed, the new CLI stops it, waits for its process and platform registration to exit, removes only the old service registration, and then registers the replacement. Session data, pairing state, managed runtimes, and logs remain in the data directory. While foreground AgentRoam or the service is running, it prevents idle system sleep but still allows the display to dim and turn off. Lid close, explicit sleep, hibernation, shutdown, and low-battery forced sleep remain controlled by the operating system.
26
+
27
+ On interactive terminals, `service install`, `start`, `status`, and `restart` print a scannable QR code beside the `Open:` URL. Piped or redirected output stays plain text, and `agentroam service install --no-qr` suppresses the code. `service url` always prints only the raw URL for scripting.
28
+
29
+ Use the installer for first installation, upgrades, and repair. Use these commands for routine control:
30
+
31
+ ```text
32
+ agentroam service start
33
+ agentroam service stop
34
+ agentroam service restart
35
+ agentroam service status
36
+ agentroam service url
37
+ agentroam service logs
38
+ agentroam service uninstall
39
+ ```
40
+
41
+ ## Data and updates
42
+
43
+ Set `AGENTROAM_DATA_DIR` before running either installer to override the default `~/.agentroam` data directory. Node is stored at `<data-dir>/runtimes/node/22.22.0`, and the launcher is stored at `<data-dir>/launcher/<version>`.
44
+
45
+ Each AgentRoam release pins its own Node patch. Updates happen by running the installer again (it resolves the newest published `preview`) or by installing a newer AgentRoam release; startup never follows a moving Node.js release channel.
46
+
47
+ To uninstall the wrapper, remove `~/.local/bin/agentroam` on macOS or `%USERPROFILE%\.agentroam\bin\agentroam.cmd` on Windows. The private runtime, launcher, session data, and configuration under the data directory are preserved until explicitly removed by the user.
48
+
49
+ ## Optional desktop app
50
+
51
+ After CLI setup succeeds, interactive installers ask whether to download the desktop app. Answer `y` to download the matching macOS DMG or Windows installer into a unique folder under Downloads, verify its release-manifest SHA-256, and show the file. Open it to complete installation. Answer `n` or press Enter to keep using CLI only. Noninteractive runs skip the prompt.
52
+
53
+ Set `AGENTROAM_INSTALL_DESKTOP=yes` or `no` explicitly for automation. The Shell installer reads `/dev/tty`, so `curl ... | sh` remains interactive. A missing desktop artifact or failed download does not undo CLI installation. This requires a published CLI that includes `bin/desktop-download.mjs` and matching desktop release assets.
54
+
55
+ On macOS, the desktop app opens its own permission guide on first launch, even before connecting to a service. Screen Recording enables phone viewing; Accessibility enables keyboard and mouse control. Returning from System Settings rechecks permissions and resumes an enabled session. Restart the desktop app if macOS requires it. Desktop live publishing follows the selected CLI service, including its actual port. Windows desktop download is supported, but the current screen/input helper is macOS-only.
@@ -0,0 +1,16 @@
1
+ #!/bin/bash
2
+ # Copied to a stable private directory: upgrades must not invalidate this job.
3
+ set -euo pipefail
4
+ codex_bin="$1"
5
+ codex_home="$2"
6
+ shared_url="$3"
7
+ export CODEX_HOME="$codex_home"
8
+ export PATH="$4"
9
+ export CODEX_APP_SERVER_FORCE_CLI=0
10
+ export CODEX_APP_SERVER_WS_URL="$shared_url"
11
+ /bin/launchctl setenv CODEX_APP_SERVER_WS_URL "$shared_url"
12
+ /bin/launchctl setenv CODEX_APP_SERVER_FORCE_CLI 0
13
+ /bin/launchctl setenv CODEX_HOME "$codex_home"
14
+ # daemon start is idempotent; never stop or replace a live daemon.
15
+ cd "$5"
16
+ exec "$codex_bin" app-server daemon start