agentroam 0.2.0-preview.7 → 0.2.0-preview.70
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 +229 -33
- 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 +129 -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 +29 -9
- 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,48 @@ 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) {
|
|
13
16
|
options.onAttempt?.(providerName);
|
|
14
|
-
|
|
17
|
+
const attempt = { tunnel: null };
|
|
18
|
+
const deadline = new AbortController();
|
|
19
|
+
const timeoutMs = options.timeoutMs ?? RELAY_START_TIMEOUT_MS;
|
|
20
|
+
const timer = setTimeout(() => deadline.abort(new Error(`relay connection timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
21
|
+
const signal = AbortSignal.any([options.signal, deadline.signal]);
|
|
15
22
|
try {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
23
|
+
return await withAbortSignal(async () => {
|
|
24
|
+
const provider = await createProvider(providerName, options);
|
|
25
|
+
signal.throwIfAborted();
|
|
26
|
+
const handle = await provider.start({ localUrl: options.localUrl, signal, log: options.log });
|
|
27
|
+
if (signal.aborted) {
|
|
28
|
+
void handle.close().catch(() => { });
|
|
29
|
+
signal.throwIfAborted();
|
|
30
|
+
}
|
|
31
|
+
attempt.tunnel = handle;
|
|
32
|
+
await readiness(handle.publicUrl, { signal });
|
|
33
|
+
signal.throwIfAborted();
|
|
34
|
+
return { tunnel: handle, publicUrl: handle.publicUrl, provider: providerName, failures };
|
|
35
|
+
}, signal);
|
|
20
36
|
}
|
|
21
37
|
catch (error) {
|
|
22
|
-
|
|
38
|
+
deadline.abort(error);
|
|
39
|
+
if (attempt.tunnel)
|
|
40
|
+
await withAbortSignal(() => attempt.tunnel.close(), AbortSignal.timeout(3_000)).catch(() => { });
|
|
41
|
+
options.signal.throwIfAborted();
|
|
23
42
|
const message = error instanceof Error ? error.message : String(error);
|
|
24
43
|
failures.push({ provider: providerName, message });
|
|
25
44
|
options.onFailure?.(providerName, message);
|
|
26
|
-
|
|
27
|
-
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
clearTimeout(timer);
|
|
28
48
|
}
|
|
29
49
|
}
|
|
30
50
|
return { tunnel: null, publicUrl: options.lanUrl, provider: "lan", failures };
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
export function updatePaths(dataDir) {
|
|
4
|
+
const directory = resolve(dataDir, "updates");
|
|
5
|
+
return { directory, stateFile: resolve(directory, "state.json"), lockFile: resolve(directory, "update.lock") };
|
|
6
|
+
}
|
|
7
|
+
export async function readUpdateState(path) {
|
|
8
|
+
try {
|
|
9
|
+
const value = JSON.parse(await readFile(path, "utf8"));
|
|
10
|
+
return value?.schemaVersion === 1 ? value : null;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export async function writeUpdateState(path, state) {
|
|
17
|
+
await mkdir(dirname(path), { recursive: true });
|
|
18
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
19
|
+
await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
20
|
+
await rename(temp, path);
|
|
21
|
+
}
|
|
22
|
+
export async function acquireUpdateLock(path, now = Date.now()) {
|
|
23
|
+
await mkdir(dirname(path), { recursive: true });
|
|
24
|
+
try {
|
|
25
|
+
const handle = await open(path, "wx", 0o600);
|
|
26
|
+
await handle.writeFile(`${process.pid}\n${now}\n`);
|
|
27
|
+
await handle.close();
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error.code !== "EEXIST")
|
|
31
|
+
throw error;
|
|
32
|
+
const age = now - (await stat(path)).mtimeMs;
|
|
33
|
+
if (age <= 30 * 60 * 1_000)
|
|
34
|
+
throw new Error("an AgentRoam update is already running");
|
|
35
|
+
await unlink(path);
|
|
36
|
+
return acquireUpdateLock(path, now);
|
|
37
|
+
}
|
|
38
|
+
return async () => { await unlink(path).catch(() => undefined); };
|
|
39
|
+
}
|
|
40
|
+
export function sanitizeUpdateError(error) {
|
|
41
|
+
const value = error instanceof Error ? error.message : String(error);
|
|
42
|
+
return value.replace(/[A-Za-z]:\\[^\s]+|\/(?:Users|home|var|tmp)\/[^\s]+/g, "<path>").slice(0, 300);
|
|
43
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createWriteStream } from "node:fs";
|
|
3
|
+
import { chmod, readFile, unlink } from "node:fs/promises";
|
|
4
|
+
import { basename, resolve } from "node:path";
|
|
5
|
+
import { pipeline } from "node:stream/promises";
|
|
6
|
+
import { Readable } from "node:stream";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { acquireUpdateLock, readUpdateState, sanitizeUpdateError, updatePaths, writeUpdateState } from "./update-state.js";
|
|
9
|
+
import { buildCliInstallScriptUrl } from "./update-install.js";
|
|
10
|
+
export async function runUpdateWorker(stateFile, fetchImpl = fetch) {
|
|
11
|
+
const initial = await readUpdateState(stateFile);
|
|
12
|
+
if (!initial)
|
|
13
|
+
throw new Error("update state is missing");
|
|
14
|
+
const paths = updatePaths(initial.dataDir);
|
|
15
|
+
if (resolve(stateFile) !== paths.stateFile)
|
|
16
|
+
throw new Error("update state is outside the data directory");
|
|
17
|
+
const releaseLock = await acquireUpdateLock(paths.lockFile);
|
|
18
|
+
const partial = resolve(paths.directory, `${basename(initial.fileName)}.partial`);
|
|
19
|
+
let state = initial;
|
|
20
|
+
const update = async (next) => {
|
|
21
|
+
state = { ...state, ...next, updatedAt: Date.now() };
|
|
22
|
+
await writeUpdateState(stateFile, state);
|
|
23
|
+
};
|
|
24
|
+
try {
|
|
25
|
+
const response = await fetchImpl(buildCliInstallScriptUrl(state.fileName));
|
|
26
|
+
if (!response.ok || !response.body)
|
|
27
|
+
throw new Error("installer download failed");
|
|
28
|
+
await pipeline(Readable.fromWeb(response.body), createWriteStream(partial, { mode: 0o700 }));
|
|
29
|
+
const actual = createHash("sha256").update(await readFile(partial)).digest("hex");
|
|
30
|
+
if (actual !== state.sha256)
|
|
31
|
+
throw new Error("installer checksum mismatch");
|
|
32
|
+
await chmod(partial, 0o700).catch(() => undefined);
|
|
33
|
+
await update({ phase: "installing" });
|
|
34
|
+
const command = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
|
|
35
|
+
const args = process.platform === "win32" ? ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", partial] : [partial];
|
|
36
|
+
// 用 AGENTROAM_VERSION 钉住版本,而不是让安装脚本自己解析 dist-tag:
|
|
37
|
+
// 一是装的必须正是检查阶段向用户承诺的那一版,二是下一步要按
|
|
38
|
+
// launcher/<targetVersion> 定位入口,版本漂了就找不到。
|
|
39
|
+
const code = await run(command, args, {
|
|
40
|
+
...process.env,
|
|
41
|
+
AGENTROAM_VERSION: state.targetVersion,
|
|
42
|
+
AGENTROAM_DATA_DIR: state.dataDir,
|
|
43
|
+
AGENTROAM_ROOT: state.roots[0],
|
|
44
|
+
AGENTROAM_INSTALL_SKIP_SERVICE: "1",
|
|
45
|
+
});
|
|
46
|
+
if (code !== 0)
|
|
47
|
+
throw new Error(`installer exited with code ${code}`);
|
|
48
|
+
const nextEntry = resolve(state.dataDir, "launcher", state.targetVersion, "node_modules", "agentroam", "bin", "agentroam.mjs");
|
|
49
|
+
const serviceArgs = [nextEntry, "service", "install"];
|
|
50
|
+
for (const root of state.roots)
|
|
51
|
+
serviceArgs.push("--root", root);
|
|
52
|
+
serviceArgs.push("--data-dir", state.dataDir, "--relay", state.relay, "--no-qr");
|
|
53
|
+
if (state.port)
|
|
54
|
+
serviceArgs.push("--port", String(state.port));
|
|
55
|
+
if (state.tunnelCommand)
|
|
56
|
+
serviceArgs.push("--tunnel-command", state.tunnelCommand);
|
|
57
|
+
if (state.localOnly)
|
|
58
|
+
serviceArgs.push("--local-only");
|
|
59
|
+
await update({ phase: "reconnecting" });
|
|
60
|
+
const serviceCode = await run(process.execPath, serviceArgs, process.env);
|
|
61
|
+
if (serviceCode !== 0)
|
|
62
|
+
throw new Error(`service activation exited with code ${serviceCode}`);
|
|
63
|
+
await update({ phase: "complete", message: `AgentRoam ${state.targetVersion} installed` });
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
await update({ phase: "failed", message: sanitizeUpdateError(error) });
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
await unlink(partial).catch(() => undefined);
|
|
71
|
+
await releaseLock();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function run(command, args, env) {
|
|
75
|
+
return new Promise((resolveRun, reject) => {
|
|
76
|
+
const child = spawn(command, args, { env, stdio: "ignore", windowsHide: true });
|
|
77
|
+
child.once("error", reject);
|
|
78
|
+
child.once("exit", resolveRun);
|
|
79
|
+
});
|
|
80
|
+
}
|