agentroam 0.2.0-preview.8 → 0.2.0-preview.81
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 +136 -5
- package/dist/cli.js +295 -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 +155 -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 +177 -0
- package/dist/device-pairing.js +228 -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/mesh/mesh-command.js +51 -0
- package/dist/mesh/mesh-config.js +95 -0
- package/dist/mesh/mesh-payload.js +20 -0
- package/dist/mesh/mesh-runtime.js +101 -0
- package/dist/native-runtime.js +68 -0
- package/dist/network.js +46 -3
- package/dist/node-runtime-manager.js +251 -0
- package/dist/opencode-runtime-manager.js +260 -0
- package/dist/platform-packages.js +18 -5
- package/dist/platform.js +6 -4
- package/dist/power/sleep-inhibitor.js +161 -0
- package/dist/runtime-manager.js +139 -19
- package/dist/self-hosted-relay.json +1 -0
- 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 +226 -0
- package/dist/service/service-controller.js +29 -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/tailscale/bundled-asset.js +43 -0
- package/dist/tailscale/daemon-manager.js +112 -0
- package/dist/tailscale/installer.js +131 -0
- package/dist/tailscale/manifest.js +15 -0
- package/dist/tailscale/tailnet-cli.js +101 -0
- package/dist/todo-mcp-command.js +27 -0
- package/dist/tunnel/cloudflare-provider.js +4 -1
- package/dist/tunnel/public-readiness.js +76 -50
- package/dist/tunnel/relay-orchestrator.js +53 -19
- package/dist/tunnel/self-hosted-provider.js +147 -0
- package/dist/tunnel/tunnel-controller.js +232 -0
- package/dist/unlock-service.js +105 -0
- package/dist/update/update-channel.js +38 -0
- package/dist/update/update-command.js +97 -0
- package/dist/update/update-install.js +34 -0
- package/dist/update/update-state.js +43 -0
- package/dist/update/update-worker.js +82 -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/install/write-relay-default.mjs +6 -0
- package/package.json +15 -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
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { access, chmod, mkdir, mkdtemp, open, rename, rm, stat } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { delimiter, isAbsolute, relative, resolve, win32 } from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { resolveNpmExecutor } from "./codex-runtime-manager.js";
|
|
8
|
+
import { withAbortSignal } from "./abort.js";
|
|
9
|
+
const execFileAsync = promisify(execFile);
|
|
10
|
+
// Default managed installation; compatibility has an independent minimum.
|
|
11
|
+
export const OPENCODE_RUNTIME_VERSION = "1.18.27";
|
|
12
|
+
export const OPENCODE_MINIMUM_VERSION = "1.18.27";
|
|
13
|
+
const OPENCODE_PACKAGE = `opencode-ai@${OPENCODE_RUNTIME_VERSION}`;
|
|
14
|
+
const NPM_REGISTRY = "https://registry.npmjs.org";
|
|
15
|
+
const defaults = {
|
|
16
|
+
accessible,
|
|
17
|
+
async run(command, args, timeoutMs, signal) {
|
|
18
|
+
try {
|
|
19
|
+
const { stdout, stderr } = await execFileAsync(command, args, {
|
|
20
|
+
encoding: "utf8",
|
|
21
|
+
timeout: timeoutMs,
|
|
22
|
+
signal,
|
|
23
|
+
killSignal: "SIGKILL",
|
|
24
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
25
|
+
windowsHide: true,
|
|
26
|
+
});
|
|
27
|
+
return { stdout, stderr };
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
const value = error;
|
|
31
|
+
throw new Error([value.message, value.stderr, value.stdout].filter(Boolean).join(": "), { cause: error });
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
sleep: (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms)),
|
|
35
|
+
now: () => Date.now(),
|
|
36
|
+
};
|
|
37
|
+
export async function resolveOpenCodeRuntime(options) {
|
|
38
|
+
return options.signal
|
|
39
|
+
? withAbortSignal(() => resolveRuntime(options), options.signal)
|
|
40
|
+
: resolveRuntime(options);
|
|
41
|
+
}
|
|
42
|
+
async function resolveRuntime(options) {
|
|
43
|
+
const environment = options.environment ?? process.env;
|
|
44
|
+
const platform = options.platform ?? process.platform;
|
|
45
|
+
const dependencies = { ...defaults, ...options.dependencies };
|
|
46
|
+
const signal = options.signal;
|
|
47
|
+
if (signal) {
|
|
48
|
+
const run = dependencies.run;
|
|
49
|
+
const sleep = dependencies.sleep;
|
|
50
|
+
dependencies.run = (command, args, timeoutMs) => withAbortSignal(() => run(command, args, timeoutMs, signal), signal);
|
|
51
|
+
dependencies.sleep = (delayMs) => withAbortSignal(() => sleep(delayMs), signal);
|
|
52
|
+
}
|
|
53
|
+
const explicit = environment.AGENT_OPENCODE_BIN?.trim();
|
|
54
|
+
if (explicit) {
|
|
55
|
+
const absolute = platform === "win32" ? win32.isAbsolute(explicit) : isAbsolute(explicit);
|
|
56
|
+
if (!absolute)
|
|
57
|
+
throw new Error("AGENT_OPENCODE_BIN must be an absolute path");
|
|
58
|
+
if (platform === "win32" && /^opencode\.(?:cmd|bat)$/i.test(win32.basename(explicit))) {
|
|
59
|
+
const bundled = await firstCompatible(windowsOpenCodeNpmCandidates(windowsNpmModules(win32.dirname(explicit)), win32.resolve), "explicit", dependencies);
|
|
60
|
+
if (bundled)
|
|
61
|
+
return bundled;
|
|
62
|
+
throw new Error("AGENT_OPENCODE_BIN points to a Windows launcher without a compatible OpenCode executable");
|
|
63
|
+
}
|
|
64
|
+
return validate(explicit, "explicit", dependencies);
|
|
65
|
+
}
|
|
66
|
+
const global = await findGlobal(environment, platform, dependencies);
|
|
67
|
+
if (global)
|
|
68
|
+
return global;
|
|
69
|
+
const managedRoot = resolve(options.dataDir, "runtimes", "opencode", OPENCODE_RUNTIME_VERSION);
|
|
70
|
+
const managed = await validateManaged(managedRoot, platform, dependencies);
|
|
71
|
+
if (managed)
|
|
72
|
+
return managed;
|
|
73
|
+
signal?.throwIfAborted();
|
|
74
|
+
if (options.installIfMissing === false)
|
|
75
|
+
throw new Error("OpenCode is not installed; optional OpenCode sessions are unavailable.");
|
|
76
|
+
options.onProgress?.(`Installing managed OpenCode ${OPENCODE_RUNTIME_VERSION}...`);
|
|
77
|
+
return install({ ...options, environment, platform, dependencies, managedRoot });
|
|
78
|
+
}
|
|
79
|
+
export function parseOpenCodeVersion(output) {
|
|
80
|
+
return output.match(/(?:^|\s)v?((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))(?:\s|$)/)?.[1] ?? null;
|
|
81
|
+
}
|
|
82
|
+
export function managedOpenCodeBinaryCandidates(root, platform) {
|
|
83
|
+
return platform === "win32"
|
|
84
|
+
? [
|
|
85
|
+
...windowsOpenCodeNpmCandidates(resolve(root, "node_modules"), resolve),
|
|
86
|
+
resolve(root, "node_modules", ".bin", "opencode.exe"),
|
|
87
|
+
]
|
|
88
|
+
: [
|
|
89
|
+
resolve(root, "node_modules", "opencode-ai", "bin", "opencode.exe"),
|
|
90
|
+
resolve(root, "node_modules", ".bin", "opencode"),
|
|
91
|
+
];
|
|
92
|
+
}
|
|
93
|
+
function windowsNpmModules(prefix) {
|
|
94
|
+
return win32.resolve(prefix, win32.basename(prefix).toLowerCase() === ".bin" ? ".." : "node_modules");
|
|
95
|
+
}
|
|
96
|
+
function windowsOpenCodeNpmCandidates(modules, resolvePath) {
|
|
97
|
+
return ["opencode-ai", "opencode-windows-x64-baseline", "opencode-windows-x64"]
|
|
98
|
+
.map(name => resolvePath(modules, name, "bin", "opencode.exe"));
|
|
99
|
+
}
|
|
100
|
+
async function findGlobal(environment, platform, dependencies) {
|
|
101
|
+
const windows = platform === "win32";
|
|
102
|
+
const directories = (environment.PATH ?? environment.Path ?? "").split(windows ? ";" : delimiter).filter(Boolean);
|
|
103
|
+
if (!windows) {
|
|
104
|
+
return firstCompatible(directories.map(dir => resolve(dir, "opencode")), "global", dependencies, true);
|
|
105
|
+
}
|
|
106
|
+
const pathDirs = directories.map(dir => dir.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
|
|
107
|
+
const roaming = environment.APPDATA || win32.join(homedir(), "AppData", "Roaming");
|
|
108
|
+
const prefixes = [environment.npm_config_prefix || environment.NPM_CONFIG_PREFIX, win32.join(roaming, "npm")];
|
|
109
|
+
return firstCompatible([
|
|
110
|
+
...pathDirs.flatMap(dir => [win32.resolve(dir, "opencode.exe"), ...windowsOpenCodeNpmCandidates(windowsNpmModules(dir), win32.resolve)]),
|
|
111
|
+
...prefixes.filter((dir) => Boolean(dir)).flatMap(dir => windowsOpenCodeNpmCandidates(windowsNpmModules(dir), win32.resolve)),
|
|
112
|
+
], "global", dependencies);
|
|
113
|
+
}
|
|
114
|
+
async function firstCompatible(candidates, source, dependencies, executable = false) {
|
|
115
|
+
for (const candidate of new Set(candidates)) {
|
|
116
|
+
if (!await dependencies.accessible(candidate, executable))
|
|
117
|
+
continue;
|
|
118
|
+
try {
|
|
119
|
+
return await validate(candidate, source, dependencies);
|
|
120
|
+
}
|
|
121
|
+
catch { /* Keep looking for a compatible install. */ }
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
async function install(options) {
|
|
126
|
+
const parent = resolve(options.dataDir, "runtimes", "opencode");
|
|
127
|
+
const lockPath = `${options.managedRoot}.lock`;
|
|
128
|
+
await mkdir(parent, { recursive: true });
|
|
129
|
+
const lock = await acquireLock(lockPath, options.managedRoot, options.platform, options.dependencies, options.lockWaitMs ?? 190_000, options.staleLockMs ?? 300_000);
|
|
130
|
+
if (lock.completed)
|
|
131
|
+
return lock.completed;
|
|
132
|
+
let temporary = null;
|
|
133
|
+
try {
|
|
134
|
+
const existing = await validateManaged(options.managedRoot, options.platform, options.dependencies);
|
|
135
|
+
if (existing)
|
|
136
|
+
return existing;
|
|
137
|
+
temporary = await mkdtemp(resolve(parent, `.${OPENCODE_RUNTIME_VERSION}-${process.pid}-`));
|
|
138
|
+
const npm = await resolveNpmExecutor({
|
|
139
|
+
environment: options.environment,
|
|
140
|
+
platform: options.platform,
|
|
141
|
+
nodeExecutable: options.nodeExecutable,
|
|
142
|
+
});
|
|
143
|
+
await options.dependencies.run(npm.command, [
|
|
144
|
+
...npm.argsPrefix,
|
|
145
|
+
"install",
|
|
146
|
+
"--no-audit",
|
|
147
|
+
"--no-fund",
|
|
148
|
+
`--registry=${NPM_REGISTRY}`,
|
|
149
|
+
"--prefix",
|
|
150
|
+
temporary,
|
|
151
|
+
OPENCODE_PACKAGE,
|
|
152
|
+
], 180_000);
|
|
153
|
+
const validated = await validateManaged(temporary, options.platform, options.dependencies);
|
|
154
|
+
if (!validated)
|
|
155
|
+
throw new Error(`validation failed after installing ${OPENCODE_PACKAGE}`);
|
|
156
|
+
options.signal?.throwIfAborted();
|
|
157
|
+
await rename(temporary, options.managedRoot);
|
|
158
|
+
temporary = null;
|
|
159
|
+
const activated = await validateManaged(options.managedRoot, options.platform, options.dependencies);
|
|
160
|
+
if (!activated)
|
|
161
|
+
throw new Error("validation failed after activation");
|
|
162
|
+
return activated;
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
options.signal?.throwIfAborted();
|
|
166
|
+
const concurrent = await validateManaged(options.managedRoot, options.platform, options.dependencies);
|
|
167
|
+
if (concurrent)
|
|
168
|
+
return concurrent;
|
|
169
|
+
throw new Error(`Unable to install managed OpenCode ${OPENCODE_RUNTIME_VERSION}: ${describe(error)}`, { cause: error });
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
if (temporary)
|
|
173
|
+
await rm(temporary, { recursive: true, force: true });
|
|
174
|
+
await lock.handle.close().catch(() => undefined);
|
|
175
|
+
await rm(lockPath, { force: true });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function acquireLock(lockPath, managedRoot, platform, dependencies, waitMs, staleMs) {
|
|
179
|
+
const deadline = dependencies.now() + waitMs;
|
|
180
|
+
while (true) {
|
|
181
|
+
try {
|
|
182
|
+
const handle = await open(lockPath, "wx", 0o600);
|
|
183
|
+
await handle.writeFile(`${process.pid}\n${dependencies.now()}\n`);
|
|
184
|
+
return { handle };
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
if (error.code !== "EEXIST")
|
|
188
|
+
throw error;
|
|
189
|
+
const completed = await validateManaged(managedRoot, platform, dependencies);
|
|
190
|
+
if (completed)
|
|
191
|
+
return { completed };
|
|
192
|
+
try {
|
|
193
|
+
if (dependencies.now() - (await stat(lockPath)).mtimeMs > staleMs) {
|
|
194
|
+
await rm(lockPath, { force: true });
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (dependencies.now() >= deadline)
|
|
202
|
+
throw new Error(`Timed out waiting for OpenCode runtime install lock: ${lockPath}`);
|
|
203
|
+
await dependencies.sleep(Math.min(250, Math.max(1, deadline - dependencies.now())));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async function validateManaged(root, platform, dependencies) {
|
|
208
|
+
for (const executable of managedOpenCodeBinaryCandidates(root, platform)) {
|
|
209
|
+
if (!within(root, executable) || !(await dependencies.accessible(executable)))
|
|
210
|
+
continue;
|
|
211
|
+
try {
|
|
212
|
+
if (platform !== "win32")
|
|
213
|
+
await chmod(executable, 0o755);
|
|
214
|
+
return await validate(executable, "managed", dependencies);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
// An unusable launcher may coexist with a working platform binary.
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
async function validate(executable, source, dependencies) {
|
|
223
|
+
if (!(await dependencies.accessible(executable)))
|
|
224
|
+
throw new Error(`OpenCode executable not found: ${executable}`);
|
|
225
|
+
const result = await dependencies.run(executable, ["--version"], 5_000);
|
|
226
|
+
const version = parseOpenCodeVersion(`${result.stdout}\n${result.stderr}`);
|
|
227
|
+
if (!version)
|
|
228
|
+
throw new Error(`Unable to parse OpenCode version from ${executable}`);
|
|
229
|
+
if (!meetsOpenCodeMinimum(version)) {
|
|
230
|
+
throw new Error(`OpenCode ${version} at ${executable} is incompatible; AgentRoam requires >=${OPENCODE_MINIMUM_VERSION}`);
|
|
231
|
+
}
|
|
232
|
+
await dependencies.run(executable, ["serve", "--help"], 5_000);
|
|
233
|
+
return { executable, version, source };
|
|
234
|
+
}
|
|
235
|
+
// Compare numeric components, so 1.18.100 and 1.19.0 both exceed 1.18.27.
|
|
236
|
+
function meetsOpenCodeMinimum(version) {
|
|
237
|
+
const actual = version.split(".").map(BigInt);
|
|
238
|
+
const minimum = OPENCODE_MINIMUM_VERSION.split(".").map(BigInt);
|
|
239
|
+
for (let index = 0; index < minimum.length; index += 1) {
|
|
240
|
+
if (actual[index] !== minimum[index])
|
|
241
|
+
return actual[index] > minimum[index];
|
|
242
|
+
}
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
async function accessible(path, executable = false) {
|
|
246
|
+
try {
|
|
247
|
+
await access(path, executable ? constants.X_OK : constants.F_OK);
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function within(root, path) {
|
|
255
|
+
const value = relative(resolve(root), resolve(path));
|
|
256
|
+
return value !== "" && !value.startsWith("..") && !isAbsolute(value);
|
|
257
|
+
}
|
|
258
|
+
function describe(error) {
|
|
259
|
+
return error instanceof Error ? error.message : String(error);
|
|
260
|
+
}
|
|
@@ -1,16 +1,27 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { dirname } from "node:path";
|
|
4
|
-
|
|
4
|
+
import { MINIMUM_NODE_VERSION, assertSupportedNodeVersion } from "../bin/runtime-policy.mjs";
|
|
5
|
+
const CLI_PACKAGE_JSON = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
6
|
+
/**
|
|
7
|
+
* CLI 自身版本。
|
|
8
|
+
*
|
|
9
|
+
* **唯一源头是 packages/cli/package.json 的 version** —— 发版时只改那一处,
|
|
10
|
+
* 本文件、bin/node-preflight.mjs、tunnel/public-readiness.ts 全部自动跟随。
|
|
11
|
+
*/
|
|
12
|
+
export const AGENTROAM_VERSION = CLI_PACKAGE_JSON.version;
|
|
13
|
+
export const PLATFORM_DEPENDENCY_VERSIONS = CLI_PACKAGE_JSON.optionalDependencies;
|
|
5
14
|
export const PLATFORM_PACKAGES = {
|
|
6
15
|
"darwin-arm64": {
|
|
7
16
|
runtime: "agentroam-runtime-darwin-arm64",
|
|
8
17
|
cloudflared: "agentroam-cloudflared-darwin-arm64",
|
|
18
|
+
tailscale: "agentroam-tailscale-darwin-arm64",
|
|
9
19
|
tui: "agentroam-tui-darwin-arm64",
|
|
10
20
|
},
|
|
11
21
|
"windows-amd64": {
|
|
12
22
|
runtime: "agentroam-runtime-win32-x64",
|
|
13
23
|
cloudflared: "agentroam-cloudflared-win32-x64",
|
|
24
|
+
tailscale: "agentroam-tailscale-win32-x64",
|
|
14
25
|
tui: "@caoqu/agentroam-tui-win32-x64",
|
|
15
26
|
},
|
|
16
27
|
};
|
|
@@ -35,14 +46,16 @@ export function resolvePlatformRuntime(target, requireFromCli = createRequire(im
|
|
|
35
46
|
throw error;
|
|
36
47
|
}
|
|
37
48
|
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
38
|
-
if (manifest.packageVersion !==
|
|
49
|
+
if (manifest.packageVersion !== PLATFORM_DEPENDENCY_VERSIONS[packageName]
|
|
39
50
|
|| manifest.target !== target
|
|
40
|
-
|| manifest.
|
|
41
|
-
|| manifest.
|
|
51
|
+
|| manifest.schemaVersion !== 2
|
|
52
|
+
|| manifest.minimumNodeVersion !== MINIMUM_NODE_VERSION
|
|
42
53
|
|| !manifest.nativeFiles
|
|
43
|
-
|| typeof manifest.nativeFiles !== "object"
|
|
54
|
+
|| typeof manifest.nativeFiles !== "object"
|
|
55
|
+
|| Array.isArray(manifest.nativeFiles)) {
|
|
44
56
|
throw new Error(`invalid AgentRoam runtime manifest: ${manifestPath}`);
|
|
45
57
|
}
|
|
58
|
+
assertSupportedNodeVersion();
|
|
46
59
|
return {
|
|
47
60
|
packageName,
|
|
48
61
|
runtimeRoot: dirname(runtimePackageJson),
|
package/dist/platform.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
if (major !== 22)
|
|
4
|
-
throw Object.assign(new Error(`Node.js 22 required (current ${nodeVersion})`), { exitCode: 2 });
|
|
1
|
+
import { assertSupportedNodeVersion } from "../bin/runtime-policy.mjs";
|
|
2
|
+
export function detectPlatformTarget(platform = process.platform, arch = process.arch) {
|
|
5
3
|
if (platform === "darwin" && arch === "arm64")
|
|
6
4
|
return "darwin-arm64";
|
|
7
5
|
if (platform === "darwin" && arch === "x64")
|
|
@@ -10,3 +8,7 @@ export function detectPlatform(platform = process.platform, arch = process.arch,
|
|
|
10
8
|
return "windows-amd64";
|
|
11
9
|
throw Object.assign(new Error(`unsupported platform: ${platform}-${arch}`), { exitCode: 2 });
|
|
12
10
|
}
|
|
11
|
+
export function detectPlatform(platform = process.platform, arch = process.arch, nodeVersion = process.versions.node) {
|
|
12
|
+
assertSupportedNodeVersion(nodeVersion);
|
|
13
|
+
return detectPlatformTarget(platform, arch);
|
|
14
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
export async function acquireSleepInhibitor(options = {}) {
|
|
3
|
+
const platform = options.platform ?? process.platform;
|
|
4
|
+
const pid = options.pid ?? process.pid;
|
|
5
|
+
const spawnProcess = options.spawnProcess ?? spawn;
|
|
6
|
+
// Windows PowerShell compiles the P/Invoke helper on first use. Cold startup
|
|
7
|
+
// and antivirus scanning can take longer than five seconds.
|
|
8
|
+
const readyTimeoutMs = options.readyTimeoutMs ?? (platform === "win32" ? 30_000 : 5_000);
|
|
9
|
+
const stopTimeoutMs = options.stopTimeoutMs ?? 2_000;
|
|
10
|
+
if (platform === "darwin") {
|
|
11
|
+
const child = spawnProcess("/usr/bin/caffeinate", ["-i", "-w", String(pid)], {
|
|
12
|
+
stdio: "ignore",
|
|
13
|
+
windowsHide: true,
|
|
14
|
+
});
|
|
15
|
+
await waitForSpawn(child, readyTimeoutMs, "macOS idle-sleep inhibitor");
|
|
16
|
+
return monitorChild(child, stopTimeoutMs, "macOS idle-sleep inhibitor");
|
|
17
|
+
}
|
|
18
|
+
if (platform === "win32") {
|
|
19
|
+
const script = buildWindowsSleepInhibitorScript(pid);
|
|
20
|
+
const child = spawnProcess("powershell.exe", [
|
|
21
|
+
"-NoProfile",
|
|
22
|
+
"-NonInteractive",
|
|
23
|
+
"-ExecutionPolicy", "Bypass",
|
|
24
|
+
"-EncodedCommand", Buffer.from(script, "utf16le").toString("base64"),
|
|
25
|
+
], {
|
|
26
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
27
|
+
windowsHide: true,
|
|
28
|
+
});
|
|
29
|
+
try {
|
|
30
|
+
await waitForReadyLine(child, readyTimeoutMs);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
// A timed-out child otherwise keeps Node alive after startup has failed.
|
|
34
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
35
|
+
child.kill("SIGKILL");
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
return monitorChild(child, stopTimeoutMs, "Windows idle-sleep inhibitor");
|
|
39
|
+
}
|
|
40
|
+
throw new Error(`idle-sleep prevention is unsupported on ${platform}`);
|
|
41
|
+
}
|
|
42
|
+
export function buildWindowsSleepInhibitorScript(parentPid) {
|
|
43
|
+
return String.raw `
|
|
44
|
+
$ErrorActionPreference = "Stop"
|
|
45
|
+
$source = @'
|
|
46
|
+
using System;
|
|
47
|
+
using System.Runtime.InteropServices;
|
|
48
|
+
public static class AgentRoamPower {
|
|
49
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
50
|
+
public static extern uint SetThreadExecutionState(uint esFlags);
|
|
51
|
+
}
|
|
52
|
+
'@
|
|
53
|
+
Add-Type -TypeDefinition $source
|
|
54
|
+
$continuous = [uint32]::Parse("80000000", [Globalization.NumberStyles]::HexNumber)
|
|
55
|
+
$systemRequired = [uint32]1
|
|
56
|
+
$result = [AgentRoamPower]::SetThreadExecutionState($continuous -bor $systemRequired)
|
|
57
|
+
if ($result -eq 0) { throw "SetThreadExecutionState failed" }
|
|
58
|
+
[Console]::Out.WriteLine("AGENTROAM_SLEEP_INHIBITOR_READY")
|
|
59
|
+
try {
|
|
60
|
+
Wait-Process -Id ${parentPid}
|
|
61
|
+
} finally {
|
|
62
|
+
[void][AgentRoamPower]::SetThreadExecutionState($continuous)
|
|
63
|
+
}
|
|
64
|
+
`;
|
|
65
|
+
}
|
|
66
|
+
function waitForSpawn(child, timeoutMs, label) {
|
|
67
|
+
return new Promise((resolveReady, rejectReady) => {
|
|
68
|
+
const timeout = setTimeout(() => finish(new Error(`${label} did not start within ${timeoutMs}ms`)), timeoutMs);
|
|
69
|
+
const onError = (error) => finish(error);
|
|
70
|
+
const onExit = (code, signal) => {
|
|
71
|
+
finish(new Error(`${label} exited before readiness (${formatExit(code, signal)})`));
|
|
72
|
+
};
|
|
73
|
+
const onSpawn = () => finish();
|
|
74
|
+
const finish = (error) => {
|
|
75
|
+
clearTimeout(timeout);
|
|
76
|
+
child.removeListener("error", onError);
|
|
77
|
+
child.removeListener("exit", onExit);
|
|
78
|
+
child.removeListener("spawn", onSpawn);
|
|
79
|
+
if (error)
|
|
80
|
+
rejectReady(error);
|
|
81
|
+
else
|
|
82
|
+
resolveReady();
|
|
83
|
+
};
|
|
84
|
+
child.once("error", onError);
|
|
85
|
+
child.once("exit", onExit);
|
|
86
|
+
child.once("spawn", onSpawn);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function waitForReadyLine(child, timeoutMs) {
|
|
90
|
+
return new Promise((resolveReady, rejectReady) => {
|
|
91
|
+
let stdout = "";
|
|
92
|
+
let stderr = "";
|
|
93
|
+
const timeout = setTimeout(() => {
|
|
94
|
+
finish(new Error(`Windows idle-sleep inhibitor did not become ready within ${timeoutMs}ms`));
|
|
95
|
+
}, timeoutMs);
|
|
96
|
+
const onStdout = (chunk) => {
|
|
97
|
+
stdout += chunk.toString();
|
|
98
|
+
if (stdout.includes("AGENTROAM_SLEEP_INHIBITOR_READY"))
|
|
99
|
+
finish();
|
|
100
|
+
};
|
|
101
|
+
const onStderr = (chunk) => { stderr += chunk.toString(); };
|
|
102
|
+
const onError = (error) => finish(error);
|
|
103
|
+
const onExit = (code, signal) => {
|
|
104
|
+
const detail = stderr.trim();
|
|
105
|
+
finish(new Error(`Windows idle-sleep inhibitor exited before readiness (${formatExit(code, signal)})${detail ? `: ${detail}` : ""}`));
|
|
106
|
+
};
|
|
107
|
+
const finish = (error) => {
|
|
108
|
+
clearTimeout(timeout);
|
|
109
|
+
child.stdout?.removeListener("data", onStdout);
|
|
110
|
+
child.stderr?.removeListener("data", onStderr);
|
|
111
|
+
child.removeListener("error", onError);
|
|
112
|
+
child.removeListener("exit", onExit);
|
|
113
|
+
if (error)
|
|
114
|
+
rejectReady(error);
|
|
115
|
+
else
|
|
116
|
+
resolveReady();
|
|
117
|
+
};
|
|
118
|
+
child.stdout?.on("data", onStdout);
|
|
119
|
+
child.stderr?.on("data", onStderr);
|
|
120
|
+
child.once("error", onError);
|
|
121
|
+
child.once("exit", onExit);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function monitorChild(child, stopTimeoutMs, label) {
|
|
125
|
+
let releasing = false;
|
|
126
|
+
let released = false;
|
|
127
|
+
let resolveLost;
|
|
128
|
+
const lost = new Promise((resolvePromise) => { resolveLost = resolvePromise; });
|
|
129
|
+
const exited = new Promise((resolveExit) => {
|
|
130
|
+
child.once("exit", (code, signal) => {
|
|
131
|
+
if (!releasing)
|
|
132
|
+
resolveLost(new Error(`${label} stopped unexpectedly (${formatExit(code, signal)})`));
|
|
133
|
+
resolveExit();
|
|
134
|
+
});
|
|
135
|
+
child.once("error", (error) => {
|
|
136
|
+
if (!releasing)
|
|
137
|
+
resolveLost(error);
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
return {
|
|
141
|
+
lost,
|
|
142
|
+
async release() {
|
|
143
|
+
if (released)
|
|
144
|
+
return;
|
|
145
|
+
released = true;
|
|
146
|
+
releasing = true;
|
|
147
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
148
|
+
return;
|
|
149
|
+
child.kill("SIGTERM");
|
|
150
|
+
await Promise.race([exited, delay(stopTimeoutMs)]);
|
|
151
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
152
|
+
child.kill("SIGKILL");
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function formatExit(code, signal) {
|
|
157
|
+
return signal ? `signal ${signal}` : `exit ${code ?? 1}`;
|
|
158
|
+
}
|
|
159
|
+
function delay(timeoutMs) {
|
|
160
|
+
return new Promise((resolveDelay) => setTimeout(resolveDelay, timeoutMs));
|
|
161
|
+
}
|