@anhlp/alp-client 0.0.1-beta.3 → 0.0.1-beta.5

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/src/index.js CHANGED
@@ -1,11 +1,14 @@
1
- import { spawn } from 'node:child_process';
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { execFileSync, spawn } from 'node:child_process';
2
3
  import { createHash, randomUUID } from 'node:crypto';
4
+ import { readFileSync } from 'node:fs';
3
5
  import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, 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 { EXECUTABLE_MARKER, entryCommand, executablePath, isExecutableName, isScript } from '@anhlp/alp-core/packaged';
9
12
  import { createSocketTransport } from './ipc.js';
10
13
  import { AlpRpcClient } from './rpc/client.js';
11
14
  import { hello } from './rpc/handshake.js';
@@ -86,12 +89,62 @@ export async function assertPrivateSocket(socketPath) {
86
89
 
87
90
  const isFile = file => stat(file).then(info => info.isFile(), () => false);
88
91
 
92
+ /**
93
+ * Whether `file` is the self-contained ALP executable (t-1e02) rather than a script or a shell
94
+ * wrapper: a native image (Mach-O, ELF or PE) named alp that carries ALP's executable marker.
95
+ * @param {string} file
96
+ */
97
+ async function isAlpExecutable(file) {
98
+ if (isScript(file) || !isExecutableName(file) || !await isFile(file)) return false;
99
+ const handle = await open(file, 'r').catch(() => undefined);
100
+ if (!handle) return false;
101
+ try {
102
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(4), 0, 4, 0);
103
+ if (bytesRead < 4) return false;
104
+ const magic = buffer.readUInt32BE(0);
105
+ const native = buffer.toString('latin1') === '\x7fELF' || buffer.subarray(0, 2).toString('latin1') === 'MZ'
106
+ || [0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe, 0xcafebabe].includes(magic);
107
+ if (!native) return false;
108
+ // Identity without running it: ALP's generated entry embeds EXECUTABLE_MARKER (an unrelated `alp` does not).
109
+ const marker = Buffer.from(EXECUTABLE_MARKER, 'latin1');
110
+ const chunk = Buffer.alloc(1 << 20);
111
+ let tail = Buffer.alloc(0);
112
+ for (let position = 0; ;) {
113
+ const { bytesRead: read } = await handle.read(chunk, 0, chunk.length, position);
114
+ if (!read) return false;
115
+ const window = Buffer.concat([tail, chunk.subarray(0, read)]);
116
+ if (window.includes(marker)) return true;
117
+ tail = window.subarray(Math.max(0, window.length - marker.length + 1));
118
+ position += read;
119
+ }
120
+ } finally { await handle.close(); }
121
+ }
122
+
89
123
  /** 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'];
124
+ 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
125
 
92
126
  /** The npm package that ships the `alp` command and alpd. */
93
127
  const CLI_PACKAGES = ['@anhlp/alp', '@anhlp/alp-cli'];
94
128
 
129
+ /**
130
+ * The ALP executable behind npm's `alp` when that is the @anhlp/alp launcher (t-cd7f): `bin/alp.js`
131
+ * of a package named @anhlp/alp, which runs @anhlp/alp-<platform>-<arch>/bin/alp. npm puts that
132
+ * package beside the launcher (a global install) or in its own node_modules.
133
+ * @param {string} launcher the real path of `alp` on PATH
134
+ */
135
+ async function npmWrapperExecutable(launcher, platform = process.platform, arch = process.arch) {
136
+ if (path.basename(launcher) !== 'alp.js') return undefined;
137
+ const root = path.resolve(path.dirname(launcher), '..');
138
+ const name = await readFile(path.join(root, 'package.json'), 'utf8').then(text => JSON.parse(text)?.name).catch(() => undefined);
139
+ if (name !== '@anhlp/alp') return undefined;
140
+ const id = `alp-${platform}-${arch}`;
141
+ const file = path.join('bin', platform === 'win32' ? 'alp.exe' : 'alp');
142
+ for (const candidate of [path.join(root, 'node_modules', '@anhlp', id, file), path.join(root, '..', id, file)]) {
143
+ if (await isAlpExecutable(candidate)) return candidate;
144
+ }
145
+ return undefined;
146
+ }
147
+
95
148
  /**
96
149
  * Finds alpd.js for a client that cannot locate it beside itself, such as the Paseo
97
150
  * plugin, which Paseo re-bundles: the first existing candidate, then where alpd last
@@ -99,26 +152,114 @@ const CLI_PACKAGES = ['@anhlp/alp', '@anhlp/alp-cli'];
99
152
  */
100
153
  export async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = /** @type {Array<string | undefined>} */ ([]) } = {}) {
101
154
  for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
155
+ // The ALP executable carries alpd itself (`alp daemon run`).
156
+ const own = executablePath();
157
+ if (own) return own;
102
158
  try {
103
159
  const { entry } = JSON.parse(await readFile(daemonPaths(home).install, 'utf8'));
104
160
  if (typeof entry === 'string' && await isFile(entry)) return entry;
105
161
  } catch {}
106
162
  for (const directory of [...(env.PATH ?? '').split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
107
- const cli = await realpath(path.join(directory, 'alp')).catch(() => undefined);
163
+ const cli = await realpath(path.join(directory, process.platform === 'win32' ? 'alp.exe' : 'alp')).catch(() => undefined);
164
+ if (cli && await isAlpExecutable(cli)) return cli;
165
+ const npmExecutable = cli && await npmWrapperExecutable(cli);
166
+ if (npmExecutable) return npmExecutable;
108
167
  if (!cli || path.basename(cli) !== 'cli.js') continue;
109
168
  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);
169
+ const name = await readFile(path.join(root, 'package.json'), 'utf8').then(text => JSON.parse(text)?.name).catch(() => undefined);
111
170
  const entry = path.join(root, 'dist', 'alpd.js');
112
171
  if (CLI_PACKAGES.includes(name) && await isFile(entry)) return entry;
113
172
  }
114
173
  return undefined;
115
174
  }
116
175
 
176
+ /**
177
+ * Integration names are single lowercase path segments: they name `<home>/integrations/<name>.lock`,
178
+ * its guard and `<home>/<name>.json`. Returns the name, or throws a TypeError.
179
+ * @param {unknown} name
180
+ * @returns {string}
181
+ */
182
+ export function assertIntegrationName(name) {
183
+ if (typeof name !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new TypeError(`Invalid integration name: ${JSON.stringify(name)}`);
184
+ return name;
185
+ }
186
+
187
+ let cachedBootId = null;
188
+
189
+ /**
190
+ * Returns a stable identifier for the current OS boot session,
191
+ * or undefined if unavailable on the platform or inaccessible.
192
+ *
193
+ * On Linux, reads /proc/sys/kernel/random/boot_id.
194
+ * On Darwin (macOS), queries sysctl kern.bootsessionuuid.
195
+ *
196
+ * @returns {string | undefined}
197
+ */
198
+ export function bootId() {
199
+ if (cachedBootId !== null) return cachedBootId;
200
+ try {
201
+ if (process.platform === 'linux') {
202
+ const id = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
203
+ if (id.length > 0) {
204
+ cachedBootId = id;
205
+ return cachedBootId;
206
+ }
207
+ } else if (process.platform === 'darwin') {
208
+ const id = execFileSync('sysctl', ['-n', 'kern.bootsessionuuid'], {
209
+ encoding: 'utf8',
210
+ stdio: ['ignore', 'pipe', 'ignore'],
211
+ timeout: 2000,
212
+ }).trim();
213
+ if (id.length > 0) {
214
+ cachedBootId = id;
215
+ return cachedBootId;
216
+ }
217
+ }
218
+ } catch {
219
+ // Platform lacks boot id or procfs/sysctl is restricted; fall back gracefully.
220
+ }
221
+ cachedBootId = undefined;
222
+ return cachedBootId;
223
+ }
224
+
225
+ /**
226
+ * Internal/testing seam: resets or sets the cached boot identifier.
227
+ * @param {string | undefined | null} [id]
228
+ */
229
+ export function _setBootIdForTest(id = null) {
230
+ cachedBootId = id;
231
+ }
232
+
117
233
  /** Wall-clock boot time; a lock from an earlier boot is stale even if its pid is reused. */
118
234
  export function bootTime() {
119
235
  return Math.round((Date.now() - os.uptime() * 1000) / 1000);
120
236
  }
121
237
 
238
+ /**
239
+ * Evaluates whether a lock record belongs to the current boot session.
240
+ *
241
+ * When both the lock and the current environment supply a bootId (Linux
242
+ * /proc/sys/kernel/random/boot_id or macOS kern.bootsessionuuid), identity is
243
+ * determined by exact bootId match, which is immune to wall-clock jumps.
244
+ *
245
+ * For legacy locks or environments without a bootId, falls back to checking
246
+ * whether wall-clock bootTime is within a 30-second window.
247
+ *
248
+ * @param {{ bootId?: string, bootTime?: number }} [lock]
249
+ * @param {{ bootId?: string, bootTime?: number }} [current]
250
+ * @returns {boolean}
251
+ */
252
+ export function isSameBoot(lock, { bootId: curBootId = bootId(), bootTime: curBootTime = bootTime() } = {}) {
253
+ if (!lock) return false;
254
+ if (typeof lock.bootId === 'string' && lock.bootId.length > 0 && typeof curBootId === 'string' && curBootId.length > 0) {
255
+ return lock.bootId === curBootId;
256
+ }
257
+ if (typeof lock.bootTime === 'number' && Number.isFinite(lock.bootTime) && Number.isFinite(curBootTime)) {
258
+ return Math.abs(lock.bootTime - curBootTime) <= 30;
259
+ }
260
+ return false;
261
+ }
262
+
122
263
  export async function readLock(home) {
123
264
  try {
124
265
  return JSON.parse(await readFile(daemonPaths(home).lock, 'utf8'));
@@ -129,7 +270,7 @@ export async function readLock(home) {
129
270
  }
130
271
 
131
272
  export function lockAlive(lock) {
132
- if (!lock || !Number.isSafeInteger(lock.pid) || Math.abs((lock.bootTime ?? 0) - bootTime()) > 30) return false;
273
+ if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
133
274
  try {
134
275
  process.kill(lock.pid, 0);
135
276
  return true;
@@ -147,7 +288,17 @@ export function lockAlive(lock) {
147
288
  */
148
289
  export async function acquireDaemonLock(home, contents) {
149
290
  const file = daemonPaths(home).lock;
150
- const lock = { pid: process.pid, startedAt: new Date().toISOString(), bootTime: bootTime(), uid: process.getuid?.() ?? -1, ready: false, ...contents };
291
+ const currentBootId = bootId();
292
+ const lock = {
293
+ pid: process.pid,
294
+ startedAt: new Date().toISOString(),
295
+ startedUptime: Math.floor(os.uptime()),
296
+ bootTime: bootTime(),
297
+ ...(currentBootId ? { bootId: currentBootId } : {}),
298
+ uid: process.getuid?.() ?? -1,
299
+ ready: false,
300
+ ...contents,
301
+ };
151
302
  for (let attempt = 0; attempt < 2; attempt++) {
152
303
  try {
153
304
  const handle = await open(file, 'wx', 0o600);
@@ -178,6 +329,14 @@ export async function releaseDaemonLock(home) {
178
329
  * CLI, alpd's tests and the Paseo plugin use.
179
330
  */
180
331
  export class AlpClient extends AlpRpcClient {
332
+ /** Host features captured by connect's handshake. @type {readonly string[]} */
333
+ capabilities = [];
334
+ /** Limits captured by connect's handshake. @type {import('@anhlp/alp-protocol').AttachmentLimits | undefined} */
335
+ attachmentLimits;
336
+ /** @type {{ readonly maxCount: number; readonly maxBytes: number; readonly maxTotalBytes: number } | undefined} */
337
+ promptImageLimits;
338
+ /** @type {import('@anhlp/alp-protocol').TerminalLimits | undefined} */
339
+ terminalLimits;
181
340
  /**
182
341
  * @param {import('node:net').Socket} socket a connected or connecting socket; the client owns it
183
342
  * @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
@@ -217,7 +376,17 @@ export async function connectSocket(socketPath, options) {
217
376
  export async function connect(socketPath, client = { name: 'alp', version: '0' }, options = {}) {
218
377
  const connection = new AlpClient(await openSocket(socketPath), options);
219
378
  try {
220
- await hello(connection, client);
379
+ const greeting = await hello(connection, client, undefined, { agent: typeof process.env.ALP_AGENT_SESSION === 'string' && process.env.ALP_AGENT_SESSION !== '' });
380
+ connection.capabilities = Object.freeze(Array.isArray(greeting.capabilities) ? greeting.capabilities.filter(value => typeof value === 'string') : []);
381
+ if (greeting.attachmentLimits && typeof greeting.attachmentLimits === 'object') {
382
+ connection.attachmentLimits = Object.freeze({ ...greeting.attachmentLimits });
383
+ }
384
+ if (greeting.promptImageLimits && typeof greeting.promptImageLimits === 'object') {
385
+ connection.promptImageLimits = Object.freeze({ ...greeting.promptImageLimits });
386
+ }
387
+ if (greeting.terminalLimits && typeof greeting.terminalLimits === 'object') {
388
+ connection.terminalLimits = Object.freeze({ ...greeting.terminalLimits });
389
+ }
221
390
  } catch (error) {
222
391
  connection.close();
223
392
  throw error;
@@ -262,7 +431,8 @@ export async function readDaemonLifecycle(home) {
262
431
  * be replaced. Reaping/release unlinks only its unique owner token, then rmdir; even
263
432
  * racing stale reapers cannot remove a successor's nonempty directory.
264
433
  */
265
- export async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}) {
434
+ export async function withDaemonLifecycle(home, action, run, { joinStart = false, signal = /** @type {AbortSignal | undefined} */ (undefined) } = {}) {
435
+ signal?.throwIfAborted();
266
436
  try {
267
437
  await assertPrivateDirectory(home, { create: true });
268
438
  } catch (cause) {
@@ -273,10 +443,17 @@ export async function withDaemonLifecycle(home, action, run, { joinStart = false
273
443
  const state = path.join(home, 'state');
274
444
  await assertPrivateDirectory(state, { create: true });
275
445
  const directory = path.join(state, 'alpd.starting');
446
+ const currentBootId = bootId();
276
447
  const token = `owner-${process.pid}-${bootTime()}-${action}-${randomUUID()}`;
277
448
  const candidate = path.join(state, `alpd.starting-${token}`);
278
449
  await mkdir(candidate, { mode: 0o700 });
279
- await writeFile(path.join(candidate, token), JSON.stringify({ pid: process.pid, bootTime: bootTime(), action }), { mode: 0o600 });
450
+ await writeFile(path.join(candidate, token), JSON.stringify({
451
+ pid: process.pid,
452
+ bootTime: bootTime(),
453
+ ...(currentBootId ? { bootId: currentBootId } : {}),
454
+ startedUptime: Math.floor(os.uptime()),
455
+ action,
456
+ }), { mode: 0o600 });
280
457
  try {
281
458
  let joined = false;
282
459
  if (joinStart) {
@@ -291,6 +468,7 @@ export async function withDaemonLifecycle(home, action, run, { joinStart = false
291
468
  }
292
469
  }
293
470
  while (!joined) {
471
+ signal?.throwIfAborted();
294
472
  try { await rename(candidate, directory); break; }
295
473
  catch (error) {
296
474
  if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(error.code)) throw error;
@@ -298,10 +476,10 @@ export async function withDaemonLifecycle(home, action, run, { joinStart = false
298
476
  if (!lockAlive(owner)) await unlink(path.join(directory, owner.token)).catch(error => { if (error.code !== 'ENOENT') throw error; });
299
477
  }
300
478
  await rmdir(directory).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
301
- await new Promise(resolve => setTimeout(resolve, 25));
479
+ await delay(25, undefined, { signal });
302
480
  }
303
481
  }
304
- try { return await run(); }
482
+ try { signal?.throwIfAborted(); return await run(); }
305
483
  finally {
306
484
  await unlink(path.join(directory, token));
307
485
  await rmdir(directory).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
@@ -317,8 +495,9 @@ export async function withDaemonLifecycle(home, action, run, { joinStart = false
317
495
  * `entry` is the daemon script; it is started through its own detaching launcher so the
318
496
  * daemon outlives the client that started it.
319
497
  */
320
- export async function ensureDaemon({ home = alpHome(), entry = /** @type {string | undefined} */ (undefined), env = process.env, execPath = process.execPath, timeoutMs = 15_000, lifecycleLocked = false } = {}) {
321
- if (!lifecycleLocked) return withDaemonLifecycle(home, 'start', () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true }));
498
+ export async function ensureDaemon({ home = alpHome(), entry = /** @type {string | undefined} */ (undefined), env = process.env, execPath = process.execPath, timeoutMs = 15_000, lifecycleLocked = false, signal = /** @type {AbortSignal | undefined} */ (undefined) } = {}) {
499
+ signal?.throwIfAborted();
500
+ if (!lifecycleLocked) return withDaemonLifecycle(home, 'start', () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true, signal }), { signal });
322
501
  const ready = async () => {
323
502
  const lock = await readLock(home);
324
503
  return lockAlive(lock) && lock.ready ? lock.socket : undefined;
@@ -330,8 +509,10 @@ export async function ensureDaemon({ home = alpHome(), entry = /** @type {string
330
509
  if (!lockAlive(held)) {
331
510
  entry ??= await findDaemonEntry({ home, env });
332
511
  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');
512
+ signal?.throwIfAborted();
333
513
  await new Promise((resolve, reject) => {
334
- const launcher = spawn(execPath, [entry, '--detach', `--startup-timeout=${timeoutMs}`], {
514
+ const launch = entryCommand(entry, 'daemon', ['--detach', `--startup-timeout=${timeoutMs}`], execPath);
515
+ const launcher = spawn(launch.command, launch.args, {
335
516
  env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: '1' },
336
517
  stdio: ['ignore', 'ignore', 'pipe'],
337
518
  windowsHide: true,
@@ -345,6 +526,7 @@ export async function ensureDaemon({ home = alpHome(), entry = /** @type {string
345
526
  }
346
527
  const deadline = Date.now() + timeoutMs;
347
528
  while (Date.now() < deadline) {
529
+ signal?.throwIfAborted();
348
530
  const socket = await ready();
349
531
  if (socket) return socket;
350
532
  await new Promise(resolve => setTimeout(resolve, 100));
@@ -391,7 +573,7 @@ async function integrationCandidateFromHome(home, name) {
391
573
  }
392
574
 
393
575
  function integrationBinaryName(name) {
394
- return name === 'web' ? 'alp-web-integration' : `alp-${name}-integration`;
576
+ return `alp-${name}-integration`;
395
577
  }
396
578
 
397
579
  /** Distribution roots that may carry a bundled integration descriptor. */
@@ -415,12 +597,26 @@ async function distributionRoots() {
415
597
  return [...new Set(roots)];
416
598
  }
417
599
 
600
+ /**
601
+ * The entry of integration `name`: an environment override, a descriptor under the home or a
602
+ * distribution root, or an `alp-<name>-integration` binary. Discovery never returns an entry for
603
+ * `web`: that name belongs to alp-web, which ships with the CLI and is started with its explicit
604
+ * entry. Everything once registered under `web` (the descriptor `integrations/web.json`, the
605
+ * `alp-web-integration` binary, `ALP_WEB_INTEGRATION`) is the Paseo integration from before its
606
+ * rename to `paseo`, which must never run under the web lock. `ALP_WEB_INTEGRATION` is read for
607
+ * `paseo` only, after `ALP_PASEO_INTEGRATION`, for one release (like the alp-web-integration alias).
608
+ * @param {string} [name]
609
+ * @param {{ home?: string }} [options]
610
+ */
418
611
  export async function discoverIntegration(name = 'web', options = {}) {
419
- // Explicit environment override always wins.
612
+ // The name becomes a descriptor path under <home>/integrations, so it must stay one safe segment.
613
+ assertIntegrationName(name);
614
+ if (name === 'web') return undefined;
615
+ // Explicit environment override always wins: the integration's own, then the generic one.
420
616
  const envCandidates = [
421
- process.env.ALP_WEB_INTEGRATION,
617
+ process.env[`ALP_${name.toUpperCase()}_INTEGRATION`],
618
+ name === 'paseo' ? process.env.ALP_WEB_INTEGRATION : undefined,
422
619
  process.env.ALP_INTEGRATION_ENTRY,
423
- name !== 'web' ? process.env[`ALP_${name.toUpperCase()}_INTEGRATION`] : undefined,
424
620
  ].filter(Boolean);
425
621
  for (const candidate of envCandidates) if (await isFile(candidate)) return candidate;
426
622
 
@@ -445,29 +641,72 @@ export async function discoverIntegration(name = 'web', options = {}) {
445
641
  return undefined;
446
642
  }
447
643
 
448
- function integrationAlive(lock) {
449
- if (!lock || !Number.isSafeInteger(lock.pid)) return false;
450
- try { process.kill(lock.pid, 0); } catch (error) {
644
+ export function integrationAlive(lock) {
645
+ if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
646
+ try {
647
+ process.kill(lock.pid, 0);
648
+ return true;
649
+ } catch (error) {
451
650
  return error?.code === 'EPERM';
452
651
  }
453
- if (typeof lock.bootTime === 'number' && Math.abs(lock.bootTime - bootTime()) > 30) return false;
454
- return true;
455
652
  }
456
653
 
654
+ /**
655
+ * What startIntegration says about integration `name`, and where its service writes its log: alp-web
656
+ * (`web`) is part of the CLI, Paseo (`paseo`) an optional package, anything else named as is.
657
+ * @param {string} name
658
+ * @param {string} home
659
+ */
660
+ function integrationText(name, home) {
661
+ const logs = path.join(home, 'logs', 'integrations');
662
+ if (name === 'web') return {
663
+ what: 'alp web',
664
+ log: path.join(logs, 'alp-web.log'),
665
+ missing: 'alp web runs the alp-web service of the ALP CLI, which is started with its entry (packages/cli/dist/alp-web.js); run `alp web`',
666
+ };
667
+ if (name === 'paseo') return {
668
+ what: 'The Paseo integration',
669
+ log: path.join(logs, 'paseo.log'),
670
+ 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.',
671
+ };
672
+ return {
673
+ what: `ALP integration ${name}`,
674
+ log: path.join(logs, `${name}.log`),
675
+ missing: `ALP integration ${name} is not installed: no ALP_${name.toUpperCase()}_INTEGRATION, descriptor <home>/integrations/${name}.json or alp-${name}-integration binary was found.`,
676
+ };
677
+ }
678
+
679
+ /**
680
+ * Starts integration `name` (default `web`) detached with `--service` (then `args`) unless its lock
681
+ * already names a live owner, then waits until its ready lock and `<home>/<name>.json` name the same
682
+ * pid. `entry` names the script to run with this Node and skips descriptor, environment and PATH
683
+ * discovery; `web` (alp-web) is never discovered, so it needs its entry. `"web": { "enabled": false }`
684
+ * in the home's settings.json refuses `web` only.
685
+ * @param {string | { name?: string, entry?: string, home?: string, args?: string[] }} [nameOrOptions]
686
+ */
457
687
  export async function startIntegration(nameOrOptions = 'web') {
458
688
  const options = typeof nameOrOptions === 'string' ? { name: nameOrOptions } : (nameOrOptions ?? {});
459
- const name = options.name ?? 'web';
689
+ const name = assertIntegrationName(options.name ?? 'web');
690
+ if (options.entry !== undefined && (typeof options.entry !== 'string' || !options.entry)) throw new TypeError('startIntegration entry must be a non-empty path');
691
+ const args = options.args ?? [];
692
+ if (!Array.isArray(args) || !args.every(arg => typeof arg === 'string')) throw new TypeError('startIntegration args must be a list of strings');
460
693
  const fs = await import('node:fs/promises');
461
694
  const pathMod = await import('node:path');
462
695
  const home = options.home ? pathMod.resolve(options.home) : alpHome();
696
+ const text = integrationText(name, home);
697
+ // An explicit entry is the caller's own service script: it must exist even when a live owner is
698
+ // reused, and it replaces descriptor, environment and PATH discovery.
699
+ const explicit = options.entry !== undefined ? pathMod.resolve(options.entry) : undefined;
700
+ if (explicit !== undefined && !(await isFile(explicit))) throw new Error(`${text.what}: integration entry not found: ${explicit}`);
463
701
  const lockPath = pathMod.join(home, 'integrations', `${name}.lock`);
464
702
  const webPath = pathMod.join(home, `${name}.json`);
703
+ const started = explicit ? ` (entry ${explicit})` : '';
465
704
 
466
- // Clear, actionable diagnostics for a disabled optional integration.
467
- let settings = {};
468
- try { settings = JSON.parse(await fs.readFile(pathMod.join(home, 'settings.json'), 'utf8')); } catch {}
469
- if (settings?.web?.enabled === false) {
470
- throw new Error('ALP web app is disabled by settings ("web.enabled": false).');
705
+ // web.enabled turns off alp web only; other integrations have their own switches.
706
+ if (name === 'web') {
707
+ let settings = {};
708
+ try { settings = JSON.parse(await fs.readFile(pathMod.join(home, 'settings.json'), 'utf8')); } catch {}
709
+ if (settings?.web?.enabled === false) throw new Error('alp web is disabled by settings ("web.enabled": false).');
471
710
  }
472
711
 
473
712
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
@@ -478,7 +717,7 @@ export async function startIntegration(nameOrOptions = 'web') {
478
717
  try { return JSON.parse(await fs.readFile(webPath, 'utf8')); } catch { return undefined; }
479
718
  };
480
719
 
481
- // The authoritative check: the ready integration lock and live web.json must name the same pid.
720
+ // The authoritative check: the ready integration lock and live <name>.json must name the same pid.
482
721
  // A loser of a concurrent start accepts the winning pid after its own contender has exited or
483
722
  // the lock already names the winner.
484
723
  async function waitForReady() {
@@ -489,40 +728,47 @@ export async function startIntegration(nameOrOptions = 'web') {
489
728
  const info = await readWeb();
490
729
  if (info && info.pid === lock.pid) return lock;
491
730
  }
731
+ // alp-web can fail during bootstrap after the initial exit check (for example a
732
+ // refused uncertain lock). Its service log carries the cause; do not mask it with
733
+ // a readiness/web.json timeout. Check a concurrent winner's ready lock first.
734
+ if (name === 'web' && webStartupFailed()) throw new Error(`${text.what}${started} failed to start; see ${text.log}`);
492
735
  await sleep(100);
493
736
  }
494
737
  const lock = await readLock();
495
- if (lock && !lock.ready) throw new Error('ALP web integration started but did not become ready; see ~/.alp/logs/integrations/paseo.log');
496
- 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.');
497
- throw new Error('ALP web integration did not publish a matching web.json lock');
738
+ if (lock && !lock.ready) throw new Error(`${text.what}${started} started but did not become ready; see ${text.log}`);
739
+ if (!lock) throw new Error(explicit ? `${text.what}${started} did not start; see ${text.log}` : text.missing);
740
+ throw new Error(`${text.what}${started} did not publish a ${name}.json matching its lock; see ${text.log}`);
498
741
  }
499
742
 
743
+ // Existing-owner waits have no child to observe.
744
+ let webStartupFailed = () => false;
500
745
  const existing = await readLock();
501
746
  if (existing && integrationAlive(existing)) {
502
747
  return waitForReady();
503
748
  }
504
749
 
505
- const entry = await discoverIntegration(name, { home });
506
- if (!entry) {
507
- 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.');
508
- }
750
+ const entry = explicit ?? await discoverIntegration(name, { home });
751
+ if (!entry) throw new Error(text.missing);
509
752
 
510
753
  const { spawn } = await import('node:child_process');
511
754
  // The child is detached with its stdio ignored, so it cannot rely on the parent's console. `--service`
512
755
  // is the generic contract: the entry writes its own log (the path its error messages advertise) and
513
756
  // keeps the process alive as a service. `--register` still prints to stdout and is not passed here.
514
- const child = spawn(process.execPath, [entry, '--service'], { stdio: 'ignore', detached: true, env: { ...process.env, ALP_HOME: home } });
757
+ // alp-web may be the ALP executable itself (`alp web serve`); other integrations are scripts.
758
+ const launch = name === 'web' ? entryCommand(entry, 'web', ['--service', ...args]) : entryCommand(entry, 'web', ['--service', ...args], undefined, { scriptOnly: true });
759
+ const child = spawn(launch.command, launch.args, { stdio: 'ignore', detached: true, env: { ...process.env, ALP_HOME: home } });
515
760
  let spawnError = null;
516
761
  child.on('error', error => { spawnError = error; });
517
762
  let exited = false;
518
763
  child.on('exit', code => { if (code !== 0 && code !== null) exited = true; });
519
764
  child.unref();
765
+ webStartupFailed = () => exited;
520
766
 
521
767
  if (spawnError) throw spawnError;
522
768
  // Give the process a moment to fail immediately on missing entry or bad permissions.
523
769
  await sleep(150);
524
770
  if (spawnError) throw spawnError;
525
- if (exited) throw new Error('ALP web integration failed to start; see ~/.alp/logs/integrations/paseo.log');
771
+ if (exited) throw new Error(`${text.what}${explicit ? started : ` (${entry})`} failed to start; see ${text.log}`);
526
772
 
527
773
  return waitForReady();
528
774
  }