@anhlp/alp-client 0.0.1-beta.4 → 0.0.1-beta.6

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,15 +152,21 @@ 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
  }
@@ -125,11 +184,82 @@ export function assertIntegrationName(name) {
125
184
  return name;
126
185
  }
127
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
+
128
233
  /** Wall-clock boot time; a lock from an earlier boot is stale even if its pid is reused. */
129
234
  export function bootTime() {
130
235
  return Math.round((Date.now() - os.uptime() * 1000) / 1000);
131
236
  }
132
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
+
133
263
  export async function readLock(home) {
134
264
  try {
135
265
  return JSON.parse(await readFile(daemonPaths(home).lock, 'utf8'));
@@ -140,7 +270,7 @@ export async function readLock(home) {
140
270
  }
141
271
 
142
272
  export function lockAlive(lock) {
143
- 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;
144
274
  try {
145
275
  process.kill(lock.pid, 0);
146
276
  return true;
@@ -158,7 +288,17 @@ export function lockAlive(lock) {
158
288
  */
159
289
  export async function acquireDaemonLock(home, contents) {
160
290
  const file = daemonPaths(home).lock;
161
- 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
+ };
162
302
  for (let attempt = 0; attempt < 2; attempt++) {
163
303
  try {
164
304
  const handle = await open(file, 'wx', 0o600);
@@ -191,6 +331,12 @@ export async function releaseDaemonLock(home) {
191
331
  export class AlpClient extends AlpRpcClient {
192
332
  /** Host features captured by connect's handshake. @type {readonly string[]} */
193
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;
194
340
  /**
195
341
  * @param {import('node:net').Socket} socket a connected or connecting socket; the client owns it
196
342
  * @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
@@ -230,8 +376,17 @@ export async function connectSocket(socketPath, options) {
230
376
  export async function connect(socketPath, client = { name: 'alp', version: '0' }, options = {}) {
231
377
  const connection = new AlpClient(await openSocket(socketPath), options);
232
378
  try {
233
- const greeting = 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 !== '' });
234
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
+ }
235
390
  } catch (error) {
236
391
  connection.close();
237
392
  throw error;
@@ -276,7 +431,8 @@ export async function readDaemonLifecycle(home) {
276
431
  * be replaced. Reaping/release unlinks only its unique owner token, then rmdir; even
277
432
  * racing stale reapers cannot remove a successor's nonempty directory.
278
433
  */
279
- 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();
280
436
  try {
281
437
  await assertPrivateDirectory(home, { create: true });
282
438
  } catch (cause) {
@@ -287,10 +443,17 @@ export async function withDaemonLifecycle(home, action, run, { joinStart = false
287
443
  const state = path.join(home, 'state');
288
444
  await assertPrivateDirectory(state, { create: true });
289
445
  const directory = path.join(state, 'alpd.starting');
446
+ const currentBootId = bootId();
290
447
  const token = `owner-${process.pid}-${bootTime()}-${action}-${randomUUID()}`;
291
448
  const candidate = path.join(state, `alpd.starting-${token}`);
292
449
  await mkdir(candidate, { mode: 0o700 });
293
- 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 });
294
457
  try {
295
458
  let joined = false;
296
459
  if (joinStart) {
@@ -305,6 +468,7 @@ export async function withDaemonLifecycle(home, action, run, { joinStart = false
305
468
  }
306
469
  }
307
470
  while (!joined) {
471
+ signal?.throwIfAborted();
308
472
  try { await rename(candidate, directory); break; }
309
473
  catch (error) {
310
474
  if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(error.code)) throw error;
@@ -312,10 +476,10 @@ export async function withDaemonLifecycle(home, action, run, { joinStart = false
312
476
  if (!lockAlive(owner)) await unlink(path.join(directory, owner.token)).catch(error => { if (error.code !== 'ENOENT') throw error; });
313
477
  }
314
478
  await rmdir(directory).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
315
- await new Promise(resolve => setTimeout(resolve, 25));
479
+ await delay(25, undefined, { signal });
316
480
  }
317
481
  }
318
- try { return await run(); }
482
+ try { signal?.throwIfAborted(); return await run(); }
319
483
  finally {
320
484
  await unlink(path.join(directory, token));
321
485
  await rmdir(directory).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
@@ -331,8 +495,9 @@ export async function withDaemonLifecycle(home, action, run, { joinStart = false
331
495
  * `entry` is the daemon script; it is started through its own detaching launcher so the
332
496
  * daemon outlives the client that started it.
333
497
  */
334
- export async function ensureDaemon({ home = alpHome(), entry = /** @type {string | undefined} */ (undefined), env = process.env, execPath = process.execPath, timeoutMs = 15_000, lifecycleLocked = false } = {}) {
335
- 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 });
336
501
  const ready = async () => {
337
502
  const lock = await readLock(home);
338
503
  return lockAlive(lock) && lock.ready ? lock.socket : undefined;
@@ -344,8 +509,10 @@ export async function ensureDaemon({ home = alpHome(), entry = /** @type {string
344
509
  if (!lockAlive(held)) {
345
510
  entry ??= await findDaemonEntry({ home, env });
346
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();
347
513
  await new Promise((resolve, reject) => {
348
- 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, {
349
516
  env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: '1' },
350
517
  stdio: ['ignore', 'ignore', 'pipe'],
351
518
  windowsHide: true,
@@ -359,6 +526,7 @@ export async function ensureDaemon({ home = alpHome(), entry = /** @type {string
359
526
  }
360
527
  const deadline = Date.now() + timeoutMs;
361
528
  while (Date.now() < deadline) {
529
+ signal?.throwIfAborted();
362
530
  const socket = await ready();
363
531
  if (socket) return socket;
364
532
  await new Promise(resolve => setTimeout(resolve, 100));
@@ -473,13 +641,14 @@ export async function discoverIntegration(name = 'web', options = {}) {
473
641
  return undefined;
474
642
  }
475
643
 
476
- function integrationAlive(lock) {
477
- if (!lock || !Number.isSafeInteger(lock.pid)) return false;
478
- 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) {
479
650
  return error?.code === 'EPERM';
480
651
  }
481
- if (typeof lock.bootTime === 'number' && Math.abs(lock.bootTime - bootTime()) > 30) return false;
482
- return true;
483
652
  }
484
653
 
485
654
  /**
@@ -559,6 +728,10 @@ export async function startIntegration(nameOrOptions = 'web') {
559
728
  const info = await readWeb();
560
729
  if (info && info.pid === lock.pid) return lock;
561
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}`);
562
735
  await sleep(100);
563
736
  }
564
737
  const lock = await readLock();
@@ -567,6 +740,8 @@ export async function startIntegration(nameOrOptions = 'web') {
567
740
  throw new Error(`${text.what}${started} did not publish a ${name}.json matching its lock; see ${text.log}`);
568
741
  }
569
742
 
743
+ // Existing-owner waits have no child to observe.
744
+ let webStartupFailed = () => false;
570
745
  const existing = await readLock();
571
746
  if (existing && integrationAlive(existing)) {
572
747
  return waitForReady();
@@ -579,12 +754,15 @@ export async function startIntegration(nameOrOptions = 'web') {
579
754
  // The child is detached with its stdio ignored, so it cannot rely on the parent's console. `--service`
580
755
  // is the generic contract: the entry writes its own log (the path its error messages advertise) and
581
756
  // keeps the process alive as a service. `--register` still prints to stdout and is not passed here.
582
- const child = spawn(process.execPath, [entry, '--service', ...args], { 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 } });
583
760
  let spawnError = null;
584
761
  child.on('error', error => { spawnError = error; });
585
762
  let exited = false;
586
763
  child.on('exit', code => { if (code !== 0 && code !== null) exited = true; });
587
764
  child.unref();
765
+ webStartupFailed = () => exited;
588
766
 
589
767
  if (spawnError) throw spawnError;
590
768
  // Give the process a moment to fail immediately on missing entry or bad permissions.
@@ -1,10 +1,12 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { mkdir, open, rename, rmdir, unlink } from 'node:fs/promises';
2
+ import { mkdir, open, rmdir, unlink } from 'node:fs/promises';
3
+ import os from 'node:os';
3
4
  import path from 'node:path';
4
- import { assertIntegrationName, bootTime } from './index.js';
5
+ import { moveFile } from '@anhlp/alp-core/atomic';
6
+ import { assertIntegrationName, bootId, bootTime, isSameBoot } from './index.js';
5
7
 
6
8
  /**
7
- * @typedef {{ pid: number, bootTime: number, startedAt: string, ready: boolean, lockVersion?: number, owner?: string }} IntegrationLockRecord
9
+ * @typedef {{ pid: number, bootTime: number, bootId?: string, startedUptime?: number, startedAt: string, ready: boolean, lockVersion?: number, owner?: string }} IntegrationLockRecord
8
10
  * @typedef {{
9
11
  * acquire(): Promise<{ acquired: boolean, lock: IntegrationLockRecord }>,
10
12
  * setReady(ready: boolean): Promise<boolean>,
@@ -29,6 +31,8 @@ export function createIntegrationLock(home, name) {
29
31
  let phase = 'new';
30
32
  /** This instance's lock while it owns it: the lifetime nonce and the file's identity. @type {{ owner: string, dev: number, ino: number } | undefined} */
31
33
  let owned;
34
+ /** Serializes concurrent in-process setReady calls to preserve FIFO order. @type {Promise<any>} */
35
+ let readyQueue = Promise.resolve();
32
36
  // The lock file as read: its record and the stats of the handle it was read through. Kept inside
33
37
  // the factory so the published declarations name only IntegrationLock and its record.
34
38
  /** @typedef {{ value: any, info: import('node:fs').Stats }} Snapshot */
@@ -89,6 +93,8 @@ export function createIntegrationLock(home, name) {
89
93
  function complete(value) {
90
94
  return value && Number.isSafeInteger(value.pid) && value.pid > 0
91
95
  && typeof value.bootTime === 'number' && Number.isFinite(value.bootTime) && value.bootTime > 0
96
+ && (value.bootId === undefined || typeof value.bootId === 'string' && value.bootId.length > 0)
97
+ && (value.startedUptime === undefined || typeof value.startedUptime === 'number' && Number.isFinite(value.startedUptime))
92
98
  && typeof value.startedAt === 'string' && Number.isFinite(Date.parse(value.startedAt))
93
99
  && typeof value.ready === 'boolean'
94
100
  && (value.lockVersion === undefined && value.owner === undefined
@@ -104,7 +110,7 @@ export function createIntegrationLock(home, name) {
104
110
  catch (error) {
105
111
  if (/** @type {any} */ (error)?.code !== 'ESRCH') return false; // EPERM and unknown errors never grant takeover.
106
112
  // Approximate wall-clock boot metadata is context, never affirmative death evidence.
107
- if (Math.abs(value.bootTime - bootTime()) > 30) throw recovery('Integration owner boot context is uncertain');
113
+ if (!isSameBoot(value)) throw recovery('Integration owner boot context is uncertain');
108
114
  return true;
109
115
  }
110
116
  }
@@ -130,8 +136,18 @@ export function createIntegrationLock(home, name) {
130
136
  if (!dead(current.value)) { phase = 'retired'; return { acquired: false, lock: current.value }; }
131
137
  await unlink(file);
132
138
  }
139
+ const currentBootId = bootId();
133
140
  /** @type {IntegrationLockRecord & { owner: string }} */
134
- const value = { pid: process.pid, bootTime: bootTime(), startedAt: new Date().toISOString(), ready: false, lockVersion: 1, owner: randomUUID() };
141
+ const value = {
142
+ pid: process.pid,
143
+ bootTime: bootTime(),
144
+ ...(currentBootId ? { bootId: currentBootId } : {}),
145
+ startedAt: new Date().toISOString(),
146
+ startedUptime: Math.floor(os.uptime()),
147
+ ready: false,
148
+ lockVersion: 1,
149
+ owner: randomUUID(),
150
+ };
135
151
  const handle = await open(file, 'wx', 0o600);
136
152
  let info;
137
153
  try { await handle.writeFile(JSON.stringify(value)); info = await handle.stat(); }
@@ -145,22 +161,30 @@ export function createIntegrationLock(home, name) {
145
161
 
146
162
  async setReady(ready) {
147
163
  if (phase !== 'owned') return false;
148
- return guarded(async () => {
164
+ const execute = async () => {
149
165
  if (phase !== 'owned') return false;
150
- const current = await snapshot();
151
- if (!current || !matches(current)) { phase = 'retired'; owned = undefined; return false; }
152
- const value = { ...current.value, ready };
153
- const tmp = `${file}.${randomUUID()}.tmp`;
154
- const handle = await open(tmp, 'wx', 0o600);
155
- let info;
156
- try {
157
- try { await handle.writeFile(JSON.stringify(value)); info = await handle.stat(); }
158
- finally { await handle.close(); }
159
- await rename(tmp, file);
160
- owned = { owner: value.owner, dev: info.dev, ino: info.ino };
161
- return true;
162
- } finally { await unlink(tmp).catch(error => { if (error?.code !== 'ENOENT') throw error; }); }
163
- });
166
+ return guarded(async () => {
167
+ if (phase !== 'owned') return false;
168
+ const current = await snapshot();
169
+ if (!current || !matches(current)) { phase = 'retired'; owned = undefined; return false; }
170
+ const value = { ...current.value, ready };
171
+ const tmp = `${file}.${randomUUID()}.tmp`;
172
+ const handle = await open(tmp, 'wx', 0o600);
173
+ let info;
174
+ try {
175
+ try { await handle.writeFile(JSON.stringify(value)); info = await handle.stat(); }
176
+ finally { await handle.close(); }
177
+ // Readers (alp web status, a polling client) may hold the lock open; Windows then refuses the
178
+ // replace with EPERM/EACCES/EBUSY for a moment, so moveFile retries it there.
179
+ await moveFile(tmp, file);
180
+ owned = { owner: value.owner, dev: info.dev, ino: info.ino };
181
+ return true;
182
+ } finally { await unlink(tmp).catch(error => { if (error?.code !== 'ENOENT') throw error; }); }
183
+ });
184
+ };
185
+ const chained = readyQueue.then(execute, execute);
186
+ readyQueue = chained.catch(() => {});
187
+ return chained;
164
188
  },
165
189
 
166
190
  async release() {
package/src/mcp-probe.js CHANGED
@@ -35,7 +35,7 @@ export function stdioSession(server, cwd, timeoutMs) {
35
35
  // Its own process group, so a launcher such as npx is stopped with what it started.
36
36
  const env = { ...process.env, ...(server.env ?? {}) };
37
37
  const launch = launchCommand(server.command, server.args ?? [], env);
38
- const child = spawn(launch.command, launch.args, { cwd: server.cwd ?? cwd, env, stdio: ['pipe', 'pipe', 'pipe'], detached: true });
38
+ const child = spawn(launch.command, launch.args, { cwd: server.cwd ?? cwd, env: launch.env ? { ...env, ...launch.env } : env, stdio: ['pipe', 'pipe', 'pipe'], detached: true });
39
39
  const signal = name => { try { process.kill(-child.pid, name); } catch { child.kill(name); } };
40
40
  let stderr = '';
41
41
  child.stderr.setEncoding('utf8');
package/src/portable.js CHANGED
@@ -23,6 +23,8 @@ export { AlpRpcClient, DEFAULT_MAX_PENDING } from './rpc/client.js';
23
23
  export { AlpClientError, CLIENT_ERROR, isAlpClientError } from './rpc/errors.js';
24
24
  export { createLineDecoder, utf8Length } from './rpc/framing.js';
25
25
  export { MAX_TIMER_MS, timerDelay } from './rpc/timers.js';
26
- export { hello } from './rpc/handshake.js';
26
+ export { AGENT_CAPABILITY, hello } from './rpc/handshake.js';
27
27
  export { backoffDelay, createReconnectingClient, retryable } from './rpc/reconnect.js';
28
28
  export { attachments, base64Encode, conversation, sha256Hex, workspaceRegistry } from './rpc/registry.js';
29
+
30
+ export { watchTerminals } from "./rpc/terminal-directory.js";
@@ -1,5 +1,8 @@
1
1
  import { PROTOCOL_VERSION } from '@anhlp/alp-protocol';
2
2
 
3
+ /** The daemon.hello capability a process an ALP agent started announces. */
4
+ export const AGENT_CAPABILITY = 'principal.agent';
5
+
3
6
  /** @typedef {{ name: string, version: string }} ClientInfo */
4
7
 
5
8
  /**
@@ -9,8 +12,10 @@ import { PROTOCOL_VERSION } from '@anhlp/alp-protocol';
9
12
  * @param {{ request(method: string, params?: unknown, options?: import('./client.js').RequestOptions): Promise<any> }} client
10
13
  * @param {ClientInfo} [info]
11
14
  * @param {import('./client.js').RequestOptions} [options]
15
+ * @param {{ agent?: boolean }} [principal] `agent`: an ALP agent started this process (the Node entry reads ALP_AGENT_SESSION).
12
16
  * @returns {Promise<{ protocolVersion: number } & Record<string, unknown>>}
13
17
  */
14
- export function hello(client, info = { name: 'alp', version: '0' }, options) {
15
- return client.request('daemon.hello', { protocolVersion: PROTOCOL_VERSION, client: info }, options);
18
+ export function hello(client, info = { name: 'alp', version: '0' }, options, { agent = false } = {}) {
19
+ // A process an ALP agent started says so (t-ca1f): alpd then refuses it what only the user may do.
20
+ return client.request('daemon.hello', { protocolVersion: PROTOCOL_VERSION, client: info, ...(agent ? { capabilities: [AGENT_CAPABILITY] } : {}) }, options);
16
21
  }
@@ -78,29 +78,92 @@ export function attachments(client) {
78
78
  * Uploads `data` and commits it: begin (or resume, with the same requestId), chunks of at most
79
79
  * the smaller of `maxChunkBytes` and what begin answered, commit with its SHA-256. A chunk
80
80
  * refused `offset_mismatch` continues from the daemon's `received`. Returns the attachment.
81
- * @param {{ sessionId: string, name: string, mimeType: string, data: Uint8Array, requestId: string, sha256?: string, maxChunkBytes?: number, onProgress?: (received: number, size: number) => void }} options
81
+ * The returned promise exposes `.uploadId` once begun and `.abort(reason?: any)` to abort on alpd.
82
+ * @param {{ sessionId: string, name: string, mimeType: string, data: Uint8Array, requestId: string, sha256?: string, maxChunkBytes?: number, signal?: AbortSignal, onBegun?: (uploadId: string) => void, onProgress?: (received: number, size: number) => void }} options
83
+ * @returns {Promise<Map['attachment.commit']['result']['attachment']> & { readonly uploadId?: string, abort(reason?: any): Promise<void> }}
82
84
  */
83
- async upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, onProgress }) {
84
- const digest = sha256 ?? await sha256Hex(data);
85
- const begun = await api.begin({ sessionId, name, size: data.length, mimeType, sha256: digest, requestId });
86
- if (begun.state === 'committed' && begun.attachmentId) return (await api.get(begun.attachmentId)).attachment;
87
- const size = Math.max(1, Math.min(begun.maxChunkBytes, maxChunkBytes ?? Infinity));
88
- let offset = begun.received;
89
- for (let realigned = 0; offset < data.length;) {
90
- const end = Math.min(data.length, offset + size);
85
+ upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, signal, onBegun, onProgress }) {
86
+ /** @type {string | undefined} */
87
+ let uploadId;
88
+ let userAborted = false;
89
+ let userAbortReason;
90
+ const isAborted = () => userAborted || (signal?.aborted ?? false);
91
+ const getAbortReason = () => userAbortReason ?? signal?.reason ?? new Error('Upload aborted');
92
+
93
+ const onSignalAbort = () => {
94
+ if (uploadId) api.abort(uploadId).catch(() => {});
95
+ };
96
+ signal?.addEventListener?.('abort', onSignalAbort, { once: true });
97
+
98
+ const run = /** @type {Promise<Map['attachment.commit']['result']['attachment']> & { uploadId?: string, abort(reason?: any): Promise<void> }} */ ((async () => {
91
99
  try {
92
- const { received } = await api.chunk({ uploadId: begun.uploadId, offset, data: base64Encode(data.subarray(offset, end)) });
93
- offset = received;
94
- } catch (error) {
95
- const held = /** @type {any} */ (error)?.data;
96
- // Another attempt got further (or less far) than this one knew: continue where the daemon is.
97
- if (held?.reason !== 'offset_mismatch' || !Number.isSafeInteger(held.received) || ++realigned > 3) throw error;
98
- offset = held.received;
99
- continue;
100
+ if (isAborted()) throw getAbortReason();
101
+ const digest = sha256 ?? await sha256Hex(data);
102
+ if (isAborted()) throw getAbortReason();
103
+ const begun = await api.begin({ sessionId, name, size: data.length, mimeType, sha256: digest, requestId });
104
+ uploadId = begun.uploadId;
105
+ try { onBegun?.(begun.uploadId); }
106
+ catch (error) {
107
+ if (begun.state !== 'committed') await api.abort(begun.uploadId).catch(() => {});
108
+ throw error;
109
+ }
110
+ if (isAborted()) {
111
+ if (begun.state !== 'committed') await api.abort(begun.uploadId).catch(() => {});
112
+ throw getAbortReason();
113
+ }
114
+ if (begun.state === 'committed' && begun.attachmentId) return (await api.get(begun.attachmentId)).attachment;
115
+ const size = Math.max(1, Math.min(begun.maxChunkBytes, maxChunkBytes ?? Infinity));
116
+ let offset = begun.received;
117
+ for (let realigned = 0; offset < data.length;) {
118
+ if (isAborted()) {
119
+ await api.abort(begun.uploadId).catch(() => {});
120
+ throw getAbortReason();
121
+ }
122
+ const end = Math.min(data.length, offset + size);
123
+ try {
124
+ const { received } = await api.chunk({ uploadId: begun.uploadId, offset, data: base64Encode(data.subarray(offset, end)) });
125
+ offset = received;
126
+ } catch (error) {
127
+ if (isAborted()) {
128
+ await api.abort(begun.uploadId).catch(() => {});
129
+ throw getAbortReason();
130
+ }
131
+ const held = /** @type {any} */ (error)?.data;
132
+ // Another attempt got further (or less far) than this one knew: continue where the daemon is.
133
+ if (held?.reason !== 'offset_mismatch' || !Number.isSafeInteger(held.received) || ++realigned > 3) throw error;
134
+ offset = held.received;
135
+ continue;
136
+ }
137
+ if (isAborted()) {
138
+ await api.abort(begun.uploadId).catch(() => {});
139
+ throw getAbortReason();
140
+ }
141
+ try { onProgress?.(offset, data.length); }
142
+ catch (error) {
143
+ await api.abort(begun.uploadId).catch(() => {});
144
+ throw error;
145
+ }
146
+ }
147
+ if (isAborted()) {
148
+ await api.abort(begun.uploadId).catch(() => {});
149
+ throw getAbortReason();
150
+ }
151
+ return (await api.commit({ uploadId: begun.uploadId, sha256: digest })).attachment;
152
+ } finally {
153
+ signal?.removeEventListener?.('abort', onSignalAbort);
100
154
  }
101
- onProgress?.(offset, data.length);
102
- }
103
- return (await api.commit({ uploadId: begun.uploadId, sha256: digest })).attachment;
155
+ })());
156
+
157
+ Object.defineProperty(run, 'uploadId', {
158
+ get: () => uploadId,
159
+ enumerable: true,
160
+ });
161
+ run.abort = async (reason) => {
162
+ userAborted = true;
163
+ userAbortReason = reason ?? new Error('Upload aborted');
164
+ if (uploadId) await api.abort(uploadId).catch(() => {});
165
+ };
166
+ return run;
104
167
  },
105
168
  };
106
169
  return api;