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
package/dist/runtime-manager.js
CHANGED
|
@@ -1,34 +1,82 @@
|
|
|
1
|
+
import { loadMeshEnvironment } from "./mesh/mesh-config.js";
|
|
1
2
|
import { mkdir } from "node:fs/promises";
|
|
2
3
|
import { delimiter, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { resolveCodexRuntime, } from "./codex-runtime-manager.js";
|
|
3
6
|
import { repairNativeRuntimePermissions } from "./native-runtime.js";
|
|
7
|
+
import { resolveOpenCodeRuntime, } from "./opencode-runtime-manager.js";
|
|
4
8
|
import { resolvePlatformRuntime } from "./platform-packages.js";
|
|
5
9
|
import { findAvailablePort } from "./port.js";
|
|
6
10
|
import { ProcessSupervisor } from "./process-supervisor.js";
|
|
11
|
+
import { ensureWindowsBackend } from "./codex-windows-backend.js";
|
|
12
|
+
import { configureCodexSharing } from "./codex-sharing.js";
|
|
13
|
+
import { withCliProgress } from "../bin/cli-progress.mjs";
|
|
14
|
+
import { withAbortSignal, withTimeout } from "./abort.js";
|
|
15
|
+
export const CODEX_PREPARATION_TIMEOUT_MS = 180_000;
|
|
16
|
+
const OPTIONAL_RUNTIME_CHECK_TIMEOUT_MS = 60_000;
|
|
17
|
+
const CODEX_SHARING_TIMEOUT_MS = 10_000;
|
|
7
18
|
export class RuntimeManager {
|
|
8
19
|
supervisor;
|
|
9
|
-
|
|
20
|
+
codexResolver;
|
|
21
|
+
report;
|
|
22
|
+
opencodeResolver;
|
|
23
|
+
constructor(supervisor = new ProcessSupervisor(), codexResolver = resolveCodexRuntime, report = (message) => process.stderr.write(`${message}\n`), opencodeResolver = resolveOpenCodeRuntime) {
|
|
10
24
|
this.supervisor = supervisor;
|
|
25
|
+
this.codexResolver = codexResolver;
|
|
26
|
+
this.report = report;
|
|
27
|
+
this.opencodeResolver = opencodeResolver;
|
|
11
28
|
}
|
|
12
|
-
async start(options,
|
|
29
|
+
async start(options, target) {
|
|
13
30
|
const port = await findAvailablePort(options.port);
|
|
14
31
|
const dataDir = resolve(options.dataDir);
|
|
15
32
|
await Promise.all(["data", "bin", "cache", "logs"].map((name) => mkdir(resolve(dataDir, name), { recursive: true })));
|
|
33
|
+
const { AGENTROAM_MESH_ACTIVATION_CODE: _, ...runtimeEnvironment } = process.env;
|
|
34
|
+
const childEnvironment = await withCliProgress("正在检查 Agent 组件;缺少 Codex 时自动安装最新版,最多等待 180 秒", () => prepareAgentRuntimeEnvironment(runtimeEnvironment, { dataDir, target }, this.codexResolver, this.report, this.opencodeResolver));
|
|
35
|
+
if (process.platform === "darwin" && childEnvironment.AGENT_CODEX_BIN) {
|
|
36
|
+
try {
|
|
37
|
+
await withTimeout(signal => configureCodexSharing(options, { environment: childEnvironment, signal }), CODEX_SHARING_TIMEOUT_MS, "Codex 共享后台配置超时(10 秒)");
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
this.report(`Codex 共享启动配置未完成,可在电脑菜单中修复:${error instanceof Error ? error.message : error}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (process.platform === "win32" && childEnvironment.AGENT_CODEX_BIN) {
|
|
44
|
+
try {
|
|
45
|
+
const backend = await ensureWindowsBackend(dataDir, { environment: childEnvironment });
|
|
46
|
+
childEnvironment.AGENT_CODEX_DESKTOP_WS_URL = backend.endpoint;
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
this.report(`Codex 共享后台未就绪,可在头像菜单重试:${error instanceof Error ? error.message : error}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
16
52
|
const { runtimeRoot } = resolvePlatformRuntime(target);
|
|
17
53
|
await repairNativeRuntimePermissions(runtimeRoot);
|
|
18
54
|
const gateway = resolve(runtimeRoot, "ws-server.mjs");
|
|
19
|
-
const
|
|
55
|
+
const meshEnvironment = await loadMeshEnvironment(dataDir, process.env).catch(error => {
|
|
56
|
+
if (process.env.AGENTROAM_MESH_ACTIVATION_CODE?.trim())
|
|
57
|
+
throw error;
|
|
58
|
+
this.report(`组网配置未加载:${error.message}`);
|
|
59
|
+
return {};
|
|
60
|
+
});
|
|
61
|
+
const child = this.supervisor.spawn(process.execPath, [gateway, ...(options.testNoPairing ? ["--test-no-pairing"] : [])], {
|
|
62
|
+
stdio: ["ignore", "pipe", "pipe", "ipc"],
|
|
20
63
|
cwd: runtimeRoot,
|
|
21
64
|
env: {
|
|
22
|
-
...
|
|
65
|
+
...childEnvironment,
|
|
66
|
+
...meshEnvironment,
|
|
23
67
|
NODE_ENV: "production",
|
|
24
68
|
NEXT_DIST_DIR: ".next",
|
|
25
69
|
PORT: String(port),
|
|
26
|
-
HOST: "
|
|
70
|
+
HOST: "0.0.0.0",
|
|
27
71
|
AGENT_DATA_DIR: resolve(dataDir, "data"),
|
|
72
|
+
// 应用日志收口到 <dataDir>/logs,与 launchd 的 service.stdout/stderr.log
|
|
73
|
+
// 及 CLI 自身的错误日志同一个目录,用户排障时只需打包这一处。
|
|
74
|
+
AGENT_LOG_DIR: resolve(dataDir, "logs"),
|
|
28
75
|
AGENT_WEB_ROOTS: options.roots.join(delimiter),
|
|
29
76
|
AGENT_TRUST_TUNNEL_PROXY: "1",
|
|
30
|
-
|
|
31
|
-
|
|
77
|
+
AGENTROAM_VERSION: resolvePlatformRuntime(target).manifest.packageVersion,
|
|
78
|
+
AGENTROAM_DATA_DIR: dataDir,
|
|
79
|
+
AGENTROAM_CLI_PATH: fileURLToPath(new URL("../bin/agentroam.mjs", import.meta.url)),
|
|
32
80
|
},
|
|
33
81
|
});
|
|
34
82
|
const log = (stream) => stream?.on("data", (chunk) => process.stderr.write(chunk));
|
|
@@ -38,7 +86,14 @@ export class RuntimeManager {
|
|
|
38
86
|
child.once("exit", (code, signal) => resolveExit({ code, signal }));
|
|
39
87
|
});
|
|
40
88
|
const localUrl = `http://127.0.0.1:${port}`;
|
|
41
|
-
|
|
89
|
+
let status;
|
|
90
|
+
try {
|
|
91
|
+
status = await withCliProgress("正在等待本机服务就绪", () => waitForHealth(`${localUrl}/api/web-auth/status`, child, 20_000));
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
await this.supervisor.stopAll();
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
42
97
|
return {
|
|
43
98
|
port,
|
|
44
99
|
localUrl,
|
|
@@ -50,18 +105,83 @@ export class RuntimeManager {
|
|
|
50
105
|
};
|
|
51
106
|
}
|
|
52
107
|
}
|
|
108
|
+
export async function prepareAgentRuntimeEnvironment(environment, options, codexResolver = resolveCodexRuntime, report = (message) => process.stderr.write(`${message}\n`), opencodeResolver = resolveOpenCodeRuntime) {
|
|
109
|
+
const [codex, opencode] = await Promise.all([
|
|
110
|
+
prepareCodexRuntimeEnvironment(environment, options, codexResolver, report),
|
|
111
|
+
prepareOpenCodeRuntimeEnvironment(environment, options, opencodeResolver, report),
|
|
112
|
+
]);
|
|
113
|
+
return {
|
|
114
|
+
...codex,
|
|
115
|
+
AGENT_OPENCODE_BIN: opencode.AGENT_OPENCODE_BIN,
|
|
116
|
+
AGENT_OPENCODE_RUNTIME_ERROR: opencode.AGENT_OPENCODE_RUNTIME_ERROR,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
export async function prepareCodexRuntimeEnvironment(environment, options, resolver = resolveCodexRuntime, report = (message) => process.stderr.write(`${message}\n`)) {
|
|
120
|
+
const childEnvironment = { ...environment };
|
|
121
|
+
const timeoutMs = options.timeoutMs ?? CODEX_PREPARATION_TIMEOUT_MS;
|
|
122
|
+
report(`Checking Codex ${options.target} runtime...`);
|
|
123
|
+
try {
|
|
124
|
+
const resolution = await withTimeout(signal => resolver({
|
|
125
|
+
dataDir: options.dataDir,
|
|
126
|
+
target: options.target,
|
|
127
|
+
signal,
|
|
128
|
+
environment,
|
|
129
|
+
onProgress: report,
|
|
130
|
+
}), timeoutMs, `Codex 组件准备超时(${timeoutMs / 1000} 秒);请检查网络后运行 agentroam doctor 重试。`);
|
|
131
|
+
childEnvironment.AGENT_CODEX_BIN = resolution.executable;
|
|
132
|
+
delete childEnvironment.AGENT_CODEX_RUNTIME_ERROR;
|
|
133
|
+
report(`Codex ${resolution.version} (${resolution.source}): ${resolution.executable}`);
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
delete childEnvironment.AGENT_CODEX_BIN;
|
|
137
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
138
|
+
childEnvironment.AGENT_CODEX_RUNTIME_ERROR = message;
|
|
139
|
+
report(`⚠ Codex 会话功能未就绪,局域网服务将继续启动;运行 agentroam doctor 修复后重启服务:${message}`);
|
|
140
|
+
}
|
|
141
|
+
return childEnvironment;
|
|
142
|
+
}
|
|
143
|
+
export async function prepareOpenCodeRuntimeEnvironment(environment, options, resolver = resolveOpenCodeRuntime, report = (message) => process.stderr.write(`${message}\n`)) {
|
|
144
|
+
const childEnvironment = { ...environment };
|
|
145
|
+
report(`Checking OpenCode ${options.target} runtime...`);
|
|
146
|
+
try {
|
|
147
|
+
const resolution = await withTimeout(signal => resolver({
|
|
148
|
+
dataDir: options.dataDir, target: options.target, environment, signal, installIfMissing: false, onProgress: report,
|
|
149
|
+
}), options.timeoutMs ?? OPTIONAL_RUNTIME_CHECK_TIMEOUT_MS, "OpenCode 组件检查超时;已跳过,不下载安装。");
|
|
150
|
+
childEnvironment.AGENT_OPENCODE_BIN = resolution.executable;
|
|
151
|
+
delete childEnvironment.AGENT_OPENCODE_RUNTIME_ERROR;
|
|
152
|
+
report(`OpenCode ${resolution.version} (${resolution.source}): ${resolution.executable}`);
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
delete childEnvironment.AGENT_OPENCODE_BIN;
|
|
156
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
157
|
+
childEnvironment.AGENT_OPENCODE_RUNTIME_ERROR = message;
|
|
158
|
+
report(`OpenCode 不可用,已跳过(不自动安装):${message}`);
|
|
159
|
+
}
|
|
160
|
+
return childEnvironment;
|
|
161
|
+
}
|
|
53
162
|
async function waitForHealth(url, child, timeoutMs) {
|
|
54
163
|
const end = Date.now() + timeoutMs;
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
164
|
+
const controller = new AbortController();
|
|
165
|
+
const timer = setTimeout(() => controller.abort(new Error("local server health check timed out")), timeoutMs);
|
|
166
|
+
try {
|
|
167
|
+
return await withAbortSignal(async () => {
|
|
168
|
+
while (Date.now() < end) {
|
|
169
|
+
controller.signal.throwIfAborted();
|
|
170
|
+
if (child.exitCode !== null)
|
|
171
|
+
throw new Error(`local server exited with ${child.exitCode}`);
|
|
172
|
+
try {
|
|
173
|
+
const response = await fetch(url, { signal: controller.signal });
|
|
174
|
+
if (response.ok)
|
|
175
|
+
return response.json();
|
|
176
|
+
void response.body?.cancel().catch(() => { });
|
|
177
|
+
}
|
|
178
|
+
catch { }
|
|
179
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 250));
|
|
180
|
+
}
|
|
181
|
+
throw new Error("local server health check timed out");
|
|
182
|
+
}, controller.signal);
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
clearTimeout(timer);
|
|
65
186
|
}
|
|
66
|
-
throw new Error("local server health check timed out");
|
|
67
187
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { lstat, readFile, readdir, realpath, rm } from "node:fs/promises";
|
|
2
|
+
import { relative, resolve, sep } from "node:path";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
const execFileAsync = promisify(execFile);
|
|
6
|
+
async function processPathsInUse() {
|
|
7
|
+
// Windows has no reliable cwd inventory here: retain old installs instead.
|
|
8
|
+
if (process.platform === "win32")
|
|
9
|
+
throw new Error("Process paths unavailable");
|
|
10
|
+
const { stdout } = await execFileAsync(process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof", ["-nP", "-d", "cwd,txt", "-Fn"], { timeout: 5_000, maxBuffer: 16 * 1024 * 1024 });
|
|
11
|
+
const paths = stdout.split("\n").filter(line => line.startsWith("n/")).map(line => line.slice(1));
|
|
12
|
+
if (!paths.length)
|
|
13
|
+
throw new Error("Incomplete process paths");
|
|
14
|
+
return [process.cwd(), ...paths];
|
|
15
|
+
}
|
|
16
|
+
function versionParts(version) {
|
|
17
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-preview\.(0|[1-9]\d*))?$/.exec(version);
|
|
18
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3]), match[4] === undefined ? Infinity : Number(match[4])] : null;
|
|
19
|
+
}
|
|
20
|
+
function older(candidate, current) {
|
|
21
|
+
const left = versionParts(candidate), right = versionParts(current);
|
|
22
|
+
if (!left || !right)
|
|
23
|
+
return false;
|
|
24
|
+
for (let i = 0; i < left.length; i++)
|
|
25
|
+
if (left[i] !== right[i])
|
|
26
|
+
return left[i] < right[i];
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
function contains(parent, child) {
|
|
30
|
+
const path = relative(parent, child);
|
|
31
|
+
return path === "" || (!path.startsWith(`..${sep}`) && path !== ".." && !path.startsWith(sep));
|
|
32
|
+
}
|
|
33
|
+
/** Remove only recognized managed launcher versions after the replacement service is ready. */
|
|
34
|
+
export async function cleanupOldLaunchers(config, log, context = {}) {
|
|
35
|
+
try {
|
|
36
|
+
const dataDir = await realpath(config.dataDir);
|
|
37
|
+
const launcherDir = resolve(dataDir, "launcher");
|
|
38
|
+
if (!(await lstat(launcherDir)).isDirectory() || (await lstat(launcherDir)).isSymbolicLink())
|
|
39
|
+
return;
|
|
40
|
+
const currentDir = resolve(launcherDir, config.version);
|
|
41
|
+
const expectedEntry = resolve(currentDir, "node_modules/agentroam/bin/agentroam.mjs");
|
|
42
|
+
if (await realpath(config.cliPath) !== expectedEntry)
|
|
43
|
+
return;
|
|
44
|
+
const roots = await Promise.all(config.roots.map(async (root) => realpath(root).catch(() => resolve(root))));
|
|
45
|
+
for (const entry of await readdir(launcherDir, { withFileTypes: true })) {
|
|
46
|
+
if (!entry.isDirectory() || !older(entry.name, config.version))
|
|
47
|
+
continue;
|
|
48
|
+
const candidate = resolve(launcherDir, entry.name);
|
|
49
|
+
try {
|
|
50
|
+
if (await lstat(`${candidate}.lock`).then(() => true, () => false))
|
|
51
|
+
continue;
|
|
52
|
+
if (roots.some(root => contains(candidate, root)))
|
|
53
|
+
continue;
|
|
54
|
+
const files = await readdir(candidate);
|
|
55
|
+
if (files.some(file => !["node_modules", "package.json", "package-lock.json"].includes(file)))
|
|
56
|
+
continue;
|
|
57
|
+
const manifestPath = resolve(candidate, "node_modules/agentroam/package.json");
|
|
58
|
+
if (await realpath(manifestPath) !== manifestPath)
|
|
59
|
+
continue;
|
|
60
|
+
const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
|
|
61
|
+
if (manifest.name !== "agentroam" || manifest.version !== entry.name)
|
|
62
|
+
continue;
|
|
63
|
+
const usedPaths = await (context.pathsInUse ?? processPathsInUse)();
|
|
64
|
+
if (usedPaths.some(path => contains(candidate, path))) {
|
|
65
|
+
log(`旧版 CLI ${entry.name} 仍被进程使用,已保留。`);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
await rm(candidate, { recursive: true });
|
|
69
|
+
log(`✓ 已清理旧版 CLI ${entry.name},配置和数据已保留`);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
log(`旧版 CLI ${entry.name} 暂未清理,将在下次安装时重试。`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
log("旧版 CLI 清理已跳过,新版服务不受影响。");
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, chmod, mkdir, readFile, rename, stat } from "node:fs/promises";
|
|
3
|
+
import { dirname, resolve } from "node:path";
|
|
4
|
+
import { SERVICE_LABEL, ensurePrivateDirectory, ensurePrivateFile, readServiceConfig, readServiceState, removeIfExists, resolveServicePaths, writePrivateJson, } from "./service-files.js";
|
|
5
|
+
import { buildStartArguments, runCommand, } from "./service-controller.js";
|
|
6
|
+
export { buildStartArguments } from "./service-controller.js";
|
|
7
|
+
export class MacLaunchAgent {
|
|
8
|
+
homeDir;
|
|
9
|
+
uid;
|
|
10
|
+
runner;
|
|
11
|
+
processExists;
|
|
12
|
+
now;
|
|
13
|
+
readyTimeoutMs;
|
|
14
|
+
stopTimeoutMs;
|
|
15
|
+
pollIntervalMs;
|
|
16
|
+
constructor(options = {}) {
|
|
17
|
+
this.homeDir = options.homeDir;
|
|
18
|
+
this.uid = options.uid ?? process.getuid?.() ?? 0;
|
|
19
|
+
this.runner = options.runner ?? runCommand;
|
|
20
|
+
this.processExists = options.processExists ?? isProcessRunning;
|
|
21
|
+
this.now = options.now ?? (() => new Date());
|
|
22
|
+
// Codex preparation (180s), sharing (10s), local server (20s), relay (30s), plus cleanup.
|
|
23
|
+
this.readyTimeoutMs = options.readyTimeoutMs ?? 270_000;
|
|
24
|
+
this.stopTimeoutMs = options.stopTimeoutMs ?? 15_000;
|
|
25
|
+
this.pollIntervalMs = options.pollIntervalMs ?? 250;
|
|
26
|
+
}
|
|
27
|
+
async install(config) {
|
|
28
|
+
await this.validateConfig(config);
|
|
29
|
+
const paths = resolveServicePaths(this.homeDir, config.dataDir);
|
|
30
|
+
const previousState = await readServiceState(paths);
|
|
31
|
+
await Promise.all([
|
|
32
|
+
mkdir(paths.launchAgentsDir, { recursive: true }),
|
|
33
|
+
ensurePrivateDirectory(paths.controlDir),
|
|
34
|
+
ensurePrivateDirectory(paths.logsDir),
|
|
35
|
+
]);
|
|
36
|
+
await Promise.all([ensurePrivateFile(paths.stdoutPath), ensurePrivateFile(paths.stderrPath)]);
|
|
37
|
+
const jsonPath = resolve(paths.controlDir, "launch-agent.json.tmp");
|
|
38
|
+
const plistTempPath = resolve(paths.controlDir, "launch-agent.plist.tmp");
|
|
39
|
+
await removeIfExists(plistTempPath);
|
|
40
|
+
await writePrivateJson(jsonPath, buildLaunchAgentPlist(config, paths));
|
|
41
|
+
try {
|
|
42
|
+
await this.runRequired("plutil", ["-convert", "xml1", "-o", plistTempPath, jsonPath]);
|
|
43
|
+
await this.runRequired("plutil", ["-lint", plistTempPath]);
|
|
44
|
+
await chmod(plistTempPath, 0o600);
|
|
45
|
+
if ((await this.inspectJob()).loaded) {
|
|
46
|
+
await this.runRequired("launchctl", ["bootout", this.serviceTarget]);
|
|
47
|
+
await this.waitForServiceExit(previousState?.pid);
|
|
48
|
+
}
|
|
49
|
+
await rename(plistTempPath, paths.plistPath);
|
|
50
|
+
await chmod(paths.plistPath, 0o600);
|
|
51
|
+
await writePrivateJson(paths.configPath, config);
|
|
52
|
+
await Promise.all([removeIfExists(paths.statePath), removeIfExists(paths.urlPath)]);
|
|
53
|
+
await this.bootstrap(paths.plistPath);
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
await Promise.all([removeIfExists(jsonPath), removeIfExists(plistTempPath)]);
|
|
57
|
+
}
|
|
58
|
+
return { paths, state: await this.waitForReady(paths), definition: paths.plistPath };
|
|
59
|
+
}
|
|
60
|
+
async start() {
|
|
61
|
+
const status = await this.status();
|
|
62
|
+
if (!status.installed)
|
|
63
|
+
throw new Error("AgentRoam service is not installed");
|
|
64
|
+
const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
|
|
65
|
+
if (status.running)
|
|
66
|
+
return this.waitForReady(paths);
|
|
67
|
+
if (status.loaded)
|
|
68
|
+
await this.runRequired("launchctl", ["kickstart", this.serviceTarget]);
|
|
69
|
+
else
|
|
70
|
+
await this.bootstrap(status.definition);
|
|
71
|
+
return this.waitForReady(paths, status.state?.pid);
|
|
72
|
+
}
|
|
73
|
+
async stop() {
|
|
74
|
+
const status = await this.status();
|
|
75
|
+
if (!status.installed)
|
|
76
|
+
throw new Error("AgentRoam service is not installed");
|
|
77
|
+
if (!status.loaded)
|
|
78
|
+
return;
|
|
79
|
+
await this.runRequired("launchctl", ["bootout", this.serviceTarget]);
|
|
80
|
+
if (status.state?.pid)
|
|
81
|
+
await this.waitForProcessExit(status.state.pid);
|
|
82
|
+
}
|
|
83
|
+
async status() {
|
|
84
|
+
const basePaths = resolveServicePaths(this.homeDir);
|
|
85
|
+
const config = await readServiceConfig(basePaths);
|
|
86
|
+
const paths = resolveServicePaths(this.homeDir, config?.dataDir);
|
|
87
|
+
const installed = await pathExists(paths.plistPath);
|
|
88
|
+
const job = installed ? await this.inspectJob() : { loaded: false, running: false, pid: undefined };
|
|
89
|
+
const state = await readServiceState(paths);
|
|
90
|
+
return {
|
|
91
|
+
installed,
|
|
92
|
+
loaded: job.loaded,
|
|
93
|
+
running: job.running,
|
|
94
|
+
config,
|
|
95
|
+
state: job.running && state?.pid !== job.pid ? null : state,
|
|
96
|
+
definition: paths.plistPath,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async url() {
|
|
100
|
+
const status = await this.status();
|
|
101
|
+
if (!status.installed)
|
|
102
|
+
throw new Error("AgentRoam service is not installed");
|
|
103
|
+
if (!status.running)
|
|
104
|
+
throw new Error("AgentRoam service is installed but not running");
|
|
105
|
+
if (status.state?.status !== "ready" || !status.state.accessUrl) {
|
|
106
|
+
throw new Error("AgentRoam service is still starting; try again shortly");
|
|
107
|
+
}
|
|
108
|
+
const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
|
|
109
|
+
const value = (await readFile(paths.urlPath, "utf8")).trim();
|
|
110
|
+
if (!value || value !== status.state.accessUrl)
|
|
111
|
+
throw new Error("AgentRoam service URL is unavailable or stale");
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
async logs(maxBytes = 64 * 1024) {
|
|
115
|
+
const basePaths = resolveServicePaths(this.homeDir);
|
|
116
|
+
const config = await readServiceConfig(basePaths);
|
|
117
|
+
const paths = resolveServicePaths(this.homeDir, config?.dataDir);
|
|
118
|
+
const [stdout, stderr] = await Promise.all([
|
|
119
|
+
readTail(paths.stdoutPath, maxBytes),
|
|
120
|
+
readTail(paths.stderrPath, maxBytes),
|
|
121
|
+
]);
|
|
122
|
+
return { stdoutPath: paths.stdoutPath, stderrPath: paths.stderrPath, stdout, stderr };
|
|
123
|
+
}
|
|
124
|
+
async restart() {
|
|
125
|
+
const status = await this.status();
|
|
126
|
+
if (!status.installed)
|
|
127
|
+
throw new Error("AgentRoam service is not installed");
|
|
128
|
+
if (status.loaded)
|
|
129
|
+
await this.runRequired("launchctl", ["kickstart", "-k", this.serviceTarget]);
|
|
130
|
+
else
|
|
131
|
+
await this.bootstrap(status.definition);
|
|
132
|
+
const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
|
|
133
|
+
return this.waitForReady(paths, status.state?.pid);
|
|
134
|
+
}
|
|
135
|
+
async uninstall() {
|
|
136
|
+
const basePaths = resolveServicePaths(this.homeDir);
|
|
137
|
+
const config = await readServiceConfig(basePaths);
|
|
138
|
+
const paths = resolveServicePaths(this.homeDir, config?.dataDir);
|
|
139
|
+
const installed = await pathExists(paths.plistPath);
|
|
140
|
+
const state = await readServiceState(paths);
|
|
141
|
+
if ((await this.inspectJob()).loaded) {
|
|
142
|
+
await this.runRequired("launchctl", ["bootout", this.serviceTarget]);
|
|
143
|
+
if (state?.pid)
|
|
144
|
+
await this.waitForProcessExit(state.pid);
|
|
145
|
+
}
|
|
146
|
+
await Promise.all([
|
|
147
|
+
removeIfExists(paths.plistPath),
|
|
148
|
+
removeIfExists(paths.configPath),
|
|
149
|
+
removeIfExists(paths.statePath),
|
|
150
|
+
removeIfExists(paths.urlPath),
|
|
151
|
+
]);
|
|
152
|
+
return { removed: installed || Boolean(config), preservedDataDir: paths.dataDir };
|
|
153
|
+
}
|
|
154
|
+
get domainTarget() {
|
|
155
|
+
return `gui/${this.uid}`;
|
|
156
|
+
}
|
|
157
|
+
get serviceTarget() {
|
|
158
|
+
return `${this.domainTarget}/${SERVICE_LABEL}`;
|
|
159
|
+
}
|
|
160
|
+
async inspectJob() {
|
|
161
|
+
const result = await this.runner("launchctl", ["print", this.serviceTarget]);
|
|
162
|
+
const pid = /\bpid\s*=\s*(\d+)\b/.exec(result.stdout);
|
|
163
|
+
return {
|
|
164
|
+
loaded: result.code === 0,
|
|
165
|
+
running: result.code === 0 && /\bstate\s*=\s*running\b/.test(result.stdout),
|
|
166
|
+
pid: pid ? Number(pid[1]) : undefined,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
async bootstrap(definition) {
|
|
170
|
+
await this.runRequired("launchctl", ["enable", this.serviceTarget]);
|
|
171
|
+
await this.runRequired("launchctl", ["bootstrap", this.domainTarget, definition]);
|
|
172
|
+
}
|
|
173
|
+
async runRequired(command, args) {
|
|
174
|
+
const result = await this.runner(command, args);
|
|
175
|
+
if (result.code !== 0) {
|
|
176
|
+
const detail = result.stderr.trim() || result.stdout.trim() || `exit ${result.code}`;
|
|
177
|
+
throw new Error(`${command} ${args[0] ?? ""} failed: ${detail}`);
|
|
178
|
+
}
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
181
|
+
async validateConfig(config) {
|
|
182
|
+
if (!config.nodePath.startsWith("/") || !config.cliPath.startsWith("/")) {
|
|
183
|
+
throw new Error("AgentRoam service requires absolute Node and CLI paths");
|
|
184
|
+
}
|
|
185
|
+
if (config.cliPath.split("/").includes("_npx")) {
|
|
186
|
+
throw new Error("service install cannot use an npx temporary package; install AgentRoam with npm install -g first");
|
|
187
|
+
}
|
|
188
|
+
await Promise.all([
|
|
189
|
+
access(config.nodePath, constants.X_OK),
|
|
190
|
+
access(config.cliPath, constants.R_OK),
|
|
191
|
+
...(config.codexPath ? [access(config.codexPath, constants.X_OK)] : []),
|
|
192
|
+
...config.roots.map(async (root) => {
|
|
193
|
+
if (!(await stat(root)).isDirectory())
|
|
194
|
+
throw new Error(`service root is not a directory: ${root}`);
|
|
195
|
+
}),
|
|
196
|
+
]);
|
|
197
|
+
}
|
|
198
|
+
async waitForReady(paths, previousPid) {
|
|
199
|
+
const deadline = Date.now() + this.readyTimeoutMs;
|
|
200
|
+
do {
|
|
201
|
+
const state = await readServiceState(paths);
|
|
202
|
+
if (state?.status === "ready" && state.accessUrl && (!previousPid || state.pid !== previousPid)) {
|
|
203
|
+
const job = await this.inspectJob();
|
|
204
|
+
if (job.running && job.pid === state.pid)
|
|
205
|
+
return state;
|
|
206
|
+
}
|
|
207
|
+
if (Date.now() >= deadline)
|
|
208
|
+
return state?.status === "ready" ? null : state;
|
|
209
|
+
await delay(this.pollIntervalMs);
|
|
210
|
+
} while (true);
|
|
211
|
+
}
|
|
212
|
+
async waitForProcessExit(pid) {
|
|
213
|
+
const deadline = Date.now() + this.stopTimeoutMs;
|
|
214
|
+
while (this.processExists(pid)) {
|
|
215
|
+
if (Date.now() >= deadline)
|
|
216
|
+
throw new Error(`service process ${pid} did not stop after launchctl bootout`);
|
|
217
|
+
await delay(this.pollIntervalMs);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async waitForServiceExit(pid) {
|
|
221
|
+
const deadline = Date.now() + this.stopTimeoutMs;
|
|
222
|
+
do {
|
|
223
|
+
const processRunning = pid ? this.processExists(pid) : false;
|
|
224
|
+
const job = await this.inspectJob();
|
|
225
|
+
if (!processRunning && !job.loaded)
|
|
226
|
+
return;
|
|
227
|
+
if (Date.now() >= deadline) {
|
|
228
|
+
if (processRunning)
|
|
229
|
+
throw new Error(`service process ${pid} did not stop after launchctl bootout`);
|
|
230
|
+
throw new Error(`service ${SERVICE_LABEL} did not unload after launchctl bootout`);
|
|
231
|
+
}
|
|
232
|
+
await delay(this.pollIntervalMs);
|
|
233
|
+
} while (true);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
export function buildLaunchAgentPlist(config, paths) {
|
|
237
|
+
const environmentVariables = {
|
|
238
|
+
AGENTROAM_SERVICE: "1",
|
|
239
|
+
PATH: config.environmentPath || `${dirname(config.nodePath)}:/usr/bin:/bin:/usr/sbin:/sbin`,
|
|
240
|
+
};
|
|
241
|
+
if (config.codexPath)
|
|
242
|
+
environmentVariables.AGENT_CODEX_BIN = config.codexPath;
|
|
243
|
+
if (config.codexHome)
|
|
244
|
+
environmentVariables.CODEX_HOME = config.codexHome;
|
|
245
|
+
return {
|
|
246
|
+
Label: SERVICE_LABEL,
|
|
247
|
+
ProgramArguments: buildStartArguments(config),
|
|
248
|
+
WorkingDirectory: config.roots[0],
|
|
249
|
+
EnvironmentVariables: environmentVariables,
|
|
250
|
+
RunAtLoad: true,
|
|
251
|
+
KeepAlive: true,
|
|
252
|
+
ThrottleInterval: 5,
|
|
253
|
+
StandardOutPath: paths.stdoutPath,
|
|
254
|
+
StandardErrorPath: paths.stderrPath,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
async function pathExists(path) {
|
|
258
|
+
try {
|
|
259
|
+
await access(path);
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function isProcessRunning(pid) {
|
|
267
|
+
try {
|
|
268
|
+
process.kill(pid, 0);
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
return error.code === "EPERM";
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
async function readTail(path, maxBytes) {
|
|
276
|
+
try {
|
|
277
|
+
const value = await readFile(path);
|
|
278
|
+
return value.subarray(Math.max(0, value.length - maxBytes)).toString("utf8");
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
if (error.code === "ENOENT")
|
|
282
|
+
return "";
|
|
283
|
+
throw error;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function delay(timeoutMs) {
|
|
287
|
+
return new Promise((resolveDelay) => setTimeout(resolveDelay, timeoutMs));
|
|
288
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { readServiceState, removeIfExists, writePrivateJson, writePrivateText, } from "./service-files.js";
|
|
2
|
+
export class ServiceRuntimeReporter {
|
|
3
|
+
paths;
|
|
4
|
+
version;
|
|
5
|
+
pid;
|
|
6
|
+
now;
|
|
7
|
+
startedAt;
|
|
8
|
+
constructor(paths, version, pid = process.pid, now = () => new Date()) {
|
|
9
|
+
this.paths = paths;
|
|
10
|
+
this.version = version;
|
|
11
|
+
this.pid = pid;
|
|
12
|
+
this.now = now;
|
|
13
|
+
this.startedAt = this.now().toISOString();
|
|
14
|
+
}
|
|
15
|
+
async starting() {
|
|
16
|
+
await removeIfExists(this.paths.urlPath);
|
|
17
|
+
await this.write({ status: "starting" });
|
|
18
|
+
}
|
|
19
|
+
async localReady(localUrl) {
|
|
20
|
+
await this.write({ status: "starting", localUrl });
|
|
21
|
+
}
|
|
22
|
+
async ready(ready) {
|
|
23
|
+
await this.write({ status: "ready", ...ready });
|
|
24
|
+
await writePrivateText(this.paths.urlPath, `${ready.accessUrl}\n`);
|
|
25
|
+
}
|
|
26
|
+
async stopped() {
|
|
27
|
+
const current = await readServiceState(this.paths);
|
|
28
|
+
if (!current || current.pid !== this.pid)
|
|
29
|
+
return false;
|
|
30
|
+
await this.write({ status: "stopped" });
|
|
31
|
+
await removeIfExists(this.paths.urlPath);
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
async write(details) {
|
|
35
|
+
await writePrivateJson(this.paths.statePath, {
|
|
36
|
+
pid: this.pid,
|
|
37
|
+
version: this.version,
|
|
38
|
+
startedAt: this.startedAt,
|
|
39
|
+
updatedAt: this.now().toISOString(),
|
|
40
|
+
...details,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
}
|