@anhlp/alp-client 0.0.0-beta.2 → 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.
Files changed (46) hide show
  1. package/README.md +23 -1
  2. package/dist/acp-probe.d.ts +3 -2
  3. package/dist/acp-probe.js +11 -2
  4. package/dist/antigravity-probe.d.ts +1 -2
  5. package/dist/antigravity-probe.js +11 -5
  6. package/dist/command.js +3 -1
  7. package/dist/doctor.d.ts +8 -0
  8. package/dist/doctor.js +276 -13
  9. package/dist/index.d.ts +123 -8
  10. package/dist/index.js +332 -52
  11. package/dist/integration-lock.d.ts +37 -0
  12. package/dist/integration-lock.js +199 -0
  13. package/dist/mcp-probe.js +1 -1
  14. package/dist/portable.d.ts +3 -1
  15. package/dist/portable.js +11 -2
  16. package/dist/render.js +3 -0
  17. package/dist/rpc/handshake.d.ts +6 -1
  18. package/dist/rpc/handshake.js +4 -2
  19. package/dist/rpc/registry.d.ts +227 -0
  20. package/dist/rpc/registry.js +223 -0
  21. package/dist/rpc/terminal-directory.d.ts +24 -0
  22. package/dist/rpc/terminal-directory.js +70 -0
  23. package/dist/service.d.ts +2 -2
  24. package/dist/service.js +3 -1
  25. package/dist/setup.d.ts +7 -1
  26. package/dist/setup.js +159 -32
  27. package/dist/supervise.d.ts +3 -1
  28. package/dist/supervise.js +26 -16
  29. package/package.json +11 -3
  30. package/src/acp-probe.js +10 -3
  31. package/src/antigravity-probe.js +12 -5
  32. package/src/command.js +3 -1
  33. package/src/doctor.d.ts +8 -0
  34. package/src/doctor.js +345 -3
  35. package/src/index.js +411 -55
  36. package/src/integration-lock.js +203 -0
  37. package/src/mcp-probe.js +1 -1
  38. package/src/portable.js +4 -1
  39. package/src/render.js +3 -0
  40. package/src/rpc/handshake.js +7 -2
  41. package/src/rpc/registry.js +229 -0
  42. package/src/rpc/terminal-directory.js +61 -0
  43. package/src/service.js +7 -3
  44. package/src/setup.js +201 -35
  45. package/src/supervise.d.ts +3 -1
  46. package/src/supervise.js +31 -19
package/src/index.js CHANGED
@@ -1,11 +1,15 @@
1
- import { spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import { open, readFile, realpath, stat, lstat, mkdir, readlink, unlink } from 'node:fs/promises';
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';
4
6
  import net from 'node:net';
5
7
  import os from 'node:os';
6
8
  import path from 'node:path';
7
9
 
8
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';
9
13
  import { createSocketTransport } from './ipc.js';
10
14
  import { AlpRpcClient } from './rpc/client.js';
11
15
  import { hello } from './rpc/handshake.js';
@@ -67,11 +71,24 @@ async function assertSafeAncestors(directory) {
67
71
  export async function assertPrivateDirectory(directory, { create = false } = {}) {
68
72
  await assertSafeAncestors(directory);
69
73
  if (create) await mkdir(directory, { recursive: true, mode: 0o700 });
70
- const info = await lstat(directory);
74
+ let info = await lstat(directory);
71
75
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('IPC requires a private directory, not a symlink');
72
- if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)) {
73
- throw new Error('IPC directory must be owned by the current user with private permissions (0700)');
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(() => {});
74
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}`);
75
92
  }
76
93
 
77
94
  export async function assertPrivateSocket(socketPath) {
@@ -87,38 +104,161 @@ export async function assertPrivateSocket(socketPath) {
87
104
  const isFile = file => stat(file).then(info => info.isFile(), () => false);
88
105
 
89
106
  /** Global bin directories that a GUI app's PATH may lack. */
90
- const BIN_DIRECTORIES = [path.join(os.homedir(), '.npm-global', 'bin'), path.join(os.homedir(), '.local', 'bin'), '/opt/homebrew/bin', '/usr/local/bin'];
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'];
91
108
 
92
109
  /** The npm package that ships the `alp` command and alpd. */
93
110
  const CLI_PACKAGES = ['@anhlp/alp', '@anhlp/alp-cli'];
94
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
+
95
153
  /**
96
154
  * Finds alpd.js for a client that cannot locate it beside itself, such as the Paseo
97
155
  * plugin, which Paseo re-bundles: the first existing candidate, then where alpd last
98
- * recorded itself ($ALP_HOME/alpd.json), then the ALP CLI (`alp`) on PATH.
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).
99
158
  */
100
- export async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = /** @type {Array<string | undefined>} */ ([]) } = {}) {
159
+ export async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = /** @type {Array<string | undefined>} */ ([]), binDirectories = BIN_DIRECTORIES } = {}) {
101
160
  for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
102
161
  try {
103
162
  const { entry } = JSON.parse(await readFile(daemonPaths(home).install, 'utf8'));
104
163
  if (typeof entry === 'string' && await isFile(entry)) return entry;
105
164
  } catch {}
106
- for (const directory of [...(env.PATH ?? '').split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
107
- const cli = await realpath(path.join(directory, 'alp')).catch(() => undefined);
108
- if (!cli || path.basename(cli) !== 'cli.js') continue;
109
- const root = path.resolve(path.dirname(cli), '..');
110
- const name = await readFile(path.join(root, 'package.json'), 'utf8').then(text => JSON.parse(text).name, () => undefined);
111
- const entry = path.join(root, 'dist', 'alpd.js');
112
- if (CLI_PACKAGES.includes(name) && await isFile(entry)) return entry;
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
+ }
113
171
  }
114
172
  return undefined;
115
173
  }
116
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
+
117
232
  /** Wall-clock boot time; a lock from an earlier boot is stale even if its pid is reused. */
118
233
  export function bootTime() {
119
234
  return Math.round((Date.now() - os.uptime() * 1000) / 1000);
120
235
  }
121
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
+
122
262
  export async function readLock(home) {
123
263
  try {
124
264
  return JSON.parse(await readFile(daemonPaths(home).lock, 'utf8'));
@@ -129,7 +269,7 @@ export async function readLock(home) {
129
269
  }
130
270
 
131
271
  export function lockAlive(lock) {
132
- if (!lock || !Number.isSafeInteger(lock.pid) || Math.abs((lock.bootTime ?? 0) - bootTime()) > 30) return false;
272
+ if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
133
273
  try {
134
274
  process.kill(lock.pid, 0);
135
275
  return true;
@@ -147,20 +287,48 @@ export function lockAlive(lock) {
147
287
  */
148
288
  export async function acquireDaemonLock(home, contents) {
149
289
  const file = daemonPaths(home).lock;
150
- const lock = { pid: process.pid, startedAt: new Date().toISOString(), bootTime: bootTime(), uid: process.getuid?.() ?? -1, ready: false, ...contents };
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
+ };
151
301
  for (let attempt = 0; attempt < 2; attempt++) {
152
302
  try {
153
303
  const handle = await open(file, 'wx', 0o600);
154
- await handle.writeFile(JSON.stringify(lock));
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
+ }
155
319
  await handle.close();
156
320
  return lock;
157
321
  } catch (error) {
158
322
  if (error?.code !== 'EEXIST') throw error;
159
323
  const current = await readLock(home);
160
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})`);
161
- // Remove the stale lock only if nobody replaced it meanwhile.
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.
162
327
  const again = await readFile(file, 'utf8').catch(() => undefined);
163
- if (again === undefined || JSON.stringify(current) === again || !lockAlive(JSON.parse(again))) await unlink(file).catch(() => {});
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(() => {});
164
332
  }
165
333
  }
166
334
  throw new Error('Could not acquire the ALP daemon lock');
@@ -178,6 +346,14 @@ export async function releaseDaemonLock(home) {
178
346
  * CLI, alpd's tests and the Paseo plugin use.
179
347
  */
180
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;
181
357
  /**
182
358
  * @param {import('node:net').Socket} socket a connected or connecting socket; the client owns it
183
359
  * @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
@@ -217,7 +393,17 @@ export async function connectSocket(socketPath, options) {
217
393
  export async function connect(socketPath, client = { name: 'alp', version: '0' }, options = {}) {
218
394
  const connection = new AlpClient(await openSocket(socketPath), options);
219
395
  try {
220
- await hello(connection, client);
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
+ }
221
407
  } catch (error) {
222
408
  connection.close();
223
409
  throw error;
@@ -242,12 +428,110 @@ async function tail(file, lines = 30) {
242
428
  try { return scrubText((await readFile(file, 'utf8')).split('\n').slice(-lines).join('\n'), { max: 8000 }); } catch { return ''; }
243
429
  }
244
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
+
245
527
  /**
246
528
  * Returns the socket of a ready daemon, starting one when none runs.
247
529
  * `entry` is the daemon script; it is started through its own detaching launcher so the
248
530
  * daemon outlives the client that started it.
249
531
  */
250
- export async function ensureDaemon({ home = alpHome(), entry = /** @type {string | undefined} */ (undefined), env = process.env, execPath = process.execPath, timeoutMs = 15_000 } = {}) {
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 });
251
535
  const ready = async () => {
252
536
  const lock = await readLock(home);
253
537
  return lockAlive(lock) && lock.ready ? lock.socket : undefined;
@@ -259,9 +543,14 @@ export async function ensureDaemon({ home = alpHome(), entry = /** @type {string
259
543
  if (!lockAlive(held)) {
260
544
  entry ??= await findDaemonEntry({ home, env });
261
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();
262
547
  await new Promise((resolve, reject) => {
263
- const launcher = spawn(execPath, [entry, '--detach'], {
264
- env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: '1' },
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,
265
554
  stdio: ['ignore', 'ignore', 'pipe'],
266
555
  windowsHide: true,
267
556
  });
@@ -274,6 +563,7 @@ export async function ensureDaemon({ home = alpHome(), entry = /** @type {string
274
563
  }
275
564
  const deadline = Date.now() + timeoutMs;
276
565
  while (Date.now() < deadline) {
566
+ signal?.throwIfAborted();
277
567
  const socket = await ready();
278
568
  if (socket) return socket;
279
569
  await new Promise(resolve => setTimeout(resolve, 100));
@@ -320,7 +610,7 @@ async function integrationCandidateFromHome(home, name) {
320
610
  }
321
611
 
322
612
  function integrationBinaryName(name) {
323
- return name === 'web' ? 'alp-web-integration' : `alp-${name}-integration`;
613
+ return `alp-${name}-integration`;
324
614
  }
325
615
 
326
616
  /** Distribution roots that may carry a bundled integration descriptor. */
@@ -344,12 +634,28 @@ async function distributionRoots() {
344
634
  return [...new Set(roots)];
345
635
  }
346
636
 
347
- export async function discoverIntegration(name = 'web', options = {}) {
348
- // Explicit environment override always wins.
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.
349
655
  const envCandidates = [
350
- process.env.ALP_WEB_INTEGRATION,
351
- process.env.ALP_INTEGRATION_ENTRY,
352
- name !== 'web' ? process.env[`ALP_${name.toUpperCase()}_INTEGRATION`] : undefined,
656
+ env[`ALP_${name.toUpperCase()}_INTEGRATION`],
657
+ name === 'paseo' ? env.ALP_WEB_INTEGRATION : undefined,
658
+ env.ALP_INTEGRATION_ENTRY,
353
659
  ].filter(Boolean);
354
660
  for (const candidate of envCandidates) if (await isFile(candidate)) return candidate;
355
661
 
@@ -358,7 +664,7 @@ export async function discoverIntegration(name = 'web', options = {}) {
358
664
  if (fromHome) return fromHome;
359
665
 
360
666
  // A full distribution may describe a bundled integration relative to its own root.
361
- for (const root of await distributionRoots()) {
667
+ for (const root of roots ?? await distributionRoots()) {
362
668
  for (const descriptorPath of [path.join(root, 'integrations', `${name}.json`), path.join(root, 'integrations', name, 'integration.json')]) {
363
669
  const entry = await readIntegrationDescriptor(descriptorPath, [root]);
364
670
  if (entry) return entry;
@@ -367,36 +673,79 @@ export async function discoverIntegration(name = 'web', options = {}) {
367
673
 
368
674
  // Installed integration packages announce themselves on PATH.
369
675
  const binary = integrationBinaryName(name);
370
- for (const directory of [...(process.env.PATH ?? '').split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
676
+ for (const directory of [...(env.PATH ?? '').split(path.delimiter).filter(Boolean), ...binDirectories]) {
371
677
  const candidate = await realpath(path.join(directory, binary)).catch(() => undefined);
372
678
  if (candidate && await isFile(candidate)) return candidate;
373
679
  }
374
680
  return undefined;
375
681
  }
376
682
 
377
- function integrationAlive(lock) {
378
- if (!lock || !Number.isSafeInteger(lock.pid)) return false;
379
- try { process.kill(lock.pid, 0); } catch (error) {
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) {
380
689
  return error?.code === 'EPERM';
381
690
  }
382
- if (typeof lock.bootTime === 'number' && Math.abs(lock.bootTime - bootTime()) > 30) return false;
383
- return true;
384
691
  }
385
692
 
386
- export async function startIntegration(nameOrOptions = 'web') {
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') {
387
727
  const options = typeof nameOrOptions === 'string' ? { name: nameOrOptions } : (nameOrOptions ?? {});
388
- const name = options.name ?? 'web';
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');
389
732
  const fs = await import('node:fs/promises');
390
733
  const pathMod = await import('node:path');
391
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}`);
392
740
  const lockPath = pathMod.join(home, 'integrations', `${name}.lock`);
393
741
  const webPath = pathMod.join(home, `${name}.json`);
742
+ const started = explicit ? ` (entry ${explicit})` : '';
394
743
 
395
- // Clear, actionable diagnostics for a disabled optional integration.
396
- let settings = {};
397
- try { settings = JSON.parse(await fs.readFile(pathMod.join(home, 'settings.json'), 'utf8')); } catch {}
398
- if (settings?.web?.enabled === false) {
399
- throw new Error('ALP web app is disabled by settings ("web.enabled": false).');
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).');
400
749
  }
401
750
 
402
751
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
@@ -407,7 +756,7 @@ export async function startIntegration(nameOrOptions = 'web') {
407
756
  try { return JSON.parse(await fs.readFile(webPath, 'utf8')); } catch { return undefined; }
408
757
  };
409
758
 
410
- // The authoritative check: the ready integration lock and live web.json must name the same pid.
759
+ // The authoritative check: the ready integration lock and live <name>.json must name the same pid.
411
760
  // A loser of a concurrent start accepts the winning pid after its own contender has exited or
412
761
  // the lock already names the winner.
413
762
  async function waitForReady() {
@@ -418,40 +767,47 @@ export async function startIntegration(nameOrOptions = 'web') {
418
767
  const info = await readWeb();
419
768
  if (info && info.pid === lock.pid) return lock;
420
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}`);
421
774
  await sleep(100);
422
775
  }
423
776
  const lock = await readLock();
424
- if (lock && !lock.ready) throw new Error('ALP web integration started but did not become ready; see ~/.alp/logs/integrations/paseo.log');
425
- if (!lock) throw new Error('ALP web app is provided by an optional integration package. Install it (for example `npm install -g @anhlp/alp-paseo@beta`) and run `alp web` again.');
426
- throw new Error('ALP web integration did not publish a matching web.json lock');
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}`);
427
780
  }
428
781
 
782
+ // Existing-owner waits have no child to observe.
783
+ let webStartupFailed = () => false;
429
784
  const existing = await readLock();
430
785
  if (existing && integrationAlive(existing)) {
431
786
  return waitForReady();
432
787
  }
433
788
 
434
- const entry = await discoverIntegration(name, { home });
435
- if (!entry) {
436
- throw new Error('ALP web app is provided by an optional integration package. Install it (for example `npm install -g @anhlp/alp-paseo@beta`) and run `alp web` again.');
437
- }
789
+ const entry = explicit ?? await discoverIntegration(name, { home });
790
+ if (!entry) throw new Error(text.missing);
438
791
 
439
792
  const { spawn } = await import('node:child_process');
440
793
  // The child is detached with its stdio ignored, so it cannot rely on the parent's console. `--service`
441
794
  // is the generic contract: the entry writes its own log (the path its error messages advertise) and
442
795
  // keeps the process alive as a service. `--register` still prints to stdout and is not passed here.
443
- const child = spawn(process.execPath, [entry, '--service'], { stdio: 'ignore', detached: true, env: { ...process.env, ALP_HOME: home } });
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 } });
444
799
  let spawnError = null;
445
800
  child.on('error', error => { spawnError = error; });
446
801
  let exited = false;
447
802
  child.on('exit', code => { if (code !== 0 && code !== null) exited = true; });
448
803
  child.unref();
804
+ webStartupFailed = () => exited;
449
805
 
450
806
  if (spawnError) throw spawnError;
451
807
  // Give the process a moment to fail immediately on missing entry or bad permissions.
452
808
  await sleep(150);
453
809
  if (spawnError) throw spawnError;
454
- if (exited) throw new Error('ALP web integration failed to start; see ~/.alp/logs/integrations/paseo.log');
810
+ if (exited) throw new Error(`${text.what}${explicit ? started : ` (${entry})`} failed to start; see ${text.log}`);
455
811
 
456
812
  return waitForReady();
457
813
  }