@anhlp/alp-client 0.0.0-stage → 0.0.1-beta.10
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/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +45 -2
- package/dist/acp-probe.d.ts +45 -0
- package/dist/acp-probe.js +46 -0
- package/dist/antigravity-probe.d.ts +33 -0
- package/dist/antigravity-probe.js +101 -0
- package/dist/command.d.ts +5 -0
- package/dist/command.js +35 -0
- package/dist/doctor.d.ts +21 -0
- package/dist/doctor.js +850 -0
- package/dist/index.d.ts +216 -0
- package/dist/index.js +702 -0
- package/dist/integration-lock.d.ts +37 -0
- package/dist/integration-lock.js +199 -0
- package/dist/ipc.d.ts +42 -0
- package/dist/ipc.js +69 -0
- package/dist/library-test.d.ts +94 -0
- package/dist/library-test.js +37 -0
- package/dist/mcp-probe.d.ts +24 -0
- package/dist/mcp-probe.js +147 -0
- package/dist/portable.d.ts +20 -0
- package/dist/portable.js +36 -0
- package/dist/prompt.d.ts +32 -0
- package/dist/prompt.js +59 -0
- package/dist/render.d.ts +6 -0
- package/dist/render.js +123 -0
- package/dist/rpc/client.d.ts +82 -0
- package/dist/rpc/client.js +292 -0
- package/dist/rpc/errors.d.ts +42 -0
- package/dist/rpc/errors.js +34 -0
- package/dist/rpc/framing.d.ts +21 -0
- package/dist/rpc/framing.js +57 -0
- package/dist/rpc/handshake.d.ts +24 -0
- package/dist/rpc/handshake.js +10 -0
- package/dist/rpc/reconnect.d.ts +97 -0
- package/dist/rpc/reconnect.js +227 -0
- package/dist/rpc/registry.d.ts +227 -0
- package/dist/rpc/registry.js +223 -0
- package/dist/rpc/terminal-directory.d.ts +24 -0
- package/dist/rpc/terminal-directory.js +70 -0
- package/dist/rpc/timers.d.ts +11 -0
- package/dist/rpc/timers.js +11 -0
- package/dist/service.d.ts +50 -0
- package/dist/service.js +145 -0
- package/dist/setup.d.ts +8 -0
- package/dist/setup.js +273 -0
- package/dist/supervise.d.ts +14 -0
- package/dist/supervise.js +91 -0
- package/dist/websocket.d.ts +51 -0
- package/dist/websocket.js +190 -0
- package/package.json +174 -4
- package/src/acp-probe.js +53 -0
- package/src/antigravity-probe.js +113 -0
- package/src/command.js +20 -0
- package/src/doctor.d.ts +21 -0
- package/src/doctor.js +912 -0
- package/src/index.js +813 -0
- package/src/integration-lock.js +203 -0
- package/src/ipc.js +92 -0
- package/src/library-test.js +41 -0
- package/src/mcp-probe.js +118 -0
- package/src/portable.js +30 -0
- package/src/prompt.js +64 -0
- package/src/render.js +139 -0
- package/src/rpc/client.js +296 -0
- package/src/rpc/errors.js +54 -0
- package/src/rpc/framing.js +61 -0
- package/src/rpc/handshake.js +21 -0
- package/src/rpc/reconnect.js +226 -0
- package/src/rpc/registry.js +229 -0
- package/src/rpc/terminal-directory.js +61 -0
- package/src/rpc/timers.js +16 -0
- package/src/service.js +158 -0
- package/src/setup.js +316 -0
- package/src/supervise.d.ts +14 -0
- package/src/supervise.js +97 -0
- package/src/websocket.js +259 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,813 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
import { execFileSync, spawn } from 'node:child_process';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { fstatSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, chmod, rename, rmdir, link } from 'node:fs/promises';
|
|
6
|
+
import net from 'node:net';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
import { scrubText } from '@anhlp/alp-core/log';
|
|
11
|
+
import { entryCommand, isNativeDaemonName, NATIVE_DAEMON } from '@anhlp/alp-core/packaged';
|
|
12
|
+
import { dashboardSettings } from '@anhlp/alp-core/user-settings';
|
|
13
|
+
import { createSocketTransport } from './ipc.js';
|
|
14
|
+
import { AlpRpcClient } from './rpc/client.js';
|
|
15
|
+
import { hello } from './rpc/handshake.js';
|
|
16
|
+
export { PROTOCOL_VERSION, MAX_FRAME, AlpRpcError, encodeFrame } from '@anhlp/alp-protocol';
|
|
17
|
+
// The Node entry carries the whole portable API and the WebSocket transport too, so Node callers need one import.
|
|
18
|
+
export * from './portable.js';
|
|
19
|
+
export { connectWebSocket, createWebSocketTransport, redactUrl, CLOSE_CODE } from './websocket.js';
|
|
20
|
+
export { createSocketTransport } from './ipc.js';
|
|
21
|
+
|
|
22
|
+
export function alpHome(env = process.env) {
|
|
23
|
+
return path.resolve(env.ALP_HOME || path.join(os.homedir(), '.alp'));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Windows uses named pipes; long Unix homes get a short socket in the temp directory. */
|
|
27
|
+
export function daemonPaths(home) {
|
|
28
|
+
const preferred = path.join(home, 'alpd.sock');
|
|
29
|
+
const socket = process.platform === 'win32'
|
|
30
|
+
? `\\\\.\\pipe\\alpd-${createHash('sha256').update(home).digest('hex').slice(0, 24)}`
|
|
31
|
+
: Buffer.byteLength(preferred) < 100
|
|
32
|
+
? preferred
|
|
33
|
+
: path.join(os.tmpdir(), `alpd-${process.getuid?.() ?? 'user'}-${createHash('sha256').update(home).digest('hex').slice(0, 12)}`, 'rpc.sock');
|
|
34
|
+
return { home, lock: path.join(home, 'alpd.lock'), socket, log: path.join(home, 'logs', 'alpd.log'), install: path.join(home, 'alpd.json') };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** IPC trusts the OS user, not every local process. Existing unsafe directories fail closed.
|
|
38
|
+
* Windows mode bits do not describe named-pipe ACLs; those remain an OS deployment assumption. */
|
|
39
|
+
async function assertSafeAncestors(directory) {
|
|
40
|
+
if (process.platform === 'win32') return;
|
|
41
|
+
const absolute = path.isAbsolute(directory) ? directory : `${process.cwd()}/${directory}`;
|
|
42
|
+
let current = path.parse(absolute).root;
|
|
43
|
+
const pending = absolute.slice(current.length).split('/');
|
|
44
|
+
let links = 0;
|
|
45
|
+
// Follow every link expansion, including intermediate targets that realpath hides.
|
|
46
|
+
// Check a directory before entering it; never create beneath an unsafe parent.
|
|
47
|
+
while (pending.length) {
|
|
48
|
+
const part = pending.shift();
|
|
49
|
+
if (!part || part === '.') continue;
|
|
50
|
+
if (part === '..') { current = path.dirname(current); continue; }
|
|
51
|
+
const candidate = path.join(current, part);
|
|
52
|
+
const info = await lstat(candidate).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
53
|
+
if (!info) { current = candidate; continue; }
|
|
54
|
+
const trustedOwner = info.uid === 0 || info.uid === process.getuid?.();
|
|
55
|
+
if (!trustedOwner) throw new Error('IPC requires ancestors owned by the current user or root');
|
|
56
|
+
if (info.isSymbolicLink()) {
|
|
57
|
+
if (++links > 40) throw new Error('IPC ancestor symlink loop');
|
|
58
|
+
const target = await readlink(candidate);
|
|
59
|
+
if (path.isAbsolute(target)) current = path.parse(target).root;
|
|
60
|
+
pending.unshift(...target.slice(path.isAbsolute(target) ? path.parse(target).root.length : 0).split('/'));
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
// Sticky shared temp directories prevent users replacing each other's entries.
|
|
64
|
+
if (!info.isDirectory() || ((info.mode & 0o022) && !(info.mode & 0o1000))) {
|
|
65
|
+
throw new Error('IPC requires trusted ancestors without shared write permissions');
|
|
66
|
+
}
|
|
67
|
+
current = candidate;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function assertPrivateDirectory(directory, { create = false } = {}) {
|
|
72
|
+
await assertSafeAncestors(directory);
|
|
73
|
+
if (create) await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
74
|
+
let info = await lstat(directory);
|
|
75
|
+
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('IPC requires a private directory, not a symlink');
|
|
76
|
+
if (process.platform === 'win32') return;
|
|
77
|
+
const shown = JSON.stringify(directory);
|
|
78
|
+
const mine = (/** @type {import('node:fs').Stats} */ entry) => entry.isDirectory() && !entry.isSymbolicLink() && entry.uid === process.getuid?.();
|
|
79
|
+
if (info.uid !== process.getuid?.()) throw new Error(`IPC directory ${shown} must be owned by the current user (it belongs to uid ${info.uid}); use a directory of your own`);
|
|
80
|
+
if ((info.mode & 0o077) === 0) return;
|
|
81
|
+
// t-37f1: a directory the user made for ALP (mkdir, mktemp) and left at 0755 is still empty:
|
|
82
|
+
// ALP tightens it. One that holds anything is left alone, with the exact command to fix it.
|
|
83
|
+
if (create && (await readdir(directory)).length === 0) {
|
|
84
|
+
await chmod(directory, 0o700).catch(() => {});
|
|
85
|
+
}
|
|
86
|
+
// Re-read: another ALP process may have tightened it meanwhile (and filled it).
|
|
87
|
+
info = await lstat(directory);
|
|
88
|
+
if (mine(info) && (info.mode & 0o077) === 0) return;
|
|
89
|
+
// Single quotes, so the command is safe to paste into a POSIX shell.
|
|
90
|
+
const quoted = `'${directory.replaceAll("'", "'\\''")}'`;
|
|
91
|
+
throw new Error(`IPC directory ${shown} must have private permissions (0700), not ${(info.mode & 0o777).toString(8).padStart(4, '0')}; fix it with: chmod 700 ${quoted}`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function assertPrivateSocket(socketPath) {
|
|
95
|
+
if (process.platform === 'win32') return;
|
|
96
|
+
await assertPrivateDirectory(path.dirname(socketPath));
|
|
97
|
+
const info = await lstat(socketPath);
|
|
98
|
+
if (!info.isSocket() || info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0) {
|
|
99
|
+
throw new Error('IPC socket must be owned by the current user with private permissions (0600)');
|
|
100
|
+
}
|
|
101
|
+
return info;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const isFile = file => stat(file).then(info => info.isFile(), () => false);
|
|
105
|
+
|
|
106
|
+
/** Global bin directories that a GUI app's PATH may lack. */
|
|
107
|
+
const BIN_DIRECTORIES = [path.join(os.homedir(), '.alp', 'bin'), path.join(os.homedir(), '.npm-global', 'bin'), path.join(os.homedir(), '.local', 'bin'), '/opt/homebrew/bin', '/usr/local/bin'];
|
|
108
|
+
|
|
109
|
+
/** The npm package that ships the `alp` command and alpd. */
|
|
110
|
+
const CLI_PACKAGES = ['@anhlp/alp', '@anhlp/alp-cli'];
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* alpd behind an `alp` found on PATH (its real path), or undefined: the ALP bundle's launcher
|
|
114
|
+
* (<bundle>/bin/alp or alp.cmd, t-1807; its native alpd when it ships one, t-81b0.9, else its alpd.js), npm's @anhlp/alp-cli (dist/cli.js) or the @anhlp/alp wrapper (bin/alp.js),
|
|
115
|
+
* which depends on @anhlp/alp-cli (installed beside it, or in its own node_modules). On Windows an
|
|
116
|
+
* alp.cmd shim of npm or install.ps1 is followed to the script it runs (t-1f14).
|
|
117
|
+
* @param {string} cli @param {number} [depth] @param {NodeJS.ProcessEnv} [env]
|
|
118
|
+
*/
|
|
119
|
+
async function cliDaemonEntry(cli, depth = 0, env = process.env) {
|
|
120
|
+
const base = path.basename(cli).toLowerCase();
|
|
121
|
+
const root = path.resolve(path.dirname(cli), '..');
|
|
122
|
+
const alpd = directory => path.join(directory, 'dist', 'alpd.js');
|
|
123
|
+
const named = async directory => readFile(path.join(directory, 'package.json'), 'utf8').then(text => JSON.parse(text)?.name).catch(() => undefined);
|
|
124
|
+
let candidates = [];
|
|
125
|
+
if (base === 'alp.cmd' && depth < 1 && !await isFile(path.join(root, 'alp-bundle.json'))) {
|
|
126
|
+
// A Windows shim that is not the bundle's own: npm's ("%dp0%\node_modules\@anhlp\alp\bin\alp.js")
|
|
127
|
+
// or install.ps1's ("<root>\app\current\lib\node_modules\@anhlp\alp-cli\dist\cli.js"): follow the script it runs.
|
|
128
|
+
const text = await stat(cli).then(info => info.size <= 64 * 1024 ? readFile(cli, 'utf8') : '', () => '');
|
|
129
|
+
for (const [, quoted] of text.matchAll(/"([^"\r\n]+\.js)"/gi)) {
|
|
130
|
+
const script = quoted.replace(/^%~?dp0%?[\\/]?/i, `${path.dirname(cli)}${path.sep}`);
|
|
131
|
+
const entry = path.isAbsolute(script) && await isFile(script) ? await cliDaemonEntry(script, depth + 1, env) : undefined;
|
|
132
|
+
if (entry) return entry;
|
|
133
|
+
}
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
if (base === 'alp' || base === 'alp.cmd') {
|
|
137
|
+
// A bundle: bin/ beside alp-bundle.json; name alpd through app/current when that is this bundle.
|
|
138
|
+
if (!await isFile(path.join(root, 'alp-bundle.json'))) return undefined;
|
|
139
|
+
const current = path.join(path.dirname(root), 'current');
|
|
140
|
+
const viaCurrent = await realpath(current).then(real => real === root, () => false);
|
|
141
|
+
const bundle = viaCurrent ? current : root;
|
|
142
|
+
// The native alpd first (t-81b0.9), as the bundle's own `alp` starts it; alpd.js where it ships none.
|
|
143
|
+
candidates = [...(env.ALP_NATIVE_DAEMON === '0' ? [] : [path.join(bundle, 'bin', NATIVE_DAEMON)]), alpd(path.join(bundle, 'lib', 'node_modules', '@anhlp', 'alp-cli'))];
|
|
144
|
+
} else if (base === 'cli.js' && CLI_PACKAGES.includes(await named(root))) {
|
|
145
|
+
candidates = [alpd(root)];
|
|
146
|
+
} else if (base === 'alp.js' && await named(root) === '@anhlp/alp') {
|
|
147
|
+
candidates = [alpd(path.join(root, 'node_modules', '@anhlp', 'alp-cli')), alpd(path.join(root, '..', 'alp-cli'))];
|
|
148
|
+
}
|
|
149
|
+
for (const candidate of candidates) if (await isFile(candidate)) return candidate;
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Finds alpd.js for a client that cannot locate it beside itself, such as the Paseo
|
|
155
|
+
* plugin, which Paseo re-bundles: the first existing candidate, then where alpd last
|
|
156
|
+
* recorded itself ($ALP_HOME/alpd.json), then the ALP CLI (`alp`) on PATH and in the usual install
|
|
157
|
+
* directories (`binDirectories`; a test passes [] so the caller's own install is not found).
|
|
158
|
+
*/
|
|
159
|
+
export async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = /** @type {Array<string | undefined>} */ ([]), binDirectories = BIN_DIRECTORIES } = {}) {
|
|
160
|
+
for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
|
|
161
|
+
try {
|
|
162
|
+
const { entry } = JSON.parse(await readFile(daemonPaths(home).install, 'utf8'));
|
|
163
|
+
if (typeof entry === 'string' && await isFile(entry)) return entry;
|
|
164
|
+
} catch {}
|
|
165
|
+
for (const directory of [...(env.PATH ?? '').split(path.delimiter).filter(Boolean), ...binDirectories]) {
|
|
166
|
+
for (const name of process.platform === 'win32' ? ['alp.cmd', 'alp'] : ['alp']) {
|
|
167
|
+
const cli = await realpath(path.join(directory, name)).catch(() => undefined);
|
|
168
|
+
const entry = cli && await cliDaemonEntry(cli, 0, env);
|
|
169
|
+
if (entry) return entry;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return undefined;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Integration names are single lowercase path segments: they name `<home>/integrations/<name>.lock`,
|
|
177
|
+
* its guard and `<home>/<name>.json`. Returns the name, or throws a TypeError.
|
|
178
|
+
* @param {unknown} name
|
|
179
|
+
* @returns {string}
|
|
180
|
+
*/
|
|
181
|
+
export function assertIntegrationName(name) {
|
|
182
|
+
if (typeof name !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new TypeError(`Invalid integration name: ${JSON.stringify(name)}`);
|
|
183
|
+
return name;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let cachedBootId = null;
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Returns a stable identifier for the current OS boot session,
|
|
190
|
+
* or undefined if unavailable on the platform or inaccessible.
|
|
191
|
+
*
|
|
192
|
+
* On Linux, reads /proc/sys/kernel/random/boot_id.
|
|
193
|
+
* On Darwin (macOS), queries sysctl kern.bootsessionuuid.
|
|
194
|
+
*
|
|
195
|
+
* @returns {string | undefined}
|
|
196
|
+
*/
|
|
197
|
+
export function bootId() {
|
|
198
|
+
if (cachedBootId !== null) return cachedBootId;
|
|
199
|
+
try {
|
|
200
|
+
if (process.platform === 'linux') {
|
|
201
|
+
const id = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
|
202
|
+
if (id.length > 0) {
|
|
203
|
+
cachedBootId = id;
|
|
204
|
+
return cachedBootId;
|
|
205
|
+
}
|
|
206
|
+
} else if (process.platform === 'darwin') {
|
|
207
|
+
const id = execFileSync('sysctl', ['-n', 'kern.bootsessionuuid'], {
|
|
208
|
+
encoding: 'utf8',
|
|
209
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
210
|
+
timeout: 2000,
|
|
211
|
+
}).trim();
|
|
212
|
+
if (id.length > 0) {
|
|
213
|
+
cachedBootId = id;
|
|
214
|
+
return cachedBootId;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
} catch {
|
|
218
|
+
// Platform lacks boot id or procfs/sysctl is restricted; fall back gracefully.
|
|
219
|
+
}
|
|
220
|
+
cachedBootId = undefined;
|
|
221
|
+
return cachedBootId;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Internal/testing seam: resets or sets the cached boot identifier.
|
|
226
|
+
* @param {string | undefined | null} [id]
|
|
227
|
+
*/
|
|
228
|
+
export function _setBootIdForTest(id = null) {
|
|
229
|
+
cachedBootId = id;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Wall-clock boot time; a lock from an earlier boot is stale even if its pid is reused. */
|
|
233
|
+
export function bootTime() {
|
|
234
|
+
return Math.round((Date.now() - os.uptime() * 1000) / 1000);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Evaluates whether a lock record belongs to the current boot session.
|
|
239
|
+
*
|
|
240
|
+
* When both the lock and the current environment supply a bootId (Linux
|
|
241
|
+
* /proc/sys/kernel/random/boot_id or macOS kern.bootsessionuuid), identity is
|
|
242
|
+
* determined by exact bootId match, which is immune to wall-clock jumps.
|
|
243
|
+
*
|
|
244
|
+
* For legacy locks or environments without a bootId, falls back to checking
|
|
245
|
+
* whether wall-clock bootTime is within a 30-second window.
|
|
246
|
+
*
|
|
247
|
+
* @param {{ bootId?: string, bootTime?: number }} [lock]
|
|
248
|
+
* @param {{ bootId?: string, bootTime?: number }} [current]
|
|
249
|
+
* @returns {boolean}
|
|
250
|
+
*/
|
|
251
|
+
export function isSameBoot(lock, { bootId: curBootId = bootId(), bootTime: curBootTime = bootTime() } = {}) {
|
|
252
|
+
if (!lock) return false;
|
|
253
|
+
if (typeof lock.bootId === 'string' && lock.bootId.length > 0 && typeof curBootId === 'string' && curBootId.length > 0) {
|
|
254
|
+
return lock.bootId === curBootId;
|
|
255
|
+
}
|
|
256
|
+
if (typeof lock.bootTime === 'number' && Number.isFinite(lock.bootTime) && Number.isFinite(curBootTime)) {
|
|
257
|
+
return Math.abs(lock.bootTime - curBootTime) <= 30;
|
|
258
|
+
}
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export async function readLock(home) {
|
|
263
|
+
try {
|
|
264
|
+
return JSON.parse(await readFile(daemonPaths(home).lock, 'utf8'));
|
|
265
|
+
} catch (error) {
|
|
266
|
+
if (error?.code === 'ENOENT' || error instanceof SyntaxError) return undefined;
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function lockAlive(lock) {
|
|
272
|
+
if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
|
|
273
|
+
try {
|
|
274
|
+
process.kill(lock.pid, 0);
|
|
275
|
+
return true;
|
|
276
|
+
} catch (error) {
|
|
277
|
+
return error?.code === 'EPERM';
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Takes alpd's single-instance lock for `home`: exclusive create; a lock whose pid or boot is
|
|
283
|
+
* gone is stale and replaced. alpd takes it to run; `alp backup` and `alp restore` take it with
|
|
284
|
+
* `maintenance` set, so no alpd starts on data they read or replace (ALPD §68).
|
|
285
|
+
* @param {string} home
|
|
286
|
+
* @param {{ version: string, protocolVersion: number, socket: string, maintenance?: string }} contents
|
|
287
|
+
*/
|
|
288
|
+
export async function acquireDaemonLock(home, contents) {
|
|
289
|
+
const file = daemonPaths(home).lock;
|
|
290
|
+
const currentBootId = bootId();
|
|
291
|
+
const lock = {
|
|
292
|
+
pid: process.pid,
|
|
293
|
+
startedAt: new Date().toISOString(),
|
|
294
|
+
startedUptime: Math.floor(os.uptime()),
|
|
295
|
+
bootTime: bootTime(),
|
|
296
|
+
...(currentBootId ? { bootId: currentBootId } : {}),
|
|
297
|
+
uid: process.getuid?.() ?? -1,
|
|
298
|
+
ready: false,
|
|
299
|
+
...contents,
|
|
300
|
+
};
|
|
301
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
302
|
+
try {
|
|
303
|
+
const handle = await open(file, 'wx', 0o600);
|
|
304
|
+
// The identity of the file this call created, taken before anything can fail on it.
|
|
305
|
+
let ours;
|
|
306
|
+
try {
|
|
307
|
+
ours = await handle.stat();
|
|
308
|
+
await handle.writeFile(JSON.stringify(lock));
|
|
309
|
+
} catch (error) {
|
|
310
|
+
// Recover the descriptor identity if async fstat failed. Never infer ownership from
|
|
311
|
+
// the pathname: another process may already have replaced it. If both stats fail,
|
|
312
|
+
// leave the unreadable lock for explicit recovery rather than unlinking a successor.
|
|
313
|
+
if (!ours) { try { ours = fstatSync(handle.fd); } catch {} }
|
|
314
|
+
await handle.close().catch(() => {});
|
|
315
|
+
const there = await lstat(file).catch(() => undefined);
|
|
316
|
+
if (ours && there && ours.ino === there.ino && ours.dev === there.dev) await unlink(file).catch(() => {});
|
|
317
|
+
throw error;
|
|
318
|
+
}
|
|
319
|
+
await handle.close();
|
|
320
|
+
return lock;
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
323
|
+
const current = await readLock(home);
|
|
324
|
+
if (lockAlive(current)) throw new Error(current.maintenance ? `ALP is busy: alp ${current.maintenance} runs (pid ${current.pid}); try again when it finishes` : `ALP daemon already running (pid ${current.pid})`);
|
|
325
|
+
// Remove the stale lock only if nobody replaced it meanwhile. A lock that cannot be read may
|
|
326
|
+
// be one another start is writing now: it stays, and this start says so.
|
|
327
|
+
const again = await readFile(file, 'utf8').catch(() => undefined);
|
|
328
|
+
let parsed;
|
|
329
|
+
try { parsed = again === undefined ? undefined : JSON.parse(again); }
|
|
330
|
+
catch { throw new Error(`ALP daemon lock ${file} cannot be read: another start may be writing it. If no alpd or alp command is starting, remove it and try again`); }
|
|
331
|
+
if (again === undefined || JSON.stringify(current) === again || !lockAlive(parsed)) await unlink(file).catch(() => {});
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
throw new Error('Could not acquire the ALP daemon lock');
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Lets go of alpd's lock if this process holds it. */
|
|
338
|
+
export async function releaseDaemonLock(home) {
|
|
339
|
+
const current = await readLock(home);
|
|
340
|
+
if (current?.pid === process.pid) await unlink(daemonPaths(home).lock).catch(() => {});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* One JSON-RPC 2.0 connection to alpd over a Unix socket or named pipe; events arrive as `event`
|
|
345
|
+
* notifications. The engine is the portable AlpRpcClient; this keeps the socket constructor the
|
|
346
|
+
* CLI, alpd's tests and the Paseo plugin use.
|
|
347
|
+
*/
|
|
348
|
+
export class AlpClient extends AlpRpcClient {
|
|
349
|
+
/** Host features captured by connect's handshake. @type {readonly string[]} */
|
|
350
|
+
capabilities = [];
|
|
351
|
+
/** Limits captured by connect's handshake. @type {import('@anhlp/alp-protocol').AttachmentLimits | undefined} */
|
|
352
|
+
attachmentLimits;
|
|
353
|
+
/** @type {{ readonly maxCount: number; readonly maxBytes: number; readonly maxTotalBytes: number } | undefined} */
|
|
354
|
+
promptImageLimits;
|
|
355
|
+
/** @type {import('@anhlp/alp-protocol').TerminalLimits | undefined} */
|
|
356
|
+
terminalLimits;
|
|
357
|
+
/**
|
|
358
|
+
* @param {import('node:net').Socket} socket a connected or connecting socket; the client owns it
|
|
359
|
+
* @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
|
|
360
|
+
*/
|
|
361
|
+
constructor(socket, { maxFrame, maxBufferedBytes, ...options } = {}) {
|
|
362
|
+
super(createSocketTransport(socket, { maxFrame, maxBufferedBytes }), { maxFrame, ...options });
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** A socket to alpd, once it is checked to be private to this user (the IPC checks above). @param {string} socketPath */
|
|
367
|
+
async function openSocket(socketPath) {
|
|
368
|
+
await assertPrivateSocket(socketPath);
|
|
369
|
+
return /** @type {Promise<import('node:net').Socket>} */ (new Promise((resolve, reject) => {
|
|
370
|
+
const candidate = net.createConnection(socketPath);
|
|
371
|
+
candidate.once('connect', () => { candidate.off('error', reject); resolve(candidate); });
|
|
372
|
+
candidate.once('error', reject);
|
|
373
|
+
}));
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* The transport to alpd's socket without the handshake, for an AlpRpcClient or a reconnecting
|
|
378
|
+
* client whose onConnect runs `hello`. `connect` is this plus `hello`.
|
|
379
|
+
* @param {string} socketPath
|
|
380
|
+
* @param {import('./ipc.js').SocketTransportOptions} [options]
|
|
381
|
+
*/
|
|
382
|
+
export async function connectSocket(socketPath, options) {
|
|
383
|
+
return createSocketTransport(await openSocket(socketPath), options);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Connects and performs the version handshake.
|
|
388
|
+
* @param {string} socketPath
|
|
389
|
+
* @param {{ name: string, version: string }} [client]
|
|
390
|
+
* @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
|
|
391
|
+
* @returns {Promise<AlpClient>}
|
|
392
|
+
*/
|
|
393
|
+
export async function connect(socketPath, client = { name: 'alp', version: '0' }, options = {}) {
|
|
394
|
+
const connection = new AlpClient(await openSocket(socketPath), options);
|
|
395
|
+
try {
|
|
396
|
+
const greeting = await hello(connection, client, undefined, { agent: typeof process.env.ALP_AGENT_SESSION === 'string' && process.env.ALP_AGENT_SESSION !== '' });
|
|
397
|
+
connection.capabilities = Object.freeze(Array.isArray(greeting.capabilities) ? greeting.capabilities.filter(value => typeof value === 'string') : []);
|
|
398
|
+
if (greeting.attachmentLimits && typeof greeting.attachmentLimits === 'object') {
|
|
399
|
+
connection.attachmentLimits = Object.freeze({ ...greeting.attachmentLimits });
|
|
400
|
+
}
|
|
401
|
+
if (greeting.promptImageLimits && typeof greeting.promptImageLimits === 'object') {
|
|
402
|
+
connection.promptImageLimits = Object.freeze({ ...greeting.promptImageLimits });
|
|
403
|
+
}
|
|
404
|
+
if (greeting.terminalLimits && typeof greeting.terminalLimits === 'object') {
|
|
405
|
+
connection.terminalLimits = Object.freeze({ ...greeting.terminalLimits });
|
|
406
|
+
}
|
|
407
|
+
} catch (error) {
|
|
408
|
+
connection.close();
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
return connection;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Why a launcher failed, from the last structured log line it wrote to stderr: code and message, scrubbed. */
|
|
415
|
+
function launcherReason(text) {
|
|
416
|
+
const line = text.trim().split('\n').filter(Boolean).at(-1);
|
|
417
|
+
if (!line) return '';
|
|
418
|
+
let reason = line;
|
|
419
|
+
try {
|
|
420
|
+
const record = JSON.parse(line);
|
|
421
|
+
reason = `${record.code ? `${record.code}, ` : ''}${record.msg}${record.error?.message ? `: ${record.error.message}` : ''}`;
|
|
422
|
+
} catch {}
|
|
423
|
+
return `: ${scrubText(reason, { max: 600 })}`;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function tail(file, lines = 30) {
|
|
427
|
+
// The tail goes into an error message, so it is scrubbed like every other log output.
|
|
428
|
+
try { return scrubText((await readFile(file, 'utf8')).split('\n').slice(-lines).join('\n'), { max: 8000 }); } catch { return ''; }
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Immutable admission identities live in filenames, including for service hard links. */
|
|
432
|
+
async function lifecycleOwners(home) {
|
|
433
|
+
const directory = path.join(home, 'state', 'alpd.starting');
|
|
434
|
+
const names = await readdir(directory).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
|
|
435
|
+
return names.map(token => {
|
|
436
|
+
const match = /^owner-(\d+)-(\d+)-(start|stop)-[a-f0-9-]+$/.exec(token);
|
|
437
|
+
if (!match) throw new Error('Invalid alpd startup admission owner');
|
|
438
|
+
return { token, pid: Number(match[1]), bootTime: Number(match[2]), action: match[3] };
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
export async function readDaemonLifecycle(home) {
|
|
443
|
+
return (await lifecycleOwners(home)).find(owner => lockAlive(owner));
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** Serializes requested starts and stops, including the time before alpd has a lock.
|
|
447
|
+
* Rename publishes a fully populated directory: an existing nonempty directory cannot
|
|
448
|
+
* be replaced. Reaping/release unlinks only its unique owner token, then rmdir; even
|
|
449
|
+
* racing stale reapers cannot remove a successor's nonempty directory.
|
|
450
|
+
*/
|
|
451
|
+
export async function withDaemonLifecycle(home, action, run, { joinStart = false, signal = /** @type {AbortSignal | undefined} */ (undefined) } = {}) {
|
|
452
|
+
signal?.throwIfAborted();
|
|
453
|
+
try {
|
|
454
|
+
await assertPrivateDirectory(home, { create: true });
|
|
455
|
+
} catch (cause) {
|
|
456
|
+
// Admission now prepares the home before the launcher can report this failure.
|
|
457
|
+
// Preserve the operator-facing startup code at this earlier boundary.
|
|
458
|
+
throw Object.assign(new Error(`ALP_HOME_UNUSABLE, alpd failed to start while preparing its home: ${cause.message}`, { cause }), { code: 'ALP_HOME_UNUSABLE' });
|
|
459
|
+
}
|
|
460
|
+
const state = path.join(home, 'state');
|
|
461
|
+
await assertPrivateDirectory(state, { create: true });
|
|
462
|
+
const directory = path.join(state, 'alpd.starting');
|
|
463
|
+
const currentBootId = bootId();
|
|
464
|
+
const token = `owner-${process.pid}-${bootTime()}-${action}-${randomUUID()}`;
|
|
465
|
+
const candidate = path.join(state, `alpd.starting-${token}`);
|
|
466
|
+
await mkdir(candidate, { mode: 0o700 });
|
|
467
|
+
await writeFile(path.join(candidate, token), JSON.stringify({
|
|
468
|
+
pid: process.pid,
|
|
469
|
+
bootTime: bootTime(),
|
|
470
|
+
...(currentBootId ? { bootId: currentBootId } : {}),
|
|
471
|
+
startedUptime: Math.floor(os.uptime()),
|
|
472
|
+
action,
|
|
473
|
+
}), { mode: 0o600 });
|
|
474
|
+
try {
|
|
475
|
+
let joined = false;
|
|
476
|
+
if (joinStart) {
|
|
477
|
+
const owner = await readDaemonLifecycle(home);
|
|
478
|
+
if (owner?.action === 'start') {
|
|
479
|
+
try {
|
|
480
|
+
// Linking the unique source token both validates this generation and
|
|
481
|
+
// pins its directory until this service has finished starting.
|
|
482
|
+
await link(path.join(directory, owner.token), path.join(directory, token));
|
|
483
|
+
joined = true;
|
|
484
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
while (!joined) {
|
|
488
|
+
signal?.throwIfAborted();
|
|
489
|
+
try { await rename(candidate, directory); break; }
|
|
490
|
+
catch (error) {
|
|
491
|
+
if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(error.code)) throw error;
|
|
492
|
+
for (const owner of await lifecycleOwners(home)) {
|
|
493
|
+
if (!lockAlive(owner)) await unlink(path.join(directory, owner.token)).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
494
|
+
}
|
|
495
|
+
await rmdir(directory).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
|
|
496
|
+
await delay(25, undefined, { signal });
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
try { signal?.throwIfAborted(); return await run(); }
|
|
500
|
+
finally {
|
|
501
|
+
await unlink(path.join(directory, token));
|
|
502
|
+
await rmdir(directory).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
|
|
503
|
+
}
|
|
504
|
+
} finally {
|
|
505
|
+
await unlink(path.join(candidate, token)).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
506
|
+
await rmdir(candidate).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** How long a start waits for alpd to be ready by default: generous, as a loaded host can take a while. */
|
|
511
|
+
export const DAEMON_START_TIMEOUT_MS = 60_000;
|
|
512
|
+
/** The largest wait ALP_DAEMON_START_TIMEOUT_MS may ask for (one hour; setTimeout's own bound is about 24 days). */
|
|
513
|
+
const DAEMON_START_TIMEOUT_MAX_MS = 3_600_000;
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* The time a start of alpd waits for it to become ready, in ms: ALP_DAEMON_START_TIMEOUT_MS when it
|
|
517
|
+
* is a positive whole number of at most one hour, else DAEMON_START_TIMEOUT_MS.
|
|
518
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
519
|
+
*/
|
|
520
|
+
export function daemonStartTimeoutMs(env = process.env) {
|
|
521
|
+
const raw = env.ALP_DAEMON_START_TIMEOUT_MS?.trim();
|
|
522
|
+
if (!raw || !/^[0-9]+$/.test(raw)) return DAEMON_START_TIMEOUT_MS;
|
|
523
|
+
const value = Number(raw);
|
|
524
|
+
return value > 0 && value <= DAEMON_START_TIMEOUT_MAX_MS ? value : DAEMON_START_TIMEOUT_MS;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Returns the socket of a ready daemon, starting one when none runs.
|
|
529
|
+
* `entry` is the daemon script; it is started through its own detaching launcher so the
|
|
530
|
+
* daemon outlives the client that started it.
|
|
531
|
+
*/
|
|
532
|
+
export async function ensureDaemon({ home = alpHome(), entry = /** @type {string | undefined} */ (undefined), env = process.env, execPath = process.execPath, timeoutMs = daemonStartTimeoutMs(env), lifecycleLocked = false, signal = /** @type {AbortSignal | undefined} */ (undefined) } = {}) {
|
|
533
|
+
signal?.throwIfAborted();
|
|
534
|
+
if (!lifecycleLocked) return withDaemonLifecycle(home, 'start', () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true, signal }), { signal });
|
|
535
|
+
const ready = async () => {
|
|
536
|
+
const lock = await readLock(home);
|
|
537
|
+
return lockAlive(lock) && lock.ready ? lock.socket : undefined;
|
|
538
|
+
};
|
|
539
|
+
const live = await ready();
|
|
540
|
+
if (live) return live;
|
|
541
|
+
const held = await readLock(home);
|
|
542
|
+
if (lockAlive(held) && held.maintenance) throw new Error(`ALP is busy: alp ${held.maintenance} runs (pid ${held.pid}); alpd starts again when it finishes`);
|
|
543
|
+
if (!lockAlive(held)) {
|
|
544
|
+
entry ??= await findDaemonEntry({ home, env });
|
|
545
|
+
if (!entry) throw new Error('ALP daemon is not running and alpd.js was not found. Install the ALP CLI and run `alp daemon start`, or set ALP_DAEMON_ENTRY to alpd.js');
|
|
546
|
+
signal?.throwIfAborted();
|
|
547
|
+
await new Promise((resolve, reject) => {
|
|
548
|
+
const launch = entryCommand(entry, 'daemon', ['--detach', `--startup-timeout=${timeoutMs}`], execPath);
|
|
549
|
+
// BUN_BE_BUN=1 would turn the native alpd (t-81b0.9) into the Bun CLI instead of starting alpd.
|
|
550
|
+
const launchEnv = { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: '1' };
|
|
551
|
+
if (isNativeDaemonName(launch.command)) delete launchEnv.BUN_BE_BUN;
|
|
552
|
+
const launcher = spawn(launch.command, launch.args, {
|
|
553
|
+
env: launchEnv,
|
|
554
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
555
|
+
windowsHide: true,
|
|
556
|
+
});
|
|
557
|
+
// The launcher writes only when it fails, and before alpd has a log to write to.
|
|
558
|
+
let failure = '';
|
|
559
|
+
launcher.stderr.on('data', chunk => { if (failure.length < 8000) failure += chunk; });
|
|
560
|
+
launcher.once('error', reject);
|
|
561
|
+
launcher.once('close', code => code === 0 ? resolve() : reject(new Error(`ALP daemon launcher exited (${code})${launcherReason(failure)}`)));
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
const deadline = Date.now() + timeoutMs;
|
|
565
|
+
while (Date.now() < deadline) {
|
|
566
|
+
signal?.throwIfAborted();
|
|
567
|
+
const socket = await ready();
|
|
568
|
+
if (socket) return socket;
|
|
569
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
570
|
+
}
|
|
571
|
+
const log = await tail(daemonPaths(home).log);
|
|
572
|
+
throw new Error(`ALP daemon did not become ready within ${timeoutMs} ms${log ? `\n${log}` : ''}`);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Registration descriptor field names, in priority order. */
|
|
576
|
+
const INTEGRATION_DESCRIPTOR_FIELDS = ['main', 'entry', 'path', 'command'];
|
|
577
|
+
|
|
578
|
+
async function readIntegrationDescriptor(file, baseDirs = []) {
|
|
579
|
+
try {
|
|
580
|
+
const raw = JSON.parse(await readFile(file, 'utf8'));
|
|
581
|
+
for (const field of INTEGRATION_DESCRIPTOR_FIELDS) {
|
|
582
|
+
const value = raw?.[field];
|
|
583
|
+
if (typeof value !== 'string' || !value.trim()) continue;
|
|
584
|
+
if (path.isAbsolute(value)) {
|
|
585
|
+
if (await isFile(value)) return value;
|
|
586
|
+
} else {
|
|
587
|
+
const bases = [path.dirname(file), ...baseDirs];
|
|
588
|
+
for (const base of bases) {
|
|
589
|
+
const resolved = path.resolve(base, value);
|
|
590
|
+
if (await isFile(resolved)) return resolved;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
} catch {}
|
|
595
|
+
return undefined;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
async function integrationCandidateFromHome(home, name) {
|
|
599
|
+
const descriptors = [
|
|
600
|
+
path.join(home, 'integrations', `${name}.json`),
|
|
601
|
+
path.join(home, 'integrations', name, 'integration.json'),
|
|
602
|
+
];
|
|
603
|
+
for (const descriptor of descriptors) {
|
|
604
|
+
const entry = await readIntegrationDescriptor(descriptor, [home]);
|
|
605
|
+
if (entry) return entry;
|
|
606
|
+
}
|
|
607
|
+
// Legacy single-file registration.
|
|
608
|
+
const legacy = path.join(home, 'integrations', name, 'main.js');
|
|
609
|
+
return (await isFile(legacy)) ? legacy : undefined;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function integrationBinaryName(name) {
|
|
613
|
+
return `alp-${name}-integration`;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** Distribution roots that may carry a bundled integration descriptor. */
|
|
617
|
+
async function distributionRoots() {
|
|
618
|
+
const roots = [];
|
|
619
|
+
const argv = process.argv[1] ? await realpath(process.argv[1]).catch(() => process.argv[1]) : undefined;
|
|
620
|
+
if (argv) {
|
|
621
|
+
// The CLI runs from <distribution>/packages/cli/dist, so the distribution root is a few levels
|
|
622
|
+
// up. Resolve the real path first so a symlinked global bin still finds its own root.
|
|
623
|
+
let directory = path.dirname(argv);
|
|
624
|
+
for (let depth = 0; depth < 4; depth += 1) { roots.push(path.resolve(directory, '..')); directory = path.resolve(directory, '..'); }
|
|
625
|
+
// Every package ancestor may carry a bundled descriptor (a full distribution, or the plugin
|
|
626
|
+
// package installed next to it).
|
|
627
|
+
for (let ancestor = path.dirname(argv); ; ancestor = path.dirname(ancestor)) {
|
|
628
|
+
if (await isFile(path.join(ancestor, 'package.json'))) roots.push(ancestor);
|
|
629
|
+
if (path.dirname(ancestor) === ancestor) break;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
// Also consider the current working directory for full distributions.
|
|
633
|
+
roots.push(process.cwd());
|
|
634
|
+
return [...new Set(roots)];
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* The entry of integration `name`: an environment override, a descriptor under the home or a
|
|
639
|
+
* distribution root, or an `alp-<name>-integration` binary. Discovery never returns an entry for
|
|
640
|
+
* `dashboard`: that is alp dashboard's service, which ships with the CLI and is started with its
|
|
641
|
+
* explicit entry; nor for `web`, its name before the rename (t-81b0.5). Everything once registered
|
|
642
|
+
* under `web` (the descriptor `integrations/web.json`, the
|
|
643
|
+
* `alp-web-integration` binary, `ALP_WEB_INTEGRATION`) is the Paseo integration from before its
|
|
644
|
+
* rename to `paseo`, which must never run under the web lock. `ALP_WEB_INTEGRATION` is read for
|
|
645
|
+
* `paseo` only, after `ALP_PASEO_INTEGRATION`, for one release (like the alp-web-integration alias).
|
|
646
|
+
* @param {string} [name]
|
|
647
|
+
* @param {{ home?: string, env?: NodeJS.ProcessEnv, binDirectories?: string[], roots?: string[] }} [options]
|
|
648
|
+
*/
|
|
649
|
+
export async function discoverIntegration(name = 'dashboard', options = {}) {
|
|
650
|
+
// The name becomes a descriptor path under <home>/integrations, so it must stay one safe segment.
|
|
651
|
+
assertIntegrationName(name);
|
|
652
|
+
if (name === 'dashboard' || name === 'web') return undefined;
|
|
653
|
+
const { env = process.env, binDirectories = BIN_DIRECTORIES, roots } = options;
|
|
654
|
+
// Explicit environment override always wins: the integration's own, then the generic one.
|
|
655
|
+
const envCandidates = [
|
|
656
|
+
env[`ALP_${name.toUpperCase()}_INTEGRATION`],
|
|
657
|
+
name === 'paseo' ? env.ALP_WEB_INTEGRATION : undefined,
|
|
658
|
+
env.ALP_INTEGRATION_ENTRY,
|
|
659
|
+
].filter(Boolean);
|
|
660
|
+
for (const candidate of envCandidates) if (await isFile(candidate)) return candidate;
|
|
661
|
+
|
|
662
|
+
const home = options?.home ? path.resolve(options.home) : alpHome();
|
|
663
|
+
const fromHome = await integrationCandidateFromHome(home, name);
|
|
664
|
+
if (fromHome) return fromHome;
|
|
665
|
+
|
|
666
|
+
// A full distribution may describe a bundled integration relative to its own root.
|
|
667
|
+
for (const root of roots ?? await distributionRoots()) {
|
|
668
|
+
for (const descriptorPath of [path.join(root, 'integrations', `${name}.json`), path.join(root, 'integrations', name, 'integration.json')]) {
|
|
669
|
+
const entry = await readIntegrationDescriptor(descriptorPath, [root]);
|
|
670
|
+
if (entry) return entry;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// Installed integration packages announce themselves on PATH.
|
|
675
|
+
const binary = integrationBinaryName(name);
|
|
676
|
+
for (const directory of [...(env.PATH ?? '').split(path.delimiter).filter(Boolean), ...binDirectories]) {
|
|
677
|
+
const candidate = await realpath(path.join(directory, binary)).catch(() => undefined);
|
|
678
|
+
if (candidate && await isFile(candidate)) return candidate;
|
|
679
|
+
}
|
|
680
|
+
return undefined;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export function integrationAlive(lock) {
|
|
684
|
+
if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
|
|
685
|
+
try {
|
|
686
|
+
process.kill(lock.pid, 0);
|
|
687
|
+
return true;
|
|
688
|
+
} catch (error) {
|
|
689
|
+
return error?.code === 'EPERM';
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* What startIntegration says about integration `name`, and where its service writes its log: alp
|
|
695
|
+
* dashboard (`dashboard`) is part of the CLI, Paseo (`paseo`) an optional package, anything else named as is.
|
|
696
|
+
* @param {string} name
|
|
697
|
+
* @param {string} home
|
|
698
|
+
*/
|
|
699
|
+
function integrationText(name, home) {
|
|
700
|
+
const logs = path.join(home, 'logs', 'integrations');
|
|
701
|
+
if (name === 'dashboard') return {
|
|
702
|
+
what: 'alp dashboard',
|
|
703
|
+
log: path.join(logs, 'alp-dashboard.log'),
|
|
704
|
+
missing: 'alp dashboard runs the alp-dashboard service of the ALP CLI, which is started with its entry (packages/cli/dist/alp-dashboard.js); run `alp dashboard`',
|
|
705
|
+
};
|
|
706
|
+
if (name === 'paseo') return {
|
|
707
|
+
what: 'The Paseo integration',
|
|
708
|
+
log: path.join(logs, 'paseo.log'),
|
|
709
|
+
missing: 'The Paseo integration is an optional integration package. Install it (for example `npm install -g @anhlp/alp-paseo@beta`), then run the command again.',
|
|
710
|
+
};
|
|
711
|
+
return {
|
|
712
|
+
what: `ALP integration ${name}`,
|
|
713
|
+
log: path.join(logs, `${name}.log`),
|
|
714
|
+
missing: `ALP integration ${name} is not installed: no ALP_${name.toUpperCase()}_INTEGRATION, descriptor <home>/integrations/${name}.json or alp-${name}-integration binary was found.`,
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Starts integration `name` (default `dashboard`) detached with `--service` (then `args`) unless its lock
|
|
720
|
+
* already names a live owner, then waits until its ready lock and `<home>/<name>.json` name the same
|
|
721
|
+
* pid. `entry` names the script to run with this Node and skips descriptor, environment and PATH
|
|
722
|
+
* discovery; `dashboard` is never discovered, so it needs its entry. `"dashboard": { "enabled": false }`
|
|
723
|
+
* in the home's settings.json (or `web.enabled`, its key before the rename) refuses `dashboard` only.
|
|
724
|
+
* @param {string | { name?: string, entry?: string, home?: string, args?: string[] }} [nameOrOptions]
|
|
725
|
+
*/
|
|
726
|
+
export async function startIntegration(nameOrOptions = 'dashboard') {
|
|
727
|
+
const options = typeof nameOrOptions === 'string' ? { name: nameOrOptions } : (nameOrOptions ?? {});
|
|
728
|
+
const name = assertIntegrationName(options.name ?? 'dashboard');
|
|
729
|
+
if (options.entry !== undefined && (typeof options.entry !== 'string' || !options.entry)) throw new TypeError('startIntegration entry must be a non-empty path');
|
|
730
|
+
const args = options.args ?? [];
|
|
731
|
+
if (!Array.isArray(args) || !args.every(arg => typeof arg === 'string')) throw new TypeError('startIntegration args must be a list of strings');
|
|
732
|
+
const fs = await import('node:fs/promises');
|
|
733
|
+
const pathMod = await import('node:path');
|
|
734
|
+
const home = options.home ? pathMod.resolve(options.home) : alpHome();
|
|
735
|
+
const text = integrationText(name, home);
|
|
736
|
+
// An explicit entry is the caller's own service script: it must exist even when a live owner is
|
|
737
|
+
// reused, and it replaces descriptor, environment and PATH discovery.
|
|
738
|
+
const explicit = options.entry !== undefined ? pathMod.resolve(options.entry) : undefined;
|
|
739
|
+
if (explicit !== undefined && !(await isFile(explicit))) throw new Error(`${text.what}: integration entry not found: ${explicit}`);
|
|
740
|
+
const lockPath = pathMod.join(home, 'integrations', `${name}.lock`);
|
|
741
|
+
const webPath = pathMod.join(home, `${name}.json`);
|
|
742
|
+
const started = explicit ? ` (entry ${explicit})` : '';
|
|
743
|
+
|
|
744
|
+
// dashboard.enabled turns off alp dashboard only; other integrations have their own switches.
|
|
745
|
+
if (name === 'dashboard') {
|
|
746
|
+
let settings = {};
|
|
747
|
+
try { settings = JSON.parse(await fs.readFile(pathMod.join(home, 'settings.json'), 'utf8')); } catch {}
|
|
748
|
+
if (dashboardSettings(settings).enabled === false) throw new Error('alp dashboard is disabled by settings ("dashboard.enabled": false).');
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
752
|
+
const readLock = async () => {
|
|
753
|
+
try { return JSON.parse(await fs.readFile(lockPath, 'utf8')); } catch { return undefined; }
|
|
754
|
+
};
|
|
755
|
+
const readWeb = async () => {
|
|
756
|
+
try { return JSON.parse(await fs.readFile(webPath, 'utf8')); } catch { return undefined; }
|
|
757
|
+
};
|
|
758
|
+
|
|
759
|
+
// The authoritative check: the ready integration lock and live <name>.json must name the same pid.
|
|
760
|
+
// A loser of a concurrent start accepts the winning pid after its own contender has exited or
|
|
761
|
+
// the lock already names the winner.
|
|
762
|
+
async function waitForReady() {
|
|
763
|
+
const deadline = Date.now() + 30_000;
|
|
764
|
+
while (Date.now() < deadline) {
|
|
765
|
+
const lock = await readLock();
|
|
766
|
+
if (lock && integrationAlive(lock) && lock.ready) {
|
|
767
|
+
const info = await readWeb();
|
|
768
|
+
if (info && info.pid === lock.pid) return lock;
|
|
769
|
+
}
|
|
770
|
+
// alp dashboard can fail during bootstrap after the initial exit check (for example a
|
|
771
|
+
// refused uncertain lock). Its service log carries the cause; do not mask it with
|
|
772
|
+
// a readiness/dashboard.json timeout. Check a concurrent winner's ready lock first.
|
|
773
|
+
if (name === 'dashboard' && webStartupFailed()) throw new Error(`${text.what}${started} failed to start; see ${text.log}`);
|
|
774
|
+
await sleep(100);
|
|
775
|
+
}
|
|
776
|
+
const lock = await readLock();
|
|
777
|
+
if (lock && !lock.ready) throw new Error(`${text.what}${started} started but did not become ready; see ${text.log}`);
|
|
778
|
+
if (!lock) throw new Error(explicit ? `${text.what}${started} did not start; see ${text.log}` : text.missing);
|
|
779
|
+
throw new Error(`${text.what}${started} did not publish a ${name}.json matching its lock; see ${text.log}`);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// Existing-owner waits have no child to observe.
|
|
783
|
+
let webStartupFailed = () => false;
|
|
784
|
+
const existing = await readLock();
|
|
785
|
+
if (existing && integrationAlive(existing)) {
|
|
786
|
+
return waitForReady();
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
const entry = explicit ?? await discoverIntegration(name, { home });
|
|
790
|
+
if (!entry) throw new Error(text.missing);
|
|
791
|
+
|
|
792
|
+
const { spawn } = await import('node:child_process');
|
|
793
|
+
// The child is detached with its stdio ignored, so it cannot rely on the parent's console. `--service`
|
|
794
|
+
// is the generic contract: the entry writes its own log (the path its error messages advertise) and
|
|
795
|
+
// keeps the process alive as a service. `--register` still prints to stdout and is not passed here.
|
|
796
|
+
// alp dashboard may be an `alp` command (`alp dashboard serve`); other integrations are scripts.
|
|
797
|
+
const launch = name === 'dashboard' ? entryCommand(entry, 'dashboard', ['--service', ...args]) : entryCommand(entry, 'dashboard', ['--service', ...args], undefined, { scriptOnly: true });
|
|
798
|
+
const child = spawn(launch.command, launch.args, { stdio: 'ignore', detached: true, env: { ...process.env, ALP_HOME: home } });
|
|
799
|
+
let spawnError = null;
|
|
800
|
+
child.on('error', error => { spawnError = error; });
|
|
801
|
+
let exited = false;
|
|
802
|
+
child.on('exit', code => { if (code !== 0 && code !== null) exited = true; });
|
|
803
|
+
child.unref();
|
|
804
|
+
webStartupFailed = () => exited;
|
|
805
|
+
|
|
806
|
+
if (spawnError) throw spawnError;
|
|
807
|
+
// Give the process a moment to fail immediately on missing entry or bad permissions.
|
|
808
|
+
await sleep(150);
|
|
809
|
+
if (spawnError) throw spawnError;
|
|
810
|
+
if (exited) throw new Error(`${text.what}${explicit ? started : ` (${entry})`} failed to start; see ${text.log}`);
|
|
811
|
+
|
|
812
|
+
return waitForReady();
|
|
813
|
+
}
|