agentroam 0.2.0-preview.7 → 0.2.0-preview.71

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 (82) hide show
  1. package/README.md +61 -15
  2. package/bin/agentroam.mjs +10 -1
  3. package/bin/cli-progress.d.mts +9 -0
  4. package/bin/cli-progress.mjs +65 -0
  5. package/bin/desktop-download.mjs +69 -0
  6. package/bin/node-preflight.mjs +171 -0
  7. package/bin/node-runtime-policy.json +4 -0
  8. package/bin/runtime-policy.d.mts +5 -0
  9. package/bin/runtime-policy.mjs +37 -0
  10. package/dist/abort.js +25 -0
  11. package/dist/args.js +102 -3
  12. package/dist/cli.js +244 -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 +153 -0
  25. package/dist/codex-windows-backend-host.js +59 -0
  26. package/dist/codex-windows-backend.js +120 -0
  27. package/dist/desktop-authorization-prompt.js +84 -0
  28. package/dist/desktop-authorization.js +161 -0
  29. package/dist/device-pairing.js +170 -0
  30. package/dist/error-log.js +113 -0
  31. package/dist/instance-takeover.js +143 -0
  32. package/dist/local-desktop-url.js +8 -0
  33. package/dist/local-service-request.js +69 -0
  34. package/dist/native-runtime.js +68 -0
  35. package/dist/network.js +32 -3
  36. package/dist/node-runtime-manager.js +251 -0
  37. package/dist/opencode-runtime-manager.js +239 -0
  38. package/dist/platform-packages.js +16 -5
  39. package/dist/platform.js +6 -4
  40. package/dist/power/sleep-inhibitor.js +161 -0
  41. package/dist/runtime-manager.js +130 -19
  42. package/dist/service/launcher-cleanup.js +79 -0
  43. package/dist/service/macos-launch-agent.js +288 -0
  44. package/dist/service/runtime-state.js +43 -0
  45. package/dist/service/service-command.js +219 -0
  46. package/dist/service/service-controller.js +27 -0
  47. package/dist/service/service-files.js +78 -0
  48. package/dist/service/windows-service-host.js +59 -0
  49. package/dist/service/windows-task-service.js +289 -0
  50. package/dist/startup-lock.js +81 -0
  51. package/dist/tunnel/cloudflare-provider.js +4 -1
  52. package/dist/tunnel/public-readiness.js +76 -50
  53. package/dist/tunnel/relay-orchestrator.js +31 -9
  54. package/dist/tunnel/tunnel-controller.js +144 -0
  55. package/dist/unlock-service.js +105 -0
  56. package/dist/update/update-channel.js +38 -0
  57. package/dist/update/update-command.js +96 -0
  58. package/dist/update/update-install.js +34 -0
  59. package/dist/update/update-state.js +43 -0
  60. package/dist/update/update-worker.js +80 -0
  61. package/install/README.md +55 -0
  62. package/install/codex-shared-watchdog.sh +16 -0
  63. package/install/install-agentroam.ps1 +358 -0
  64. package/install/install-agentroam.sh +457 -0
  65. package/install/install-manifest.json +15 -0
  66. package/install/start-codex-desktop-shared.sh +152 -0
  67. package/package.json +13 -10
  68. package/dist/args.test.js +0 -27
  69. package/dist/cloudflared/bundled-asset.test.js +0 -76
  70. package/dist/cloudflared/installer.test.js +0 -95
  71. package/dist/native-runtime.test.js +0 -19
  72. package/dist/network.test.js +0 -20
  73. package/dist/pairing.js +0 -2
  74. package/dist/platform-packages.test.js +0 -75
  75. package/dist/platform.test.js +0 -3
  76. package/dist/port.test.js +0 -3
  77. package/dist/process-supervisor.test.js +0 -42
  78. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  79. package/dist/tunnel/pinggy-provider.test.js +0 -40
  80. package/dist/tunnel/proxy-settings.test.js +0 -111
  81. package/dist/tunnel/public-readiness.test.js +0 -104
  82. package/dist/tunnel/relay-orchestrator.test.js +0 -72
@@ -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,170 @@
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
+ export async function printPairingCode(dataDir, log = console.log, options = {}) {
34
+ const result = await withCliProgress("Generating device pairing code", () => pairingAdmin(dataDir, "code"));
35
+ log(`Pairing code: ${result.code.slice(0, 4)} ${result.code.slice(4)}`);
36
+ log("Valid for 5 minutes, single use. After entering it on your phone, confirm the verification phrase on this computer.");
37
+ if ((options.qr ?? true) && (options.interactive ?? process.stdout.isTTY)) {
38
+ const accessUrl = options.accessUrl ?? await readFile(join(dataDir, "tunnel.url"), "utf8").then((value) => value.trim(), () => null);
39
+ if (accessUrl) {
40
+ // Validate the public address before minting an invitation. Never persist the grant.
41
+ pairingQrPayload(accessUrl, "a".repeat(43));
42
+ const qr = await withCliProgress("Generating phone connection QR code", async () => {
43
+ const { grant } = await pairingAdmin(dataDir, "qr");
44
+ return renderQr(pairingQrPayload(accessUrl, grant));
45
+ });
46
+ log("Scan with your phone to connect (valid for 5 minutes, single use; do not share screenshots):");
47
+ log(qr);
48
+ }
49
+ else
50
+ log("Generate an app authorization QR code: agentroam pair --url <phone-accessible-server-url>");
51
+ }
52
+ const approvalInput = resolveApprovalInput(options);
53
+ if (approvalInput) {
54
+ await withCliProgress("Waiting for your phone to scan or enter the pairing code", () => watchPairingApproval(dataDir, result.expiresAt, { log, signal: options.signal, input: approvalInput }));
55
+ }
56
+ else
57
+ log("View requests: agentroam approvals; approve: agentroam approve <request-id> --phrase <phone-verification-phrase>");
58
+ }
59
+ /** Open the controlling terminal (`/dev/tty`) — the same source install-agentroam.sh reads from. */
60
+ function openControllingTerminal() {
61
+ if (process.platform === "win32")
62
+ return undefined;
63
+ let fd;
64
+ try {
65
+ fd = openSync("/dev/tty", "r");
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ // Use libuv's cancellable TTY handle. A filesystem read on /dev/tty can keep
71
+ // the process alive after destroy(), waiting for one more line of input.
72
+ return new ReadStream(fd);
73
+ }
74
+ /**
75
+ * Pick the stream the approval phrase is read from.
76
+ *
77
+ * Never fall back to `process.stdin` when it is not a TTY: the installer runs as
78
+ * `curl … | sh`, so stdin is *the install script itself*. Reading it consumes
79
+ * the rest of the install, echoes it back to the terminal, and answers the
80
+ * prompt with the next script line instead of the user's "yes" — which silently
81
+ * rejects the device and swallows the remaining install steps.
82
+ */
83
+ export function resolveApprovalInput(context = {}) {
84
+ const stdinIsTTY = context.stdinIsTTY ?? process.stdin.isTTY === true;
85
+ const stdoutIsTTY = context.stdoutIsTTY ?? process.stdout.isTTY === true;
86
+ if (!(context.interactive ?? (stdinIsTTY && stdoutIsTTY)))
87
+ return undefined;
88
+ if (stdinIsTTY)
89
+ return process.stdin;
90
+ return (context.openTerminal ?? openControllingTerminal)();
91
+ }
92
+ /** Watch only while the printed code is usable; approval gets the request's own deadline. */
93
+ export async function watchPairingApproval(dataDir, codeExpiresAt, options = {}) {
94
+ const admin = options.admin ?? pairingAdmin;
95
+ const log = options.log ?? console.log;
96
+ log("Waiting for your phone to connect...");
97
+ while (Date.now() < codeExpiresAt && !options.signal?.aborted) {
98
+ const result = await admin(dataDir, "requests");
99
+ if (result.locked) {
100
+ log("Remote access is locked");
101
+ return;
102
+ }
103
+ if (result.qrClaimed) {
104
+ log("App connected via QR code.");
105
+ return;
106
+ }
107
+ const request = result.requests.find((r) => r.created >= codeExpiresAt - 300_000);
108
+ if (request) {
109
+ log(`New device connection request: ${terminalText(request.name)}`);
110
+ log(`Request ID: ${request.id}`);
111
+ log(`Verification phrase: ${request.phrase}`);
112
+ const confirm = options.confirm ?? ((request, signal) => confirmOnTerminal(request, signal, options.input));
113
+ const approved = await withoutCliProgress(() => confirm(request, options.signal));
114
+ if (options.signal?.aborted)
115
+ return;
116
+ if (Date.now() >= request.expires) {
117
+ log("Authorization request expired. Please pair again.");
118
+ return;
119
+ }
120
+ await admin(dataDir, approved ? "approve" : "deny", { id: request.id, ...(approved ? { phrase: request.phrase } : {}) });
121
+ log(approved ? "Approved. Your phone will connect automatically." : "Device rejected.");
122
+ return;
123
+ }
124
+ try {
125
+ await delay(800, undefined, { signal: options.signal });
126
+ }
127
+ catch {
128
+ return;
129
+ }
130
+ }
131
+ if (!options.signal?.aborted)
132
+ log("Pairing code expired. Run agentroam pair to generate a new code.");
133
+ }
134
+ async function confirmOnTerminal(request, signal, terminal = resolveApprovalInput()) {
135
+ // A piped stdin is the install script, and a closed one can never answer.
136
+ if (!terminal || (terminal === process.stdin && process.stdin.isTTY !== true))
137
+ return false;
138
+ const controller = new AbortController();
139
+ const timer = setTimeout(() => controller.abort(), Math.max(0, request.expires - Date.now()));
140
+ // Read the terminal in canonical mode: the tty echoes the keystrokes itself,
141
+ // so letting readline echo them again would double every character.
142
+ const input = createInterface(terminal === process.stdin
143
+ ? { input: terminal, output: process.stdout }
144
+ : { input: terminal, output: process.stdout, terminal: false });
145
+ input.once("SIGINT", () => controller.abort());
146
+ try {
147
+ 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 });
148
+ return answer.trim().toLowerCase() === "yes";
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ finally {
154
+ clearTimeout(timer);
155
+ input.close();
156
+ }
157
+ }
158
+ export async function installedDataDir(fallback) {
159
+ if (resolve(fallback) !== resolve(homedir(), ".agentroam"))
160
+ return fallback;
161
+ try {
162
+ const config = JSON.parse(await readFile(join(homedir(), ".agentroam", "service", "config.json"), "utf8"));
163
+ return typeof config.dataDir === "string" ? resolve(config.dataDir) : fallback;
164
+ }
165
+ catch (error) {
166
+ if (error.code === "ENOENT")
167
+ return fallback;
168
+ throw error;
169
+ }
170
+ }
@@ -0,0 +1,113 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ // Self-contained daily error log for the CLI process. The CLI cannot depend
4
+ // on @agent/core (it ships as a thin launcher), so this mirrors the exact
5
+ // NDJSON entry format of core's DailyFileLogger
6
+ // (`{ts, level, source, message, error?, data?}`) into `<dataDir>/logs/`.
7
+ // It records uncaughtException / unhandledRejection so launcher failures are
8
+ // strictly persisted, matching the server/desktop log series.
9
+ const LEVELS = new Set(["debug", "info", "warn", "error", "fatal"]);
10
+ function localDateString(date) {
11
+ const y = date.getFullYear();
12
+ const m = String(date.getMonth() + 1).padStart(2, "0");
13
+ const d = String(date.getDate()).padStart(2, "0");
14
+ return `${y}-${m}-${d}`;
15
+ }
16
+ function serializeError(err) {
17
+ if (err === undefined || err === null)
18
+ return undefined;
19
+ if (err instanceof Error) {
20
+ const out = { name: err.name, message: err.message };
21
+ if (err.stack)
22
+ out.stack = err.stack;
23
+ return out;
24
+ }
25
+ if (typeof err === "object") {
26
+ const anyErr = err;
27
+ const out = {
28
+ name: typeof anyErr.name === "string" ? anyErr.name : "NonError",
29
+ message: typeof anyErr.message === "string" ? anyErr.message : String(err),
30
+ };
31
+ if (typeof anyErr.stack === "string")
32
+ out.stack = anyErr.stack;
33
+ return out;
34
+ }
35
+ return { name: "NonError", message: String(err) };
36
+ }
37
+ function safeStringify(value) {
38
+ try {
39
+ return JSON.stringify(value) ?? "null";
40
+ }
41
+ catch {
42
+ return '"[unserializable]"';
43
+ }
44
+ }
45
+ export function createCliErrorLog(logsDir) {
46
+ let reportedWriteFailure = false;
47
+ const write = (line) => {
48
+ try {
49
+ if (!existsSync(logsDir))
50
+ mkdirSync(logsDir, { recursive: true });
51
+ appendFileSync(join(logsDir, `${localDateString(new Date())}.log`), line, "utf8");
52
+ }
53
+ catch {
54
+ if (!reportedWriteFailure) {
55
+ reportedWriteFailure = true;
56
+ try {
57
+ process.stderr.write(`[agentroam] failed to write error log to ${logsDir}; further failures are silent\n`);
58
+ }
59
+ catch { /* stderr gone */ }
60
+ }
61
+ }
62
+ };
63
+ const cleanupOldFiles = () => {
64
+ // 30-day retention, aligned with the core logger default. Best effort.
65
+ try {
66
+ if (!existsSync(logsDir))
67
+ return;
68
+ const cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000;
69
+ for (const name of readdirSync(logsDir)) {
70
+ if (!/^\d{4}-\d{2}-\d{2}\.log$/.test(name))
71
+ continue;
72
+ const full = join(logsDir, name);
73
+ try {
74
+ if (statSync(full).mtimeMs < cutoff)
75
+ unlinkSync(full);
76
+ }
77
+ catch { /* concurrent removal */ }
78
+ }
79
+ }
80
+ catch { /* best effort */ }
81
+ };
82
+ const log = (level, message, error, data) => {
83
+ if (!LEVELS.has(level))
84
+ level = "error";
85
+ const entry = {
86
+ ts: new Date().toISOString(),
87
+ level,
88
+ source: "cli",
89
+ message: typeof message === "string" ? message.slice(0, 4000) : String(message),
90
+ };
91
+ const serialized = serializeError(error);
92
+ if (serialized)
93
+ entry.error = serialized;
94
+ if (data !== undefined)
95
+ entry.data = data;
96
+ write(`${safeStringify(entry)}\n`);
97
+ };
98
+ return {
99
+ log,
100
+ installGlobalErrorHandlers: (options = {}) => {
101
+ const exitOnUncaughtException = options.exitOnUncaughtException ?? true;
102
+ process.on("uncaughtException", (err) => {
103
+ log("fatal", "uncaughtException", err);
104
+ if (exitOnUncaughtException)
105
+ process.exit(1);
106
+ });
107
+ process.on("unhandledRejection", (reason) => {
108
+ log("error", "unhandledRejection", reason);
109
+ });
110
+ cleanupOldFiles();
111
+ },
112
+ };
113
+ }