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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +61 -15
  2. package/bin/agentroam.mjs +10 -1
  3. package/bin/cli-progress.d.mts +9 -0
  4. package/bin/cli-progress.mjs +65 -0
  5. package/bin/desktop-download.mjs +69 -0
  6. package/bin/node-preflight.mjs +171 -0
  7. package/bin/node-runtime-policy.json +4 -0
  8. package/bin/runtime-policy.d.mts +5 -0
  9. package/bin/runtime-policy.mjs +37 -0
  10. package/dist/abort.js +25 -0
  11. package/dist/args.js +136 -5
  12. package/dist/cli.js +295 -44
  13. package/dist/cloudflared/bundled-asset.js +3 -2
  14. package/dist/cloudflared/manifest.js +2 -2
  15. package/dist/codex-desktop-command.js +70 -0
  16. package/dist/codex-desktop-force-stop.js +46 -0
  17. package/dist/codex-desktop-idle-guard.js +15 -0
  18. package/dist/codex-desktop-preflight.js +63 -0
  19. package/dist/codex-desktop-probe.js +152 -0
  20. package/dist/codex-desktop-setup.js +154 -0
  21. package/dist/codex-desktop-status.js +85 -0
  22. package/dist/codex-desktop-windows.js +122 -0
  23. package/dist/codex-runtime-manager.js +368 -0
  24. package/dist/codex-sharing.js +155 -0
  25. package/dist/codex-windows-backend-host.js +59 -0
  26. package/dist/codex-windows-backend.js +120 -0
  27. package/dist/desktop-authorization-prompt.js +84 -0
  28. package/dist/desktop-authorization.js +161 -0
  29. package/dist/device-pairing.js +228 -0
  30. package/dist/error-log.js +113 -0
  31. package/dist/instance-takeover.js +143 -0
  32. package/dist/local-desktop-url.js +8 -0
  33. package/dist/local-service-request.js +69 -0
  34. package/dist/mesh/mesh-command.js +51 -0
  35. package/dist/mesh/mesh-config.js +95 -0
  36. package/dist/mesh/mesh-payload.js +20 -0
  37. package/dist/mesh/mesh-runtime.js +101 -0
  38. package/dist/native-runtime.js +68 -0
  39. package/dist/network.js +46 -3
  40. package/dist/node-runtime-manager.js +251 -0
  41. package/dist/opencode-runtime-manager.js +260 -0
  42. package/dist/platform-packages.js +18 -5
  43. package/dist/platform.js +6 -4
  44. package/dist/power/sleep-inhibitor.js +161 -0
  45. package/dist/runtime-manager.js +139 -19
  46. package/dist/self-hosted-relay.json +1 -0
  47. package/dist/service/launcher-cleanup.js +79 -0
  48. package/dist/service/macos-launch-agent.js +288 -0
  49. package/dist/service/runtime-state.js +43 -0
  50. package/dist/service/service-command.js +226 -0
  51. package/dist/service/service-controller.js +29 -0
  52. package/dist/service/service-files.js +78 -0
  53. package/dist/service/windows-service-host.js +59 -0
  54. package/dist/service/windows-task-service.js +289 -0
  55. package/dist/startup-lock.js +81 -0
  56. package/dist/tailscale/bundled-asset.js +43 -0
  57. package/dist/tailscale/daemon-manager.js +112 -0
  58. package/dist/tailscale/installer.js +131 -0
  59. package/dist/tailscale/manifest.js +15 -0
  60. package/dist/tailscale/tailnet-cli.js +101 -0
  61. package/dist/todo-mcp-command.js +27 -0
  62. package/dist/tunnel/cloudflare-provider.js +4 -1
  63. package/dist/tunnel/public-readiness.js +76 -50
  64. package/dist/tunnel/relay-orchestrator.js +53 -19
  65. package/dist/tunnel/self-hosted-provider.js +147 -0
  66. package/dist/tunnel/tunnel-controller.js +232 -0
  67. package/dist/unlock-service.js +105 -0
  68. package/dist/update/update-channel.js +38 -0
  69. package/dist/update/update-command.js +97 -0
  70. package/dist/update/update-install.js +34 -0
  71. package/dist/update/update-state.js +43 -0
  72. package/dist/update/update-worker.js +82 -0
  73. package/install/README.md +55 -0
  74. package/install/codex-shared-watchdog.sh +16 -0
  75. package/install/install-agentroam.ps1 +358 -0
  76. package/install/install-agentroam.sh +457 -0
  77. package/install/install-manifest.json +15 -0
  78. package/install/start-codex-desktop-shared.sh +152 -0
  79. package/install/write-relay-default.mjs +6 -0
  80. package/package.json +15 -10
  81. package/dist/args.test.js +0 -27
  82. package/dist/cloudflared/bundled-asset.test.js +0 -76
  83. package/dist/cloudflared/installer.test.js +0 -95
  84. package/dist/native-runtime.test.js +0 -19
  85. package/dist/network.test.js +0 -20
  86. package/dist/pairing.js +0 -2
  87. package/dist/platform-packages.test.js +0 -75
  88. package/dist/platform.test.js +0 -3
  89. package/dist/port.test.js +0 -3
  90. package/dist/process-supervisor.test.js +0 -42
  91. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  92. package/dist/tunnel/pinggy-provider.test.js +0 -40
  93. package/dist/tunnel/proxy-settings.test.js +0 -111
  94. package/dist/tunnel/public-readiness.test.js +0 -104
  95. package/dist/tunnel/relay-orchestrator.test.js +0 -72
@@ -0,0 +1,147 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { link, readFile, unlink } from "node:fs/promises";
4
+ import { connect } from "node:net";
5
+ import { join } from "node:path";
6
+ import { WebSocket, createWebSocketStream } from "ws";
7
+ import { writePrivateText } from "../service/service-files.js";
8
+ const tokenPattern = /^[A-Za-z0-9_-]{43}$/;
9
+ export function relayOrigin(value) {
10
+ const url = new URL(value);
11
+ if (url.protocol !== "https:" || url.port || url.username || url.password || url.pathname !== "/" ||
12
+ url.search || url.hash || !/^(?:[a-z0-9-]+\.)+[a-z][a-z0-9-]*$/.test(url.hostname)) {
13
+ throw new Error("自建 HTTPS 入口需要一个 HTTPS 域名");
14
+ }
15
+ return url;
16
+ }
17
+ export function readDefaultRelayUrl() {
18
+ const configured = process.env.AGENTROAM_HTTPS_RELAY_URL?.trim();
19
+ if (configured)
20
+ return configured;
21
+ const path = new URL("../self-hosted-relay.json", import.meta.url);
22
+ try {
23
+ const url = JSON.parse(readFileSync(path, "utf8")).url;
24
+ return typeof url === "string" ? url : null;
25
+ }
26
+ catch (error) {
27
+ if (error.code !== "ENOENT")
28
+ throw error;
29
+ return null;
30
+ }
31
+ }
32
+ async function installationToken(dataDir) {
33
+ const path = join(dataDir, "relay", "identity");
34
+ const existing = await readToken(path);
35
+ if (existing)
36
+ return existing;
37
+ const temporary = `${path}.${randomBytes(8).toString("hex")}.pending`;
38
+ await writePrivateText(temporary, randomBytes(32).toString("base64url"));
39
+ try {
40
+ await link(temporary, path);
41
+ }
42
+ catch (error) {
43
+ if (error.code !== "EEXIST")
44
+ throw error;
45
+ }
46
+ finally {
47
+ await unlink(temporary);
48
+ }
49
+ const token = await readToken(path);
50
+ if (!token)
51
+ throw new Error("自建 HTTPS 入口的本机身份未能保存");
52
+ return token;
53
+ }
54
+ async function readToken(path) {
55
+ const token = await readFile(path, "utf8").catch((error) => {
56
+ if (error.code === "ENOENT")
57
+ return null;
58
+ throw error;
59
+ });
60
+ if (token !== null && !tokenPattern.test(token))
61
+ throw new Error("自建 HTTPS 入口的本机身份文件无效");
62
+ return token;
63
+ }
64
+ export class SelfHostedTunnelProvider {
65
+ url;
66
+ dataDir;
67
+ dial;
68
+ constructor(url, dataDir, dial = (url, options) => new WebSocket(url, options)) {
69
+ this.url = url;
70
+ this.dataDir = dataDir;
71
+ this.dial = dial;
72
+ }
73
+ async start({ localUrl, signal }) {
74
+ const root = relayOrigin(this.url);
75
+ const token = await installationToken(this.dataDir);
76
+ const local = new URL(localUrl);
77
+ if (local.protocol !== "http:" || local.hostname !== "127.0.0.1" || !local.port) {
78
+ throw new Error("自建 HTTPS 入口只能转发本机 AgentRoam 服务");
79
+ }
80
+ const name = createHash("sha256").update(token).digest("hex").slice(0, 32);
81
+ const publicUrl = `https://d-${name}.${root.host}`;
82
+ const options = { headers: { authorization: `Bearer ${token}` }, handshakeTimeout: 8_000, maxPayload: 1024 * 1024, perMessageDeflate: false };
83
+ const websocket = (path) => this.dial(new URL(`wss://${root.host}${path}`), options);
84
+ signal.throwIfAborted();
85
+ const control = websocket("/v1/connect");
86
+ const streams = new Set();
87
+ const close = () => {
88
+ control.terminate();
89
+ for (const socket of streams)
90
+ socket.terminate();
91
+ };
92
+ const exited = new Promise((resolve) => {
93
+ control.once("close", code => {
94
+ signal.removeEventListener("abort", close);
95
+ for (const socket of streams)
96
+ socket.terminate();
97
+ resolve({ code, signal: null });
98
+ });
99
+ });
100
+ signal.addEventListener("abort", close, { once: true });
101
+ try {
102
+ await new Promise((resolve, reject) => {
103
+ let ready = false;
104
+ control.on("error", reject);
105
+ void exited.then(() => reject(new Error("自建 HTTPS 入口连接已断开")));
106
+ control.on("message", chunk => {
107
+ try {
108
+ const message = JSON.parse(String(chunk));
109
+ if (!ready && message?.type === "ready" && message.publicUrl === publicUrl) {
110
+ ready = true;
111
+ resolve();
112
+ }
113
+ else if (ready && message?.type === "stream" && /^[a-f0-9]{32}$/.test(message.id) && streams.size < 64) {
114
+ const socket = websocket(`/v1/streams/${message.id}`);
115
+ streams.add(socket);
116
+ socket.once("close", () => streams.delete(socket));
117
+ connectToLoopback(socket, Number(local.port));
118
+ }
119
+ else {
120
+ close();
121
+ }
122
+ }
123
+ catch (error) {
124
+ reject(error);
125
+ close();
126
+ }
127
+ });
128
+ });
129
+ signal.throwIfAborted();
130
+ return { publicUrl, exited, close: async () => { close(); await exited; } };
131
+ }
132
+ catch (error) {
133
+ close();
134
+ throw error;
135
+ }
136
+ }
137
+ }
138
+ function connectToLoopback(socket, port) {
139
+ const stream = createWebSocketStream(socket);
140
+ // The remote can send immediately after the WebSocket handshake. Buffer on
141
+ // the stream until the local service accepts the socket.
142
+ const local = connect({ host: "127.0.0.1", port });
143
+ stream.on("error", () => local.destroy());
144
+ local.on("error", () => stream.destroy());
145
+ stream.once("close", () => local.destroy());
146
+ local.once("connect", () => stream.pipe(local).pipe(stream));
147
+ }
@@ -0,0 +1,232 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { pairingNetworkRoutes } from "../network.js";
3
+ import { waitForPublicReadiness } from "./public-readiness.js";
4
+ import { resolveRelayProvider, selectRelay } from "./relay-orchestrator.js";
5
+ import { readDefaultRelayUrl } from "./self-hosted-provider.js";
6
+ /** Owns only the public route. Server, agents and terminals have a separate lifetime. */
7
+ export class TunnelController {
8
+ options;
9
+ abort = new AbortController();
10
+ selection = null;
11
+ pairingRelays = new Map();
12
+ pending = null;
13
+ stopped = false;
14
+ observers = new Set();
15
+ state;
16
+ writes = Promise.resolve();
17
+ constructor(options) {
18
+ this.options = options;
19
+ this.state = { phase: "idle", mode: "local", provider: "lan", accessUrl: `${options.relay.localUrl}/web` };
20
+ if (options.relay.cli.testNoPairing)
21
+ this.state = { ...this.state, phase: "unsupported", error: "测试模式不支持公网连接,请以正常配对模式启动服务。" };
22
+ }
23
+ status() { return { ...this.state }; }
24
+ pairingRoutes() {
25
+ if (this.stopped || this.state.phase === "unsupported")
26
+ return [];
27
+ const choices = [];
28
+ if (this.options.relay.cli.relayUrl || readDefaultRelayUrl())
29
+ choices.push({ id: "self-hosted", kind: "self-hosted" });
30
+ choices.push({ id: "cloudflare", kind: "cloudflare" });
31
+ return choices.concat((this.options.networkRoutes ?? pairingNetworkRoutes)());
32
+ }
33
+ async pairingUrl(via) {
34
+ if (this.stopped || this.state.phase === "unsupported")
35
+ throw new Error("当前后台不支持切换配对线路。");
36
+ if (via === "self-hosted" || via === "cloudflare")
37
+ return this.publicPairingUrl(via);
38
+ const choices = (this.options.networkRoutes ?? pairingNetworkRoutes)();
39
+ const routedAddress = via === "lan" ? new URL(await this.currentLocalUrl()).hostname : undefined;
40
+ const route = via === "lan"
41
+ ? choices.find(choice => choice.kind === "lan" && choice.address === routedAddress) ?? choices.find(choice => choice.kind === "lan")
42
+ : choices.find(choice => choice.id === via || (via === "tailscale" && choice.kind === "tailscale"));
43
+ if (!route?.address)
44
+ throw new Error("所选网络地址当前不可用,请刷新连接选项。");
45
+ const origin = `http://${route.address}:${this.options.relay.port}`;
46
+ try {
47
+ await (this.options.checkNetworkRoute ?? waitForPublicReadiness)(origin, {
48
+ timeoutMs: 3000, proxyResolver: async () => null, signal: this.abort.signal,
49
+ fetchImpl: (url, init) => fetch(url, { ...init, redirect: "error" }),
50
+ });
51
+ }
52
+ catch {
53
+ throw new Error("无法通过所选 IP 访问本机服务,请检查网络和防火墙。");
54
+ }
55
+ return `${origin}/web`;
56
+ }
57
+ async publicPairingUrl(via) {
58
+ if (via === "self-hosted" && !this.options.relay.cli.relayUrl && !readDefaultRelayUrl())
59
+ throw new Error("自建 HTTPS 入口地址未配置。");
60
+ if (resolveRelayProvider(this.options.relay.cli) === via) {
61
+ const status = await this.connect();
62
+ if (status.provider === via && status.phase === "ready" && status.accessUrl)
63
+ return status.accessUrl;
64
+ throw new Error(status.error || "所选公网线路未连接,请重试。");
65
+ }
66
+ let pending = this.pairingRelays.get(via);
67
+ if (!pending) {
68
+ const start = (this.options.select ?? selectRelay)({
69
+ ...this.options.relay, signal: this.abort.signal, lanUrl: this.options.relay.localUrl,
70
+ cli: { ...this.options.relay.cli, relay: via, localOnly: false }, onAttempt: undefined, onFailure: undefined,
71
+ });
72
+ const clear = () => { if (this.pairingRelays.get(via) === pending)
73
+ this.pairingRelays.delete(via); };
74
+ pending = start.then(result => {
75
+ if (!result.tunnel)
76
+ throw new Error(`${via === "cloudflare" ? "Cloudflare" : "自建 HTTPS"} 未连接,请检查电脑网络后重试。`);
77
+ void result.tunnel.exited.then(clear, clear);
78
+ return result;
79
+ }).catch(error => { clear(); throw error; });
80
+ this.pairingRelays.set(via, pending);
81
+ }
82
+ return `${(await pending).publicUrl}/web`;
83
+ }
84
+ subscribe(listener) {
85
+ this.observers.add(listener);
86
+ listener(this.status());
87
+ return () => this.observers.delete(listener);
88
+ }
89
+ connect(forcePublic = true) {
90
+ if (this.pending)
91
+ return this.pending;
92
+ if (this.stopped || this.state.phase === "ready" || this.state.phase === "unsupported")
93
+ return Promise.resolve(this.status());
94
+ this.set({ ...this.state, phase: "connecting", stage: "connecting", error: undefined });
95
+ this.pending = this.attempt(forcePublic).finally(() => { this.pending = null; });
96
+ return this.pending;
97
+ }
98
+ async attempt(forcePublic) {
99
+ let lanUrl = this.options.relay.localUrl;
100
+ try {
101
+ lanUrl = await this.options.lanUrl();
102
+ if (this.stopped)
103
+ return this.status();
104
+ this.set({ ...this.fallback(lanUrl), phase: "connecting", stage: "connecting" });
105
+ await this.persist();
106
+ const result = await (this.options.select ?? selectRelay)({
107
+ ...this.options.relay, lanUrl, signal: this.abort.signal,
108
+ cli: { ...this.options.relay.cli, localOnly: forcePublic ? false : this.options.relay.cli.localOnly },
109
+ onStage: stage => this.set({ ...this.state, stage }),
110
+ });
111
+ if (this.stopped) {
112
+ await result.tunnel?.close();
113
+ return this.status();
114
+ }
115
+ this.selection = result;
116
+ const error = result.failures.length ? this.failureMessage() : undefined;
117
+ if (!result.tunnel)
118
+ lanUrl = await this.currentLocalUrl();
119
+ if (this.stopped)
120
+ return this.status();
121
+ await this.commit(result.tunnel
122
+ ? { phase: "ready", mode: "public", provider: result.provider, accessUrl: `${result.publicUrl}/web` }
123
+ : { ...this.fallback(lanUrl), phase: error ? "error" : "idle", error });
124
+ if (result.tunnel)
125
+ void result.tunnel.exited.then(() => this.disconnected(result)).catch(error => this.report(error));
126
+ }
127
+ catch (error) {
128
+ if (!this.stopped) {
129
+ this.report(error);
130
+ const current = this.selection;
131
+ this.selection = null;
132
+ await current?.tunnel?.close().catch(error => this.report(error));
133
+ lanUrl = await this.currentLocalUrl();
134
+ if (this.stopped)
135
+ return this.status();
136
+ this.set({ ...this.fallback(lanUrl), phase: "error", error: "公网连接未完成,请检查电脑网络或代理后重试。" });
137
+ await this.persist();
138
+ }
139
+ }
140
+ return this.status();
141
+ }
142
+ failureMessage() {
143
+ return this.state.stage === "checking"
144
+ ? "公网地址可达性检查未通过,请检查电脑网络或代理后重试。"
145
+ : "公网隧道连接失败或超时,请检查电脑网络后重试。";
146
+ }
147
+ fallback(url) {
148
+ return { phase: "idle", mode: url === this.options.relay.localUrl ? "local" : "lan", provider: "lan", accessUrl: `${url}/web` };
149
+ }
150
+ currentLocalUrl() {
151
+ return this.options.lanUrl().catch(() => this.options.relay.localUrl);
152
+ }
153
+ async disconnected(selection) {
154
+ if (this.stopped || this.selection !== selection)
155
+ return;
156
+ this.selection = null;
157
+ const url = await this.currentLocalUrl();
158
+ if (this.stopped)
159
+ return;
160
+ await this.commit({ ...this.fallback(url), phase: "error", error: "公网连接已断开,请重试连接。" });
161
+ if (selection.provider !== "self-hosted")
162
+ return;
163
+ for (const wait of [1000, 2000, 5000]) {
164
+ await delay(wait, undefined, { signal: this.abort.signal }).catch(() => { });
165
+ if (this.stopped || this.state.phase === "ready")
166
+ return;
167
+ if ((await this.connect()).phase === "ready")
168
+ return;
169
+ }
170
+ }
171
+ set(status) {
172
+ this.state = status;
173
+ for (const observer of this.observers)
174
+ observer(this.status());
175
+ }
176
+ persist() {
177
+ const status = this.status();
178
+ const write = this.writes.then(() => this.options.publish(status));
179
+ this.writes = write.catch(error => this.report(error));
180
+ return write;
181
+ }
182
+ async commit(status) {
183
+ const previous = this.state;
184
+ this.state = status;
185
+ try {
186
+ await this.persist();
187
+ }
188
+ catch (error) {
189
+ this.state = previous;
190
+ throw error;
191
+ }
192
+ if (!this.stopped)
193
+ for (const observer of this.observers)
194
+ observer(this.status());
195
+ }
196
+ report(error) { this.options.onError?.(error); }
197
+ async close() {
198
+ this.stopped = true;
199
+ this.abort.abort();
200
+ await this.pending;
201
+ await this.selection?.tunnel?.close().catch(error => this.report(error));
202
+ this.selection = null;
203
+ await Promise.allSettled([...this.pairingRelays.values()].map(async (relay) => (await relay).tunnel?.close()));
204
+ this.pairingRelays.clear();
205
+ await this.writes;
206
+ this.observers.clear();
207
+ }
208
+ }
209
+ export function attachTunnelControl(child, controller) {
210
+ const unsubscribe = controller.subscribe(status => {
211
+ if (child.connected)
212
+ child.send({ type: "agentroam:tunnel-status", status }, () => { });
213
+ });
214
+ const receive = (message) => {
215
+ if (message?.type === "agentroam:tunnel-connect")
216
+ void controller.connect().catch(() => { });
217
+ const request = message;
218
+ if (request?.type !== "agentroam:pairing-route" || typeof request.id !== "string")
219
+ return;
220
+ const id = request.id;
221
+ const reply = (result, error) => {
222
+ if (child.connected)
223
+ child.send({ type: "agentroam:pairing-route-result", id, result, error }, () => { });
224
+ };
225
+ const work = request.route === undefined
226
+ ? Promise.resolve().then(() => ({ routes: controller.pairingRoutes() }))
227
+ : controller.pairingUrl(request.route).then(accessUrl => ({ accessUrl }));
228
+ void work.then(result => reply(result), error => reply(undefined, error instanceof Error ? error.message : "无法准备所选线路。"));
229
+ };
230
+ child.on("message", receive);
231
+ return () => { unsubscribe(); child.removeListener("message", receive); };
232
+ }
@@ -0,0 +1,105 @@
1
+ import { execFile } from "node:child_process";
2
+ import { resolve } from "node:path";
3
+ const SERVICE_NAME = "AgentRoamUnlock";
4
+ const DISPLAY_NAME = "AgentRoam Remote Unlock";
5
+ // Keep the event loop free while PowerShell waits for UAC or service control.
6
+ const runFile = (file, args, options) => new Promise((resolveResult) => {
7
+ execFile(file, [...args], options, (error, stdout, stderr) => {
8
+ resolveResult({ stdout, stderr, status: error ? 1 : 0,
9
+ ...(error && typeof error.code !== "number" ? { error } : {}),
10
+ });
11
+ });
12
+ });
13
+ function psQuote(value) {
14
+ return `'${value.replaceAll("'", "''")}'`;
15
+ }
16
+ export function encodePowerShell(script) {
17
+ return Buffer.from(script, "utf16le").toString("base64");
18
+ }
19
+ export function unlockServiceExecutable(runtimeRoot) {
20
+ return resolve(runtimeRoot, "native", "agentroam-remote-unlock.exe");
21
+ }
22
+ export function buildUnlockServiceAdminScript(action, executable) {
23
+ const common = `$ErrorActionPreference = 'Stop'\n$serviceName = '${SERVICE_NAME}'`;
24
+ if (action === "uninstall") {
25
+ return `${common}
26
+ $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
27
+ if ($service) {
28
+ if ($service.Status -ne 'Stopped') { Stop-Service -Name $serviceName -Force -ErrorAction Stop }
29
+ & "$env:SystemRoot\\System32\\sc.exe" delete $serviceName | Out-Null
30
+ if ($LASTEXITCODE -ne 0) { throw "sc.exe delete failed: $LASTEXITCODE" }
31
+ }
32
+ `;
33
+ }
34
+ const binaryPath = `\"${executable}\" --service`;
35
+ return `${common}
36
+ $binary = ${psQuote(executable)}
37
+ if (-not (Test-Path -LiteralPath $binary -PathType Leaf)) { throw "Remote unlock helper is missing: $binary" }
38
+ $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
39
+ if ($service) {
40
+ if ($service.Status -ne 'Stopped') { Stop-Service -Name $serviceName -Force -ErrorAction Stop }
41
+ & "$env:SystemRoot\\System32\\sc.exe" delete $serviceName | Out-Null
42
+ if ($LASTEXITCODE -ne 0) { throw "sc.exe delete failed: $LASTEXITCODE" }
43
+ for ($attempt = 0; $attempt -lt 50 -and (Get-Service -Name $serviceName -ErrorAction SilentlyContinue); $attempt++) { Start-Sleep -Milliseconds 100 }
44
+ }
45
+ New-Service -Name $serviceName -BinaryPathName ${psQuote(binaryPath)} -DisplayName '${DISPLAY_NAME}' -StartupType Automatic | Out-Null
46
+ & "$env:SystemRoot\\System32\\sc.exe" description $serviceName "Allows an authorized AgentRoam session to wake and unlock the Windows secure desktop." | Out-Null
47
+ Start-Service -Name $serviceName -ErrorAction Stop
48
+ `;
49
+ }
50
+ export function buildElevatedPowerShell(adminScript) {
51
+ const payload = encodePowerShell(adminScript);
52
+ return `$ErrorActionPreference = 'Stop'
53
+ $powershell = Join-Path $PSHOME 'powershell.exe'
54
+ $process = Start-Process -FilePath $powershell -Verb RunAs -Wait -PassThru -ArgumentList @('-NoLogo','-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','${payload}')
55
+ exit $process.ExitCode
56
+ `;
57
+ }
58
+ export function parseUnlockServiceStatus(output) {
59
+ const value = output.trim().split(/\r?\n/).at(-1)?.trim().toLowerCase();
60
+ if (value === "running" || value === "stopped" || value === "missing")
61
+ return value;
62
+ throw new Error("无法读取远程解锁服务状态");
63
+ }
64
+ function runPowerShell(script, runner) {
65
+ return runner("powershell.exe", [
66
+ "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
67
+ "-EncodedCommand", encodePowerShell(script),
68
+ ], { encoding: "utf8", windowsHide: true });
69
+ }
70
+ export async function queryUnlockServiceStatus(runner = runFile) {
71
+ const script = `$service = Get-Service -Name '${SERVICE_NAME}' -ErrorAction SilentlyContinue
72
+ if (-not $service) { Write-Output 'missing' } elseif ($service.Status -eq 'Running') { Write-Output 'running' } else { Write-Output 'stopped' }
73
+ `;
74
+ const result = await runPowerShell(script, runner);
75
+ if (result.error)
76
+ throw result.error;
77
+ if (result.status !== 0)
78
+ throw new Error((result.stderr || "远程解锁服务状态查询失败").trim());
79
+ return parseUnlockServiceStatus(result.stdout || "");
80
+ }
81
+ export async function runUnlockServiceCommand(action, runtimeRoot, options = {}) {
82
+ const platform = options.platform ?? process.platform;
83
+ const runner = options.runner ?? runFile;
84
+ const log = options.log ?? console.log;
85
+ if (platform !== "win32")
86
+ throw new Error("远程解锁服务仅支持 Windows 10/11 x64");
87
+ if (action === "status") {
88
+ const status = await queryUnlockServiceStatus(runner);
89
+ log(status === "running" ? "远程解锁服务正在运行" : status === "stopped" ? "远程解锁服务已安装但未运行" : "远程解锁服务未安装");
90
+ return;
91
+ }
92
+ const executable = unlockServiceExecutable(runtimeRoot);
93
+ const result = await runPowerShell(buildElevatedPowerShell(buildUnlockServiceAdminScript(action, executable)), runner);
94
+ if (result.error)
95
+ throw result.error;
96
+ if (result.status !== 0) {
97
+ throw new Error((result.stderr || (action === "install" ? "远程解锁服务安装失败或已取消管理员授权" : "远程解锁服务卸载失败或已取消管理员授权")).trim());
98
+ }
99
+ const status = await queryUnlockServiceStatus(runner);
100
+ if (action === "install" && status !== "running")
101
+ throw new Error("远程解锁服务安装后未能启动");
102
+ if (action === "uninstall" && status !== "missing")
103
+ throw new Error("远程解锁服务卸载后仍然存在");
104
+ log(action === "install" ? "远程解锁服务已安装并启动" : "远程解锁服务已卸载");
105
+ }
@@ -0,0 +1,38 @@
1
+ const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-preview\.(0|[1-9]\d*))?$/;
2
+ export function parseAgentRoamVersion(value) {
3
+ const match = VERSION.exec(value);
4
+ if (!match)
5
+ return null;
6
+ return {
7
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
8
+ preview: match[4] === undefined ? null : Number(match[4]),
9
+ };
10
+ }
11
+ // A prerelease installation follows the preview channel; a stable installation
12
+ // follows latest. Preview users are also offered a newer stable release so they
13
+ // can migrate to the stable track without reinstalling.
14
+ export function resolveUpdateChannel(currentVersion) {
15
+ const parsed = parseAgentRoamVersion(currentVersion);
16
+ if (!parsed)
17
+ throw new Error("invalid AgentRoam version");
18
+ return parsed.preview === null ? "latest" : "preview";
19
+ }
20
+ export function resolveReleaseChannel(version) {
21
+ const parsed = parseAgentRoamVersion(version);
22
+ if (!parsed)
23
+ throw new Error("invalid AgentRoam version");
24
+ return parsed.preview === null ? "latest" : "preview";
25
+ }
26
+ export function registryUrlsForChannel(channel, registryBase) {
27
+ return channel === "preview" ? [`${registryBase}/latest`, `${registryBase}/preview`] : [`${registryBase}/latest`];
28
+ }
29
+ export function parseChannelVersion(value, channel) {
30
+ if (typeof value !== "string")
31
+ return null;
32
+ const parsed = parseAgentRoamVersion(value);
33
+ if (!parsed)
34
+ return null;
35
+ if (parsed.preview === null)
36
+ return value;
37
+ return channel === "preview" ? value : null;
38
+ }
@@ -0,0 +1,97 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { fileURLToPath } from "node:url";
5
+ import { resolve } from "node:path";
6
+ import { updatePaths, writeUpdateState } from "./update-state.js";
7
+ import { parseChannelVersion, registryUrlsForChannel, resolveUpdateChannel, } from "./update-channel.js";
8
+ import { buildCliInstallManifestUrl, validateCliInstallManifest } from "./update-install.js";
9
+ const REGISTRY_BASE = "https://registry.npmjs.org/agentroam";
10
+ export async function resolveUpdate(options, fetchImpl = fetch) {
11
+ const channel = resolveUpdateChannel(options.currentVersion);
12
+ const target = await readRegistryCandidate(fetchImpl, channel);
13
+ if (!target)
14
+ throw new Error("unable to check the npm release channel");
15
+ if (options.requestedVersion && options.requestedVersion !== target)
16
+ throw new Error("requested version is not the current npm candidate");
17
+ if (compare(target, options.currentVersion) <= 0)
18
+ throw new Error("AgentRoam is already up to date");
19
+ const response = await fetchWithTimeout(fetchImpl, buildCliInstallManifestUrl());
20
+ if (!response.ok)
21
+ throw new Error("CLI install manifest is unavailable");
22
+ const asset = validateCliInstallManifest(await response.json(), options.target);
23
+ return { targetVersion: target, fileName: asset.fileName, sha256: asset.sha256 };
24
+ }
25
+ // Preview installations follow the higher of the preview and latest npm
26
+ // dist-tags so a newer stable release can move them onto the stable track.
27
+ async function readRegistryCandidate(fetchImpl, channel) {
28
+ let best = null;
29
+ for (const url of registryUrlsForChannel(channel, REGISTRY_BASE)) {
30
+ const response = await fetchWithTimeout(fetchImpl, url).catch(() => null);
31
+ if (!response?.ok)
32
+ continue;
33
+ const candidate = parseChannelVersion((await response.json()).version, channel);
34
+ if (!candidate)
35
+ continue;
36
+ if (!best || compare(candidate, best) > 0)
37
+ best = candidate;
38
+ }
39
+ return best;
40
+ }
41
+ export async function startUpdate(options) {
42
+ const release = await resolveUpdate(options);
43
+ const paths = updatePaths(options.dataDir);
44
+ const service = await readServiceConfig();
45
+ const state = {
46
+ schemaVersion: 1,
47
+ phase: "downloading",
48
+ currentVersion: options.currentVersion,
49
+ ...release,
50
+ dataDir: resolve(options.dataDir),
51
+ roots: service?.roots?.length ? service.roots : [process.cwd()],
52
+ port: service?.port ?? null,
53
+ relay: service?.relay ?? "auto",
54
+ tunnelCommand: service?.tunnelCommand ?? null,
55
+ ...(service?.relayUrl ? { relayUrl: service.relayUrl } : {}),
56
+ localOnly: service?.localOnly ?? false,
57
+ cliPath: resolve(options.cliPath),
58
+ updatedAt: Date.now(),
59
+ };
60
+ await writeUpdateState(paths.stateFile, state);
61
+ const child = spawn(process.execPath, [options.cliPath, "update-worker", paths.stateFile], { detached: true, stdio: "ignore", windowsHide: true });
62
+ child.unref();
63
+ return state;
64
+ }
65
+ async function readServiceConfig() {
66
+ try {
67
+ return JSON.parse(await readFile(resolve(homedir(), ".agentroam", "service", "config.json"), "utf8"));
68
+ }
69
+ catch { }
70
+ return null;
71
+ }
72
+ async function fetchWithTimeout(fetchImpl, url) {
73
+ const controller = new AbortController();
74
+ const timer = setTimeout(() => controller.abort(), 4_000);
75
+ timer.unref?.();
76
+ try {
77
+ return await fetchImpl(url, { headers: { accept: "application/json" }, signal: controller.signal });
78
+ }
79
+ finally {
80
+ clearTimeout(timer);
81
+ }
82
+ }
83
+ function compare(left, right) {
84
+ const parse = (value) => {
85
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-preview\.(\d+))?$/.exec(value);
86
+ if (!match)
87
+ throw new Error("invalid AgentRoam version");
88
+ return [...match.slice(1, 4).map(Number), match[4] === undefined ? Number.MAX_SAFE_INTEGER : Number(match[4])];
89
+ };
90
+ const a = parse(left);
91
+ const b = parse(right);
92
+ for (let i = 0; i < a.length; i += 1)
93
+ if (a[i] !== b[i])
94
+ return a[i] > b[i] ? 1 : -1;
95
+ return 0;
96
+ }
97
+ export const currentCliPath = () => fileURLToPath(new URL("../../bin/agentroam.mjs", import.meta.url));
@@ -0,0 +1,34 @@
1
+ const REPOSITORY_BASE = "https://github.com/tclxqu-cao/team-agent";
2
+ const REPOSITORY_BRANCH = "main";
3
+ const INSTALL_BASE = `${REPOSITORY_BASE}/raw/${REPOSITORY_BRANCH}/packages/cli/install`;
4
+ export const CLI_INSTALL_FILE_NAMES = {
5
+ "darwin-arm64": "install-agentroam.sh",
6
+ "windows-amd64": "install-agentroam.ps1",
7
+ };
8
+ export function buildCliInstallManifestUrl() {
9
+ return `${INSTALL_BASE}/install-manifest.json`;
10
+ }
11
+ export function buildCliInstallScriptUrl(fileName) {
12
+ if (!Object.values(CLI_INSTALL_FILE_NAMES).includes(fileName))
13
+ throw new Error("invalid CLI installer file name");
14
+ return `${INSTALL_BASE}/${fileName}`;
15
+ }
16
+ export function validateCliInstallManifest(value, platform) {
17
+ const expected = CLI_INSTALL_FILE_NAMES[platform];
18
+ if (!expected)
19
+ throw new Error("CLI install manifest does not support this platform");
20
+ if (typeof value !== "object" || value === null)
21
+ throw new Error("invalid CLI install manifest identity");
22
+ const manifest = value;
23
+ if (manifest.schemaVersion !== 1 || typeof manifest.installers !== "object" || manifest.installers === null) {
24
+ throw new Error("invalid CLI install manifest identity");
25
+ }
26
+ const asset = manifest.installers[platform];
27
+ if (!asset || asset.fileName !== expected || typeof asset.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(asset.sha256)) {
28
+ throw new Error("invalid CLI installer metadata");
29
+ }
30
+ if (asset.size !== undefined && (!Number.isSafeInteger(asset.size) || asset.size <= 0)) {
31
+ throw new Error("invalid CLI installer size");
32
+ }
33
+ return { fileName: expected, sha256: asset.sha256, ...(asset.size === undefined ? {} : { size: asset.size }) };
34
+ }