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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +61 -15
  2. package/bin/agentroam.mjs +10 -1
  3. package/bin/cli-progress.d.mts +9 -0
  4. package/bin/cli-progress.mjs +65 -0
  5. package/bin/desktop-download.mjs +69 -0
  6. package/bin/node-preflight.mjs +171 -0
  7. package/bin/node-runtime-policy.json +4 -0
  8. package/bin/runtime-policy.d.mts +5 -0
  9. package/bin/runtime-policy.mjs +37 -0
  10. package/dist/abort.js +25 -0
  11. package/dist/args.js +136 -5
  12. package/dist/cli.js +295 -44
  13. package/dist/cloudflared/bundled-asset.js +3 -2
  14. package/dist/cloudflared/manifest.js +2 -2
  15. package/dist/codex-desktop-command.js +70 -0
  16. package/dist/codex-desktop-force-stop.js +46 -0
  17. package/dist/codex-desktop-idle-guard.js +15 -0
  18. package/dist/codex-desktop-preflight.js +63 -0
  19. package/dist/codex-desktop-probe.js +152 -0
  20. package/dist/codex-desktop-setup.js +154 -0
  21. package/dist/codex-desktop-status.js +85 -0
  22. package/dist/codex-desktop-windows.js +122 -0
  23. package/dist/codex-runtime-manager.js +368 -0
  24. package/dist/codex-sharing.js +155 -0
  25. package/dist/codex-windows-backend-host.js +59 -0
  26. package/dist/codex-windows-backend.js +120 -0
  27. package/dist/desktop-authorization-prompt.js +84 -0
  28. package/dist/desktop-authorization.js +161 -0
  29. package/dist/device-pairing.js +228 -0
  30. package/dist/error-log.js +113 -0
  31. package/dist/instance-takeover.js +143 -0
  32. package/dist/local-desktop-url.js +8 -0
  33. package/dist/local-service-request.js +69 -0
  34. package/dist/mesh/mesh-command.js +51 -0
  35. package/dist/mesh/mesh-config.js +95 -0
  36. package/dist/mesh/mesh-payload.js +20 -0
  37. package/dist/mesh/mesh-runtime.js +101 -0
  38. package/dist/native-runtime.js +68 -0
  39. package/dist/network.js +46 -3
  40. package/dist/node-runtime-manager.js +251 -0
  41. package/dist/opencode-runtime-manager.js +260 -0
  42. package/dist/platform-packages.js +18 -5
  43. package/dist/platform.js +6 -4
  44. package/dist/power/sleep-inhibitor.js +161 -0
  45. package/dist/runtime-manager.js +139 -19
  46. package/dist/self-hosted-relay.json +1 -0
  47. package/dist/service/launcher-cleanup.js +79 -0
  48. package/dist/service/macos-launch-agent.js +288 -0
  49. package/dist/service/runtime-state.js +43 -0
  50. package/dist/service/service-command.js +226 -0
  51. package/dist/service/service-controller.js +29 -0
  52. package/dist/service/service-files.js +78 -0
  53. package/dist/service/windows-service-host.js +59 -0
  54. package/dist/service/windows-task-service.js +289 -0
  55. package/dist/startup-lock.js +81 -0
  56. package/dist/tailscale/bundled-asset.js +43 -0
  57. package/dist/tailscale/daemon-manager.js +112 -0
  58. package/dist/tailscale/installer.js +131 -0
  59. package/dist/tailscale/manifest.js +15 -0
  60. package/dist/tailscale/tailnet-cli.js +101 -0
  61. package/dist/todo-mcp-command.js +27 -0
  62. package/dist/tunnel/cloudflare-provider.js +4 -1
  63. package/dist/tunnel/public-readiness.js +76 -50
  64. package/dist/tunnel/relay-orchestrator.js +53 -19
  65. package/dist/tunnel/self-hosted-provider.js +147 -0
  66. package/dist/tunnel/tunnel-controller.js +232 -0
  67. package/dist/unlock-service.js +105 -0
  68. package/dist/update/update-channel.js +38 -0
  69. package/dist/update/update-command.js +97 -0
  70. package/dist/update/update-install.js +34 -0
  71. package/dist/update/update-state.js +43 -0
  72. package/dist/update/update-worker.js +82 -0
  73. package/install/README.md +55 -0
  74. package/install/codex-shared-watchdog.sh +16 -0
  75. package/install/install-agentroam.ps1 +358 -0
  76. package/install/install-agentroam.sh +457 -0
  77. package/install/install-manifest.json +15 -0
  78. package/install/start-codex-desktop-shared.sh +152 -0
  79. package/install/write-relay-default.mjs +6 -0
  80. package/package.json +15 -10
  81. package/dist/args.test.js +0 -27
  82. package/dist/cloudflared/bundled-asset.test.js +0 -76
  83. package/dist/cloudflared/installer.test.js +0 -95
  84. package/dist/native-runtime.test.js +0 -19
  85. package/dist/network.test.js +0 -20
  86. package/dist/pairing.js +0 -2
  87. package/dist/platform-packages.test.js +0 -75
  88. package/dist/platform.test.js +0 -3
  89. package/dist/port.test.js +0 -3
  90. package/dist/process-supervisor.test.js +0 -42
  91. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  92. package/dist/tunnel/pinggy-provider.test.js +0 -40
  93. package/dist/tunnel/proxy-settings.test.js +0 -111
  94. package/dist/tunnel/public-readiness.test.js +0 -104
  95. package/dist/tunnel/relay-orchestrator.test.js +0 -72
@@ -0,0 +1,59 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { promisify } from "node:util";
5
+ import { pathToFileURL } from "node:url";
6
+ import { createInterface } from "node:readline";
7
+ import { WebSocketServer, WebSocket } from "ws";
8
+ import { validateWindowsBackend } from "./codex-windows-backend.js";
9
+ export async function startWindowsBackendHost(config, dependencies = {}) {
10
+ validateWindowsBackend(config);
11
+ const environment = { ...process.env, CODEX_HOME: config.codexHome };
12
+ await (dependencies.startDaemon ?? (async (executable, env) => {
13
+ await promisify(execFile)(executable, ["app-server", "daemon", "start"], { env, cwd: homedir(), windowsHide: true, timeout: 30_000 });
14
+ }))(config.executable, environment);
15
+ const endpoint = new URL(config.endpoint);
16
+ const server = new WebSocketServer({ host: "127.0.0.1", port: Number(endpoint.port), path: endpoint.pathname, maxPayload: 32 * 1024 * 1024, perMessageDeflate: false });
17
+ server.on("connection", socket => {
18
+ const child = (dependencies.spawnProxy ?? spawn)(config.executable, ["app-server", "proxy"], { env: environment, cwd: homedir(), windowsHide: true, stdio: ["pipe", "pipe", "ignore"] });
19
+ const lines = createInterface({ input: child.stdout });
20
+ lines.on("line", line => { if (socket.readyState === WebSocket.OPEN) {
21
+ if (socket.bufferedAmount > 32 * 1024 * 1024)
22
+ socket.close(1013);
23
+ else
24
+ socket.send(line);
25
+ } });
26
+ socket.on("message", (data, binary) => {
27
+ if (binary || (Array.isArray(data) ? data.reduce((size, chunk) => size + chunk.length, 0) : data.byteLength) > 32 * 1024 * 1024) {
28
+ socket.close(1003);
29
+ return;
30
+ }
31
+ try {
32
+ const message = JSON.parse(String(data));
33
+ if (!message || typeof message !== "object" || Array.isArray(message) || child.stdin.writableLength > 32 * 1024 * 1024) {
34
+ socket.close(1008);
35
+ return;
36
+ }
37
+ child.stdin.write(`${JSON.stringify(message)}\n`);
38
+ }
39
+ catch {
40
+ socket.close(1007);
41
+ }
42
+ });
43
+ socket.on("error", () => { });
44
+ const close = () => { lines.close(); child.stdin.end(); if (child.exitCode === null)
45
+ child.kill(); };
46
+ socket.once("close", close);
47
+ child.once("error", () => socket.close(1011));
48
+ child.once("exit", () => socket.close(1011));
49
+ });
50
+ await new Promise((resolve, reject) => { server.once("listening", resolve); server.once("error", reject); });
51
+ return server;
52
+ }
53
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
54
+ const path = process.argv[2];
55
+ if (!path)
56
+ process.exitCode = 1;
57
+ else
58
+ readFile(path, "utf8").then(text => startWindowsBackendHost(validateWindowsBackend(JSON.parse(text)))).catch(() => { console.error("Windows shared backend failed to start"); process.exitCode = 1; });
59
+ }
@@ -0,0 +1,120 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile, mkdir, writeFile, rename, rm, open, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { promisify } from "node:util";
7
+ import { randomBytes } from "node:crypto";
8
+ import { createServer } from "node:net";
9
+ import { resolveCodexRuntime } from "./codex-runtime-manager.js";
10
+ import { withDesktopRpc } from "./codex-desktop-probe.js";
11
+ const executeFile = promisify(execFile);
12
+ export const WINDOWS_CODEX_TASK = "AgentRoam-Codex-Shared";
13
+ export function windowsBackendPath(home = homedir()) { return join(home, ".agentroam", "codex-desktop", "windows-backend.json"); }
14
+ export function psLiteral(value) { return `'${value.replaceAll("'", "''")}'`; }
15
+ export function quoteWindowsArgument(value) { return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`; }
16
+ export function validateWindowsBackend(value) {
17
+ const config = value;
18
+ const url = new URL(config.endpoint);
19
+ if (config.version !== 1 || url.protocol !== "ws:" || url.hostname !== "127.0.0.1" || !url.port
20
+ || !/^\/[a-f0-9]{48}$/.test(url.pathname) || url.search || url.hash || url.username || url.password
21
+ || !/^[A-Za-z]:\\.*\.exe$/i.test(config.executable) || !/^[A-Za-z]:\\/.test(config.codexHome))
22
+ throw new Error("Invalid Windows shared backend configuration");
23
+ return config;
24
+ }
25
+ export async function readWindowsBackend(home = homedir()) {
26
+ try {
27
+ return validateWindowsBackend(JSON.parse(await readFile(windowsBackendPath(home), "utf8")));
28
+ }
29
+ catch (error) {
30
+ if (error.code === "ENOENT")
31
+ return null;
32
+ throw error;
33
+ }
34
+ }
35
+ export async function ensureWindowsBackend(dataDir, context = {}) {
36
+ const home = context.homeDir ?? homedir();
37
+ const environment = context.environment ?? process.env;
38
+ const path = windowsBackendPath(home), root = join(home, ".agentroam", "codex-desktop");
39
+ const execute = context.execute ?? executeFile;
40
+ const run = (script) => execute("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `$ErrorActionPreference='Stop'; ${script}`], { env: environment, encoding: "utf8", timeout: 30_000, maxBuffer: 1024 * 1024, windowsHide: true });
41
+ await mkdir(root, { recursive: true });
42
+ await run(`$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; & icacls.exe ${psLiteral(root)} /inheritance:r /grant:r "\${sid}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' | Out-Null; if ($LASTEXITCODE -ne 0) { throw 'Cannot protect shared backend directory' }`);
43
+ const lockPath = `${path}.lock`;
44
+ let lock;
45
+ for (let attempt = 0; attempt < 120; attempt++) {
46
+ try {
47
+ lock = await open(lockPath, "wx");
48
+ await lock.writeFile(String(process.pid));
49
+ break;
50
+ }
51
+ catch (error) {
52
+ if (error.code !== "EEXIST")
53
+ throw error;
54
+ try {
55
+ const owner = Number(await readFile(lockPath, "utf8"));
56
+ const age = Date.now() - (await stat(lockPath)).mtimeMs;
57
+ if (Number.isSafeInteger(owner) && owner > 1) {
58
+ try {
59
+ process.kill(owner, 0);
60
+ }
61
+ catch (probeError) {
62
+ if (probeError.code === "ESRCH")
63
+ await rm(lockPath, { force: true });
64
+ }
65
+ }
66
+ else if (age > 30_000)
67
+ await rm(lockPath, { force: true });
68
+ }
69
+ catch (readError) {
70
+ if (readError.code !== "ENOENT")
71
+ throw readError;
72
+ }
73
+ await new Promise(resolve => setTimeout(resolve, 500));
74
+ }
75
+ }
76
+ if (!lock)
77
+ throw new Error("Windows shared backend setup is busy; retry shortly");
78
+ try {
79
+ let config = await readWindowsBackend(home);
80
+ const executable = await (context.resolveExecutable ?? (async () => environment.AGENT_CODEX_BIN || (await resolveCodexRuntime({ dataDir, target: "windows-amd64", platform: "win32", environment })).executable))();
81
+ if (!config) {
82
+ const port = await (context.allocatePort ?? (() => new Promise((resolve, reject) => {
83
+ const server = createServer();
84
+ server.once("error", reject);
85
+ server.listen(0, "127.0.0.1", () => { const address = server.address(); if (!address || typeof address === "string") {
86
+ server.close();
87
+ reject(new Error("No loopback port"));
88
+ return;
89
+ } server.close(error => error ? reject(error) : resolve(address.port)); });
90
+ })))();
91
+ config = { version: 1, endpoint: `ws://127.0.0.1:${port}/${randomBytes(24).toString("hex")}`, executable, codexHome: environment.CODEX_HOME || join(home, ".codex") };
92
+ }
93
+ else
94
+ config = { ...config, executable };
95
+ validateWindowsBackend(config);
96
+ const temporary = `${path}.${process.pid}.tmp`;
97
+ await writeFile(temporary, JSON.stringify(config), { mode: 0o600 });
98
+ await rename(temporary, path);
99
+ const host = fileURLToPath(new URL("./codex-windows-backend-host.js", import.meta.url));
100
+ const argumentsValue = `${quoteWindowsArgument(host)} ${quoteWindowsArgument(path)}`;
101
+ await run(`$action=New-ScheduledTaskAction -Execute ${psLiteral(process.execPath)} -Argument ${psLiteral(argumentsValue)} -WorkingDirectory ${psLiteral(home)}; $user=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; $trigger=New-ScheduledTaskTrigger -AtLogOn -User $user; $principal=New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited; $settings=New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries; Register-ScheduledTask -TaskName ${psLiteral(WINDOWS_CODEX_TASK)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null; Start-ScheduledTask -TaskName ${psLiteral(WINDOWS_CODEX_TASK)}`);
102
+ const probe = context.probe ?? (async (endpoint) => { await withDesktopRpc(endpoint, async (request) => { await request("config/read", { includeLayers: false }); }, 2_000); });
103
+ for (let attempt = 0; attempt < 8; attempt++) {
104
+ try {
105
+ await probe(config.endpoint);
106
+ return config;
107
+ }
108
+ catch (error) {
109
+ if (attempt === 7)
110
+ throw new Error("Windows 共享后台未就绪,已保留 Codex 桌面。", { cause: error });
111
+ await (context.wait ?? (() => new Promise(resolve => setTimeout(resolve, 500))))();
112
+ }
113
+ }
114
+ throw new Error("Shared backend unavailable");
115
+ }
116
+ finally {
117
+ await lock.close();
118
+ await rm(`${path}.lock`, { force: true });
119
+ }
120
+ }
@@ -0,0 +1,84 @@
1
+ import { createInterface } from "node:readline";
2
+ import { Readable } from "node:stream";
3
+ export class DesktopAuthorizationInterrupted extends Error {
4
+ kind;
5
+ constructor(kind) {
6
+ super(kind === "skip" ? "Remote desktop authorization skipped." : "Remote desktop authorization timed out and was skipped.");
7
+ this.kind = kind;
8
+ }
9
+ }
10
+ /** One terminal owns confirmation and cancellation, including curl | sh installs. */
11
+ export class DesktopAuthorizationPrompt {
12
+ options;
13
+ signal;
14
+ controller = new AbortController();
15
+ timer;
16
+ reader;
17
+ answer;
18
+ constructor(options) {
19
+ this.options = options;
20
+ this.signal = options.signal ? AbortSignal.any([options.signal, this.controller.signal]) : this.controller.signal;
21
+ this.timer = setTimeout(() => this.controller.abort(new DesktopAuthorizationInterrupted("timeout")), options.timeoutMs);
22
+ process.on("SIGINT", this.skip);
23
+ if (options.input) {
24
+ // The controlling tty echoes canonical input; readline must not echo it again.
25
+ this.reader = createInterface({ input: options.input, terminal: false });
26
+ this.reader.on("line", this.onLine);
27
+ this.reader.on("close", this.skip);
28
+ this.reader.on("SIGINT", this.skip);
29
+ this.reader.on("error", this.skip);
30
+ }
31
+ }
32
+ skip = () => { this.controller.abort(new DesktopAuthorizationInterrupted("skip")); };
33
+ onLine = (line) => {
34
+ if (this.answer) {
35
+ const answer = this.answer;
36
+ this.answer = undefined;
37
+ answer(/^(y|yes)$/i.test(line.trim()));
38
+ }
39
+ else if (/^(s|skip|n|no|跳过)$/i.test(line.trim()))
40
+ this.skip();
41
+ };
42
+ confirm() {
43
+ if (!this.reader)
44
+ return Promise.resolve(false);
45
+ return new Promise((resolve) => {
46
+ this.answer = resolve;
47
+ this.options.log("Authorize remote desktop now, allowing paired devices to view and control this computer? [y/N] (Enter to skip): ");
48
+ });
49
+ }
50
+ close() {
51
+ clearTimeout(this.timer);
52
+ process.off("SIGINT", this.skip);
53
+ this.reader?.off("line", this.onLine);
54
+ this.reader?.off("close", this.skip);
55
+ this.reader?.off("SIGINT", this.skip);
56
+ this.reader?.off("error", this.skip);
57
+ this.reader?.close();
58
+ this.answer?.(false);
59
+ this.answer = undefined;
60
+ if (this.options.ownsInput && this.options.input instanceof Readable)
61
+ this.options.input.destroy();
62
+ }
63
+ }
64
+ /** A deadline must also cover a request or injected operation that never settles. */
65
+ export function withAuthorizationSignal(operation, signal) {
66
+ signal.throwIfAborted();
67
+ return new Promise((resolve, reject) => {
68
+ const abort = () => { signal.removeEventListener("abort", abort); reject(signal.reason); };
69
+ signal.addEventListener("abort", abort, { once: true });
70
+ try {
71
+ operation().then((value) => {
72
+ signal.removeEventListener("abort", abort);
73
+ if (signal.aborted)
74
+ reject(signal.reason);
75
+ else
76
+ resolve(value);
77
+ }, (error) => { signal.removeEventListener("abort", abort); reject(error); });
78
+ }
79
+ catch (error) {
80
+ signal.removeEventListener("abort", abort);
81
+ reject(error);
82
+ }
83
+ });
84
+ }
@@ -0,0 +1,161 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { resolveApprovalInput, terminalText } from "./device-pairing.js";
3
+ import { localServiceRequest } from "./local-service-request.js";
4
+ import { DesktopAuthorizationInterrupted, DesktopAuthorizationPrompt, withAuthorizationSignal } from "./desktop-authorization-prompt.js";
5
+ import { withCliProgress, withoutCliProgress } from "../bin/cli-progress.mjs";
6
+ const endpoint = "/api/remote-authorization";
7
+ async function requestAuthorization(dataDir, body, signal) {
8
+ const status = await localServiceRequest(dataDir, endpoint, {
9
+ method: body ? "POST" : "GET", body, signal, timeoutMs: body?.action === "request-permission" ? 135_000 : 30_000,
10
+ });
11
+ if (status.local !== true || typeof status.supported !== "boolean" || typeof status.installed !== "boolean"
12
+ || typeof status.enabled !== "boolean" || typeof status.screen !== "boolean" || typeof status.accessibility !== "boolean"
13
+ || typeof status.online !== "boolean" || typeof status.platform !== "string"
14
+ || (status.error !== null && typeof status.error !== "string")) {
15
+ throw new Error("Invalid local authorization status. Upgrade the CLI and retry");
16
+ }
17
+ return status;
18
+ }
19
+ function recoveryHint(log) {
20
+ log("Authorize later: agentroam desktop authorize, or use the Remote Authorization panel in a local browser.");
21
+ }
22
+ function stalePermissionHint(permission, log) {
23
+ const service = permission === "screen" ? "ScreenCapture" : "Accessibility";
24
+ log("If System Settings already shows AgentRoam Remote Desktop as enabled, macOS may still be using a grant for an older component signature.");
25
+ log(`Manual repair only after closing other AgentRoam instances: /usr/bin/tccutil reset ${service} com.agentroam.remote-desktop; then rerun agentroam desktop authorize.`);
26
+ }
27
+ function reportComponent(status, log) {
28
+ if (!status.component)
29
+ return;
30
+ const component = status.component;
31
+ log(`Remote desktop component: ${terminalText(component.version === 'legacy' ? 'legacy (version unknown)' : component.version)}`);
32
+ log(`${status.platform === 'win32' ? 'Component path' : 'Authorization app path'}: ${terminalText(component.path)}`);
33
+ if (component.updatePending)
34
+ log('An older component is still in use. Stop desktop sharing in other AgentRoam instances, then authorize again to update.');
35
+ }
36
+ function complete(status) {
37
+ return status.enabled && status.screen && status.accessibility && !status.error;
38
+ }
39
+ /** Request permissions without enabling sharing, then verify before activation. */
40
+ export async function authorizeRemoteDesktop(dataDir, context = {}) {
41
+ const log = context.log ?? console.log;
42
+ if (!(context.isTTY ?? process.stdout.isTTY === true)) {
43
+ log("No interactive terminal detected. Remote desktop authorization skipped.");
44
+ recoveryHint(log);
45
+ return false;
46
+ }
47
+ const request = context.request ?? requestAuthorization;
48
+ const input = context.input === undefined ? resolveApprovalInput({ interactive: true }) : context.input ?? undefined;
49
+ const prompt = new DesktopAuthorizationPrompt({ input, ownsInput: context.input === undefined && input !== process.stdin,
50
+ signal: context.signal, timeoutMs: context.timeoutMs ?? 60_000, log });
51
+ const run = (operation) => withAuthorizationSignal(operation, prompt.signal);
52
+ let reportedComponent = '';
53
+ const check = async (body) => {
54
+ const status = await run(() => request(dataDir, body, prompt.signal));
55
+ const identity = JSON.stringify(status.component) ?? '';
56
+ if (identity !== reportedComponent) {
57
+ reportComponent(status, log);
58
+ reportedComponent = identity;
59
+ }
60
+ return status;
61
+ };
62
+ log("Remote desktop authorization is optional. Type s and Enter or press Ctrl+C to skip; you can authorize later.");
63
+ try {
64
+ let status = await withCliProgress("Checking local remote desktop permissions", () => check());
65
+ if (!status.supported)
66
+ throw new Error("Remote desktop requires Apple Silicon with macOS 14 or later, or Windows 10/11 x64");
67
+ if (!status.installed)
68
+ throw new Error("This CLI does not include the authorization component. Upgrade the CLI");
69
+ if (status.enabled) {
70
+ status = await check({ action: "recheck" });
71
+ if (complete(status)) {
72
+ log("✓ Remote desktop authorized and sharing enabled.");
73
+ return true;
74
+ }
75
+ }
76
+ const platform = context.platform ?? process.platform;
77
+ const confirm = context.confirm ?? (() => prompt.confirm());
78
+ const confirmed = await withoutCliProgress(() => run(confirm));
79
+ if (!confirmed) {
80
+ log("Remote desktop authorization skipped.");
81
+ recoveryHint(log);
82
+ return false;
83
+ }
84
+ status = await check({ action: "recheck" });
85
+ const wait = context.wait ?? ((milliseconds) => delay(milliseconds, undefined, { signal: prompt.signal }));
86
+ if (platform === "darwin") {
87
+ for (const permission of ["screen", "accessibility"]) {
88
+ if (status[permission])
89
+ continue;
90
+ const name = permission === "screen" ? "Screen Recording" : "Accessibility";
91
+ // TCC grants belong to the bundle ID across all installed runtimes.
92
+ // A false probe here must never revoke another runtime's permission.
93
+ log(`Requesting ${name} permission. Allow AgentRoam Remote Desktop in System Settings...`);
94
+ status = await withCliProgress(`Waiting for ${name} permission; type s and Enter to skip`, async () => {
95
+ let current = await check({ action: "request-permission", permission });
96
+ for (let attempt = 0; !current[permission] && attempt < (context.pollAttempts ?? 60); attempt++) {
97
+ await run(() => wait(2000));
98
+ current = await check({ action: "recheck" });
99
+ }
100
+ return current;
101
+ });
102
+ if (!status[permission]) {
103
+ log(`${name} permission was not granted. Sharing was not enabled.`);
104
+ stalePermissionHint(permission, log);
105
+ recoveryHint(log);
106
+ return false;
107
+ }
108
+ }
109
+ }
110
+ if (!status.screen || !status.accessibility) {
111
+ log("Remote desktop is unavailable. Check system permissions and desktop state. Sharing was not enabled.");
112
+ recoveryHint(log);
113
+ return false;
114
+ }
115
+ status = await withCliProgress("Enabling and checking remote desktop sharing", () => check({ action: "enable" }));
116
+ if (!complete(status))
117
+ throw new Error(status.error ? terminalText(status.error) : "Remote desktop sharing is not ready. Check system permissions");
118
+ log("✓ Remote desktop authorization complete; sharing enabled. Your phone still needs device pairing on first connection.");
119
+ return true;
120
+ }
121
+ catch (error) {
122
+ if (!prompt.signal.aborted)
123
+ throw error;
124
+ log(prompt.signal.reason instanceof DesktopAuthorizationInterrupted ? prompt.signal.reason.message : "Remote desktop authorization cancelled.");
125
+ recoveryHint(log);
126
+ return false;
127
+ }
128
+ finally {
129
+ prompt.close();
130
+ }
131
+ }
132
+ export async function runDesktopCommand(options, context = {}) {
133
+ const log = context.log ?? console.log;
134
+ const request = context.request ?? requestAuthorization;
135
+ if (options.desktopAction === "authorize") {
136
+ try {
137
+ if (!await authorizeRemoteDesktop(options.dataDir, context))
138
+ process.exitCode = 1;
139
+ }
140
+ catch (error) {
141
+ recoveryHint(log);
142
+ throw error;
143
+ }
144
+ return;
145
+ }
146
+ let status = await request(options.dataDir);
147
+ if (options.desktopAction === "disable") {
148
+ status = await request(options.dataDir, { action: "disable" });
149
+ if (status.enabled)
150
+ throw new Error("Remote desktop sharing is still enabled. Retry");
151
+ log("✓ Remote desktop sharing disabled; system permissions retained. Enable again: agentroam desktop authorize");
152
+ return;
153
+ }
154
+ if (status.supported && status.installed)
155
+ status = await request(options.dataDir, { action: "recheck" });
156
+ reportComponent(status, log);
157
+ log(`Remote desktop: ${status.supported ? "supported" : "unsupported"}; sharing: ${status.enabled ? "enabled" : "disabled"}; Screen Recording: ${status.screen ? "granted" : "not granted or desktop unavailable"}; Accessibility: ${status.accessibility ? "granted" : "not granted"}`);
158
+ if (status.error)
159
+ log(`Status: ${terminalText(status.error)}`);
160
+ recoveryHint(log);
161
+ }
@@ -0,0 +1,228 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { openSync } from "node:fs";
4
+ import { ReadStream } from "node:tty";
5
+ import { readFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { join, resolve } from "node:path";
8
+ import { renderQr } from "./qr.js";
9
+ import { localServiceRequest, LocalServiceHttpError } from "./local-service-request.js";
10
+ import { withCliProgress, withoutCliProgress } from "../bin/cli-progress.mjs";
11
+ /** Resolve a private local descriptor; never send the administrative token to a tunnel URL. */
12
+ export async function pairingAdmin(dataDir, action, body, options = {}) {
13
+ const readOnly = ["devices", "requests", "audit"].includes(action);
14
+ try {
15
+ return await localServiceRequest(dataDir, `/api/pairing/admin/${action}`, {
16
+ ...options, method: readOnly ? "GET" : "POST", ...(readOnly ? {} : { body: body ?? {} }),
17
+ });
18
+ }
19
+ catch (error) {
20
+ if (!(error instanceof LocalServiceHttpError))
21
+ throw error;
22
+ const message = error.status === 423 ? "Remote access is locked. Run agentroam unlock first" : error.status === 410 ? "Request expired or already handled" : error.status === 409 ? "Verification phrase does not match" : `Device authorization failed (HTTP ${error.status})`;
23
+ throw new Error(message);
24
+ }
25
+ }
26
+ export function terminalText(value) { return value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ""); }
27
+ export function pairingQrPayload(accessUrl, grant) {
28
+ const url = new URL(accessUrl);
29
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || !/^[A-Za-z0-9_-]{43}$/.test(grant))
30
+ throw new Error("Invalid pairing URL or authorization grant");
31
+ return `${url.origin}/pair#pair=${grant}`;
32
+ }
33
+ async function joinedMeshAddress(dataDir) {
34
+ const mesh = await localServiceRequest(dataDir, "/api/mesh/status").catch(() => null);
35
+ return mesh?.phase === "joined" ? mesh.accessUrl : undefined;
36
+ }
37
+ export async function printPairingRoutes(dataDir, log = console.log) {
38
+ const [{ routes }, mesh] = await Promise.all([
39
+ localServiceRequest(dataDir, "/api/desktop/tunnel/routes"), joinedMeshAddress(dataDir),
40
+ ]);
41
+ const labels = {
42
+ "self-hosted": "自建 HTTPS", cloudflare: "Cloudflare", lan: "局域网", tailscale: "Tailscale / 组网地址", vpn: "本机网络地址", headscale: "Headscale",
43
+ };
44
+ log("agentroam pair --via <线路或 IP>");
45
+ for (const route of routes)
46
+ log(` ${route.id} ${labels[route.kind]}${route.interfaceName ? ` · ${terminalText(route.interfaceName)}` : ""}`);
47
+ if (routes.some(route => route.kind === "lan"))
48
+ log(" lan 自动选择局域网地址");
49
+ if (routes.some(route => route.kind === "tailscale"))
50
+ log(" tailscale 自动选择 100.x 组网地址");
51
+ if (mesh)
52
+ log(` headscale ${new URL(mesh).origin}`);
53
+ }
54
+ export async function printPairingVia(dataDir, via, log = console.log) {
55
+ const accessUrl = await withCliProgress("正在准备所选配对线路", async () => {
56
+ if (via === "headscale") {
57
+ const mesh = await joinedMeshAddress(dataDir);
58
+ if (!mesh)
59
+ throw new Error("电脑尚未加入自建 Headscale 组网。");
60
+ return mesh;
61
+ }
62
+ const route = await localServiceRequest(dataDir, `/api/desktop/tunnel/routes?via=${encodeURIComponent(via)}`, { method: "POST", timeoutMs: 40_000 });
63
+ return route.accessUrl;
64
+ });
65
+ log(`Pairing route: ${new URL(accessUrl).origin}`);
66
+ await printPairingQr(dataDir, accessUrl, log);
67
+ }
68
+ export async function printPairingCode(dataDir, log = console.log, options = {}) {
69
+ const interactiveQr = (options.qr ?? true) && (options.interactive ?? process.stdout.isTTY);
70
+ if (interactiveQr && options.accessUrl === undefined) {
71
+ const relay = await localServiceRequest(dataDir, "/api/desktop/tunnel", { signal: options.signal }).catch(() => null);
72
+ if (relay?.phase === "ready" && relay.provider === "self-hosted" && relay.accessUrl) {
73
+ await printPairingQr(dataDir, relay.accessUrl, log);
74
+ return;
75
+ }
76
+ }
77
+ const result = await withCliProgress("Generating device pairing code", () => pairingAdmin(dataDir, "code"));
78
+ log(`Pairing code: ${result.code.slice(0, 4)} ${result.code.slice(4)}`);
79
+ log("Valid for 5 minutes, single use. After entering it on your phone, confirm the verification phrase on this computer.");
80
+ if (interactiveQr) {
81
+ const accessUrl = await resolvePairingAccessUrl(dataDir, options);
82
+ if (accessUrl)
83
+ await printPairingQr(dataDir, accessUrl, log);
84
+ else
85
+ log("Generate an app authorization QR code: agentroam pair --url <phone-accessible-server-url>");
86
+ }
87
+ const approvalInput = resolveApprovalInput(options);
88
+ if (approvalInput) {
89
+ await withCliProgress("Waiting for your phone to scan or enter the pairing code", () => watchPairingApproval(dataDir, result.expiresAt, { log, signal: options.signal, input: approvalInput }));
90
+ }
91
+ else
92
+ log("View requests: agentroam approvals; approve: agentroam approve <request-id> --phrase <phone-verification-phrase>");
93
+ }
94
+ async function printPairingQr(dataDir, accessUrl, log) {
95
+ pairingQrPayload(accessUrl, "a".repeat(43));
96
+ const qr = await withCliProgress("Generating phone connection QR code", async () => {
97
+ const { grant } = await pairingAdmin(dataDir, "qr");
98
+ return renderQr(pairingQrPayload(accessUrl, grant));
99
+ });
100
+ log("Scan with your phone to connect (valid for 5 minutes, single use; do not share screenshots):");
101
+ log(qr);
102
+ }
103
+ export async function resolvePairingAccessUrl(dataDir, options = {}) {
104
+ if (options.accessUrl !== undefined)
105
+ return options.accessUrl;
106
+ const readMesh = () => localServiceRequest(dataDir, "/api/mesh/status", { signal: options.signal }).catch(() => null);
107
+ const deadline = Date.now() + 20_000;
108
+ let mesh = await readMesh();
109
+ while (options.waitForMesh && mesh?.phase === "ready" && Date.now() < deadline) {
110
+ await delay(400, undefined, { signal: options.signal });
111
+ mesh = await readMesh();
112
+ }
113
+ if (mesh?.phase === "joined" && mesh.accessUrl)
114
+ return mesh.accessUrl;
115
+ return options.fallbackUrl ?? await readFile(join(dataDir, "tunnel.url"), "utf8").then(value => value.trim(), () => null);
116
+ }
117
+ /** Open the controlling terminal (`/dev/tty`) — the same source install-agentroam.sh reads from. */
118
+ function openControllingTerminal() {
119
+ if (process.platform === "win32")
120
+ return undefined;
121
+ let fd;
122
+ try {
123
+ fd = openSync("/dev/tty", "r");
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ // Use libuv's cancellable TTY handle. A filesystem read on /dev/tty can keep
129
+ // the process alive after destroy(), waiting for one more line of input.
130
+ return new ReadStream(fd);
131
+ }
132
+ /**
133
+ * Pick the stream the approval phrase is read from.
134
+ *
135
+ * Never fall back to `process.stdin` when it is not a TTY: the installer runs as
136
+ * `curl … | sh`, so stdin is *the install script itself*. Reading it consumes
137
+ * the rest of the install, echoes it back to the terminal, and answers the
138
+ * prompt with the next script line instead of the user's "yes" — which silently
139
+ * rejects the device and swallows the remaining install steps.
140
+ */
141
+ export function resolveApprovalInput(context = {}) {
142
+ const stdinIsTTY = context.stdinIsTTY ?? process.stdin.isTTY === true;
143
+ const stdoutIsTTY = context.stdoutIsTTY ?? process.stdout.isTTY === true;
144
+ if (!(context.interactive ?? (stdinIsTTY && stdoutIsTTY)))
145
+ return undefined;
146
+ if (stdinIsTTY)
147
+ return process.stdin;
148
+ return (context.openTerminal ?? openControllingTerminal)();
149
+ }
150
+ /** Watch only while the printed code is usable; approval gets the request's own deadline. */
151
+ export async function watchPairingApproval(dataDir, codeExpiresAt, options = {}) {
152
+ const admin = options.admin ?? pairingAdmin;
153
+ const log = options.log ?? console.log;
154
+ log("Waiting for your phone to connect...");
155
+ while (Date.now() < codeExpiresAt && !options.signal?.aborted) {
156
+ const result = await admin(dataDir, "requests");
157
+ if (result.locked) {
158
+ log("Remote access is locked");
159
+ return;
160
+ }
161
+ if (result.qrClaimed) {
162
+ log("App connected via QR code.");
163
+ return;
164
+ }
165
+ const request = result.requests.find((r) => r.created >= codeExpiresAt - 300_000);
166
+ if (request) {
167
+ log(`New device connection request: ${terminalText(request.name)}`);
168
+ log(`Request ID: ${request.id}`);
169
+ log(`Verification phrase: ${request.phrase}`);
170
+ const confirm = options.confirm ?? ((request, signal) => confirmOnTerminal(request, signal, options.input));
171
+ const approved = await withoutCliProgress(() => confirm(request, options.signal));
172
+ if (options.signal?.aborted)
173
+ return;
174
+ if (Date.now() >= request.expires) {
175
+ log("Authorization request expired. Please pair again.");
176
+ return;
177
+ }
178
+ await admin(dataDir, approved ? "approve" : "deny", { id: request.id, ...(approved ? { phrase: request.phrase } : {}) });
179
+ log(approved ? "Approved. Your phone will connect automatically." : "Device rejected.");
180
+ return;
181
+ }
182
+ try {
183
+ await delay(800, undefined, { signal: options.signal });
184
+ }
185
+ catch {
186
+ return;
187
+ }
188
+ }
189
+ if (!options.signal?.aborted)
190
+ log("Pairing code expired. Run agentroam pair to generate a new code.");
191
+ }
192
+ async function confirmOnTerminal(request, signal, terminal = resolveApprovalInput()) {
193
+ // A piped stdin is the install script, and a closed one can never answer.
194
+ if (!terminal || (terminal === process.stdin && process.stdin.isTTY !== true))
195
+ return false;
196
+ const controller = new AbortController();
197
+ const timer = setTimeout(() => controller.abort(), Math.max(0, request.expires - Date.now()));
198
+ // Read the terminal in canonical mode: the tty echoes the keystrokes itself,
199
+ // so letting readline echo them again would double every character.
200
+ const input = createInterface(terminal === process.stdin
201
+ ? { input: terminal, output: process.stdout }
202
+ : { input: terminal, output: process.stdout, terminal: false });
203
+ input.once("SIGINT", () => controller.abort());
204
+ try {
205
+ const answer = await input.question("Does your phone show the same phrase? Type yes to approve, anything else to reject: ", { signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal });
206
+ return answer.trim().toLowerCase() === "yes";
207
+ }
208
+ catch {
209
+ return false;
210
+ }
211
+ finally {
212
+ clearTimeout(timer);
213
+ input.close();
214
+ }
215
+ }
216
+ export async function installedDataDir(fallback) {
217
+ if (resolve(fallback) !== resolve(homedir(), ".agentroam"))
218
+ return fallback;
219
+ try {
220
+ const config = JSON.parse(await readFile(join(homedir(), ".agentroam", "service", "config.json"), "utf8"));
221
+ return typeof config.dataDir === "string" ? resolve(config.dataDir) : fallback;
222
+ }
223
+ catch (error) {
224
+ if (error.code === "ENOENT")
225
+ return fallback;
226
+ throw error;
227
+ }
228
+ }