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,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,177 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { resolveApprovalInput, terminalText } from "./device-pairing.js";
5
+ import { localServiceRequest } from "./local-service-request.js";
6
+ import { resolvePlatformRuntime } from "./platform-packages.js";
7
+ import { DesktopAuthorizationInterrupted, DesktopAuthorizationPrompt, withAuthorizationSignal } from "./desktop-authorization-prompt.js";
8
+ import { withCliProgress, withoutCliProgress } from "../bin/cli-progress.mjs";
9
+ const endpoint = "/api/remote-authorization";
10
+ async function prepareInstalledMacComponent(permission) {
11
+ const { runtimeRoot } = resolvePlatformRuntime("darwin-arm64");
12
+ const module = await import(pathToFileURL(join(runtimeRoot, "lib/remote-control/helper-manager.mjs")).href);
13
+ // An independently versioned older runtime can still serve its normal wizard.
14
+ await module.prepareMacRemoteComponent?.(undefined, permission);
15
+ }
16
+ async function requestAuthorization(dataDir, body, signal) {
17
+ const status = await localServiceRequest(dataDir, endpoint, {
18
+ method: body ? "POST" : "GET", body, signal, timeoutMs: body?.action === "request-permission" ? 135_000 : 30_000,
19
+ });
20
+ if (status.local !== true || typeof status.supported !== "boolean" || typeof status.installed !== "boolean"
21
+ || typeof status.enabled !== "boolean" || typeof status.screen !== "boolean" || typeof status.accessibility !== "boolean"
22
+ || typeof status.online !== "boolean" || typeof status.platform !== "string"
23
+ || (status.error !== null && typeof status.error !== "string")) {
24
+ throw new Error("Invalid local authorization status. Upgrade the CLI and retry");
25
+ }
26
+ return status;
27
+ }
28
+ function recoveryHint(log) {
29
+ log("Authorize later: agentroam desktop authorize, or use the Remote Authorization panel in a local browser.");
30
+ }
31
+ function stalePermissionHint(permission, log) {
32
+ const service = permission === "screen" ? "ScreenCapture" : "Accessibility";
33
+ log("If System Settings already shows AgentRoam Remote Desktop as enabled, macOS may still be using a grant for an older component signature.");
34
+ log(`Manual repair only after closing other AgentRoam instances: /usr/bin/tccutil reset ${service} com.agentroam.remote-desktop; then rerun agentroam desktop authorize.`);
35
+ }
36
+ function reportComponent(status, log) {
37
+ if (!status.component)
38
+ return;
39
+ const component = status.component;
40
+ log(`Remote desktop component: ${terminalText(component.version === 'legacy' ? 'legacy (version unknown)' : component.version)}`);
41
+ log(`${status.platform === 'win32' ? 'Component path' : 'Authorization app path'}: ${terminalText(component.path)}`);
42
+ if (component.updatePending)
43
+ log('An older component is still in use. Stop desktop sharing in other AgentRoam instances, then authorize again to update.');
44
+ }
45
+ function complete(status) {
46
+ return status.enabled && status.screen && status.accessibility && !status.error;
47
+ }
48
+ /** Request permissions without enabling sharing, then verify before activation. */
49
+ export async function authorizeRemoteDesktop(dataDir, context = {}) {
50
+ const log = context.log ?? console.log;
51
+ if (!(context.isTTY ?? process.stdout.isTTY === true)) {
52
+ log("No interactive terminal detected. Remote desktop authorization skipped.");
53
+ recoveryHint(log);
54
+ return false;
55
+ }
56
+ const request = context.request ?? requestAuthorization;
57
+ const input = context.input === undefined ? resolveApprovalInput({ interactive: true }) : context.input ?? undefined;
58
+ const prompt = new DesktopAuthorizationPrompt({ input, ownsInput: context.input === undefined && input !== process.stdin,
59
+ signal: context.signal, timeoutMs: context.timeoutMs ?? 60_000, log });
60
+ const run = (operation) => withAuthorizationSignal(operation, prompt.signal);
61
+ let reportedComponent = '';
62
+ const check = async (body) => {
63
+ const status = await run(() => request(dataDir, body, prompt.signal));
64
+ const identity = JSON.stringify(status.component) ?? '';
65
+ if (identity !== reportedComponent) {
66
+ reportComponent(status, log);
67
+ reportedComponent = identity;
68
+ }
69
+ return status;
70
+ };
71
+ log("Remote desktop authorization is optional. Type s and Enter or press Ctrl+C to skip; you can authorize later.");
72
+ try {
73
+ let status = await withCliProgress("Checking local remote desktop permissions", () => check());
74
+ if (!status.supported)
75
+ throw new Error("Remote desktop requires Apple Silicon with macOS 14 or later, or Windows 10/11 x64");
76
+ if (!status.installed)
77
+ throw new Error("This CLI does not include the authorization component. Upgrade the CLI");
78
+ const platform = context.platform ?? process.platform;
79
+ const prepare = context.prepareMacComponent ?? prepareInstalledMacComponent;
80
+ const alreadyEnabled = status.enabled;
81
+ if (status.enabled) {
82
+ if (platform === "darwin")
83
+ await run(() => prepare());
84
+ status = await check({ action: "recheck" });
85
+ if (complete(status)) {
86
+ log("✓ Remote desktop authorized and sharing enabled.");
87
+ return true;
88
+ }
89
+ }
90
+ const confirm = context.confirm ?? (() => prompt.confirm());
91
+ const confirmed = await withoutCliProgress(() => run(confirm));
92
+ if (!confirmed) {
93
+ log("Remote desktop authorization skipped.");
94
+ recoveryHint(log);
95
+ return false;
96
+ }
97
+ if (platform === "darwin" && !alreadyEnabled)
98
+ await run(() => prepare());
99
+ status = await check({ action: "recheck" });
100
+ const wait = context.wait ?? ((milliseconds) => delay(milliseconds, undefined, { signal: prompt.signal }));
101
+ if (platform === "darwin") {
102
+ for (const permission of ["screen", "accessibility"]) {
103
+ if (status[permission])
104
+ continue;
105
+ const name = permission === "screen" ? "Screen Recording" : "Accessibility";
106
+ // The shared helper handles signature changes before prompting. CLI
107
+ // polling only observes the currently installed component.
108
+ log(`Requesting ${name} permission. Allow AgentRoam Remote Desktop in System Settings...`);
109
+ status = await withCliProgress(`Waiting for ${name} permission; type s and Enter to skip`, async () => {
110
+ await run(() => prepare(permission));
111
+ let current = await check({ action: "request-permission", permission });
112
+ for (let attempt = 0; !current[permission] && attempt < (context.pollAttempts ?? 60); attempt++) {
113
+ await run(() => wait(2000));
114
+ current = await check({ action: "recheck" });
115
+ }
116
+ return current;
117
+ });
118
+ if (!status[permission]) {
119
+ log(`${name} permission was not granted. Sharing was not enabled.`);
120
+ stalePermissionHint(permission, log);
121
+ recoveryHint(log);
122
+ return false;
123
+ }
124
+ }
125
+ }
126
+ if (!status.screen || !status.accessibility) {
127
+ log("Remote desktop is unavailable. Check system permissions and desktop state. Sharing was not enabled.");
128
+ recoveryHint(log);
129
+ return false;
130
+ }
131
+ status = await withCliProgress("Enabling and checking remote desktop sharing", () => check({ action: "enable" }));
132
+ if (!complete(status))
133
+ throw new Error(status.error ? terminalText(status.error) : "Remote desktop sharing is not ready. Check system permissions");
134
+ log("✓ Remote desktop authorization complete; sharing enabled. Your phone still needs device pairing on first connection.");
135
+ return true;
136
+ }
137
+ catch (error) {
138
+ if (!prompt.signal.aborted)
139
+ throw error;
140
+ log(prompt.signal.reason instanceof DesktopAuthorizationInterrupted ? prompt.signal.reason.message : "Remote desktop authorization cancelled.");
141
+ recoveryHint(log);
142
+ return false;
143
+ }
144
+ finally {
145
+ prompt.close();
146
+ }
147
+ }
148
+ export async function runDesktopCommand(options, context = {}) {
149
+ const log = context.log ?? console.log;
150
+ const request = context.request ?? requestAuthorization;
151
+ if (options.desktopAction === "authorize") {
152
+ try {
153
+ if (!await authorizeRemoteDesktop(options.dataDir, context))
154
+ process.exitCode = 1;
155
+ }
156
+ catch (error) {
157
+ recoveryHint(log);
158
+ throw error;
159
+ }
160
+ return;
161
+ }
162
+ let status = await request(options.dataDir);
163
+ if (options.desktopAction === "disable") {
164
+ status = await request(options.dataDir, { action: "disable" });
165
+ if (status.enabled)
166
+ throw new Error("Remote desktop sharing is still enabled. Retry");
167
+ log("✓ Remote desktop sharing disabled; system permissions retained. Enable again: agentroam desktop authorize");
168
+ return;
169
+ }
170
+ if (status.supported && status.installed)
171
+ status = await request(options.dataDir, { action: "recheck" });
172
+ reportComponent(status, log);
173
+ 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"}`);
174
+ if (status.error)
175
+ log(`Status: ${terminalText(status.error)}`);
176
+ recoveryHint(log);
177
+ }