agentroam 0.2.0-preview.70 → 0.2.0-preview.72

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.
package/dist/cli.js CHANGED
@@ -2,6 +2,7 @@ import { printLocalDesktopUrl } from './local-desktop-url.js';
2
2
  import { createRequire } from "node:module";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { join } from "node:path";
5
+ import { readFile, rm } from "node:fs/promises";
5
6
  import { parseArgs } from "./args.js";
6
7
  import { ensureCloudflared } from "./cloudflared/installer.js";
7
8
  import { resolveCodexRuntime } from "./codex-runtime-manager.js";
@@ -15,8 +16,8 @@ import { CODEX_PREPARATION_TIMEOUT_MS, RuntimeManager } from "./runtime-manager.
15
16
  import { withTimeout } from "./abort.js";
16
17
  import { ServiceRuntimeReporter } from "./service/runtime-state.js";
17
18
  import { runServiceCommand } from "./service/service-command.js";
18
- import { resolveServicePaths } from "./service/service-files.js";
19
- import { selectRelay } from "./tunnel/relay-orchestrator.js";
19
+ import { resolveServicePaths, writePrivateText } from "./service/service-files.js";
20
+ import { TunnelController, attachTunnelControl } from "./tunnel/tunnel-controller.js";
20
21
  import { currentCliPath, startUpdate } from "./update/update-command.js";
21
22
  import { runUpdateWorker } from "./update/update-worker.js";
22
23
  import { lockInstanceStartup, stopPreviousInstances } from "./instance-takeover.js";
@@ -159,7 +160,8 @@ async function executeCommand(options, argv) {
159
160
  const sleepInhibitor = await withCliProgress("Preparing startup environment", () => acquireSleepInhibitor());
160
161
  const controller = new AbortController();
161
162
  let runtime = null;
162
- let relay = null;
163
+ let tunnel = null;
164
+ let detachTunnel;
163
165
  let closing = false;
164
166
  let releaseStartup;
165
167
  let closePromise;
@@ -173,7 +175,8 @@ async function executeCommand(options, argv) {
173
175
  closing = true;
174
176
  controller.abort();
175
177
  closePromise = withCliProgress("Stopping local service and connections", async () => {
176
- await relay?.tunnel?.close().catch(() => { });
178
+ detachTunnel?.();
179
+ await tunnel?.close().catch(() => { });
177
180
  await runtime?.close().catch(() => { });
178
181
  });
179
182
  return closePromise;
@@ -195,44 +198,41 @@ async function executeCommand(options, argv) {
195
198
  }
196
199
  void runtime.exited.then(() => controller.abort());
197
200
  await serviceReporter?.localReady(runtime.localUrl);
198
- const lanUrl = await findRoutedLanUrl(runtime.port) ?? runtime.localUrl;
199
201
  const relayRuntime = runtime;
200
- relay = await withCliProgress("Preparing phone access", () => selectRelay({
201
- cli: options,
202
- target,
203
- localUrl: relayRuntime.localUrl,
204
- lanUrl,
205
- port: relayRuntime.port,
206
- signal: controller.signal,
207
- log: (line) => process.stderr.write(`${line}\n`),
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.`),
210
- }));
211
- if (controller.signal.aborted) {
212
- await relay.tunnel?.close();
202
+ tunnel = new TunnelController({
203
+ relay: {
204
+ cli: options, target, localUrl: relayRuntime.localUrl, port: relayRuntime.port,
205
+ log: line => process.stderr.write(`${line}\n`),
206
+ onAttempt: provider => console.log(`▲ Connecting to ${providerDisplayName(provider)} (up to 30s, then LAN fallback)…`),
207
+ onFailure: (provider, message) => console.error(`⚠ ${providerDisplayName(provider)} unavailable: ${message}; falling back to LAN.`),
208
+ },
209
+ lanUrl: async () => await findRoutedLanUrl(relayRuntime.port) ?? relayRuntime.localUrl,
210
+ publish: async (status) => {
211
+ const accessUrl = status.accessUrl;
212
+ if (serviceReporter && status.phase !== "connecting") {
213
+ await serviceReporter.ready({ localUrl: relayRuntime.localUrl, publicUrl: new URL(accessUrl).origin, accessUrl, provider: status.provider });
214
+ }
215
+ else
216
+ await writePrivateText(resolveServicePaths(undefined, options.dataDir).urlPath, `${accessUrl}\n`);
217
+ },
218
+ onError: error => console.error("Tunnel status update failed:", error),
219
+ });
220
+ detachTunnel = attachTunnelControl(runtime.process, tunnel);
221
+ const relay = await withCliProgress("Preparing phone access", () => tunnel.connect(false));
222
+ if (controller.signal.aborted)
213
223
  return;
214
- }
215
- if (relay.provider === "lan") {
216
- if (relay.failures.length > 0)
217
- console.error(` Continuing with local network access: ${relay.publicUrl}/web`);
218
- else
219
- console.log(`✓ Local network: ${relay.publicUrl}/web`);
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
+ if (relay.mode !== "public") {
225
+ console.log(`✓ Local network: ${relay.accessUrl}`);
226
+ console.log(relay.mode === "local" ? "Local access only. Connect to Wi-Fi or Ethernet to enable phone access." : "Connect your phone to the same LAN to use this address or QR code.");
221
227
  }
222
228
  else {
223
- console.log(`✓ ${providerDisplayName(relay.provider)} tunnel ready: ${relay.publicUrl}`);
229
+ console.log(`✓ ${providerDisplayName(relay.provider)} tunnel ready: ${new URL(relay.accessUrl).origin}`);
224
230
  }
225
231
  if (relay.provider === "pinggy") {
226
232
  console.log(" Pinggy free tunnels expire after 60 minutes and use a new hostname each session.");
227
233
  console.log(" The phone browser may show a one-time Pinggy security confirmation before pairing.");
228
234
  }
229
- const accessUrl = `${relay.publicUrl}/web`;
230
- await serviceReporter?.ready({
231
- localUrl: runtime.localUrl,
232
- publicUrl: relay.publicUrl,
233
- accessUrl,
234
- provider: relay.provider,
235
- });
235
+ const accessUrl = relay.accessUrl;
236
236
  await releaseStartup();
237
237
  if (serviceReporter) {
238
238
  console.log("✓ Background service URL written to the private state file.");
@@ -246,7 +246,6 @@ async function executeCommand(options, argv) {
246
246
  }
247
247
  await Promise.race([
248
248
  runtime.exited,
249
- relay.tunnel?.exited ?? new Promise(() => { }),
250
249
  sleepInhibitor.lost.then(async (error) => {
251
250
  await new Promise((resolveTurn) => setImmediate(resolveTurn));
252
251
  if (!closing)
@@ -258,6 +257,11 @@ async function executeCommand(options, argv) {
258
257
  process.removeListener("SIGINT", requestClose);
259
258
  process.removeListener("SIGTERM", requestClose);
260
259
  await close();
260
+ if (!serviceReporter && tunnel) {
261
+ const urlPath = resolveServicePaths(undefined, options.dataDir).urlPath;
262
+ if (await readFile(urlPath, "utf8").then(value => value.trim() === tunnel.status().accessUrl, () => false))
263
+ await rm(urlPath, { force: true });
264
+ }
261
265
  await releaseStartup?.();
262
266
  if (reportedStarting)
263
267
  await serviceReporter?.stopped().catch(() => { });
@@ -51,6 +51,7 @@ export class RuntimeManager {
51
51
  await repairNativeRuntimePermissions(runtimeRoot);
52
52
  const gateway = resolve(runtimeRoot, "ws-server.mjs");
53
53
  const child = this.supervisor.spawn(process.execPath, [gateway, ...(options.testNoPairing ? ["--test-no-pairing"] : [])], {
54
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
54
55
  cwd: runtimeRoot,
55
56
  env: {
56
57
  ...childEnvironment,
@@ -13,6 +13,7 @@ export async function selectRelay(options) {
13
13
  const failures = [];
14
14
  const readiness = options.readiness ?? waitForPublicReadiness;
15
15
  for (const providerName of providers) {
16
+ options.onStage?.("connecting");
16
17
  options.onAttempt?.(providerName);
17
18
  const attempt = { tunnel: null };
18
19
  const deadline = new AbortController();
@@ -29,6 +30,7 @@ export async function selectRelay(options) {
29
30
  signal.throwIfAborted();
30
31
  }
31
32
  attempt.tunnel = handle;
33
+ options.onStage?.("checking");
32
34
  await readiness(handle.publicUrl, { signal });
33
35
  signal.throwIfAborted();
34
36
  return { tunnel: handle, publicUrl: handle.publicUrl, provider: providerName, failures };
@@ -0,0 +1,144 @@
1
+ import { selectRelay } from "./relay-orchestrator.js";
2
+ /** Owns only the public route. Server, agents and terminals have a separate lifetime. */
3
+ export class TunnelController {
4
+ options;
5
+ abort = new AbortController();
6
+ selection = null;
7
+ pending = null;
8
+ stopped = false;
9
+ observers = new Set();
10
+ state;
11
+ writes = Promise.resolve();
12
+ constructor(options) {
13
+ this.options = options;
14
+ this.state = { phase: "idle", mode: "local", provider: "lan", accessUrl: `${options.relay.localUrl}/web` };
15
+ if (options.relay.cli.testNoPairing)
16
+ this.state = { ...this.state, phase: "unsupported", error: "测试模式不支持公网连接,请以正常配对模式启动服务。" };
17
+ }
18
+ status() { return { ...this.state }; }
19
+ subscribe(listener) {
20
+ this.observers.add(listener);
21
+ listener(this.status());
22
+ return () => this.observers.delete(listener);
23
+ }
24
+ connect(forcePublic = true) {
25
+ if (this.pending)
26
+ return this.pending;
27
+ if (this.stopped || this.state.phase === "ready" || this.state.phase === "unsupported")
28
+ return Promise.resolve(this.status());
29
+ this.set({ ...this.state, phase: "connecting", stage: "connecting", error: undefined });
30
+ this.pending = this.attempt(forcePublic).finally(() => { this.pending = null; });
31
+ return this.pending;
32
+ }
33
+ async attempt(forcePublic) {
34
+ let lanUrl = this.options.relay.localUrl;
35
+ try {
36
+ lanUrl = await this.options.lanUrl();
37
+ if (this.stopped)
38
+ return this.status();
39
+ this.set({ ...this.fallback(lanUrl), phase: "connecting", stage: "connecting" });
40
+ await this.persist();
41
+ const result = await (this.options.select ?? selectRelay)({
42
+ ...this.options.relay, lanUrl, signal: this.abort.signal,
43
+ cli: { ...this.options.relay.cli, localOnly: forcePublic ? false : this.options.relay.cli.localOnly },
44
+ onStage: stage => this.set({ ...this.state, stage }),
45
+ });
46
+ if (this.stopped) {
47
+ await result.tunnel?.close();
48
+ return this.status();
49
+ }
50
+ this.selection = result;
51
+ const error = result.failures.length ? this.failureMessage() : undefined;
52
+ if (!result.tunnel)
53
+ lanUrl = await this.currentLocalUrl();
54
+ if (this.stopped)
55
+ return this.status();
56
+ await this.commit(result.tunnel
57
+ ? { phase: "ready", mode: "public", provider: result.provider, accessUrl: `${result.publicUrl}/web` }
58
+ : { ...this.fallback(lanUrl), phase: error ? "error" : "idle", error });
59
+ if (result.tunnel)
60
+ void result.tunnel.exited.then(() => this.disconnected(result)).catch(error => this.report(error));
61
+ }
62
+ catch (error) {
63
+ if (!this.stopped) {
64
+ this.report(error);
65
+ const current = this.selection;
66
+ this.selection = null;
67
+ await current?.tunnel?.close().catch(error => this.report(error));
68
+ lanUrl = await this.currentLocalUrl();
69
+ if (this.stopped)
70
+ return this.status();
71
+ this.set({ ...this.fallback(lanUrl), phase: "error", error: "公网连接未完成,请检查电脑网络或代理后重试。" });
72
+ await this.persist();
73
+ }
74
+ }
75
+ return this.status();
76
+ }
77
+ failureMessage() {
78
+ return this.state.stage === "checking"
79
+ ? "公网地址可达性检查未通过,请检查电脑网络或代理后重试。"
80
+ : "公网隧道连接失败或超时,请检查电脑网络后重试。";
81
+ }
82
+ fallback(url) {
83
+ return { phase: "idle", mode: url === this.options.relay.localUrl ? "local" : "lan", provider: "lan", accessUrl: `${url}/web` };
84
+ }
85
+ currentLocalUrl() {
86
+ return this.options.lanUrl().catch(() => this.options.relay.localUrl);
87
+ }
88
+ async disconnected(selection) {
89
+ if (this.stopped || this.selection !== selection)
90
+ return;
91
+ this.selection = null;
92
+ const url = await this.currentLocalUrl();
93
+ if (this.stopped)
94
+ return;
95
+ await this.commit({ ...this.fallback(url), phase: "error", error: "公网连接已断开,请重试连接。" });
96
+ }
97
+ set(status) {
98
+ this.state = status;
99
+ for (const observer of this.observers)
100
+ observer(this.status());
101
+ }
102
+ persist() {
103
+ const status = this.status();
104
+ const write = this.writes.then(() => this.options.publish(status));
105
+ this.writes = write.catch(error => this.report(error));
106
+ return write;
107
+ }
108
+ async commit(status) {
109
+ const previous = this.state;
110
+ this.state = status;
111
+ try {
112
+ await this.persist();
113
+ }
114
+ catch (error) {
115
+ this.state = previous;
116
+ throw error;
117
+ }
118
+ if (!this.stopped)
119
+ for (const observer of this.observers)
120
+ observer(this.status());
121
+ }
122
+ report(error) { this.options.onError?.(error); }
123
+ async close() {
124
+ this.stopped = true;
125
+ this.abort.abort();
126
+ await this.pending;
127
+ await this.selection?.tunnel?.close().catch(error => this.report(error));
128
+ this.selection = null;
129
+ await this.writes;
130
+ this.observers.clear();
131
+ }
132
+ }
133
+ export function attachTunnelControl(child, controller) {
134
+ const unsubscribe = controller.subscribe(status => {
135
+ if (child.connected)
136
+ child.send({ type: "agentroam:tunnel-status", status }, () => { });
137
+ });
138
+ const receive = (message) => {
139
+ if (message?.type === "agentroam:tunnel-connect")
140
+ void controller.connect().catch(() => { });
141
+ };
142
+ child.on("message", receive);
143
+ return () => { unsubscribe(); child.removeListener("message", receive); };
144
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentroam",
3
- "version": "0.2.0-preview.70",
3
+ "version": "0.2.0-preview.72",
4
4
  "description": "Zero-install mobile remote terminal and file console",
5
5
  "type": "module",
6
6
  "bin": {
@@ -27,12 +27,12 @@
27
27
  "ws": "^8.21.3"
28
28
  },
29
29
  "optionalDependencies": {
30
- "agentroam-runtime-darwin-arm64": "0.2.0-preview.70",
31
- "agentroam-runtime-win32-x64": "0.2.0-preview.70",
32
- "agentroam-cloudflared-darwin-arm64": "0.2.0-preview.58",
33
- "agentroam-cloudflared-win32-x64": "0.2.0-preview.58",
34
- "agentroam-tui-darwin-arm64": "0.2.0-preview.70",
35
- "@caoqu/agentroam-tui-win32-x64": "0.2.0-preview.70"
30
+ "agentroam-runtime-darwin-arm64": "0.2.0-preview.72",
31
+ "agentroam-runtime-win32-x64": "0.2.0-preview.72",
32
+ "agentroam-cloudflared-darwin-arm64": "0.2.0-preview.72",
33
+ "agentroam-cloudflared-win32-x64": "0.2.0-preview.72",
34
+ "agentroam-tui-darwin-arm64": "0.2.0-preview.72",
35
+ "@caoqu/agentroam-tui-win32-x64": "0.2.0-preview.72"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/node": "^22.0.0",