agentroam 0.2.0-preview.7 → 0.2.0-preview.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -15
- package/bin/agentroam.mjs +10 -1
- package/bin/cli-progress.d.mts +9 -0
- package/bin/cli-progress.mjs +65 -0
- package/bin/desktop-download.mjs +69 -0
- package/bin/node-preflight.mjs +171 -0
- package/bin/node-runtime-policy.json +4 -0
- package/bin/runtime-policy.d.mts +5 -0
- package/bin/runtime-policy.mjs +37 -0
- package/dist/abort.js +25 -0
- package/dist/args.js +102 -3
- package/dist/cli.js +244 -44
- package/dist/cloudflared/bundled-asset.js +3 -2
- package/dist/cloudflared/manifest.js +2 -2
- package/dist/codex-desktop-command.js +70 -0
- package/dist/codex-desktop-force-stop.js +46 -0
- package/dist/codex-desktop-idle-guard.js +15 -0
- package/dist/codex-desktop-preflight.js +63 -0
- package/dist/codex-desktop-probe.js +152 -0
- package/dist/codex-desktop-setup.js +154 -0
- package/dist/codex-desktop-status.js +85 -0
- package/dist/codex-desktop-windows.js +122 -0
- package/dist/codex-runtime-manager.js +368 -0
- package/dist/codex-sharing.js +153 -0
- package/dist/codex-windows-backend-host.js +59 -0
- package/dist/codex-windows-backend.js +120 -0
- package/dist/desktop-authorization-prompt.js +84 -0
- package/dist/desktop-authorization.js +161 -0
- package/dist/device-pairing.js +170 -0
- package/dist/error-log.js +113 -0
- package/dist/instance-takeover.js +143 -0
- package/dist/local-desktop-url.js +8 -0
- package/dist/local-service-request.js +69 -0
- package/dist/native-runtime.js +68 -0
- package/dist/network.js +32 -3
- package/dist/node-runtime-manager.js +251 -0
- package/dist/opencode-runtime-manager.js +239 -0
- package/dist/platform-packages.js +16 -5
- package/dist/platform.js +6 -4
- package/dist/power/sleep-inhibitor.js +161 -0
- package/dist/runtime-manager.js +130 -19
- package/dist/service/launcher-cleanup.js +79 -0
- package/dist/service/macos-launch-agent.js +288 -0
- package/dist/service/runtime-state.js +43 -0
- package/dist/service/service-command.js +219 -0
- package/dist/service/service-controller.js +27 -0
- package/dist/service/service-files.js +78 -0
- package/dist/service/windows-service-host.js +59 -0
- package/dist/service/windows-task-service.js +289 -0
- package/dist/startup-lock.js +81 -0
- package/dist/tunnel/cloudflare-provider.js +4 -1
- package/dist/tunnel/public-readiness.js +76 -50
- package/dist/tunnel/relay-orchestrator.js +31 -9
- package/dist/tunnel/tunnel-controller.js +144 -0
- package/dist/unlock-service.js +105 -0
- package/dist/update/update-channel.js +38 -0
- package/dist/update/update-command.js +96 -0
- package/dist/update/update-install.js +34 -0
- package/dist/update/update-state.js +43 -0
- package/dist/update/update-worker.js +80 -0
- package/install/README.md +55 -0
- package/install/codex-shared-watchdog.sh +16 -0
- package/install/install-agentroam.ps1 +358 -0
- package/install/install-agentroam.sh +457 -0
- package/install/install-manifest.json +15 -0
- package/install/start-codex-desktop-shared.sh +152 -0
- package/package.json +13 -10
- package/dist/args.test.js +0 -27
- package/dist/cloudflared/bundled-asset.test.js +0 -76
- package/dist/cloudflared/installer.test.js +0 -95
- package/dist/native-runtime.test.js +0 -19
- package/dist/network.test.js +0 -20
- package/dist/pairing.js +0 -2
- package/dist/platform-packages.test.js +0 -75
- package/dist/platform.test.js +0 -3
- package/dist/port.test.js +0 -3
- package/dist/process-supervisor.test.js +0 -42
- package/dist/tunnel/cloudflare-provider.test.js +0 -33
- package/dist/tunnel/pinggy-provider.test.js +0 -40
- package/dist/tunnel/proxy-settings.test.js +0 -111
- package/dist/tunnel/public-readiness.test.js +0 -104
- package/dist/tunnel/relay-orchestrator.test.js +0 -72
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { printLocalDesktopUrl } from '../local-desktop-url.js';
|
|
2
|
+
import { delimiter, dirname, isAbsolute, resolve, win32 } from "node:path";
|
|
3
|
+
import { resolveCodexRuntime } from "../codex-runtime-manager.js";
|
|
4
|
+
import { detectPlatform } from "../platform.js";
|
|
5
|
+
import { printPairingCode } from "../device-pairing.js";
|
|
6
|
+
import { renderQr } from "../qr.js";
|
|
7
|
+
import { MacLaunchAgent } from "./macos-launch-agent.js";
|
|
8
|
+
import { WindowsTaskService } from "./windows-task-service.js";
|
|
9
|
+
import { assertSupportedNodeVersion } from "../../bin/runtime-policy.mjs";
|
|
10
|
+
import { cleanupOldLaunchers } from "./launcher-cleanup.js";
|
|
11
|
+
import { configureCodexSharing } from "../codex-sharing.js";
|
|
12
|
+
import { setupCodexDesktop } from "../codex-desktop-setup.js";
|
|
13
|
+
import { authorizeRemoteDesktop } from "../desktop-authorization.js";
|
|
14
|
+
import { withCliProgress } from "../../bin/cli-progress.mjs";
|
|
15
|
+
import { withTimeout } from "../abort.js";
|
|
16
|
+
export async function runServiceCommand(options, context) {
|
|
17
|
+
const platform = context.platform ?? process.platform;
|
|
18
|
+
const log = context.log ?? console.log;
|
|
19
|
+
const stdoutIsTTY = context.isTTY ?? process.stdout.isTTY === true;
|
|
20
|
+
const logAccessUrl = async (accessUrl) => {
|
|
21
|
+
log(`Open: ${accessUrl}`);
|
|
22
|
+
if (!options.qr || !stdoutIsTTY)
|
|
23
|
+
return;
|
|
24
|
+
log("");
|
|
25
|
+
log(await renderQr(accessUrl));
|
|
26
|
+
};
|
|
27
|
+
const controller = context.controller ?? context.launchAgent ?? createController(platform, context.homeDir);
|
|
28
|
+
switch (options.serviceAction) {
|
|
29
|
+
case "install": {
|
|
30
|
+
const nodeVersion = context.nodeVersion ?? process.versions.node;
|
|
31
|
+
assertSupportedNodeVersion(nodeVersion);
|
|
32
|
+
const now = context.now?.() ?? new Date();
|
|
33
|
+
const environment = context.environment ?? process.env;
|
|
34
|
+
const environmentPath = buildServiceEnvironmentPath(context.nodePath, environment.PATH ?? environment.Path, platform);
|
|
35
|
+
let codexPath;
|
|
36
|
+
try {
|
|
37
|
+
const codex = await withCliProgress("Checking Codex; the background service installs it if missing", () => withTimeout(signal => (context.codexResolver ?? resolveCodexRuntime)({
|
|
38
|
+
dataDir: options.dataDir,
|
|
39
|
+
target: detectPlatform(platform, context.arch ?? process.arch, nodeVersion),
|
|
40
|
+
environment: { ...environment, PATH: environmentPath },
|
|
41
|
+
platform,
|
|
42
|
+
nodeExecutable: context.nodePath,
|
|
43
|
+
installIfMissing: false,
|
|
44
|
+
signal,
|
|
45
|
+
onProgress: (message) => log(`… ${message}`),
|
|
46
|
+
}), 60_000, "Codex check timed out; the background service will continue checking."));
|
|
47
|
+
codexPath = codex.executable;
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
log(`Codex will be checked and installed during service startup: ${error instanceof Error ? error.message : error}`);
|
|
51
|
+
}
|
|
52
|
+
const config = {
|
|
53
|
+
version: context.version,
|
|
54
|
+
nodePath: context.nodePath,
|
|
55
|
+
cliPath: context.cliPath,
|
|
56
|
+
environmentPath,
|
|
57
|
+
...(codexPath ? { codexPath } : {}),
|
|
58
|
+
...(environment.CODEX_HOME?.trim() ? { codexHome: resolve(environment.CODEX_HOME.trim()) } : {}),
|
|
59
|
+
roots: options.roots,
|
|
60
|
+
port: options.port,
|
|
61
|
+
relay: options.relay,
|
|
62
|
+
tunnelCommand: options.tunnelCommand,
|
|
63
|
+
localOnly: options.localOnly,
|
|
64
|
+
dataDir: options.dataDir,
|
|
65
|
+
installedAt: now.toISOString(),
|
|
66
|
+
};
|
|
67
|
+
if (platform === "darwin" && codexPath) {
|
|
68
|
+
try {
|
|
69
|
+
await withTimeout(signal => (context.configureSharing ?? configureCodexSharing)(options, {
|
|
70
|
+
homeDir: context.homeDir, environment: { ...environment, PATH: environmentPath, AGENT_CODEX_BIN: codexPath }, signal,
|
|
71
|
+
}), 10_000, "Codex sharing setup timed out (10 seconds)");
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
log(`Codex sharing setup incomplete; repair it from the computer menu: ${error instanceof Error ? error.message : error}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const { definition, state } = await withCliProgress("Starting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.install(config));
|
|
78
|
+
log(`✓ AgentRoam service installed: ${definition}`);
|
|
79
|
+
if (state?.status !== "ready" && state?.localUrl)
|
|
80
|
+
printLocalDesktopUrl(state.localUrl, log, platform);
|
|
81
|
+
requireReadyService(state);
|
|
82
|
+
log(`Open: ${state.accessUrl}`);
|
|
83
|
+
if (state.localUrl)
|
|
84
|
+
printLocalDesktopUrl(state.localUrl, log, platform);
|
|
85
|
+
printLanFallback(state, log);
|
|
86
|
+
if (state?.localUrl && state.status !== "stopped" && (platform === "darwin" || platform === "win32")) {
|
|
87
|
+
if (environment.AGENTROAM_INSTALL_REMOTE_DESKTOP === "skip") {
|
|
88
|
+
log("Remote desktop authorization skipped. Run agentroam desktop authorize later.");
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
try {
|
|
92
|
+
await (context.desktopAuthorization ?? authorizeRemoteDesktop)(options.dataDir, { platform, isTTY: stdoutIsTTY, timeoutMs: 60_000, log });
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
log(`Remote desktop authorization incomplete: ${error instanceof Error ? error.message : error}`);
|
|
96
|
+
log("Installation continues. Retry with agentroam desktop authorize or the local browser authorization panel.");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (platform === "darwin" && !options.desktopSetup)
|
|
101
|
+
log("Codex Desktop sharing: agentroam codex-desktop --setup; preview: agentroam codex-desktop --dry-run.");
|
|
102
|
+
if (state.version === config.version)
|
|
103
|
+
await cleanupOldLaunchers(config, log);
|
|
104
|
+
if (options.desktopSetup && ["darwin", "win32"].includes(platform)) {
|
|
105
|
+
await withCliProgress("Configuring Codex Desktop sharing", () => (context.desktopSetup ?? setupCodexDesktop)(options, { platform, environment, service: config, log }));
|
|
106
|
+
}
|
|
107
|
+
await (context.pairingPrinter ?? printPairingCode)(options.dataDir, log, { accessUrl: state.accessUrl, qr: options.qr, interactive: stdoutIsTTY });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
case "start": {
|
|
111
|
+
const state = await withCliProgress("Starting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.start());
|
|
112
|
+
if (state?.status !== "ready" && state?.localUrl)
|
|
113
|
+
printLocalDesktopUrl(state.localUrl, log, platform);
|
|
114
|
+
requireReadyService(state);
|
|
115
|
+
log(`Open: ${state.accessUrl}`);
|
|
116
|
+
if (state.localUrl)
|
|
117
|
+
printLocalDesktopUrl(state.localUrl, log, platform);
|
|
118
|
+
printLanFallback(state, log);
|
|
119
|
+
log("✓ AgentRoam service started");
|
|
120
|
+
if (options.qr && stdoutIsTTY)
|
|
121
|
+
log(await renderQr(state.accessUrl));
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
case "stop":
|
|
125
|
+
await withCliProgress("Stopping background service", () => controller.stop());
|
|
126
|
+
log("✓ AgentRoam service stopped");
|
|
127
|
+
return;
|
|
128
|
+
case "status": {
|
|
129
|
+
const status = await controller.status();
|
|
130
|
+
if (!status.installed) {
|
|
131
|
+
log("AgentRoam service: not installed");
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
log(`AgentRoam service: ${status.running ? "running" : "installed but stopped"}`);
|
|
135
|
+
if (status.config) {
|
|
136
|
+
log(`Version: ${status.config.version}`);
|
|
137
|
+
log(`Root: ${status.config.roots.join(", ")}`);
|
|
138
|
+
}
|
|
139
|
+
if (status.running && status.state?.status !== "ready" && status.state?.localUrl)
|
|
140
|
+
printLocalDesktopUrl(status.state.localUrl, log, platform);
|
|
141
|
+
if (status.running && status.state?.status === "ready" && status.state.accessUrl) {
|
|
142
|
+
printLanFallback(status.state, log);
|
|
143
|
+
await logAccessUrl(status.state.accessUrl);
|
|
144
|
+
if (status.state.localUrl)
|
|
145
|
+
printLocalDesktopUrl(status.state.localUrl, log, platform);
|
|
146
|
+
}
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
case "url":
|
|
150
|
+
log(await controller.url());
|
|
151
|
+
return;
|
|
152
|
+
case "logs": {
|
|
153
|
+
const logs = await controller.logs();
|
|
154
|
+
log(`stdout: ${logs.stdoutPath}`);
|
|
155
|
+
if (logs.stdout)
|
|
156
|
+
log(logs.stdout.trimEnd());
|
|
157
|
+
log(`stderr: ${logs.stderrPath}`);
|
|
158
|
+
if (logs.stderr)
|
|
159
|
+
log(logs.stderr.trimEnd());
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
case "restart": {
|
|
163
|
+
const state = await withCliProgress("Restarting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.restart());
|
|
164
|
+
if (state?.status !== "ready" && state?.localUrl)
|
|
165
|
+
printLocalDesktopUrl(state.localUrl, log, platform);
|
|
166
|
+
requireReadyService(state);
|
|
167
|
+
log(`Open: ${state.accessUrl}`);
|
|
168
|
+
if (state.localUrl)
|
|
169
|
+
printLocalDesktopUrl(state.localUrl, log, platform);
|
|
170
|
+
printLanFallback(state, log);
|
|
171
|
+
log("✓ AgentRoam service restarted");
|
|
172
|
+
if (options.qr && stdoutIsTTY)
|
|
173
|
+
log(await renderQr(state.accessUrl));
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
case "uninstall": {
|
|
177
|
+
const result = await controller.uninstall();
|
|
178
|
+
log(result.removed ? "✓ AgentRoam service uninstalled" : "AgentRoam service was not installed");
|
|
179
|
+
log(`Application data preserved: ${result.preservedDataDir}`);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
default:
|
|
183
|
+
throw cliError("service action is required");
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
function printLanFallback(state, log) {
|
|
187
|
+
if (state.provider !== "lan")
|
|
188
|
+
return;
|
|
189
|
+
if (state.accessUrl && ["127.0.0.1", "localhost", "[::1]"].includes(new URL(state.accessUrl).hostname)) {
|
|
190
|
+
log("✓ Local access only. Connect to Wi-Fi or Ethernet and restart to enable phone access.");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
log("✓ Service ready on LAN. Connect your phone to the same network to pair.");
|
|
194
|
+
}
|
|
195
|
+
function requireReadyService(state) {
|
|
196
|
+
if (state?.status !== "ready" || !state.accessUrl) {
|
|
197
|
+
throw Object.assign(new Error(`AgentRoam service is not ready (${state?.status ?? "no state"}). Run agentroam service logs, fix the error, then run agentroam service start and agentroam pair.`), { exitCode: 1 });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
export function buildServiceEnvironmentPath(nodePath, pathValue, platform) {
|
|
201
|
+
const separator = platform === "win32" ? ";" : delimiter;
|
|
202
|
+
const nodeDirectory = platform === "win32" ? win32.dirname(nodePath) : dirname(nodePath);
|
|
203
|
+
const absolute = platform === "win32" ? win32.isAbsolute : isAbsolute;
|
|
204
|
+
const required = platform === "darwin" ? ["/usr/bin", "/bin", "/usr/sbin", "/sbin"] : [];
|
|
205
|
+
const entries = [nodeDirectory, ...(pathValue ?? "").split(separator), ...required]
|
|
206
|
+
.map((entry) => entry.trim())
|
|
207
|
+
.filter((entry) => entry && absolute(entry));
|
|
208
|
+
return [...new Set(entries)].join(separator);
|
|
209
|
+
}
|
|
210
|
+
function createController(platform, homeDir) {
|
|
211
|
+
if (platform === "darwin")
|
|
212
|
+
return new MacLaunchAgent({ homeDir });
|
|
213
|
+
if (platform === "win32")
|
|
214
|
+
return new WindowsTaskService({ homeDir });
|
|
215
|
+
throw cliError(`agentroam service is unavailable on ${platform}; supported platforms are macOS and Windows`);
|
|
216
|
+
}
|
|
217
|
+
function cliError(message) {
|
|
218
|
+
return Object.assign(new Error(message), { exitCode: 2 });
|
|
219
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
export function buildStartArguments(config) {
|
|
3
|
+
const args = [config.nodePath, config.cliPath, "start"];
|
|
4
|
+
for (const root of config.roots)
|
|
5
|
+
args.push("--root", root);
|
|
6
|
+
if (config.port !== null)
|
|
7
|
+
args.push("--port", String(config.port));
|
|
8
|
+
if (config.localOnly)
|
|
9
|
+
args.push("--local-only");
|
|
10
|
+
else
|
|
11
|
+
args.push("--relay", config.relay);
|
|
12
|
+
if (!config.localOnly && config.tunnelCommand)
|
|
13
|
+
args.push("--tunnel-command", config.tunnelCommand);
|
|
14
|
+
args.push("--data-dir", config.dataDir, "--no-qr");
|
|
15
|
+
return args;
|
|
16
|
+
}
|
|
17
|
+
export function runCommand(command, args) {
|
|
18
|
+
return new Promise((resolveResult, reject) => {
|
|
19
|
+
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
20
|
+
let stdout = "";
|
|
21
|
+
let stderr = "";
|
|
22
|
+
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
23
|
+
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
|
24
|
+
child.once("error", reject);
|
|
25
|
+
child.once("exit", (code) => resolveResult({ code: code ?? 1, stdout, stderr }));
|
|
26
|
+
});
|
|
27
|
+
}
|