agentroam 0.2.0-preview.7 → 0.2.0-preview.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -15
- package/bin/agentroam.mjs +10 -1
- package/bin/cli-progress.d.mts +9 -0
- package/bin/cli-progress.mjs +65 -0
- package/bin/desktop-download.mjs +69 -0
- package/bin/node-preflight.mjs +171 -0
- package/bin/node-runtime-policy.json +4 -0
- package/bin/runtime-policy.d.mts +5 -0
- package/bin/runtime-policy.mjs +37 -0
- package/dist/abort.js +25 -0
- package/dist/args.js +102 -3
- package/dist/cli.js +244 -44
- package/dist/cloudflared/bundled-asset.js +3 -2
- package/dist/cloudflared/manifest.js +2 -2
- package/dist/codex-desktop-command.js +70 -0
- package/dist/codex-desktop-force-stop.js +46 -0
- package/dist/codex-desktop-idle-guard.js +15 -0
- package/dist/codex-desktop-preflight.js +63 -0
- package/dist/codex-desktop-probe.js +152 -0
- package/dist/codex-desktop-setup.js +154 -0
- package/dist/codex-desktop-status.js +85 -0
- package/dist/codex-desktop-windows.js +122 -0
- package/dist/codex-runtime-manager.js +368 -0
- package/dist/codex-sharing.js +153 -0
- package/dist/codex-windows-backend-host.js +59 -0
- package/dist/codex-windows-backend.js +120 -0
- package/dist/desktop-authorization-prompt.js +84 -0
- package/dist/desktop-authorization.js +161 -0
- package/dist/device-pairing.js +170 -0
- package/dist/error-log.js +113 -0
- package/dist/instance-takeover.js +143 -0
- package/dist/local-desktop-url.js +8 -0
- package/dist/local-service-request.js +69 -0
- package/dist/native-runtime.js +68 -0
- package/dist/network.js +32 -3
- package/dist/node-runtime-manager.js +251 -0
- package/dist/opencode-runtime-manager.js +239 -0
- package/dist/platform-packages.js +16 -5
- package/dist/platform.js +6 -4
- package/dist/power/sleep-inhibitor.js +161 -0
- package/dist/runtime-manager.js +130 -19
- package/dist/service/launcher-cleanup.js +79 -0
- package/dist/service/macos-launch-agent.js +288 -0
- package/dist/service/runtime-state.js +43 -0
- package/dist/service/service-command.js +219 -0
- package/dist/service/service-controller.js +27 -0
- package/dist/service/service-files.js +78 -0
- package/dist/service/windows-service-host.js +59 -0
- package/dist/service/windows-task-service.js +289 -0
- package/dist/startup-lock.js +81 -0
- package/dist/tunnel/cloudflare-provider.js +4 -1
- package/dist/tunnel/public-readiness.js +76 -50
- package/dist/tunnel/relay-orchestrator.js +31 -9
- package/dist/tunnel/tunnel-controller.js +144 -0
- package/dist/unlock-service.js +105 -0
- package/dist/update/update-channel.js +38 -0
- package/dist/update/update-command.js +96 -0
- package/dist/update/update-install.js +34 -0
- package/dist/update/update-state.js +43 -0
- package/dist/update/update-worker.js +80 -0
- package/install/README.md +55 -0
- package/install/codex-shared-watchdog.sh +16 -0
- package/install/install-agentroam.ps1 +358 -0
- package/install/install-agentroam.sh +457 -0
- package/install/install-manifest.json +15 -0
- package/install/start-codex-desktop-shared.sh +152 -0
- package/package.json +13 -10
- package/dist/args.test.js +0 -27
- package/dist/cloudflared/bundled-asset.test.js +0 -76
- package/dist/cloudflared/installer.test.js +0 -95
- package/dist/native-runtime.test.js +0 -19
- package/dist/network.test.js +0 -20
- package/dist/pairing.js +0 -2
- package/dist/platform-packages.test.js +0 -75
- package/dist/platform.test.js +0 -3
- package/dist/port.test.js +0 -3
- package/dist/process-supervisor.test.js +0 -42
- package/dist/tunnel/cloudflare-provider.test.js +0 -33
- package/dist/tunnel/pinggy-provider.test.js +0 -40
- package/dist/tunnel/proxy-settings.test.js +0 -111
- package/dist/tunnel/public-readiness.test.js +0 -104
- package/dist/tunnel/relay-orchestrator.test.js +0 -72
|
@@ -1,63 +1,83 @@
|
|
|
1
1
|
import { fetch as undiciFetch, ProxyAgent } from "undici";
|
|
2
2
|
import { resolveProxyForUrl } from "./proxy-settings.js";
|
|
3
|
+
import { AGENTROAM_VERSION } from "../platform-packages.js";
|
|
4
|
+
import { withAbortSignal } from "../abort.js";
|
|
3
5
|
export async function waitForPublicReadiness(publicUrl, options = {}) {
|
|
4
6
|
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
5
7
|
const intervalMs = options.intervalMs ?? 750;
|
|
6
8
|
const endpoint = new URL("/api/web-auth/status", `${publicUrl.replace(/\/$/, "")}/`);
|
|
7
|
-
|
|
9
|
+
const deadline = Date.now() + timeoutMs;
|
|
10
|
+
const controller = new AbortController();
|
|
11
|
+
let lastFailure = "no response";
|
|
12
|
+
const timer = setTimeout(() => {
|
|
13
|
+
const detail = lastFailure === "no response" ? "request timed out" : `${lastFailure} (request timed out)`;
|
|
14
|
+
controller.abort(new Error(`public tunnel not ready: ${detail}`));
|
|
15
|
+
}, timeoutMs);
|
|
16
|
+
const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
|
|
17
|
+
const connection = { proxy: null };
|
|
8
18
|
let fetchImpl = options.fetchImpl;
|
|
9
|
-
if (!fetchImpl) {
|
|
10
|
-
const proxyResolver = options.proxyResolver ?? resolveProxyForUrl;
|
|
11
|
-
const proxyUrl = await proxyResolver(endpoint).catch(() => null);
|
|
12
|
-
if (proxyUrl)
|
|
13
|
-
proxyFetch = (options.proxyFetchFactory ?? createProxyFetch)(proxyUrl);
|
|
14
|
-
fetchImpl = proxyFetch?.fetch ?? fetch;
|
|
15
|
-
}
|
|
16
19
|
try {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
20
|
+
await withAbortSignal(async () => {
|
|
21
|
+
if (!fetchImpl) {
|
|
22
|
+
const proxyResolver = options.proxyResolver ?? resolveProxyForUrl;
|
|
23
|
+
const proxyUrl = await proxyResolver(endpoint).catch(() => null);
|
|
24
|
+
signal.throwIfAborted();
|
|
25
|
+
if (proxyUrl)
|
|
26
|
+
connection.proxy = (options.proxyFetchFactory ?? createProxyFetch)(proxyUrl);
|
|
27
|
+
fetchImpl = connection.proxy?.fetch ?? fetch;
|
|
28
|
+
}
|
|
29
|
+
while (Date.now() <= deadline) {
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
try {
|
|
32
|
+
const response = await fetchImpl(endpoint, {
|
|
33
|
+
cache: "no-store",
|
|
34
|
+
headers: { "user-agent": `agentroam-readiness/${AGENTROAM_VERSION}` },
|
|
35
|
+
signal,
|
|
36
|
+
});
|
|
37
|
+
if (response.ok) {
|
|
38
|
+
let body;
|
|
39
|
+
try {
|
|
40
|
+
body = (await response.json());
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw new FatalReadinessError("HTTP 200 with invalid auth status JSON");
|
|
44
|
+
}
|
|
45
|
+
signal.throwIfAborted();
|
|
46
|
+
if (typeof body.authenticated === "boolean" && typeof body.needsSetup === "boolean")
|
|
47
|
+
return;
|
|
34
48
|
throw new FatalReadinessError("HTTP 200 with invalid auth status JSON");
|
|
35
49
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
50
|
+
else {
|
|
51
|
+
lastFailure = `HTTP ${response.status}`;
|
|
52
|
+
void response.body?.cancel().catch(() => { });
|
|
53
|
+
if (![404, 502, 503, 530].includes(response.status))
|
|
54
|
+
throw new FatalReadinessError(lastFailure);
|
|
55
|
+
}
|
|
39
56
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (options.signal?.aborted)
|
|
59
|
+
throw new Error("public tunnel readiness aborted");
|
|
60
|
+
signal.throwIfAborted();
|
|
61
|
+
if (error instanceof FatalReadinessError)
|
|
62
|
+
throw new Error(`public tunnel not ready: ${error.message}`);
|
|
63
|
+
lastFailure = error instanceof Error ? error.message : String(error);
|
|
44
64
|
}
|
|
65
|
+
if (Date.now() + intervalMs > deadline)
|
|
66
|
+
break;
|
|
67
|
+
await delay(intervalMs, signal);
|
|
45
68
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
if (Date.now() + intervalMs > deadline)
|
|
54
|
-
break;
|
|
55
|
-
await delay(intervalMs, options.signal);
|
|
56
|
-
}
|
|
57
|
-
throw new Error(`public tunnel not ready: ${lastFailure}`);
|
|
69
|
+
throw new Error(`public tunnel not ready: ${lastFailure}`);
|
|
70
|
+
}, signal);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (options.signal?.aborted)
|
|
74
|
+
throw new Error("public tunnel readiness aborted");
|
|
75
|
+
throw error;
|
|
58
76
|
}
|
|
59
77
|
finally {
|
|
60
|
-
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
if (connection.proxy)
|
|
80
|
+
await withAbortSignal(() => connection.proxy.close(), AbortSignal.timeout(3_000)).catch(() => { });
|
|
61
81
|
}
|
|
62
82
|
}
|
|
63
83
|
class FatalReadinessError extends Error {
|
|
@@ -67,16 +87,22 @@ function createProxyFetch(proxyUrl) {
|
|
|
67
87
|
return {
|
|
68
88
|
fetch: async (input, init) => (await undiciFetch(input, { ...init, dispatcher })),
|
|
69
89
|
close: async () => {
|
|
70
|
-
await dispatcher.
|
|
90
|
+
await dispatcher.destroy();
|
|
71
91
|
},
|
|
72
92
|
};
|
|
73
93
|
}
|
|
74
94
|
function delay(milliseconds, signal) {
|
|
75
95
|
return new Promise((resolvePromise, reject) => {
|
|
76
|
-
const
|
|
77
|
-
signal?.addEventListener("abort", () => {
|
|
96
|
+
const abort = () => {
|
|
78
97
|
clearTimeout(timer);
|
|
79
|
-
reject(
|
|
80
|
-
}
|
|
98
|
+
reject(signal?.reason);
|
|
99
|
+
};
|
|
100
|
+
const timer = setTimeout(() => {
|
|
101
|
+
signal?.removeEventListener("abort", abort);
|
|
102
|
+
resolvePromise();
|
|
103
|
+
}, milliseconds);
|
|
104
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
105
|
+
if (signal?.aborted)
|
|
106
|
+
abort();
|
|
81
107
|
});
|
|
82
108
|
}
|
|
@@ -3,28 +3,50 @@ import { CloudflareTunnelProvider } from "./cloudflare-provider.js";
|
|
|
3
3
|
import { CustomCommandTunnelProvider } from "./custom-command-provider.js";
|
|
4
4
|
import { PinggyTunnelProvider } from "./pinggy-provider.js";
|
|
5
5
|
import { waitForPublicReadiness } from "./public-readiness.js";
|
|
6
|
+
import { withAbortSignal } from "../abort.js";
|
|
7
|
+
export const RELAY_START_TIMEOUT_MS = 30_000;
|
|
6
8
|
export async function selectRelay(options) {
|
|
9
|
+
options.signal.throwIfAborted();
|
|
7
10
|
if (options.cli.localOnly)
|
|
8
11
|
return { tunnel: null, publicUrl: options.lanUrl, provider: "lan", failures: [] };
|
|
9
|
-
const providers = options.cli.relay === "auto" ? ["cloudflare"
|
|
12
|
+
const providers = options.cli.relay === "auto" ? ["cloudflare"] : [options.cli.relay];
|
|
10
13
|
const failures = [];
|
|
11
14
|
const readiness = options.readiness ?? waitForPublicReadiness;
|
|
12
15
|
for (const providerName of providers) {
|
|
16
|
+
options.onStage?.("connecting");
|
|
13
17
|
options.onAttempt?.(providerName);
|
|
14
|
-
|
|
18
|
+
const attempt = { tunnel: null };
|
|
19
|
+
const deadline = new AbortController();
|
|
20
|
+
const timeoutMs = options.timeoutMs ?? RELAY_START_TIMEOUT_MS;
|
|
21
|
+
const timer = setTimeout(() => deadline.abort(new Error(`relay connection timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
22
|
+
const signal = AbortSignal.any([options.signal, deadline.signal]);
|
|
15
23
|
try {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
24
|
+
return await withAbortSignal(async () => {
|
|
25
|
+
const provider = await createProvider(providerName, options);
|
|
26
|
+
signal.throwIfAborted();
|
|
27
|
+
const handle = await provider.start({ localUrl: options.localUrl, signal, log: options.log });
|
|
28
|
+
if (signal.aborted) {
|
|
29
|
+
void handle.close().catch(() => { });
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
}
|
|
32
|
+
attempt.tunnel = handle;
|
|
33
|
+
options.onStage?.("checking");
|
|
34
|
+
await readiness(handle.publicUrl, { signal });
|
|
35
|
+
signal.throwIfAborted();
|
|
36
|
+
return { tunnel: handle, publicUrl: handle.publicUrl, provider: providerName, failures };
|
|
37
|
+
}, signal);
|
|
20
38
|
}
|
|
21
39
|
catch (error) {
|
|
22
|
-
|
|
40
|
+
deadline.abort(error);
|
|
41
|
+
if (attempt.tunnel)
|
|
42
|
+
await withAbortSignal(() => attempt.tunnel.close(), AbortSignal.timeout(3_000)).catch(() => { });
|
|
43
|
+
options.signal.throwIfAborted();
|
|
23
44
|
const message = error instanceof Error ? error.message : String(error);
|
|
24
45
|
failures.push({ provider: providerName, message });
|
|
25
46
|
options.onFailure?.(providerName, message);
|
|
26
|
-
|
|
27
|
-
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
clearTimeout(timer);
|
|
28
50
|
}
|
|
29
51
|
}
|
|
30
52
|
return { tunnel: null, publicUrl: options.lanUrl, provider: "lan", 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
|
+
}
|
|
@@ -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,96 @@
|
|
|
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
|
+
localOnly: service?.localOnly ?? false,
|
|
56
|
+
cliPath: resolve(options.cliPath),
|
|
57
|
+
updatedAt: Date.now(),
|
|
58
|
+
};
|
|
59
|
+
await writeUpdateState(paths.stateFile, state);
|
|
60
|
+
const child = spawn(process.execPath, [options.cliPath, "update-worker", paths.stateFile], { detached: true, stdio: "ignore", windowsHide: true });
|
|
61
|
+
child.unref();
|
|
62
|
+
return state;
|
|
63
|
+
}
|
|
64
|
+
async function readServiceConfig() {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(await readFile(resolve(homedir(), ".agentroam", "service", "config.json"), "utf8"));
|
|
67
|
+
}
|
|
68
|
+
catch { }
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
async function fetchWithTimeout(fetchImpl, url) {
|
|
72
|
+
const controller = new AbortController();
|
|
73
|
+
const timer = setTimeout(() => controller.abort(), 4_000);
|
|
74
|
+
timer.unref?.();
|
|
75
|
+
try {
|
|
76
|
+
return await fetchImpl(url, { headers: { accept: "application/json" }, signal: controller.signal });
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function compare(left, right) {
|
|
83
|
+
const parse = (value) => {
|
|
84
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:-preview\.(\d+))?$/.exec(value);
|
|
85
|
+
if (!match)
|
|
86
|
+
throw new Error("invalid AgentRoam version");
|
|
87
|
+
return [...match.slice(1, 4).map(Number), match[4] === undefined ? Number.MAX_SAFE_INTEGER : Number(match[4])];
|
|
88
|
+
};
|
|
89
|
+
const a = parse(left);
|
|
90
|
+
const b = parse(right);
|
|
91
|
+
for (let i = 0; i < a.length; i += 1)
|
|
92
|
+
if (a[i] !== b[i])
|
|
93
|
+
return a[i] > b[i] ? 1 : -1;
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
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
|
+
}
|