@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/dist/index.js CHANGED
@@ -1,11 +1,14 @@
1
1
  // packages/client/src/index.js
2
- import { spawn } from "node:child_process";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { execFileSync, spawn } from "node:child_process";
3
4
  import { createHash, randomUUID } from "node:crypto";
5
+ import { readFileSync } from "node:fs";
4
6
  import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, rename, rmdir, link } from "node:fs/promises";
5
7
  import net from "node:net";
6
8
  import os from "node:os";
7
9
  import path from "node:path";
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";
@@ -76,31 +79,116 @@ async function assertPrivateSocket(socketPath) {
76
79
  return info;
77
80
  }
78
81
  var isFile = (file) => stat(file).then((info) => info.isFile(), () => false);
79
- var BIN_DIRECTORIES = [path.join(os.homedir(), ".npm-global", "bin"), path.join(os.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin"];
82
+ async function isAlpExecutable(file) {
83
+ if (isScript(file) || !isExecutableName(file) || !await isFile(file)) return false;
84
+ const handle = await open(file, "r").catch(() => void 0);
85
+ if (!handle) return false;
86
+ try {
87
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(4), 0, 4, 0);
88
+ if (bytesRead < 4) return false;
89
+ const magic = buffer.readUInt32BE(0);
90
+ const native = buffer.toString("latin1") === "\x7FELF" || buffer.subarray(0, 2).toString("latin1") === "MZ" || [4277009102, 4277009103, 3472551422, 3489328638, 3405691582].includes(magic);
91
+ if (!native) return false;
92
+ const marker = Buffer.from(EXECUTABLE_MARKER, "latin1");
93
+ const chunk = Buffer.alloc(1 << 20);
94
+ let tail2 = Buffer.alloc(0);
95
+ for (let position = 0; ; ) {
96
+ const { bytesRead: read } = await handle.read(chunk, 0, chunk.length, position);
97
+ if (!read) return false;
98
+ const window = Buffer.concat([tail2, chunk.subarray(0, read)]);
99
+ if (window.includes(marker)) return true;
100
+ tail2 = window.subarray(Math.max(0, window.length - marker.length + 1));
101
+ position += read;
102
+ }
103
+ } finally {
104
+ await handle.close();
105
+ }
106
+ }
107
+ var 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"];
80
108
  var CLI_PACKAGES = ["@anhlp/alp", "@anhlp/alp-cli"];
109
+ async function npmWrapperExecutable(launcher, platform = process.platform, arch = process.arch) {
110
+ if (path.basename(launcher) !== "alp.js") return void 0;
111
+ const root = path.resolve(path.dirname(launcher), "..");
112
+ const name = await readFile(path.join(root, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
113
+ if (name !== "@anhlp/alp") return void 0;
114
+ const id = `alp-${platform}-${arch}`;
115
+ const file = path.join("bin", platform === "win32" ? "alp.exe" : "alp");
116
+ for (const candidate of [path.join(root, "node_modules", "@anhlp", id, file), path.join(root, "..", id, file)]) {
117
+ if (await isAlpExecutable(candidate)) return candidate;
118
+ }
119
+ return void 0;
120
+ }
81
121
  async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = (
82
122
  /** @type {Array<string | undefined>} */
83
123
  []
84
124
  ) } = {}) {
85
125
  for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
126
+ const own = executablePath();
127
+ if (own) return own;
86
128
  try {
87
129
  const { entry } = JSON.parse(await readFile(daemonPaths(home).install, "utf8"));
88
130
  if (typeof entry === "string" && await isFile(entry)) return entry;
89
131
  } catch {
90
132
  }
91
133
  for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
92
- const cli = await realpath(path.join(directory, "alp")).catch(() => void 0);
134
+ const cli = await realpath(path.join(directory, process.platform === "win32" ? "alp.exe" : "alp")).catch(() => void 0);
135
+ if (cli && await isAlpExecutable(cli)) return cli;
136
+ const npmExecutable = cli && await npmWrapperExecutable(cli);
137
+ if (npmExecutable) return npmExecutable;
93
138
  if (!cli || path.basename(cli) !== "cli.js") continue;
94
139
  const root = path.resolve(path.dirname(cli), "..");
95
- const name = await readFile(path.join(root, "package.json"), "utf8").then((text) => JSON.parse(text).name, () => void 0);
140
+ const name = await readFile(path.join(root, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
96
141
  const entry = path.join(root, "dist", "alpd.js");
97
142
  if (CLI_PACKAGES.includes(name) && await isFile(entry)) return entry;
98
143
  }
99
144
  return void 0;
100
145
  }
146
+ function assertIntegrationName(name) {
147
+ if (typeof name !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new TypeError(`Invalid integration name: ${JSON.stringify(name)}`);
148
+ return name;
149
+ }
150
+ var cachedBootId = null;
151
+ function bootId() {
152
+ if (cachedBootId !== null) return cachedBootId;
153
+ try {
154
+ if (process.platform === "linux") {
155
+ const id = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
156
+ if (id.length > 0) {
157
+ cachedBootId = id;
158
+ return cachedBootId;
159
+ }
160
+ } else if (process.platform === "darwin") {
161
+ const id = execFileSync("sysctl", ["-n", "kern.bootsessionuuid"], {
162
+ encoding: "utf8",
163
+ stdio: ["ignore", "pipe", "ignore"],
164
+ timeout: 2e3
165
+ }).trim();
166
+ if (id.length > 0) {
167
+ cachedBootId = id;
168
+ return cachedBootId;
169
+ }
170
+ }
171
+ } catch {
172
+ }
173
+ cachedBootId = void 0;
174
+ return cachedBootId;
175
+ }
176
+ function _setBootIdForTest(id = null) {
177
+ cachedBootId = id;
178
+ }
101
179
  function bootTime() {
102
180
  return Math.round((Date.now() - os.uptime() * 1e3) / 1e3);
103
181
  }
182
+ function isSameBoot(lock, { bootId: curBootId = bootId(), bootTime: curBootTime = bootTime() } = {}) {
183
+ if (!lock) return false;
184
+ if (typeof lock.bootId === "string" && lock.bootId.length > 0 && typeof curBootId === "string" && curBootId.length > 0) {
185
+ return lock.bootId === curBootId;
186
+ }
187
+ if (typeof lock.bootTime === "number" && Number.isFinite(lock.bootTime) && Number.isFinite(curBootTime)) {
188
+ return Math.abs(lock.bootTime - curBootTime) <= 30;
189
+ }
190
+ return false;
191
+ }
104
192
  async function readLock(home) {
105
193
  try {
106
194
  return JSON.parse(await readFile(daemonPaths(home).lock, "utf8"));
@@ -110,7 +198,7 @@ async function readLock(home) {
110
198
  }
111
199
  }
112
200
  function lockAlive(lock) {
113
- if (!lock || !Number.isSafeInteger(lock.pid) || Math.abs((lock.bootTime ?? 0) - bootTime()) > 30) return false;
201
+ if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
114
202
  try {
115
203
  process.kill(lock.pid, 0);
116
204
  return true;
@@ -120,7 +208,17 @@ function lockAlive(lock) {
120
208
  }
121
209
  async function acquireDaemonLock(home, contents) {
122
210
  const file = daemonPaths(home).lock;
123
- const lock = { pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString(), bootTime: bootTime(), uid: process.getuid?.() ?? -1, ready: false, ...contents };
211
+ const currentBootId = bootId();
212
+ const lock = {
213
+ pid: process.pid,
214
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
215
+ startedUptime: Math.floor(os.uptime()),
216
+ bootTime: bootTime(),
217
+ ...currentBootId ? { bootId: currentBootId } : {},
218
+ uid: process.getuid?.() ?? -1,
219
+ ready: false,
220
+ ...contents
221
+ };
124
222
  for (let attempt = 0; attempt < 2; attempt++) {
125
223
  try {
126
224
  const handle = await open(file, "wx", 384);
@@ -144,6 +242,14 @@ async function releaseDaemonLock(home) {
144
242
  });
145
243
  }
146
244
  var AlpClient = class extends AlpRpcClient {
245
+ /** Host features captured by connect's handshake. @type {readonly string[]} */
246
+ capabilities = [];
247
+ /** Limits captured by connect's handshake. @type {import('@anhlp/alp-protocol').AttachmentLimits | undefined} */
248
+ attachmentLimits;
249
+ /** @type {{ readonly maxCount: number; readonly maxBytes: number; readonly maxTotalBytes: number } | undefined} */
250
+ promptImageLimits;
251
+ /** @type {import('@anhlp/alp-protocol').TerminalLimits | undefined} */
252
+ terminalLimits;
147
253
  /**
148
254
  * @param {import('node:net').Socket} socket a connected or connecting socket; the client owns it
149
255
  * @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
@@ -172,7 +278,17 @@ async function connectSocket(socketPath, options) {
172
278
  async function connect(socketPath, client = { name: "alp", version: "0" }, options = {}) {
173
279
  const connection = new AlpClient(await openSocket(socketPath), options);
174
280
  try {
175
- await hello(connection, client);
281
+ const greeting = await hello(connection, client, void 0, { agent: typeof process.env.ALP_AGENT_SESSION === "string" && process.env.ALP_AGENT_SESSION !== "" });
282
+ connection.capabilities = Object.freeze(Array.isArray(greeting.capabilities) ? greeting.capabilities.filter((value) => typeof value === "string") : []);
283
+ if (greeting.attachmentLimits && typeof greeting.attachmentLimits === "object") {
284
+ connection.attachmentLimits = Object.freeze({ ...greeting.attachmentLimits });
285
+ }
286
+ if (greeting.promptImageLimits && typeof greeting.promptImageLimits === "object") {
287
+ connection.promptImageLimits = Object.freeze({ ...greeting.promptImageLimits });
288
+ }
289
+ if (greeting.terminalLimits && typeof greeting.terminalLimits === "object") {
290
+ connection.terminalLimits = Object.freeze({ ...greeting.terminalLimits });
291
+ }
176
292
  } catch (error) {
177
293
  connection.close();
178
294
  throw error;
@@ -212,7 +328,11 @@ async function lifecycleOwners(home) {
212
328
  async function readDaemonLifecycle(home) {
213
329
  return (await lifecycleOwners(home)).find((owner) => lockAlive(owner));
214
330
  }
215
- async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}) {
331
+ async function withDaemonLifecycle(home, action, run, { joinStart = false, signal = (
332
+ /** @type {AbortSignal | undefined} */
333
+ void 0
334
+ ) } = {}) {
335
+ signal?.throwIfAborted();
216
336
  try {
217
337
  await assertPrivateDirectory(home, { create: true });
218
338
  } catch (cause) {
@@ -221,10 +341,17 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
221
341
  const state = path.join(home, "state");
222
342
  await assertPrivateDirectory(state, { create: true });
223
343
  const directory = path.join(state, "alpd.starting");
344
+ const currentBootId = bootId();
224
345
  const token = `owner-${process.pid}-${bootTime()}-${action}-${randomUUID()}`;
225
346
  const candidate = path.join(state, `alpd.starting-${token}`);
226
347
  await mkdir(candidate, { mode: 448 });
227
- await writeFile(path.join(candidate, token), JSON.stringify({ pid: process.pid, bootTime: bootTime(), action }), { mode: 384 });
348
+ await writeFile(path.join(candidate, token), JSON.stringify({
349
+ pid: process.pid,
350
+ bootTime: bootTime(),
351
+ ...currentBootId ? { bootId: currentBootId } : {},
352
+ startedUptime: Math.floor(os.uptime()),
353
+ action
354
+ }), { mode: 384 });
228
355
  try {
229
356
  let joined = false;
230
357
  if (joinStart) {
@@ -239,6 +366,7 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
239
366
  }
240
367
  }
241
368
  while (!joined) {
369
+ signal?.throwIfAborted();
242
370
  try {
243
371
  await rename(candidate, directory);
244
372
  break;
@@ -252,10 +380,11 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
252
380
  await rmdir(directory).catch((error2) => {
253
381
  if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error2.code)) throw error2;
254
382
  });
255
- await new Promise((resolve) => setTimeout(resolve, 25));
383
+ await delay(25, void 0, { signal });
256
384
  }
257
385
  }
258
386
  try {
387
+ signal?.throwIfAborted();
259
388
  return await run();
260
389
  } finally {
261
390
  await unlink(path.join(directory, token));
@@ -275,8 +404,12 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
275
404
  async function ensureDaemon({ home = alpHome(), entry = (
276
405
  /** @type {string | undefined} */
277
406
  void 0
278
- ), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false } = {}) {
279
- if (!lifecycleLocked) return withDaemonLifecycle(home, "start", () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true }));
407
+ ), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false, signal = (
408
+ /** @type {AbortSignal | undefined} */
409
+ void 0
410
+ ) } = {}) {
411
+ signal?.throwIfAborted();
412
+ if (!lifecycleLocked) return withDaemonLifecycle(home, "start", () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true, signal }), { signal });
280
413
  const ready = async () => {
281
414
  const lock = await readLock(home);
282
415
  return lockAlive(lock) && lock.ready ? lock.socket : void 0;
@@ -288,8 +421,10 @@ async function ensureDaemon({ home = alpHome(), entry = (
288
421
  if (!lockAlive(held)) {
289
422
  entry ??= await findDaemonEntry({ home, env });
290
423
  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");
424
+ signal?.throwIfAborted();
291
425
  await new Promise((resolve, reject) => {
292
- const launcher = spawn(execPath, [entry, "--detach", `--startup-timeout=${timeoutMs}`], {
426
+ const launch = entryCommand(entry, "daemon", ["--detach", `--startup-timeout=${timeoutMs}`], execPath);
427
+ const launcher = spawn(launch.command, launch.args, {
293
428
  env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: "1" },
294
429
  stdio: ["ignore", "ignore", "pipe"],
295
430
  windowsHide: true
@@ -304,6 +439,7 @@ async function ensureDaemon({ home = alpHome(), entry = (
304
439
  }
305
440
  const deadline = Date.now() + timeoutMs;
306
441
  while (Date.now() < deadline) {
442
+ signal?.throwIfAborted();
307
443
  const socket = await ready();
308
444
  if (socket) return socket;
309
445
  await new Promise((resolve) => setTimeout(resolve, 100));
@@ -346,7 +482,7 @@ async function integrationCandidateFromHome(home, name) {
346
482
  return await isFile(legacy) ? legacy : void 0;
347
483
  }
348
484
  function integrationBinaryName(name) {
349
- return name === "web" ? "alp-web-integration" : `alp-${name}-integration`;
485
+ return `alp-${name}-integration`;
350
486
  }
351
487
  async function distributionRoots() {
352
488
  const roots = [];
@@ -366,10 +502,12 @@ async function distributionRoots() {
366
502
  return [...new Set(roots)];
367
503
  }
368
504
  async function discoverIntegration(name = "web", options = {}) {
505
+ assertIntegrationName(name);
506
+ if (name === "web") return void 0;
369
507
  const envCandidates = [
370
- process.env.ALP_WEB_INTEGRATION,
371
- process.env.ALP_INTEGRATION_ENTRY,
372
- name !== "web" ? process.env[`ALP_${name.toUpperCase()}_INTEGRATION`] : void 0
508
+ process.env[`ALP_${name.toUpperCase()}_INTEGRATION`],
509
+ name === "paseo" ? process.env.ALP_WEB_INTEGRATION : void 0,
510
+ process.env.ALP_INTEGRATION_ENTRY
373
511
  ].filter(Boolean);
374
512
  for (const candidate of envCandidates) if (await isFile(candidate)) return candidate;
375
513
  const home = options?.home ? path.resolve(options.home) : alpHome();
@@ -389,30 +527,54 @@ async function discoverIntegration(name = "web", options = {}) {
389
527
  return void 0;
390
528
  }
391
529
  function integrationAlive(lock) {
392
- if (!lock || !Number.isSafeInteger(lock.pid)) return false;
530
+ if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
393
531
  try {
394
532
  process.kill(lock.pid, 0);
533
+ return true;
395
534
  } catch (error) {
396
535
  return error?.code === "EPERM";
397
536
  }
398
- if (typeof lock.bootTime === "number" && Math.abs(lock.bootTime - bootTime()) > 30) return false;
399
- return true;
537
+ }
538
+ function integrationText(name, home) {
539
+ const logs = path.join(home, "logs", "integrations");
540
+ if (name === "web") return {
541
+ what: "alp web",
542
+ log: path.join(logs, "alp-web.log"),
543
+ 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`"
544
+ };
545
+ if (name === "paseo") return {
546
+ what: "The Paseo integration",
547
+ log: path.join(logs, "paseo.log"),
548
+ 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."
549
+ };
550
+ return {
551
+ what: `ALP integration ${name}`,
552
+ log: path.join(logs, `${name}.log`),
553
+ missing: `ALP integration ${name} is not installed: no ALP_${name.toUpperCase()}_INTEGRATION, descriptor <home>/integrations/${name}.json or alp-${name}-integration binary was found.`
554
+ };
400
555
  }
401
556
  async function startIntegration(nameOrOptions = "web") {
402
557
  const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
403
- const name = options.name ?? "web";
558
+ const name = assertIntegrationName(options.name ?? "web");
559
+ if (options.entry !== void 0 && (typeof options.entry !== "string" || !options.entry)) throw new TypeError("startIntegration entry must be a non-empty path");
560
+ const args = options.args ?? [];
561
+ if (!Array.isArray(args) || !args.every((arg) => typeof arg === "string")) throw new TypeError("startIntegration args must be a list of strings");
404
562
  const fs = await import("node:fs/promises");
405
563
  const pathMod = await import("node:path");
406
564
  const home = options.home ? pathMod.resolve(options.home) : alpHome();
565
+ const text = integrationText(name, home);
566
+ const explicit = options.entry !== void 0 ? pathMod.resolve(options.entry) : void 0;
567
+ if (explicit !== void 0 && !await isFile(explicit)) throw new Error(`${text.what}: integration entry not found: ${explicit}`);
407
568
  const lockPath = pathMod.join(home, "integrations", `${name}.lock`);
408
569
  const webPath = pathMod.join(home, `${name}.json`);
409
- let settings = {};
410
- try {
411
- settings = JSON.parse(await fs.readFile(pathMod.join(home, "settings.json"), "utf8"));
412
- } catch {
413
- }
414
- if (settings?.web?.enabled === false) {
415
- throw new Error('ALP web app is disabled by settings ("web.enabled": false).');
570
+ const started = explicit ? ` (entry ${explicit})` : "";
571
+ if (name === "web") {
572
+ let settings = {};
573
+ try {
574
+ settings = JSON.parse(await fs.readFile(pathMod.join(home, "settings.json"), "utf8"));
575
+ } catch {
576
+ }
577
+ if (settings?.web?.enabled === false) throw new Error('alp web is disabled by settings ("web.enabled": false).');
416
578
  }
417
579
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
418
580
  const readLock2 = async () => {
@@ -437,23 +599,24 @@ async function startIntegration(nameOrOptions = "web") {
437
599
  const info = await readWeb();
438
600
  if (info && info.pid === lock2.pid) return lock2;
439
601
  }
602
+ if (name === "web" && webStartupFailed()) throw new Error(`${text.what}${started} failed to start; see ${text.log}`);
440
603
  await sleep(100);
441
604
  }
442
605
  const lock = await readLock2();
443
- if (lock && !lock.ready) throw new Error("ALP web integration started but did not become ready; see ~/.alp/logs/integrations/paseo.log");
444
- 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.");
445
- throw new Error("ALP web integration did not publish a matching web.json lock");
606
+ if (lock && !lock.ready) throw new Error(`${text.what}${started} started but did not become ready; see ${text.log}`);
607
+ if (!lock) throw new Error(explicit ? `${text.what}${started} did not start; see ${text.log}` : text.missing);
608
+ throw new Error(`${text.what}${started} did not publish a ${name}.json matching its lock; see ${text.log}`);
446
609
  }
610
+ let webStartupFailed = () => false;
447
611
  const existing = await readLock2();
448
612
  if (existing && integrationAlive(existing)) {
449
613
  return waitForReady();
450
614
  }
451
- const entry = await discoverIntegration(name, { home });
452
- if (!entry) {
453
- 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.");
454
- }
615
+ const entry = explicit ?? await discoverIntegration(name, { home });
616
+ if (!entry) throw new Error(text.missing);
455
617
  const { spawn: spawn2 } = await import("node:child_process");
456
- const child = spawn2(process.execPath, [entry, "--service"], { stdio: "ignore", detached: true, env: { ...process.env, ALP_HOME: home } });
618
+ const launch = name === "web" ? entryCommand(entry, "web", ["--service", ...args]) : entryCommand(entry, "web", ["--service", ...args], void 0, { scriptOnly: true });
619
+ const child = spawn2(launch.command, launch.args, { stdio: "ignore", detached: true, env: { ...process.env, ALP_HOME: home } });
457
620
  let spawnError = null;
458
621
  child.on("error", (error) => {
459
622
  spawnError = error;
@@ -463,10 +626,11 @@ async function startIntegration(nameOrOptions = "web") {
463
626
  if (code !== 0 && code !== null) exited = true;
464
627
  });
465
628
  child.unref();
629
+ webStartupFailed = () => exited;
466
630
  if (spawnError) throw spawnError;
467
631
  await sleep(150);
468
632
  if (spawnError) throw spawnError;
469
- if (exited) throw new Error("ALP web integration failed to start; see ~/.alp/logs/integrations/paseo.log");
633
+ if (exited) throw new Error(`${text.what}${explicit ? started : ` (${entry})`} failed to start; see ${text.log}`);
470
634
  return waitForReady();
471
635
  }
472
636
  export {
@@ -475,10 +639,13 @@ export {
475
639
  CLOSE_CODE,
476
640
  MAX_FRAME,
477
641
  PROTOCOL_VERSION,
642
+ _setBootIdForTest,
478
643
  acquireDaemonLock,
479
644
  alpHome,
645
+ assertIntegrationName,
480
646
  assertPrivateDirectory,
481
647
  assertPrivateSocket,
648
+ bootId,
482
649
  bootTime,
483
650
  connect,
484
651
  connectSocket,
@@ -490,6 +657,8 @@ export {
490
657
  encodeFrame,
491
658
  ensureDaemon,
492
659
  findDaemonEntry,
660
+ integrationAlive,
661
+ isSameBoot,
493
662
  lockAlive,
494
663
  readDaemonLifecycle,
495
664
  readLock,
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @typedef {{ pid: number, bootTime: number, bootId?: string, startedUptime?: number, startedAt: string, ready: boolean, lockVersion?: number, owner?: string }} IntegrationLockRecord
3
+ * @typedef {{
4
+ * acquire(): Promise<{ acquired: boolean, lock: IntegrationLockRecord }>,
5
+ * setReady(ready: boolean): Promise<boolean>,
6
+ * release(): Promise<boolean>,
7
+ * }} IntegrationLock
8
+ */
9
+ /**
10
+ * The single-owner lock of one integration service, at `<home>/integrations/<name>.lock`, with its
11
+ * mutation guard `<name>.lock.reclaim`. Each instance is single-use: acquire once, then setReady and
12
+ * release while it owns the lock.
13
+ *
14
+ * Single-host, same PID namespace, private local filesystem only. Never reap the mutation guard.
15
+ * @param {string} home the ALP_HOME the integration runs under
16
+ * @param {string} name the integration name, for example `web`
17
+ * @returns {IntegrationLock}
18
+ */
19
+ export function createIntegrationLock(home: string, name: string): IntegrationLock;
20
+ export type IntegrationLockRecord = {
21
+ pid: number;
22
+ bootTime: number;
23
+ bootId?: string;
24
+ startedUptime?: number;
25
+ startedAt: string;
26
+ ready: boolean;
27
+ lockVersion?: number;
28
+ owner?: string;
29
+ };
30
+ export type IntegrationLock = {
31
+ acquire(): Promise<{
32
+ acquired: boolean;
33
+ lock: IntegrationLockRecord;
34
+ }>;
35
+ setReady(ready: boolean): Promise<boolean>;
36
+ release(): Promise<boolean>;
37
+ };
@@ -0,0 +1,199 @@
1
+ // packages/client/src/integration-lock.js
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, open, rmdir, unlink } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { moveFile } from "@anhlp/alp-core/atomic";
7
+ import { assertIntegrationName, bootId, bootTime, isSameBoot } from "./index.js";
8
+ function createIntegrationLock(home, name) {
9
+ const file = path.join(home, "integrations", `${assertIntegrationName(name)}.lock`);
10
+ const guard = `${file}.reclaim`;
11
+ let phase = "new";
12
+ let owned;
13
+ let readyQueue = Promise.resolve();
14
+ const recovery = (reason) => new Error(`${reason}. Stop ALL integration processes using this ALP_HOME before manual lock-only recovery of ${file} and ${guard}; see docs/modular-monorepo.md`);
15
+ async function guarded(run) {
16
+ await mkdir(path.dirname(file), { recursive: true, mode: 448 });
17
+ const deadline = Date.now() + 2e4;
18
+ for (; ; ) {
19
+ try {
20
+ await mkdir(guard, { mode: 448 });
21
+ break;
22
+ } catch (error) {
23
+ if (
24
+ /** @type {any} */
25
+ error?.code !== "EEXIST"
26
+ ) throw error;
27
+ if (Date.now() >= deadline) throw recovery("Integration mutation guard remains busy or abandoned");
28
+ await new Promise((resolve) => setTimeout(resolve, 25));
29
+ }
30
+ }
31
+ const token = path.join(guard, `owner-${process.pid}-${randomUUID()}`);
32
+ try {
33
+ const handle = await open(token, "wx", 384);
34
+ await handle.close();
35
+ } catch (error) {
36
+ throw recovery(`Integration guard initialization failed: ${String(error)}`);
37
+ }
38
+ try {
39
+ return await run();
40
+ } finally {
41
+ try {
42
+ await unlink(token);
43
+ } catch (error) {
44
+ throw recovery(
45
+ /** @type {any} */
46
+ error?.code === "ENOENT" ? "Integration guard ownership was lost" : `Integration guard token cleanup failed: ${String(error)}`
47
+ );
48
+ }
49
+ try {
50
+ await rmdir(guard);
51
+ } catch (error) {
52
+ throw recovery(`Integration guard cleanup failed: ${String(error)}`);
53
+ }
54
+ }
55
+ }
56
+ async function snapshot() {
57
+ let handle;
58
+ try {
59
+ handle = await open(file, "r");
60
+ } catch (error) {
61
+ if (
62
+ /** @type {any} */
63
+ error?.code === "ENOENT"
64
+ ) return void 0;
65
+ throw error;
66
+ }
67
+ try {
68
+ const info = await handle.stat();
69
+ const raw = await handle.readFile("utf8");
70
+ let value;
71
+ try {
72
+ value = JSON.parse(raw);
73
+ } catch {
74
+ value = void 0;
75
+ }
76
+ return { value, info };
77
+ } finally {
78
+ await handle.close();
79
+ }
80
+ }
81
+ function complete(value) {
82
+ return value && Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.bootTime === "number" && Number.isFinite(value.bootTime) && value.bootTime > 0 && (value.bootId === void 0 || typeof value.bootId === "string" && value.bootId.length > 0) && (value.startedUptime === void 0 || typeof value.startedUptime === "number" && Number.isFinite(value.startedUptime)) && typeof value.startedAt === "string" && Number.isFinite(Date.parse(value.startedAt)) && typeof value.ready === "boolean" && (value.lockVersion === void 0 && value.owner === void 0 || value.lockVersion === 1 && typeof value.owner === "string" && /^[a-f0-9-]{36}$/.test(value.owner));
83
+ }
84
+ function dead(value) {
85
+ try {
86
+ process.kill(value.pid, 0);
87
+ return false;
88
+ } catch (error) {
89
+ if (
90
+ /** @type {any} */
91
+ error?.code !== "ESRCH"
92
+ ) return false;
93
+ if (!isSameBoot(value)) throw recovery("Integration owner boot context is uncertain");
94
+ return true;
95
+ }
96
+ }
97
+ function matches(current) {
98
+ return !!owned && current?.value?.owner === owned.owner && current.info.dev === owned.dev && current.info.ino === owned.ino;
99
+ }
100
+ return {
101
+ async acquire() {
102
+ if (phase !== "new") throw new Error("Integration lock instance has already been used");
103
+ phase = "acquiring";
104
+ try {
105
+ return await guarded(async () => {
106
+ const current = await snapshot();
107
+ if (current) {
108
+ if (!complete(current.value)) throw recovery("Integration lock is malformed, incomplete or unsupported");
109
+ if (!dead(current.value)) {
110
+ phase = "retired";
111
+ return { acquired: false, lock: current.value };
112
+ }
113
+ await unlink(file);
114
+ }
115
+ const currentBootId = bootId();
116
+ const value = {
117
+ pid: process.pid,
118
+ bootTime: bootTime(),
119
+ ...currentBootId ? { bootId: currentBootId } : {},
120
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
121
+ startedUptime: Math.floor(os.uptime()),
122
+ ready: false,
123
+ lockVersion: 1,
124
+ owner: randomUUID()
125
+ };
126
+ const handle = await open(file, "wx", 384);
127
+ let info;
128
+ try {
129
+ await handle.writeFile(JSON.stringify(value));
130
+ info = await handle.stat();
131
+ } finally {
132
+ await handle.close();
133
+ }
134
+ owned = { owner: value.owner, dev: info.dev, ino: info.ino };
135
+ phase = "owned";
136
+ return { acquired: true, lock: value };
137
+ });
138
+ } catch (error) {
139
+ phase = "retired";
140
+ owned = void 0;
141
+ throw error;
142
+ }
143
+ },
144
+ async setReady(ready) {
145
+ if (phase !== "owned") return false;
146
+ const execute = async () => {
147
+ if (phase !== "owned") return false;
148
+ return guarded(async () => {
149
+ if (phase !== "owned") return false;
150
+ const current = await snapshot();
151
+ if (!current || !matches(current)) {
152
+ phase = "retired";
153
+ owned = void 0;
154
+ return false;
155
+ }
156
+ const value = { ...current.value, ready };
157
+ const tmp = `${file}.${randomUUID()}.tmp`;
158
+ const handle = await open(tmp, "wx", 384);
159
+ let info;
160
+ try {
161
+ try {
162
+ await handle.writeFile(JSON.stringify(value));
163
+ info = await handle.stat();
164
+ } finally {
165
+ await handle.close();
166
+ }
167
+ await moveFile(tmp, file);
168
+ owned = { owner: value.owner, dev: info.dev, ino: info.ino };
169
+ return true;
170
+ } finally {
171
+ await unlink(tmp).catch((error) => {
172
+ if (error?.code !== "ENOENT") throw error;
173
+ });
174
+ }
175
+ });
176
+ };
177
+ const chained = readyQueue.then(execute, execute);
178
+ readyQueue = chained.catch(() => {
179
+ });
180
+ return chained;
181
+ },
182
+ async release() {
183
+ if (phase !== "owned") return false;
184
+ return guarded(async () => {
185
+ if (phase !== "owned") return false;
186
+ const current = await snapshot();
187
+ const ours = matches(current);
188
+ phase = "retired";
189
+ owned = void 0;
190
+ if (!ours) return false;
191
+ await unlink(file);
192
+ return true;
193
+ });
194
+ }
195
+ };
196
+ }
197
+ export {
198
+ createIntegrationLock
199
+ };