agentroam 0.2.0-preview.60 → 0.2.0-preview.62

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.
@@ -31,7 +31,7 @@ class ProgressReporter {
31
31
  this.timer = setTimeout(() => {
32
32
  const step = this.steps.at(-1);
33
33
  const seconds = Math.floor((Date.now() - step.started) / 1000);
34
- this.log(`… ${step.label}(已等待 ${seconds} 秒)`);
34
+ this.log(`… ${step.label} (elapsed ${seconds}s)`);
35
35
  this.schedule(this.intervalMs);
36
36
  }, milliseconds);
37
37
  this.timer.unref?.();
@@ -58,12 +58,12 @@ export async function downloadDesktop(version, { platform = process.platform, ar
58
58
 
59
59
  if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
60
60
  try {
61
- const destination = await withCliProgress('正在下载并校验桌面端安装包', () => downloadDesktop(process.argv[2]));
62
- console.log(`桌面端安装包已下载:${destination}\n请打开安装包完成安装。首次打开 AgentRoam 后,按提示授权远程桌面。`);
61
+ const destination = await withCliProgress('Downloading and verifying the desktop installer', () => downloadDesktop(process.argv[2]));
62
+ console.log(`Desktop installer downloaded: ${destination}\nOpen the installer, then follow the remote desktop authorization prompts.`);
63
63
  if (process.platform === 'darwin') execFile('/usr/bin/open', ['-R', destination], () => undefined);
64
64
  else if (process.platform === 'win32') execFile('explorer.exe', [`/select,${destination}`], () => undefined);
65
65
  } catch (error) {
66
- console.error(`桌面端下载未完成:${error.message}。CLI 已安装,可继续使用。`);
66
+ console.error(`Desktop download failed: ${error.message}. CLI is installed and ready to use.`);
67
67
  process.exitCode = 1;
68
68
  }
69
69
  }
package/dist/cli.js CHANGED
@@ -6,7 +6,7 @@ import { parseArgs } from "./args.js";
6
6
  import { ensureCloudflared } from "./cloudflared/installer.js";
7
7
  import { resolveCodexRuntime } from "./codex-runtime-manager.js";
8
8
  import { probeSQLiteRuntime, probeTerminalRuntime, repairNativeRuntimePermissions } from "./native-runtime.js";
9
- import { findLanUrl } from "./network.js";
9
+ import { findRoutedLanUrl } from "./network.js";
10
10
  import { installedDataDir, pairingAdmin, printPairingCode, terminalText } from "./device-pairing.js";
11
11
  import { detectPlatform } from "./platform.js";
12
12
  import { AGENTROAM_VERSION, resolvePlatformRuntime, resolvePlatformTui } from "./platform-packages.js";
@@ -60,13 +60,13 @@ export async function main(argv) {
60
60
  // Foreground start remains alive after readiness; only its startup stages load.
61
61
  if (options.command === "start" || options.command === "update-worker")
62
62
  return executeCommand(options, argv);
63
- const label = options.command === "service" ? `正在处理后台服务:${options.serviceAction}`
64
- : options.command === "desktop" ? "正在检查远程桌面授权"
65
- : options.command === "codex-desktop" ? "正在配置官方 Codex 桌面连接"
66
- : options.command === "doctor" ? "正在检查运行组件"
67
- : options.command === "update" ? "正在检查并准备更新"
68
- : options.command === "unlock-service" ? "正在处理 Windows 解锁服务,请留意管理员授权弹窗"
69
- : "正在处理设备授权命令";
63
+ const label = options.command === "service" ? `Processing background service: ${options.serviceAction}`
64
+ : options.command === "desktop" ? "Checking remote desktop authorization"
65
+ : options.command === "codex-desktop" ? "Configuring Codex Desktop connection"
66
+ : options.command === "doctor" ? "Checking runtime components"
67
+ : options.command === "update" ? "Checking and preparing updates"
68
+ : options.command === "unlock-service" ? "Configuring Windows unlock service; watch for the administrator prompt"
69
+ : "Processing device authorization";
70
70
  await withCliProgress(label, () => executeCommand(options, argv));
71
71
  }
72
72
  async function executeCommand(options, argv) {
@@ -156,7 +156,7 @@ async function executeCommand(options, argv) {
156
156
  return;
157
157
  }
158
158
  console.log(`AgentRoam ${VERSION}\n✓ Node ${process.versions.node} · ${target}`);
159
- const sleepInhibitor = await withCliProgress("正在准备启动环境", () => acquireSleepInhibitor());
159
+ const sleepInhibitor = await withCliProgress("Preparing startup environment", () => acquireSleepInhibitor());
160
160
  const controller = new AbortController();
161
161
  let runtime = null;
162
162
  let relay = null;
@@ -172,7 +172,7 @@ async function executeCommand(options, argv) {
172
172
  return closePromise;
173
173
  closing = true;
174
174
  controller.abort();
175
- closePromise = withCliProgress("正在停止本机服务和访问连接", async () => {
175
+ closePromise = withCliProgress("Stopping local service and connections", async () => {
176
176
  await relay?.tunnel?.close().catch(() => { });
177
177
  await runtime?.close().catch(() => { });
178
178
  });
@@ -182,25 +182,22 @@ async function executeCommand(options, argv) {
182
182
  process.once("SIGINT", requestClose);
183
183
  process.once("SIGTERM", requestClose);
184
184
  try {
185
- releaseStartup = await withCliProgress("正在等待启动锁", () => lockInstanceStartup(options.dataDir));
186
- await withCliProgress("正在接管旧实例", () => stopPreviousInstances(options.dataDir, console.log));
185
+ releaseStartup = await withCliProgress("Waiting for startup lock", () => lockInstanceStartup(options.dataDir));
186
+ await withCliProgress("Taking over previous instances", () => stopPreviousInstances(options.dataDir, console.log));
187
187
  if (controller.signal.aborted)
188
188
  return;
189
189
  await serviceReporter?.starting();
190
190
  reportedStarting = Boolean(serviceReporter);
191
- runtime = await withCliProgress("正在启动本机服务", () => new RuntimeManager().start(options, target));
191
+ runtime = await withCliProgress("Starting local service", () => new RuntimeManager().start(options, target));
192
192
  if (controller.signal.aborted) {
193
193
  await runtime.close();
194
194
  return;
195
195
  }
196
196
  void runtime.exited.then(() => controller.abort());
197
- console.log(`✓ Local server: ${runtime.localUrl}/web`);
198
197
  await serviceReporter?.localReady(runtime.localUrl);
199
- if (!serviceReporter)
200
- printLocalDesktopUrl(runtime.localUrl);
201
- const lanUrl = findLanUrl(runtime.port) ?? runtime.localUrl;
198
+ const lanUrl = await findRoutedLanUrl(runtime.port) ?? runtime.localUrl;
202
199
  const relayRuntime = runtime;
203
- relay = await withCliProgress("正在建立手机访问连接", () => selectRelay({
200
+ relay = await withCliProgress("Preparing phone access", () => selectRelay({
204
201
  cli: options,
205
202
  target,
206
203
  localUrl: relayRuntime.localUrl,
@@ -208,8 +205,8 @@ async function executeCommand(options, argv) {
208
205
  port: relayRuntime.port,
209
206
  signal: controller.signal,
210
207
  log: (line) => process.stderr.write(`${line}\n`),
211
- onAttempt: (provider) => console.log(`▲ 正在连接 ${providerDisplayName(provider)}(最多 30 秒,失败后使用局域网)…`),
212
- onFailure: (provider, message) => console.error(`⚠ ${providerDisplayName(provider)} 不可用:${message};正在切换到局域网。`),
208
+ onAttempt: (provider) => console.log(`▲ Connecting to ${providerDisplayName(provider)} (up to 30s, then LAN fallback)…`),
209
+ onFailure: (provider, message) => console.error(`⚠ ${providerDisplayName(provider)} unavailable: ${message}; falling back to LAN.`),
213
210
  }));
214
211
  if (controller.signal.aborted) {
215
212
  await relay.tunnel?.close();
@@ -220,7 +217,7 @@ async function executeCommand(options, argv) {
220
217
  console.error(` Continuing with local network access: ${relay.publicUrl}/web`);
221
218
  else
222
219
  console.log(`✓ Local network: ${relay.publicUrl}/web`);
223
- console.log(lanUrl === runtime.localUrl ? "当前没有可用的局域网地址,可先在本机使用;连接 Wi-Fi 或有线网络后重启服务以生成手机访问地址。" : "手机与电脑连接同一局域网后,即可使用以上地址或二维码连接。");
220
+ console.log(lanUrl === runtime.localUrl ? "Local access only. Connect to Wi-Fi or Ethernet and restart to enable phone access." : "Connect your phone to the same LAN to use this address or QR code.");
224
221
  }
225
222
  else {
226
223
  console.log(`✓ ${providerDisplayName(relay.provider)} tunnel ready: ${relay.publicUrl}`);
@@ -242,6 +239,7 @@ async function executeCommand(options, argv) {
242
239
  }
243
240
  else {
244
241
  console.log(`\nOpen: ${accessUrl}`);
242
+ printLocalDesktopUrl(runtime.localUrl);
245
243
  if (!options.testNoPairing)
246
244
  await printPairingCode(options.dataDir, console.log, { signal: controller.signal, accessUrl, qr: options.qr });
247
245
  console.log("Ctrl+C stops the tunnel and local server.");
@@ -283,7 +281,7 @@ async function doctor(target, dataDir) {
283
281
  ["better-sqlite3", probeSQLiteRuntime],
284
282
  ]) {
285
283
  try {
286
- await withCliProgress(`正在检查 ${module}`, () => probe(runtimeRequire));
284
+ await withCliProgress(`Checking ${module}`, () => probe(runtimeRequire));
287
285
  console.log(`✓ ${module}`);
288
286
  }
289
287
  catch (error) {
@@ -298,19 +296,19 @@ async function doctor(target, dataDir) {
298
296
  reportDoctorFailure(error, "agent-tui: ");
299
297
  }
300
298
  try {
301
- const codex = await withCliProgress("正在检查和准备 Codex(最多 180 秒)", () => withTimeout(signal => resolveCodexRuntime({
299
+ const codex = await withCliProgress("Checking and preparing Codex (up to 180s)", () => withTimeout(signal => resolveCodexRuntime({
302
300
  dataDir,
303
301
  target,
304
302
  signal,
305
303
  onProgress: (message) => console.log(`… ${message}`),
306
- }), CODEX_PREPARATION_TIMEOUT_MS, "Codex 组件准备超时(180 秒);请检查网络后重试。"));
304
+ }), CODEX_PREPARATION_TIMEOUT_MS, "Codex preparation timed out (180s); check your network and retry."));
307
305
  console.log(`✓ Codex ${codex.version} (${codex.source}) ${codex.executable}`);
308
306
  }
309
307
  catch (error) {
310
308
  reportDoctorFailure(error, "Codex: ");
311
309
  }
312
310
  try {
313
- const executable = await withCliProgress("正在检查和准备 Cloudflare 组件", () => ensureCloudflared(target, dataDir));
311
+ const executable = await withCliProgress("Checking and preparing Cloudflare", () => ensureCloudflared(target, dataDir));
314
312
  console.log(`✓ cloudflared ${executable}`);
315
313
  }
316
314
  catch (error) {
@@ -18,13 +18,13 @@ export async function setupCodexDesktop(options, context = {}) {
18
18
  environment.AGENT_CODEX_BIN = context.service.codexPath;
19
19
  }
20
20
  const inspect = context.inspect ?? inspectCodexDesktop;
21
- const deferred = () => log("已保留当前 Codex 桌面端。扫码仍可连接 AgentRoam;原桌面会话暂未共享,可稍后执行 agentroam codex-desktop --setup。");
21
+ const deferred = () => log("Current Codex Desktop preserved. Scan to connect to AgentRoam; existing desktop sessions are not shared yet. Run agentroam codex-desktop --setup later.");
22
22
  try {
23
23
  await (context.configureSharing ?? configureCodexSharing)(options, { environment });
24
- log("已保存默认共享启动与后台自动恢复配置。");
24
+ log("Saved default shared startup and background recovery settings.");
25
25
  let snapshot = await inspect(environment);
26
26
  if (snapshot.status === "not-installed") {
27
- log("未安装官方 Codex 桌面端,继续生成扫码连接入口。");
27
+ log("Codex Desktop is not installed. Continuing with phone pairing.");
28
28
  return;
29
29
  }
30
30
  const original = snapshot;
@@ -33,17 +33,17 @@ export async function setupCodexDesktop(options, context = {}) {
33
33
  // Read every loaded thread again immediately before choosing automatic restart.
34
34
  snapshot = await inspect(environment);
35
35
  if (!sameDesktop(original, snapshot)) {
36
- log("桌面进程已变化,本次保留桌面。");
36
+ log("Desktop process changed. Preserving Desktop.");
37
37
  deferred();
38
38
  return;
39
39
  }
40
40
  }
41
41
  if (snapshot.status === "running" && snapshot.activity.state !== "idle") {
42
42
  const reason = snapshot.activity.state === "busy"
43
- ? `官方 Codex 桌面端当前有 ${snapshot.activity.activeCount} 个运行中的会话。`
44
- : "无法可靠确认官方 Codex 桌面端的全部任务已结束。";
43
+ ? `Codex Desktop has ${snapshot.activity.activeCount} active sessions.`
44
+ : "Cannot reliably confirm that all Codex Desktop tasks have finished.";
45
45
  log(reason);
46
- const answer = await withoutCliProgress(() => (context.confirm ?? confirmDesktopRestart)("现在重启桌面端以共享会话?重启可能中断桌面端的所有运行任务;选择保留则暂不能共享原桌面会话 [y/N]:"));
46
+ const answer = await withoutCliProgress(() => (context.confirm ?? confirmDesktopRestart)("Restart Desktop now to share sessions? This may interrupt all running desktop tasks. Keeping Desktop running leaves existing sessions unshared [y/N]: "));
47
47
  if (!answer || !/^(?:y|yes)$/i.test(answer.trim())) {
48
48
  deferred();
49
49
  return;
@@ -51,7 +51,7 @@ export async function setupCodexDesktop(options, context = {}) {
51
51
  restartConfirmed = true;
52
52
  const checked = await inspect(environment);
53
53
  if (!sameDesktop(snapshot, checked)) {
54
- log("确认后桌面进程已变化,本次保留桌面。");
54
+ log("Desktop process changed after confirmation. Preserving Desktop.");
55
55
  deferred();
56
56
  return;
57
57
  }
@@ -71,13 +71,13 @@ export async function setupCodexDesktop(options, context = {}) {
71
71
  }
72
72
  const launchOptions = { ...options, command: "codex-desktop", desktopSetup: false,
73
73
  desktopDryRun: false, desktopRestart: snapshot.status === "running" };
74
- log(snapshot.status === "stopped" ? "正在启动官方 Codex 桌面端并连接共享后端…" : "正在重新连接官方 Codex 桌面端的共享后端…");
74
+ log(snapshot.status === "stopped" ? "Starting Codex Desktop and connecting to the shared backend..." : "Reconnecting Codex Desktop to the shared backend...");
75
75
  await (context.launch ?? ((args, env) => runCodexDesktopCommand(args, { environment: env, log })))(launchOptions, environment);
76
- log("已尝试桌面连接,随后显示扫码入口。AgentRoam 将根据实际连接结果,依次使用桌面、shared、standalone 后端。");
76
+ log("Desktop connection attempted. Pairing follows. AgentRoam selects the desktop, shared, or standalone backend based on actual connectivity.");
77
77
  }
78
78
  catch (error) {
79
- log(`桌面共享连接未完成:${error instanceof Error ? error.message : error}`);
80
- log("AgentRoam 安装继续,扫码可连接;后端按桌面 → shared → standalone 回退。原桌面会话暂未确认共享,可稍后执行 agentroam codex-desktop --setup 重试。");
79
+ log(`Desktop sharing connection incomplete: ${error instanceof Error ? error.message : error}`);
80
+ log("AgentRoam installation continues; scan to connect. Backend fallback: desktop -> shared -> standalone. Existing desktop sharing is unconfirmed. Retry later with agentroam codex-desktop --setup.");
81
81
  }
82
82
  }
83
83
  function sameDesktop(previous, current) {
@@ -3,7 +3,7 @@ import { Readable } from "node:stream";
3
3
  export class DesktopAuthorizationInterrupted extends Error {
4
4
  kind;
5
5
  constructor(kind) {
6
- super(kind === "skip" ? "已跳过远程桌面授权。" : "远程桌面授权等待超时,已跳过。");
6
+ super(kind === "skip" ? "Remote desktop authorization skipped." : "Remote desktop authorization timed out and was skipped.");
7
7
  this.kind = kind;
8
8
  }
9
9
  }
@@ -44,7 +44,7 @@ export class DesktopAuthorizationPrompt {
44
44
  return Promise.resolve(false);
45
45
  return new Promise((resolve) => {
46
46
  this.answer = resolve;
47
- this.options.log("现在授权远程桌面,允许已配对设备查看和控制这台电脑?[y/N](回车跳过):");
47
+ this.options.log("Authorize remote desktop now, allowing paired devices to view and control this computer? [y/N] (Enter to skip): ");
48
48
  });
49
49
  }
50
50
  close() {
@@ -12,21 +12,21 @@ async function requestAuthorization(dataDir, body, signal) {
12
12
  || typeof status.enabled !== "boolean" || typeof status.screen !== "boolean" || typeof status.accessibility !== "boolean"
13
13
  || typeof status.online !== "boolean" || typeof status.platform !== "string"
14
14
  || (status.error !== null && typeof status.error !== "string")) {
15
- throw new Error("本机远程授权状态无效,请升级 CLI 后重试");
15
+ throw new Error("Invalid local authorization status. Upgrade the CLI and retry");
16
16
  }
17
17
  return status;
18
18
  }
19
19
  function recoveryHint(log) {
20
- log("稍后重新授权:agentroam desktop authorize;也可在本机浏览器的“远程授权”面板中操作。");
20
+ log("Authorize later: agentroam desktop authorize, or use the Remote Authorization panel in a local browser.");
21
21
  }
22
22
  function reportComponent(status, log) {
23
23
  if (!status.component)
24
24
  return;
25
25
  const component = status.component;
26
- log(`远控组件:${terminalText(component.version === 'legacy' ? '旧版(未记录版本)' : component.version)}`);
27
- log(`${status.platform === 'win32' ? '组件位置' : '授权应用位置'}:${terminalText(component.path)}`);
26
+ log(`Remote desktop component: ${terminalText(component.version === 'legacy' ? 'legacy (version unknown)' : component.version)}`);
27
+ log(`${status.platform === 'win32' ? 'Component path' : 'Authorization app path'}: ${terminalText(component.path)}`);
28
28
  if (component.updatePending)
29
- log('旧版远控组件仍在使用;结束其他 AgentRoam 的桌面共享后,重新授权即可更新。');
29
+ log('An older component is still in use. Stop desktop sharing in other AgentRoam instances, then authorize again to update.');
30
30
  }
31
31
  function complete(status) {
32
32
  return status.enabled && status.screen && status.accessibility && !status.error;
@@ -35,7 +35,7 @@ function complete(status) {
35
35
  export async function authorizeRemoteDesktop(dataDir, context = {}) {
36
36
  const log = context.log ?? console.log;
37
37
  if (!(context.isTTY ?? process.stdout.isTTY === true)) {
38
- log("未检测到交互终端,已跳过远程桌面授权。");
38
+ log("No interactive terminal detected. Remote desktop authorization skipped.");
39
39
  recoveryHint(log);
40
40
  return false;
41
41
  }
@@ -54,17 +54,17 @@ export async function authorizeRemoteDesktop(dataDir, context = {}) {
54
54
  }
55
55
  return status;
56
56
  };
57
- log("远程桌面授权可选;输入 s 后回车或按 Ctrl+C 可跳过,稍后可重新授权。");
57
+ log("Remote desktop authorization is optional. Type s and Enter or press Ctrl+C to skip; you can authorize later.");
58
58
  try {
59
- let status = await withCliProgress("正在检查本机远程桌面权限", () => check());
59
+ let status = await withCliProgress("Checking local remote desktop permissions", () => check());
60
60
  if (!status.supported)
61
- throw new Error("远程桌面支持 macOS 14 及以上的 Apple Silicon 电脑和 Windows 10/11 x64");
61
+ throw new Error("Remote desktop requires Apple Silicon with macOS 14 or later, or Windows 10/11 x64");
62
62
  if (!status.installed)
63
- throw new Error("当前 CLI 未包含远程授权组件,请升级 CLI");
63
+ throw new Error("This CLI does not include the authorization component. Upgrade the CLI");
64
64
  if (status.enabled) {
65
65
  status = await check({ action: "recheck" });
66
66
  if (complete(status)) {
67
- log("✓ 远程桌面已授权并开启共享。");
67
+ log("✓ Remote desktop authorized and sharing enabled.");
68
68
  return true;
69
69
  }
70
70
  }
@@ -72,7 +72,7 @@ export async function authorizeRemoteDesktop(dataDir, context = {}) {
72
72
  const confirm = context.confirm ?? (() => prompt.confirm());
73
73
  const confirmed = await withoutCliProgress(() => run(confirm));
74
74
  if (!confirmed) {
75
- log("已跳过远程桌面授权。");
75
+ log("Remote desktop authorization skipped.");
76
76
  recoveryHint(log);
77
77
  return false;
78
78
  }
@@ -82,11 +82,11 @@ export async function authorizeRemoteDesktop(dataDir, context = {}) {
82
82
  for (const permission of ["screen", "accessibility"]) {
83
83
  if (status[permission])
84
84
  continue;
85
- const name = permission === "screen" ? "屏幕录制" : "辅助功能";
85
+ const name = permission === "screen" ? "Screen Recording" : "Accessibility";
86
86
  // TCC grants belong to the bundle ID across all installed runtimes.
87
87
  // A false probe here must never revoke another runtime's permission.
88
- log(`正在请求${name}权限,请在系统设置中允许 AgentRoam Remote Desktop…`);
89
- status = await withCliProgress(`正在等待${name}权限;输入 s 后回车可跳过`, async () => {
88
+ log(`Requesting ${name} permission. Allow AgentRoam Remote Desktop in System Settings...`);
89
+ status = await withCliProgress(`Waiting for ${name} permission; type s and Enter to skip`, async () => {
90
90
  let current = await check({ action: "request-permission", permission });
91
91
  for (let attempt = 0; !current[permission] && attempt < (context.pollAttempts ?? 60); attempt++) {
92
92
  await run(() => wait(2000));
@@ -95,27 +95,27 @@ export async function authorizeRemoteDesktop(dataDir, context = {}) {
95
95
  return current;
96
96
  });
97
97
  if (!status[permission]) {
98
- log(`${name}权限尚未授予,本次未开启共享。`);
98
+ log(`${name} permission was not granted. Sharing was not enabled.`);
99
99
  recoveryHint(log);
100
100
  return false;
101
101
  }
102
102
  }
103
103
  }
104
104
  if (!status.screen || !status.accessibility) {
105
- log("远程桌面尚不可用,请确认系统权限及当前桌面状态,本次未开启共享。");
105
+ log("Remote desktop is unavailable. Check system permissions and desktop state. Sharing was not enabled.");
106
106
  recoveryHint(log);
107
107
  return false;
108
108
  }
109
- status = await withCliProgress("正在开启并检查远程桌面共享", () => check({ action: "enable" }));
109
+ status = await withCliProgress("Enabling and checking remote desktop sharing", () => check({ action: "enable" }));
110
110
  if (!complete(status))
111
- throw new Error(status.error ? terminalText(status.error) : "远程桌面共享未就绪,请重新检查系统权限");
112
- log("✓ 远程桌面授权完成,已开启共享。手机首次连接仍需设备配对。");
111
+ throw new Error(status.error ? terminalText(status.error) : "Remote desktop sharing is not ready. Check system permissions");
112
+ log("✓ Remote desktop authorization complete; sharing enabled. Your phone still needs device pairing on first connection.");
113
113
  return true;
114
114
  }
115
115
  catch (error) {
116
116
  if (!prompt.signal.aborted)
117
117
  throw error;
118
- log(prompt.signal.reason instanceof DesktopAuthorizationInterrupted ? prompt.signal.reason.message : "已取消远程桌面授权。");
118
+ log(prompt.signal.reason instanceof DesktopAuthorizationInterrupted ? prompt.signal.reason.message : "Remote desktop authorization cancelled.");
119
119
  recoveryHint(log);
120
120
  return false;
121
121
  }
@@ -141,15 +141,15 @@ export async function runDesktopCommand(options, context = {}) {
141
141
  if (options.desktopAction === "disable") {
142
142
  status = await request(options.dataDir, { action: "disable" });
143
143
  if (status.enabled)
144
- throw new Error("远程桌面共享尚未关闭,请重试");
145
- log("✓ 已关闭远程桌面共享,系统权限保留。重新开启:agentroam desktop authorize");
144
+ throw new Error("Remote desktop sharing is still enabled. Retry");
145
+ log("✓ Remote desktop sharing disabled; system permissions retained. Enable again: agentroam desktop authorize");
146
146
  return;
147
147
  }
148
148
  if (status.supported && status.installed)
149
149
  status = await request(options.dataDir, { action: "recheck" });
150
150
  reportComponent(status, log);
151
- log(`远程桌面:${status.supported ? "支持" : "不支持"};共享:${status.enabled ? "已开启" : "未开启"};屏幕录制:${status.screen ? "已授权" : "未授权或桌面不可用"};辅助功能:${status.accessibility ? "已授权" : "未授权"}`);
151
+ 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"}`);
152
152
  if (status.error)
153
- log(`状态提示:${terminalText(status.error)}`);
153
+ log(`Status: ${terminalText(status.error)}`);
154
154
  recoveryHint(log);
155
155
  }
@@ -19,7 +19,7 @@ export async function pairingAdmin(dataDir, action, body, options = {}) {
19
19
  catch (error) {
20
20
  if (!(error instanceof LocalServiceHttpError))
21
21
  throw error;
22
- const message = error.status === 423 ? "远程访问已锁定,请先执行 agentroam unlock" : error.status === 410 ? "请求已过期或已处理" : error.status === 409 ? "核对短语不匹配" : `设备授权操作失败 (HTTP ${error.status})`;
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
23
  throw new Error(message);
24
24
  }
25
25
  }
@@ -27,34 +27,34 @@ export function terminalText(value) { return value.replace(/[\x00-\x1f\x7f-\x9f\
27
27
  export function pairingQrPayload(accessUrl, grant) {
28
28
  const url = new URL(accessUrl);
29
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("无效的配对地址或授权凭据");
30
+ throw new Error("Invalid pairing URL or authorization grant");
31
31
  return `${url.origin}/pair#pair=${grant}`;
32
32
  }
33
33
  export async function printPairingCode(dataDir, log = console.log, options = {}) {
34
- const result = await withCliProgress("正在生成设备配对码", () => pairingAdmin(dataDir, "code"));
35
- log(`配对码:${result.code.slice(0, 4)} ${result.code.slice(4)}`);
36
- log("5 分钟内有效,仅可使用一次。手机输入后仍需在电脑上确认核对短语。");
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
37
  if ((options.qr ?? true) && (options.interactive ?? process.stdout.isTTY)) {
38
38
  const accessUrl = options.accessUrl ?? await readFile(join(dataDir, "tunnel.url"), "utf8").then((value) => value.trim(), () => null);
39
39
  if (accessUrl) {
40
40
  // Validate the public address before minting an invitation. Never persist the grant.
41
41
  pairingQrPayload(accessUrl, "a".repeat(43));
42
- const qr = await withCliProgress("正在生成手机连接二维码", async () => {
42
+ const qr = await withCliProgress("Generating phone connection QR code", async () => {
43
43
  const { grant } = await pairingAdmin(dataDir, "qr");
44
44
  return renderQr(pairingQrPayload(accessUrl, grant));
45
45
  });
46
- log("手机扫码直接连接(5 分钟、一次有效,请勿分享截图):");
46
+ log("Scan with your phone to connect (valid for 5 minutes, single use; do not share screenshots):");
47
47
  log(qr);
48
48
  }
49
49
  else
50
- log("生成 App 授权二维码:agentroam pair --url <手机可访问的服务器地址>");
50
+ log("Generate an app authorization QR code: agentroam pair --url <phone-accessible-server-url>");
51
51
  }
52
52
  const approvalInput = resolveApprovalInput(options);
53
53
  if (approvalInput) {
54
- await withCliProgress("正在等待手机扫码或输入配对码", () => watchPairingApproval(dataDir, result.expiresAt, { log, signal: options.signal, input: 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
55
  }
56
56
  else
57
- log("查看请求:agentroam approvals;批准:agentroam approve <请求ID> --phrase <手机核对短语>");
57
+ log("View requests: agentroam approvals; approve: agentroam approve <request-id> --phrase <phone-verification-phrase>");
58
58
  }
59
59
  /** Open the controlling terminal (`/dev/tty`) — the same source install-agentroam.sh reads from. */
60
60
  function openControllingTerminal() {
@@ -93,32 +93,32 @@ export function resolveApprovalInput(context = {}) {
93
93
  export async function watchPairingApproval(dataDir, codeExpiresAt, options = {}) {
94
94
  const admin = options.admin ?? pairingAdmin;
95
95
  const log = options.log ?? console.log;
96
- log("等待手机发起连接…");
96
+ log("Waiting for your phone to connect...");
97
97
  while (Date.now() < codeExpiresAt && !options.signal?.aborted) {
98
98
  const result = await admin(dataDir, "requests");
99
99
  if (result.locked) {
100
- log("远程访问已锁定");
100
+ log("Remote access is locked");
101
101
  return;
102
102
  }
103
103
  if (result.qrClaimed) {
104
- log("App 已扫码连接。");
104
+ log("App connected via QR code.");
105
105
  return;
106
106
  }
107
107
  const request = result.requests.find((r) => r.created >= codeExpiresAt - 300_000);
108
108
  if (request) {
109
- log(`新设备请求连接:${terminalText(request.name)}`);
110
- log(`请求 ID:${request.id}`);
111
- log(`核对短语:${request.phrase}`);
109
+ log(`New device connection request: ${terminalText(request.name)}`);
110
+ log(`Request ID: ${request.id}`);
111
+ log(`Verification phrase: ${request.phrase}`);
112
112
  const confirm = options.confirm ?? ((request, signal) => confirmOnTerminal(request, signal, options.input));
113
113
  const approved = await withoutCliProgress(() => confirm(request, options.signal));
114
114
  if (options.signal?.aborted)
115
115
  return;
116
116
  if (Date.now() >= request.expires) {
117
- log("授权请求已过期,请重新配对。");
117
+ log("Authorization request expired. Please pair again.");
118
118
  return;
119
119
  }
120
120
  await admin(dataDir, approved ? "approve" : "deny", { id: request.id, ...(approved ? { phrase: request.phrase } : {}) });
121
- log(approved ? "已批准,手机将自动进入。" : "已拒绝此设备。");
121
+ log(approved ? "Approved. Your phone will connect automatically." : "Device rejected.");
122
122
  return;
123
123
  }
124
124
  try {
@@ -129,7 +129,7 @@ export async function watchPairingApproval(dataDir, codeExpiresAt, options = {})
129
129
  }
130
130
  }
131
131
  if (!options.signal?.aborted)
132
- log("配对码已过期,执行 agentroam pair 生成新码。");
132
+ log("Pairing code expired. Run agentroam pair to generate a new code.");
133
133
  }
134
134
  async function confirmOnTerminal(request, signal, terminal = resolveApprovalInput()) {
135
135
  // A piped stdin is the install script, and a closed one can never answer.
@@ -144,7 +144,7 @@ async function confirmOnTerminal(request, signal, terminal = resolveApprovalInpu
144
144
  : { input: terminal, output: process.stdout, terminal: false });
145
145
  input.once("SIGINT", () => controller.abort());
146
146
  try {
147
- const answer = await input.question("确认手机显示相同短语?输入 yes 批准,其他输入拒绝:", { signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal });
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
148
  return answer.trim().toLowerCase() === "yes";
149
149
  }
150
150
  catch {
@@ -1,7 +1,7 @@
1
- import { readdir, readFile, mkdir, writeFile, rm, realpath, rename } from "node:fs/promises";
1
+ import { readdir, readFile, mkdir, realpath, rename } from "node:fs/promises";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { homedir } from "node:os";
4
- import { dirname, join, resolve } from "node:path";
4
+ import { dirname, join } from "node:path";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { runCommand } from "./service/service-controller.js";
7
7
  import { MacLaunchAgent } from "./service/macos-launch-agent.js";
@@ -140,28 +140,4 @@ export async function stopPreviousInstances(dataDir, log, dependencies = {}) {
140
140
  log("✓ 旧 CLI 已停止,继续启动新实例");
141
141
  }
142
142
  }
143
- /** Serialize startup within a data directory; never remove a live owner's lock. */
144
- export async function lockInstanceStartup(dataDir) {
145
- await mkdir(dataDir, { recursive: true });
146
- const path = resolve(await realpath(dataDir), ".cli-start.lock");
147
- try {
148
- await mkdir(path, { mode: 0o700 });
149
- }
150
- catch (error) {
151
- if (error.code !== "EEXIST")
152
- throw error;
153
- throw new Error("此数据目录已有 CLI 正在启动;请等它完成后重试。若上次异常退出,请确认无启动进程后移除 .cli-start.lock。");
154
- }
155
- try {
156
- await writeFile(join(path, "pid"), String(process.pid), { mode: 0o600 });
157
- }
158
- catch (error) {
159
- await rm(path, { recursive: true, force: true });
160
- throw error;
161
- }
162
- let released = false;
163
- return async () => { if (!released) {
164
- released = true;
165
- await rm(path, { recursive: true, force: true });
166
- } };
167
- }
143
+ export { lockInstanceStartup } from "./startup-lock.js";
@@ -1,8 +1,8 @@
1
1
  export function printLocalDesktopUrl(localUrl, log = console.log, platform = process.platform) {
2
- log(`远程桌面授权地址:${localUrl.replace(/\/$/, '')}/web`);
3
- log('重新授权:agentroam desktop authorize;浏览器备用入口:在这台电脑打开上述地址,配对后点击“远程授权”(盾牌图标)。');
2
+ log(`Local-only desktop authorization (open on this computer, not your phone): ${localUrl.replace(/\/$/, '')}/web`);
3
+ log('Authorize again: agentroam desktop authorize. Browser fallback: open the local URL on this computer, pair, then click Remote Authorization (shield icon).');
4
4
  if (platform === 'win32')
5
- log('点击“开启共享”。请保持 Windows 已登录且未锁屏;暂不支持 UAC 安全桌面和管理员窗口控制。');
5
+ log('Click Enable Sharing. Keep Windows signed in and unlocked; UAC secure desktop and administrator windows are not supported.');
6
6
  else
7
- log('按提示授予“屏幕录制”和“辅助功能”权限,然后点击“开启共享”。');
7
+ log('Grant Screen Recording and Accessibility permissions when prompted, then click Enable Sharing.');
8
8
  }
package/dist/network.js CHANGED
@@ -1,17 +1,46 @@
1
1
  import { networkInterfaces } from "node:os";
2
- export function findLanUrl(port, interfaces = networkInterfaces()) {
2
+ import { createSocket } from "node:dgram";
3
+ export function findLanUrl(port, interfaces = networkInterfaces(), routedAddress) {
3
4
  const addresses = Object.values(interfaces)
4
5
  .flatMap((entries) => entries ?? [])
5
6
  .filter((entry) => entry.family === "IPv4" && !entry.internal)
6
7
  .map((entry) => entry.address);
7
- const address = addresses.find(isPrivateIpv4) ?? addresses[0];
8
+ const address = routedAddress && addresses.includes(routedAddress) && isPrivateIpv4(routedAddress)
9
+ ? routedAddress : addresses.find(isPreferredLanIpv4);
8
10
  return address ? `http://${address}:${port}` : null;
9
11
  }
12
+ /** UDP connect selects the OS route without sending a packet to the destination. */
13
+ export async function findRoutedLanUrl(port) {
14
+ const routedAddress = await new Promise((done) => {
15
+ const socket = createSocket("udp4");
16
+ let settled = false;
17
+ const finish = (address) => {
18
+ if (settled)
19
+ return;
20
+ settled = true;
21
+ clearTimeout(timer);
22
+ try {
23
+ socket.close();
24
+ }
25
+ catch { /* A failed bind may leave no socket to close. */ }
26
+ done(address);
27
+ };
28
+ const timer = setTimeout(() => finish(null), 1_000);
29
+ socket.once("error", () => finish(null));
30
+ socket.connect(53, "1.1.1.1", () => { if (!settled)
31
+ finish(socket.address().address); });
32
+ });
33
+ return findLanUrl(port, networkInterfaces(), routedAddress);
34
+ }
10
35
  function isPrivateIpv4(address) {
36
+ const parts = address.split(".").map(Number);
37
+ return isPreferredLanIpv4(address) || (parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255)
38
+ && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31);
39
+ }
40
+ function isPreferredLanIpv4(address) {
11
41
  const parts = address.split(".").map(Number);
12
42
  if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255))
13
43
  return false;
14
44
  return parts[0] === 10 ||
15
- (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
16
45
  (parts[0] === 192 && parts[1] === 168);
17
46
  }
@@ -3,7 +3,9 @@ export async function acquireSleepInhibitor(options = {}) {
3
3
  const platform = options.platform ?? process.platform;
4
4
  const pid = options.pid ?? process.pid;
5
5
  const spawnProcess = options.spawnProcess ?? spawn;
6
- const readyTimeoutMs = options.readyTimeoutMs ?? 5_000;
6
+ // Windows PowerShell compiles the P/Invoke helper on first use. Cold startup
7
+ // and antivirus scanning can take longer than five seconds.
8
+ const readyTimeoutMs = options.readyTimeoutMs ?? (platform === "win32" ? 30_000 : 5_000);
7
9
  const stopTimeoutMs = options.stopTimeoutMs ?? 2_000;
8
10
  if (platform === "darwin") {
9
11
  const child = spawnProcess("/usr/bin/caffeinate", ["-i", "-w", String(pid)], {
@@ -24,7 +26,15 @@ export async function acquireSleepInhibitor(options = {}) {
24
26
  stdio: ["ignore", "pipe", "pipe"],
25
27
  windowsHide: true,
26
28
  });
27
- await waitForReadyLine(child, readyTimeoutMs);
29
+ try {
30
+ await waitForReadyLine(child, readyTimeoutMs);
31
+ }
32
+ catch (error) {
33
+ // A timed-out child otherwise keeps Node alive after startup has failed.
34
+ if (child.exitCode === null && child.signalCode === null)
35
+ child.kill("SIGKILL");
36
+ throw error;
37
+ }
28
38
  return monitorChild(child, stopTimeoutMs, "Windows idle-sleep inhibitor");
29
39
  }
30
40
  throw new Error(`idle-sleep prevention is unsupported on ${platform}`);
@@ -34,7 +34,7 @@ export async function runServiceCommand(options, context) {
34
34
  const environmentPath = buildServiceEnvironmentPath(context.nodePath, environment.PATH ?? environment.Path, platform);
35
35
  let codexPath;
36
36
  try {
37
- const codex = await withCliProgress("正在检查已有 Codex;缺失时由后台服务限时安装最新版", () => withTimeout(signal => (context.codexResolver ?? resolveCodexRuntime)({
37
+ const codex = await withCliProgress("Checking Codex; the background service installs it if missing", () => withTimeout(signal => (context.codexResolver ?? resolveCodexRuntime)({
38
38
  dataDir: options.dataDir,
39
39
  target: detectPlatform(platform, context.arch ?? process.arch, nodeVersion),
40
40
  environment: { ...environment, PATH: environmentPath },
@@ -43,11 +43,11 @@ export async function runServiceCommand(options, context) {
43
43
  installIfMissing: false,
44
44
  signal,
45
45
  onProgress: (message) => log(`… ${message}`),
46
- }), 60_000, "检查已有 Codex 超时;后台服务将继续检查。"));
46
+ }), 60_000, "Codex check timed out; the background service will continue checking."));
47
47
  codexPath = codex.executable;
48
48
  }
49
49
  catch (error) {
50
- log(`Codex 将在后台服务启动时检查并限时补齐:${error instanceof Error ? error.message : error}`);
50
+ log(`Codex will be checked and installed during service startup: ${error instanceof Error ? error.message : error}`);
51
51
  }
52
52
  const config = {
53
53
  version: context.version,
@@ -68,55 +68,61 @@ export async function runServiceCommand(options, context) {
68
68
  try {
69
69
  await withTimeout(signal => (context.configureSharing ?? configureCodexSharing)(options, {
70
70
  homeDir: context.homeDir, environment: { ...environment, PATH: environmentPath, AGENT_CODEX_BIN: codexPath }, signal,
71
- }), 10_000, "Codex 默认共享配置超时(10 秒)");
71
+ }), 10_000, "Codex sharing setup timed out (10 seconds)");
72
72
  }
73
73
  catch (error) {
74
- log(`Codex 默认共享配置未完成,可在电脑菜单中修复:${error instanceof Error ? error.message : error}`);
74
+ log(`Codex sharing setup incomplete; repair it from the computer menu: ${error instanceof Error ? error.message : error}`);
75
75
  }
76
76
  }
77
- const { definition, state } = await withCliProgress("正在启动后台服务;Codex 准备最多 180 秒,公网连接最多等待 30 秒,失败后使用局域网", () => controller.install(config));
77
+ const { definition, state } = await withCliProgress("Starting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.install(config));
78
78
  log(`✓ AgentRoam service installed: ${definition}`);
79
- if (state?.localUrl && state.status !== "stopped")
79
+ if (state?.status !== "ready" && state?.localUrl)
80
80
  printLocalDesktopUrl(state.localUrl, log, platform);
81
81
  requireReadyService(state);
82
+ log(`Open: ${state.accessUrl}`);
83
+ if (state.localUrl)
84
+ printLocalDesktopUrl(state.localUrl, log, platform);
82
85
  printLanFallback(state, log);
83
86
  if (state?.localUrl && state.status !== "stopped" && (platform === "darwin" || platform === "win32")) {
84
87
  if (environment.AGENTROAM_INSTALL_REMOTE_DESKTOP === "skip") {
85
- log("已跳过安装时远程桌面授权,可稍后执行 agentroam desktop authorize。");
88
+ log("Remote desktop authorization skipped. Run agentroam desktop authorize later.");
86
89
  }
87
90
  else {
88
91
  try {
89
92
  await (context.desktopAuthorization ?? authorizeRemoteDesktop)(options.dataDir, { platform, isTTY: stdoutIsTTY, timeoutMs: 60_000, log });
90
93
  }
91
94
  catch (error) {
92
- log(`远程桌面授权未完成:${error instanceof Error ? error.message : error}`);
93
- log("AgentRoam 安装继续;可稍后执行 agentroam desktop authorize,或在本机浏览器的“远程授权”面板中重试。");
95
+ log(`Remote desktop authorization incomplete: ${error instanceof Error ? error.message : error}`);
96
+ log("Installation continues. Retry with agentroam desktop authorize or the local browser authorization panel.");
94
97
  }
95
98
  }
96
99
  }
97
100
  if (platform === "darwin" && !options.desktopSetup)
98
- log("官方 Codex 桌面共享后端:agentroam codex-desktop --setup;预演:agentroam codex-desktop --dry-run。");
101
+ log("Codex Desktop sharing: agentroam codex-desktop --setup; preview: agentroam codex-desktop --dry-run.");
99
102
  if (state.version === config.version)
100
103
  await cleanupOldLaunchers(config, log);
101
104
  if (options.desktopSetup && platform === "darwin") {
102
- await withCliProgress("正在配置官方 Codex 桌面共享连接", () => (context.desktopSetup ?? setupCodexDesktop)(options, { platform, environment, service: config, log }));
105
+ await withCliProgress("Configuring Codex Desktop sharing", () => (context.desktopSetup ?? setupCodexDesktop)(options, { platform, environment, service: config, log }));
103
106
  }
104
- log(`Open: ${state.accessUrl}`);
105
107
  await (context.pairingPrinter ?? printPairingCode)(options.dataDir, log, { accessUrl: state.accessUrl, qr: options.qr, interactive: stdoutIsTTY });
106
108
  return;
107
109
  }
108
110
  case "start": {
109
- const state = await withCliProgress("正在启动后台服务;Codex 准备最多 180 秒,公网连接最多等待 30 秒,失败后使用局域网", () => controller.start());
110
- if (state?.localUrl && state.status !== "stopped")
111
+ const state = await withCliProgress("Starting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.start());
112
+ if (state?.status !== "ready" && state?.localUrl)
111
113
  printLocalDesktopUrl(state.localUrl, log, platform);
112
114
  requireReadyService(state);
115
+ log(`Open: ${state.accessUrl}`);
116
+ if (state.localUrl)
117
+ printLocalDesktopUrl(state.localUrl, log, platform);
113
118
  printLanFallback(state, log);
114
119
  log("✓ AgentRoam service started");
115
- await logAccessUrl(state.accessUrl);
120
+ if (options.qr && stdoutIsTTY)
121
+ log(await renderQr(state.accessUrl));
116
122
  return;
117
123
  }
118
124
  case "stop":
119
- await withCliProgress("正在停止后台服务", () => controller.stop());
125
+ await withCliProgress("Stopping background service", () => controller.stop());
120
126
  log("✓ AgentRoam service stopped");
121
127
  return;
122
128
  case "status": {
@@ -130,11 +136,13 @@ export async function runServiceCommand(options, context) {
130
136
  log(`Version: ${status.config.version}`);
131
137
  log(`Root: ${status.config.roots.join(", ")}`);
132
138
  }
133
- if (status.running && status.state?.localUrl)
139
+ if (status.running && status.state?.status !== "ready" && status.state?.localUrl)
134
140
  printLocalDesktopUrl(status.state.localUrl, log, platform);
135
141
  if (status.running && status.state?.status === "ready" && status.state.accessUrl) {
136
142
  printLanFallback(status.state, log);
137
143
  await logAccessUrl(status.state.accessUrl);
144
+ if (status.state.localUrl)
145
+ printLocalDesktopUrl(status.state.localUrl, log, platform);
138
146
  }
139
147
  return;
140
148
  }
@@ -152,13 +160,17 @@ export async function runServiceCommand(options, context) {
152
160
  return;
153
161
  }
154
162
  case "restart": {
155
- const state = await withCliProgress("正在重启后台服务;Codex 准备最多 180 秒,公网连接最多等待 30 秒,失败后使用局域网", () => controller.restart());
156
- if (state?.localUrl && state.status !== "stopped")
163
+ const state = await withCliProgress("Restarting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.restart());
164
+ if (state?.status !== "ready" && state?.localUrl)
157
165
  printLocalDesktopUrl(state.localUrl, log, platform);
158
166
  requireReadyService(state);
167
+ log(`Open: ${state.accessUrl}`);
168
+ if (state.localUrl)
169
+ printLocalDesktopUrl(state.localUrl, log, platform);
159
170
  printLanFallback(state, log);
160
171
  log("✓ AgentRoam service restarted");
161
- await logAccessUrl(state.accessUrl);
172
+ if (options.qr && stdoutIsTTY)
173
+ log(await renderQr(state.accessUrl));
162
174
  return;
163
175
  }
164
176
  case "uninstall": {
@@ -175,14 +187,14 @@ function printLanFallback(state, log) {
175
187
  if (state.provider !== "lan")
176
188
  return;
177
189
  if (state.accessUrl && ["127.0.0.1", "localhost", "[::1]"].includes(new URL(state.accessUrl).hostname)) {
178
- log("✓ 本机服务已启动;当前没有局域网地址,连接 Wi-Fi 或有线网络后重启服务即可生成手机访问地址。");
190
+ log("✓ Local access only. Connect to Wi-Fi or Ethernet and restart to enable phone access.");
179
191
  return;
180
192
  }
181
- log("✓ 后台服务已通过局域网启动;手机与电脑连接同一局域网后扫码连接。");
193
+ log("✓ Service ready on LAN. Connect your phone to the same network to pair.");
182
194
  }
183
195
  function requireReadyService(state) {
184
196
  if (state?.status !== "ready" || !state.accessUrl) {
185
- throw Object.assign(new Error(`AgentRoam 后台服务未就绪(${state?.status ?? "未取得状态"})。请运行 agentroam service logs 查看原因,修复后运行 agentroam service start,再执行 agentroam pair。`), { exitCode: 1 });
197
+ throw Object.assign(new Error(`AgentRoam service is not ready (${state?.status ?? "no state"}). Run agentroam service logs, fix the error, then run agentroam service start and agentroam pair.`), { exitCode: 1 });
186
198
  }
187
199
  }
188
200
  export function buildServiceEnvironmentPath(nodePath, pathValue, platform) {
@@ -0,0 +1,81 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
3
+ import { createServer } from "node:net";
4
+ import { join, resolve } from "node:path";
5
+ function alive(pid) {
6
+ try {
7
+ process.kill(pid, 0);
8
+ return true;
9
+ }
10
+ catch (error) {
11
+ return error.code !== "ESRCH";
12
+ }
13
+ }
14
+ /** Serialize startup within a data directory; never remove a live owner's lock. */
15
+ export async function lockInstanceStartup(dataDir) {
16
+ await mkdir(dataDir, { recursive: true });
17
+ const path = resolve(await realpath(dataDir), ".cli-start.lock");
18
+ // Task Scheduler can terminate the CLI without running finally. A named pipe
19
+ // is released by Windows even on forced termination; retain the PID marker
20
+ // so older launchers still see an in-progress startup.
21
+ let closePipe;
22
+ const busy = () => new Error("此数据目录已有 CLI 正在启动;请等它完成后重试。");
23
+ if (process.platform === "win32") {
24
+ const pipe = createServer();
25
+ const name = createHash("sha256").update(path.toLowerCase()).digest("hex");
26
+ await new Promise((done, reject) => {
27
+ const onError = (error) => reject(error.code === "EADDRINUSE" ? busy() : error);
28
+ pipe.once("error", onError);
29
+ pipe.listen(`\\\\.\\pipe\\agentroam-startup-${name}`, () => { pipe.removeListener("error", onError); done(); });
30
+ });
31
+ closePipe = () => new Promise((done, reject) => pipe.close(error => error ? reject(error) : done()));
32
+ try {
33
+ const owner = (await readFile(join(path, "pid"), "utf8").catch(error => {
34
+ if (error.code === "ENOENT")
35
+ return null;
36
+ throw error;
37
+ }))?.trim();
38
+ if (owner !== undefined && owner !== null) {
39
+ const pid = Number(owner);
40
+ // Be conservative with corrupt markers and potentially reused live PIDs.
41
+ if (!Number.isSafeInteger(pid) || pid <= 1 || alive(pid))
42
+ throw busy();
43
+ await rm(path, { recursive: true, force: true });
44
+ }
45
+ }
46
+ catch (error) {
47
+ await closePipe();
48
+ throw error;
49
+ }
50
+ }
51
+ try {
52
+ try {
53
+ await mkdir(path, { mode: 0o700 });
54
+ }
55
+ catch (error) {
56
+ if (error.code !== "EEXIST")
57
+ throw error;
58
+ throw new Error("此数据目录已有 CLI 正在启动;请等它完成后重试。若上次异常退出,请确认无启动进程后移除 .cli-start.lock。");
59
+ }
60
+ try {
61
+ await writeFile(join(path, "pid"), String(process.pid), { mode: 0o600 });
62
+ }
63
+ catch (error) {
64
+ await rm(path, { recursive: true, force: true });
65
+ throw error;
66
+ }
67
+ let release;
68
+ return () => release ??= (async () => {
69
+ try {
70
+ await rm(path, { recursive: true, force: true });
71
+ }
72
+ finally {
73
+ await closePipe?.();
74
+ }
75
+ })();
76
+ }
77
+ catch (error) {
78
+ await closePipe?.();
79
+ throw error;
80
+ }
81
+ }
@@ -334,7 +334,7 @@ if ($env:AGENTROAM_INSTALL_SKIP_SERVICE -eq "1") {
334
334
  Write-Host "AgentRoam service registration skipped for isolated verification."
335
335
  } else {
336
336
  & $NodeBin $Entry service install --root $ServiceRoot --data-dir $DataDir
337
- if ($LASTEXITCODE -ne 0) { throw "CLI 已安装,但后台服务安装或启动失败(exit $LASTEXITCODE),尚不能扫码连接。请运行 agentroam service logs 查看原因,修复后运行 agentroam service start,再执行 agentroam pair。" }
337
+ if ($LASTEXITCODE -ne 0) { throw "CLI installed, but the background service failed (exit $LASTEXITCODE). Run agentroam service logs, fix the error, then run agentroam service start and agentroam pair." }
338
338
  }
339
339
  Write-Host "`nAgentRoam $AgentRoamVersion installed: $WrapperPath"
340
340
  Write-Host "Open a new terminal, then run: agentroam service status"
@@ -344,15 +344,15 @@ if ($env:AGENTROAM_INSTALL_SKIP_SERVICE -eq "1" -and $DesktopChoice -eq "ask") {
344
344
  if ($DesktopChoice -eq "ask") {
345
345
  $DesktopChoice = "no"
346
346
  if ([Environment]::UserInteractive -and -not [Console]::IsInputRedirected) {
347
- try { $DesktopChoice = Read-Host "是否下载桌面端?用于手机查看和控制电脑桌面 [y/N]" } catch { $DesktopChoice = "no" }
347
+ try { $DesktopChoice = Read-Host "Download the desktop app for remote viewing and control? [y/N]" } catch { $DesktopChoice = "no" }
348
348
  }
349
349
  }
350
350
  if ($DesktopChoice -match '^(y|yes|是)$') {
351
351
  $DesktopHelper = Join-Path $LauncherRoot "node_modules\agentroam\bin\desktop-download.mjs"
352
352
  if (Test-Path -LiteralPath $DesktopHelper -PathType Leaf) {
353
353
  & $NodeBin $DesktopHelper $AgentRoamVersion
354
- if ($LASTEXITCODE -ne 0) { Write-Warning "CLI 安装已完成,桌面端可稍后重新下载。" }
354
+ if ($LASTEXITCODE -ne 0) { Write-Warning "CLI installation completed. You can retry the desktop download later." }
355
355
  } else {
356
- Write-Warning "当前发布的 CLI 尚未包含桌面下载功能,请在新版发布后重试。CLI 安装已完成。"
356
+ Write-Warning "This CLI version does not support desktop downloads. CLI installation completed; upgrade to retry."
357
357
  }
358
- } else { Write-Host "已跳过桌面端下载,CLI 可正常使用。" }
358
+ } else { Write-Host "Desktop download skipped. CLI is ready to use." }
@@ -43,7 +43,7 @@ stop_progress() {
43
43
  start_progress() {
44
44
  stop_progress
45
45
  [ "${AGENTROAM_NO_PROGRESS:-}" != "1" ] || return 0
46
- printf '… %s(已等待 0 秒)\n' "$1" >&2
46
+ printf '… %s (elapsed 0s)\n' "$1" >&2
47
47
  (
48
48
  progress_label=$1
49
49
  progress_started=$(date +%s)
@@ -56,7 +56,7 @@ start_progress() {
56
56
  wait "$progress_sleep_pid" || exit 0
57
57
  progress_sleep_pid=""
58
58
  progress_now=$(date +%s)
59
- printf '… %s(已等待 %s 秒)\n' "$progress_label" "$((progress_now - progress_started))" >&2
59
+ printf '… %s (elapsed %ss)\n' "$progress_label" "$((progress_now - progress_started))" >&2
60
60
  done
61
61
  ) </dev/null &
62
62
  PROGRESS_PID=$!
@@ -167,7 +167,7 @@ acquire_directory_lock() {
167
167
  done
168
168
  }
169
169
 
170
- start_progress "正在检查可用的 Node.js"
170
+ start_progress "Checking available Node.js"
171
171
  SYSTEM_NODE=$(command -v node 2>/dev/null || true)
172
172
  if [ "${AGENTROAM_BOOTSTRAP_TEST:-}" = "1" ] && [ "${AGENTROAM_FORCE_PRIVATE_NODE:-}" = "1" ]; then
173
173
  SYSTEM_NODE=""
@@ -185,7 +185,7 @@ else
185
185
  printf 'Using Node.js %s from NVM: %s\n' "$("$NODE_BIN" --version)" "$NODE_BIN"
186
186
  else
187
187
  if ! runtime_is_valid; then
188
- start_progress "正在等待 Node.js 安装锁"
188
+ start_progress "Waiting for the Node.js installation lock"
189
189
  acquire_directory_lock "$NODE_LOCK"
190
190
  stop_progress
191
191
  OWN_NODE_LOCK=1
@@ -195,7 +195,7 @@ else
195
195
  extract_path="$TEMP_ROOT/extract"
196
196
  mkdir "$extract_path"
197
197
  printf 'Downloading Node.js %s...\n' "$NODE_VERSION"
198
- start_progress "正在下载 Node.js $NODE_VERSION"
198
+ start_progress "Downloading Node.js $NODE_VERSION"
199
199
  if [ -n "${AGENTROAM_NODE_ARCHIVE_FILE:-}" ]; then
200
200
  cp "$AGENTROAM_NODE_ARCHIVE_FILE" "$archive_path"
201
201
  else
@@ -206,10 +206,10 @@ else
206
206
  sleep "$download_attempt"
207
207
  done
208
208
  fi
209
- start_progress "正在校验 Node.js 安装包"
209
+ start_progress "Verifying the Node.js archive"
210
210
  actual_sha=$(shasum -a 256 "$archive_path" | awk '{print $1}')
211
211
  [ "$actual_sha" = "$NODE_SHA256" ] || fail "Node.js archive checksum mismatch"
212
- start_progress "正在解压并验证 Node.js"
212
+ start_progress "Extracting and verifying Node.js"
213
213
  /usr/bin/tar -xJf "$archive_path" -C "$extract_path"
214
214
  entry_count=$(find "$extract_path" -mindepth 1 -maxdepth 1 | wc -l | tr -d ' ')
215
215
  [ "$entry_count" = "1" ] || fail "unexpected Node.js archive layout"
@@ -258,7 +258,7 @@ case "$AGENTROAM_VERSION_REQUEST" in
258
258
  *)
259
259
  # A dist-tag (default "preview") — resolve to the newest published version
260
260
  # so installs always pick up the latest release without touching this file.
261
- start_progress "正在查询 AgentRoam $AGENTROAM_VERSION_REQUEST 最新版本"
261
+ start_progress "Resolving AgentRoam $AGENTROAM_VERSION_REQUEST version"
262
262
  resolved_version="$("$NODE_BIN" "$NPM_CLI" view "agentroam@$AGENTROAM_VERSION_REQUEST" version --registry "$NPM_REGISTRY" 2>/dev/null | tail -1 | tr -d '[:space:]')"
263
263
  stop_progress
264
264
  [ -n "$resolved_version" ] || fail "could not resolve agentroam@$AGENTROAM_VERSION_REQUEST from $NPM_REGISTRY"
@@ -362,9 +362,9 @@ launcher_is_valid() {
362
362
  launcher_check "$LAUNCHER_ROOT" verify >/dev/null 2>&1
363
363
  }
364
364
 
365
- start_progress "正在检查已安装的 CLI"
365
+ start_progress "Checking the installed CLI"
366
366
  if ! launcher_is_valid; then
367
- start_progress "正在等待 CLI 安装锁"
367
+ start_progress "Waiting for the CLI installation lock"
368
368
  acquire_directory_lock "$LAUNCHER_LOCK"
369
369
  stop_progress
370
370
  OWN_LAUNCHER_LOCK=1
@@ -372,15 +372,15 @@ if ! launcher_is_valid; then
372
372
  TEMP_ROOT=$(mktemp -d "$LAUNCHER_PARENT/.launcher-$AGENTROAM_VERSION.XXXXXX")
373
373
  # Test-only extra specs are whitespace-delimited artifact paths in isolated CI directories.
374
374
  # shellcheck disable=SC2086
375
- run_with_progress "正在下载和安装 CLI 及平台组件" "$NODE_BIN" "$NPM_CLI" install --no-audit --no-fund --registry "$NPM_REGISTRY" --prefix "$TEMP_ROOT" $EXTRA_PACKAGE_SPECS "$PACKAGE_SPEC"
375
+ run_with_progress "Downloading and installing CLI and platform components" "$NODE_BIN" "$NPM_CLI" install --no-audit --no-fund --registry "$NPM_REGISTRY" --prefix "$TEMP_ROOT" $EXTRA_PACKAGE_SPECS "$PACKAGE_SPEC"
376
376
  runtime_spec=$(launcher_check "$TEMP_ROOT" spec)
377
377
  if ! launcher_check "$TEMP_ROOT" verify; then
378
378
  # A matching runtime is required even though npm treats platform packages as optional.
379
379
  rm -rf "$TEMP_ROOT/node_modules/agentroam-runtime-darwin-arm64"
380
- run_with_progress "正在安装必需的运行组件" "$NODE_BIN" "$NPM_CLI" install --save-exact --include=optional --no-audit --no-fund --registry "$NPM_REGISTRY" --prefix "$TEMP_ROOT" "$runtime_spec"
380
+ run_with_progress "Installing required runtime components" "$NODE_BIN" "$NPM_CLI" install --save-exact --include=optional --no-audit --no-fund --registry "$NPM_REGISTRY" --prefix "$TEMP_ROOT" "$runtime_spec"
381
381
  fi
382
- run_with_progress "正在验证运行组件" launcher_check "$TEMP_ROOT" verify
383
- start_progress "正在验证并启用 CLI"
382
+ run_with_progress "Verifying runtime components" launcher_check "$TEMP_ROOT" verify
383
+ start_progress "Verifying and activating CLI"
384
384
  if [ -e "$LAUNCHER_ROOT" ]; then
385
385
  PREVIOUS_LAUNCHER_ROOT=$(mktemp -d "$LAUNCHER_PARENT/.previous-$AGENTROAM_VERSION.XXXXXX")
386
386
  rmdir "$PREVIOUS_LAUNCHER_ROOT"
@@ -405,25 +405,25 @@ wrapper_temp=$(mktemp "$WRAPPER_DIR/.agentroam.XXXXXX")
405
405
  chmod 755 "$wrapper_temp"
406
406
  mv "$wrapper_temp" "$WRAPPER_PATH"
407
407
 
408
- if ! run_with_progress "正在检查运行组件" env AGENTROAM_NO_PROGRESS=1 "$NODE_BIN" "$entry" doctor --data-dir "$DATA_DIR"; then
408
+ if ! run_with_progress "Checking runtime components" env AGENTROAM_NO_PROGRESS=1 "$NODE_BIN" "$entry" doctor --data-dir "$DATA_DIR"; then
409
409
  printf 'Warning: some component checks failed; continuing background service installation. Affected features may be unavailable. Run agentroam doctor to retry.\n' >&2
410
410
  fi
411
411
  if [ "${AGENTROAM_INSTALL_SKIP_SERVICE:-}" = "1" ]; then
412
412
  printf 'AgentRoam service registration skipped for isolated verification.\n'
413
413
  else
414
414
  # The CLI owns progress here so it can pause for confirmations and print QR intact.
415
- printf '… 正在安装后台服务;随后检查远程桌面授权并生成手机连接二维码\n' >&2
415
+ printf '… Installing background service; remote desktop authorization and phone pairing follow\n' >&2
416
416
  codex_setup_module="$(dirname "$entry")/../dist/codex-desktop-setup.js"
417
417
  install_background_service() {
418
418
  if [ -f "$codex_setup_module" ]; then
419
419
  "$NODE_BIN" "$entry" service install --root "$SERVICE_ROOT" --data-dir "$DATA_DIR" --setup-codex-desktop
420
420
  else
421
- printf '当前发布的 CLI 尚未包含官方 Codex 桌面共享配置;扫码可连接 AgentRoam,原桌面会话暂未共享,请升级 CLI 后重试。\n'
421
+ printf 'This CLI does not include Codex Desktop sharing setup yet. You can connect to AgentRoam, but existing desktop sessions are not shared. Upgrade the CLI and retry.\n'
422
422
  "$NODE_BIN" "$entry" service install --root "$SERVICE_ROOT" --data-dir "$DATA_DIR"
423
423
  fi
424
424
  }
425
425
  if ! install_background_service; then
426
- printf 'CLI 已安装,但后台服务安装或启动失败,尚不能扫码连接。请运行 agentroam service logs 查看原因,修复后运行 agentroam service start,再执行 agentroam pair。\n' >&2
426
+ printf 'CLI installed, but the background service failed to start. Run agentroam service logs, fix the error, then run agentroam service start and agentroam pair.\n' >&2
427
427
  exit 1
428
428
  fi
429
429
  fi
@@ -440,7 +440,7 @@ if [ "${AGENTROAM_INSTALL_SKIP_SERVICE:-}" = "1" ] && [ "$desktop_choice" = "ask
440
440
  if [ "$desktop_choice" = "ask" ]; then
441
441
  desktop_choice=no
442
442
  if ( : </dev/tty ) 2>/dev/null; then
443
- printf '\n是否下载桌面端?用于手机查看和控制电脑桌面 [y/N]:' >/dev/tty
443
+ printf '\nDownload the desktop app for remote viewing and control? [y/N]: ' >/dev/tty
444
444
  IFS= read -r desktop_choice </dev/tty || desktop_choice=no
445
445
  fi
446
446
  fi
@@ -448,10 +448,10 @@ case "$desktop_choice" in
448
448
  y|Y|yes|YES|是)
449
449
  desktop_helper="$LAUNCHER_ROOT/node_modules/agentroam/bin/desktop-download.mjs"
450
450
  if [ -f "$desktop_helper" ]; then
451
- run_with_progress "正在下载并校验桌面端安装包" env AGENTROAM_NO_PROGRESS=1 "$NODE_BIN" "$desktop_helper" "$AGENTROAM_VERSION" || printf 'CLI 安装已完成,桌面端可稍后重新下载。\n'
451
+ run_with_progress "Downloading and verifying the desktop installer" env AGENTROAM_NO_PROGRESS=1 "$NODE_BIN" "$desktop_helper" "$AGENTROAM_VERSION" || printf 'CLI installation completed. You can retry the desktop download later.\n'
452
452
  else
453
- printf '当前发布的 CLI 尚未包含桌面下载功能,请在新版发布后重试。CLI 安装已完成。\n'
453
+ printf 'This CLI version does not support desktop downloads. CLI installation completed; upgrade to retry.\n'
454
454
  fi
455
455
  ;;
456
- *) printf '已跳过桌面端下载,CLI 可正常使用。\n' ;;
456
+ *) printf 'Desktop download skipped. CLI is ready to use.\n' ;;
457
457
  esac
@@ -3,13 +3,13 @@
3
3
  "installers": {
4
4
  "darwin-arm64": {
5
5
  "fileName": "install-agentroam.sh",
6
- "sha256": "c399354e39001b4717bad7aae81e5f53b1346188befdf308f73e3dcd99580cb0",
7
- "size": 19873
6
+ "sha256": "11e233307f893c509c20f0481d92d6da4f6e62b8cd7958702b9da65859b58ca2",
7
+ "size": 19865
8
8
  },
9
9
  "windows-amd64": {
10
10
  "fileName": "install-agentroam.ps1",
11
- "sha256": "766f1c59d436f762ae5b874175a5fe117da1a6dfdc2bc3442a599dff851b73fe",
12
- "size": 19124
11
+ "sha256": "dca596063a75a452bbf30b51f0746c48380428c60c5f1c5b87f93c5d538bd103",
12
+ "size": 19067
13
13
  }
14
14
  }
15
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentroam",
3
- "version": "0.2.0-preview.60",
3
+ "version": "0.2.0-preview.62",
4
4
  "description": "Zero-install mobile remote terminal and file console",
5
5
  "type": "module",
6
6
  "bin": {