@anhlp/alp-client 0.0.0-beta.2 → 0.0.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +23 -1
  2. package/dist/acp-probe.d.ts +3 -2
  3. package/dist/acp-probe.js +11 -2
  4. package/dist/antigravity-probe.d.ts +1 -2
  5. package/dist/antigravity-probe.js +11 -5
  6. package/dist/command.js +3 -1
  7. package/dist/doctor.d.ts +8 -0
  8. package/dist/doctor.js +276 -13
  9. package/dist/index.d.ts +123 -8
  10. package/dist/index.js +332 -52
  11. package/dist/integration-lock.d.ts +37 -0
  12. package/dist/integration-lock.js +199 -0
  13. package/dist/mcp-probe.js +1 -1
  14. package/dist/portable.d.ts +3 -1
  15. package/dist/portable.js +11 -2
  16. package/dist/render.js +3 -0
  17. package/dist/rpc/handshake.d.ts +6 -1
  18. package/dist/rpc/handshake.js +4 -2
  19. package/dist/rpc/registry.d.ts +227 -0
  20. package/dist/rpc/registry.js +223 -0
  21. package/dist/rpc/terminal-directory.d.ts +24 -0
  22. package/dist/rpc/terminal-directory.js +70 -0
  23. package/dist/service.d.ts +2 -2
  24. package/dist/service.js +3 -1
  25. package/dist/setup.d.ts +7 -1
  26. package/dist/setup.js +159 -32
  27. package/dist/supervise.d.ts +3 -1
  28. package/dist/supervise.js +26 -16
  29. package/package.json +11 -3
  30. package/src/acp-probe.js +10 -3
  31. package/src/antigravity-probe.js +12 -5
  32. package/src/command.js +3 -1
  33. package/src/doctor.d.ts +8 -0
  34. package/src/doctor.js +345 -3
  35. package/src/index.js +411 -55
  36. package/src/integration-lock.js +203 -0
  37. package/src/mcp-probe.js +1 -1
  38. package/src/portable.js +4 -1
  39. package/src/render.js +3 -0
  40. package/src/rpc/handshake.js +7 -2
  41. package/src/rpc/registry.js +229 -0
  42. package/src/rpc/terminal-directory.js +61 -0
  43. package/src/service.js +7 -3
  44. package/src/setup.js +201 -35
  45. package/src/supervise.d.ts +3 -1
  46. package/src/supervise.js +31 -19
package/dist/index.js CHANGED
@@ -1,11 +1,15 @@
1
1
  // packages/client/src/index.js
2
- import { spawn } from "node:child_process";
3
- import { createHash } from "node:crypto";
4
- import { open, readFile, realpath, stat, lstat, mkdir, readlink, unlink } from "node:fs/promises";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { execFileSync, spawn } from "node:child_process";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { fstatSync, readFileSync } from "node:fs";
6
+ import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, chmod, 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 { entryCommand, isNativeDaemonName, NATIVE_DAEMON } from "@anhlp/alp-core/packaged";
12
+ import { dashboardSettings } from "@anhlp/alp-core/user-settings";
9
13
  import { createSocketTransport } from "./ipc.js";
10
14
  import { AlpRpcClient } from "./rpc/client.js";
11
15
  import { hello } from "./rpc/handshake.js";
@@ -60,11 +64,21 @@ async function assertSafeAncestors(directory) {
60
64
  async function assertPrivateDirectory(directory, { create = false } = {}) {
61
65
  await assertSafeAncestors(directory);
62
66
  if (create) await mkdir(directory, { recursive: true, mode: 448 });
63
- const info = await lstat(directory);
67
+ let info = await lstat(directory);
64
68
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("IPC requires a private directory, not a symlink");
65
- if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 63) !== 0)) {
66
- throw new Error("IPC directory must be owned by the current user with private permissions (0700)");
69
+ if (process.platform === "win32") return;
70
+ const shown = JSON.stringify(directory);
71
+ const mine = (entry) => entry.isDirectory() && !entry.isSymbolicLink() && entry.uid === process.getuid?.();
72
+ if (info.uid !== process.getuid?.()) throw new Error(`IPC directory ${shown} must be owned by the current user (it belongs to uid ${info.uid}); use a directory of your own`);
73
+ if ((info.mode & 63) === 0) return;
74
+ if (create && (await readdir(directory)).length === 0) {
75
+ await chmod(directory, 448).catch(() => {
76
+ });
67
77
  }
78
+ info = await lstat(directory);
79
+ if (mine(info) && (info.mode & 63) === 0) return;
80
+ const quoted = `'${directory.replaceAll("'", "'\\''")}'`;
81
+ throw new Error(`IPC directory ${shown} must have private permissions (0700), not ${(info.mode & 511).toString(8).padStart(4, "0")}; fix it with: chmod 700 ${quoted}`);
68
82
  }
69
83
  async function assertPrivateSocket(socketPath) {
70
84
  if (process.platform === "win32") return;
@@ -76,31 +90,102 @@ async function assertPrivateSocket(socketPath) {
76
90
  return info;
77
91
  }
78
92
  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"];
93
+ 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
94
  var CLI_PACKAGES = ["@anhlp/alp", "@anhlp/alp-cli"];
95
+ async function cliDaemonEntry(cli, depth = 0, env = process.env) {
96
+ const base = path.basename(cli).toLowerCase();
97
+ const root = path.resolve(path.dirname(cli), "..");
98
+ const alpd = (directory) => path.join(directory, "dist", "alpd.js");
99
+ const named = async (directory) => readFile(path.join(directory, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
100
+ let candidates = [];
101
+ if (base === "alp.cmd" && depth < 1 && !await isFile(path.join(root, "alp-bundle.json"))) {
102
+ const text = await stat(cli).then((info) => info.size <= 64 * 1024 ? readFile(cli, "utf8") : "", () => "");
103
+ for (const [, quoted] of text.matchAll(/"([^"\r\n]+\.js)"/gi)) {
104
+ const script = quoted.replace(/^%~?dp0%?[\\/]?/i, `${path.dirname(cli)}${path.sep}`);
105
+ const entry = path.isAbsolute(script) && await isFile(script) ? await cliDaemonEntry(script, depth + 1, env) : void 0;
106
+ if (entry) return entry;
107
+ }
108
+ return void 0;
109
+ }
110
+ if (base === "alp" || base === "alp.cmd") {
111
+ if (!await isFile(path.join(root, "alp-bundle.json"))) return void 0;
112
+ const current = path.join(path.dirname(root), "current");
113
+ const viaCurrent = await realpath(current).then((real) => real === root, () => false);
114
+ const bundle = viaCurrent ? current : root;
115
+ candidates = [...env.ALP_NATIVE_DAEMON === "0" ? [] : [path.join(bundle, "bin", NATIVE_DAEMON)], alpd(path.join(bundle, "lib", "node_modules", "@anhlp", "alp-cli"))];
116
+ } else if (base === "cli.js" && CLI_PACKAGES.includes(await named(root))) {
117
+ candidates = [alpd(root)];
118
+ } else if (base === "alp.js" && await named(root) === "@anhlp/alp") {
119
+ candidates = [alpd(path.join(root, "node_modules", "@anhlp", "alp-cli")), alpd(path.join(root, "..", "alp-cli"))];
120
+ }
121
+ for (const candidate of candidates) if (await isFile(candidate)) return candidate;
122
+ return void 0;
123
+ }
81
124
  async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = (
82
125
  /** @type {Array<string | undefined>} */
83
126
  []
84
- ) } = {}) {
127
+ ), binDirectories = BIN_DIRECTORIES } = {}) {
85
128
  for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
86
129
  try {
87
130
  const { entry } = JSON.parse(await readFile(daemonPaths(home).install, "utf8"));
88
131
  if (typeof entry === "string" && await isFile(entry)) return entry;
89
132
  } catch {
90
133
  }
91
- 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);
93
- if (!cli || path.basename(cli) !== "cli.js") continue;
94
- 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);
96
- const entry = path.join(root, "dist", "alpd.js");
97
- if (CLI_PACKAGES.includes(name) && await isFile(entry)) return entry;
134
+ for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...binDirectories]) {
135
+ for (const name of process.platform === "win32" ? ["alp.cmd", "alp"] : ["alp"]) {
136
+ const cli = await realpath(path.join(directory, name)).catch(() => void 0);
137
+ const entry = cli && await cliDaemonEntry(cli, 0, env);
138
+ if (entry) return entry;
139
+ }
98
140
  }
99
141
  return void 0;
100
142
  }
143
+ function assertIntegrationName(name) {
144
+ if (typeof name !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new TypeError(`Invalid integration name: ${JSON.stringify(name)}`);
145
+ return name;
146
+ }
147
+ var cachedBootId = null;
148
+ function bootId() {
149
+ if (cachedBootId !== null) return cachedBootId;
150
+ try {
151
+ if (process.platform === "linux") {
152
+ const id = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
153
+ if (id.length > 0) {
154
+ cachedBootId = id;
155
+ return cachedBootId;
156
+ }
157
+ } else if (process.platform === "darwin") {
158
+ const id = execFileSync("sysctl", ["-n", "kern.bootsessionuuid"], {
159
+ encoding: "utf8",
160
+ stdio: ["ignore", "pipe", "ignore"],
161
+ timeout: 2e3
162
+ }).trim();
163
+ if (id.length > 0) {
164
+ cachedBootId = id;
165
+ return cachedBootId;
166
+ }
167
+ }
168
+ } catch {
169
+ }
170
+ cachedBootId = void 0;
171
+ return cachedBootId;
172
+ }
173
+ function _setBootIdForTest(id = null) {
174
+ cachedBootId = id;
175
+ }
101
176
  function bootTime() {
102
177
  return Math.round((Date.now() - os.uptime() * 1e3) / 1e3);
103
178
  }
179
+ function isSameBoot(lock, { bootId: curBootId = bootId(), bootTime: curBootTime = bootTime() } = {}) {
180
+ if (!lock) return false;
181
+ if (typeof lock.bootId === "string" && lock.bootId.length > 0 && typeof curBootId === "string" && curBootId.length > 0) {
182
+ return lock.bootId === curBootId;
183
+ }
184
+ if (typeof lock.bootTime === "number" && Number.isFinite(lock.bootTime) && Number.isFinite(curBootTime)) {
185
+ return Math.abs(lock.bootTime - curBootTime) <= 30;
186
+ }
187
+ return false;
188
+ }
104
189
  async function readLock(home) {
105
190
  try {
106
191
  return JSON.parse(await readFile(daemonPaths(home).lock, "utf8"));
@@ -110,7 +195,7 @@ async function readLock(home) {
110
195
  }
111
196
  }
112
197
  function lockAlive(lock) {
113
- if (!lock || !Number.isSafeInteger(lock.pid) || Math.abs((lock.bootTime ?? 0) - bootTime()) > 30) return false;
198
+ if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
114
199
  try {
115
200
  process.kill(lock.pid, 0);
116
201
  return true;
@@ -120,11 +205,38 @@ function lockAlive(lock) {
120
205
  }
121
206
  async function acquireDaemonLock(home, contents) {
122
207
  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 };
208
+ const currentBootId = bootId();
209
+ const lock = {
210
+ pid: process.pid,
211
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
212
+ startedUptime: Math.floor(os.uptime()),
213
+ bootTime: bootTime(),
214
+ ...currentBootId ? { bootId: currentBootId } : {},
215
+ uid: process.getuid?.() ?? -1,
216
+ ready: false,
217
+ ...contents
218
+ };
124
219
  for (let attempt = 0; attempt < 2; attempt++) {
125
220
  try {
126
221
  const handle = await open(file, "wx", 384);
127
- await handle.writeFile(JSON.stringify(lock));
222
+ let ours;
223
+ try {
224
+ ours = await handle.stat();
225
+ await handle.writeFile(JSON.stringify(lock));
226
+ } catch (error) {
227
+ if (!ours) {
228
+ try {
229
+ ours = fstatSync(handle.fd);
230
+ } catch {
231
+ }
232
+ }
233
+ await handle.close().catch(() => {
234
+ });
235
+ const there = await lstat(file).catch(() => void 0);
236
+ if (ours && there && ours.ino === there.ino && ours.dev === there.dev) await unlink(file).catch(() => {
237
+ });
238
+ throw error;
239
+ }
128
240
  await handle.close();
129
241
  return lock;
130
242
  } catch (error) {
@@ -132,7 +244,13 @@ async function acquireDaemonLock(home, contents) {
132
244
  const current = await readLock(home);
133
245
  if (lockAlive(current)) throw new Error(current.maintenance ? `ALP is busy: alp ${current.maintenance} runs (pid ${current.pid}); try again when it finishes` : `ALP daemon already running (pid ${current.pid})`);
134
246
  const again = await readFile(file, "utf8").catch(() => void 0);
135
- if (again === void 0 || JSON.stringify(current) === again || !lockAlive(JSON.parse(again))) await unlink(file).catch(() => {
247
+ let parsed;
248
+ try {
249
+ parsed = again === void 0 ? void 0 : JSON.parse(again);
250
+ } catch {
251
+ throw new Error(`ALP daemon lock ${file} cannot be read: another start may be writing it. If no alpd or alp command is starting, remove it and try again`);
252
+ }
253
+ if (again === void 0 || JSON.stringify(current) === again || !lockAlive(parsed)) await unlink(file).catch(() => {
136
254
  });
137
255
  }
138
256
  }
@@ -144,6 +262,14 @@ async function releaseDaemonLock(home) {
144
262
  });
145
263
  }
146
264
  var AlpClient = class extends AlpRpcClient {
265
+ /** Host features captured by connect's handshake. @type {readonly string[]} */
266
+ capabilities = [];
267
+ /** Limits captured by connect's handshake. @type {import('@anhlp/alp-protocol').AttachmentLimits | undefined} */
268
+ attachmentLimits;
269
+ /** @type {{ readonly maxCount: number; readonly maxBytes: number; readonly maxTotalBytes: number } | undefined} */
270
+ promptImageLimits;
271
+ /** @type {import('@anhlp/alp-protocol').TerminalLimits | undefined} */
272
+ terminalLimits;
147
273
  /**
148
274
  * @param {import('node:net').Socket} socket a connected or connecting socket; the client owns it
149
275
  * @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
@@ -172,7 +298,17 @@ async function connectSocket(socketPath, options) {
172
298
  async function connect(socketPath, client = { name: "alp", version: "0" }, options = {}) {
173
299
  const connection = new AlpClient(await openSocket(socketPath), options);
174
300
  try {
175
- await hello(connection, client);
301
+ const greeting = await hello(connection, client, void 0, { agent: typeof process.env.ALP_AGENT_SESSION === "string" && process.env.ALP_AGENT_SESSION !== "" });
302
+ connection.capabilities = Object.freeze(Array.isArray(greeting.capabilities) ? greeting.capabilities.filter((value) => typeof value === "string") : []);
303
+ if (greeting.attachmentLimits && typeof greeting.attachmentLimits === "object") {
304
+ connection.attachmentLimits = Object.freeze({ ...greeting.attachmentLimits });
305
+ }
306
+ if (greeting.promptImageLimits && typeof greeting.promptImageLimits === "object") {
307
+ connection.promptImageLimits = Object.freeze({ ...greeting.promptImageLimits });
308
+ }
309
+ if (greeting.terminalLimits && typeof greeting.terminalLimits === "object") {
310
+ connection.terminalLimits = Object.freeze({ ...greeting.terminalLimits });
311
+ }
176
312
  } catch (error) {
177
313
  connection.close();
178
314
  throw error;
@@ -197,10 +333,111 @@ async function tail(file, lines = 30) {
197
333
  return "";
198
334
  }
199
335
  }
336
+ async function lifecycleOwners(home) {
337
+ const directory = path.join(home, "state", "alpd.starting");
338
+ const names = await readdir(directory).catch((error) => {
339
+ if (error.code === "ENOENT") return [];
340
+ throw error;
341
+ });
342
+ return names.map((token) => {
343
+ const match = /^owner-(\d+)-(\d+)-(start|stop)-[a-f0-9-]+$/.exec(token);
344
+ if (!match) throw new Error("Invalid alpd startup admission owner");
345
+ return { token, pid: Number(match[1]), bootTime: Number(match[2]), action: match[3] };
346
+ });
347
+ }
348
+ async function readDaemonLifecycle(home) {
349
+ return (await lifecycleOwners(home)).find((owner) => lockAlive(owner));
350
+ }
351
+ async function withDaemonLifecycle(home, action, run, { joinStart = false, signal = (
352
+ /** @type {AbortSignal | undefined} */
353
+ void 0
354
+ ) } = {}) {
355
+ signal?.throwIfAborted();
356
+ try {
357
+ await assertPrivateDirectory(home, { create: true });
358
+ } catch (cause) {
359
+ throw Object.assign(new Error(`ALP_HOME_UNUSABLE, alpd failed to start while preparing its home: ${cause.message}`, { cause }), { code: "ALP_HOME_UNUSABLE" });
360
+ }
361
+ const state = path.join(home, "state");
362
+ await assertPrivateDirectory(state, { create: true });
363
+ const directory = path.join(state, "alpd.starting");
364
+ const currentBootId = bootId();
365
+ const token = `owner-${process.pid}-${bootTime()}-${action}-${randomUUID()}`;
366
+ const candidate = path.join(state, `alpd.starting-${token}`);
367
+ await mkdir(candidate, { mode: 448 });
368
+ await writeFile(path.join(candidate, token), JSON.stringify({
369
+ pid: process.pid,
370
+ bootTime: bootTime(),
371
+ ...currentBootId ? { bootId: currentBootId } : {},
372
+ startedUptime: Math.floor(os.uptime()),
373
+ action
374
+ }), { mode: 384 });
375
+ try {
376
+ let joined = false;
377
+ if (joinStart) {
378
+ const owner = await readDaemonLifecycle(home);
379
+ if (owner?.action === "start") {
380
+ try {
381
+ await link(path.join(directory, owner.token), path.join(directory, token));
382
+ joined = true;
383
+ } catch (error) {
384
+ if (error.code !== "ENOENT") throw error;
385
+ }
386
+ }
387
+ }
388
+ while (!joined) {
389
+ signal?.throwIfAborted();
390
+ try {
391
+ await rename(candidate, directory);
392
+ break;
393
+ } catch (error) {
394
+ if (!["EEXIST", "ENOTEMPTY", "EPERM", "EACCES"].includes(error.code)) throw error;
395
+ for (const owner of await lifecycleOwners(home)) {
396
+ if (!lockAlive(owner)) await unlink(path.join(directory, owner.token)).catch((error2) => {
397
+ if (error2.code !== "ENOENT") throw error2;
398
+ });
399
+ }
400
+ await rmdir(directory).catch((error2) => {
401
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error2.code)) throw error2;
402
+ });
403
+ await delay(25, void 0, { signal });
404
+ }
405
+ }
406
+ try {
407
+ signal?.throwIfAborted();
408
+ return await run();
409
+ } finally {
410
+ await unlink(path.join(directory, token));
411
+ await rmdir(directory).catch((error) => {
412
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code)) throw error;
413
+ });
414
+ }
415
+ } finally {
416
+ await unlink(path.join(candidate, token)).catch((error) => {
417
+ if (error.code !== "ENOENT") throw error;
418
+ });
419
+ await rmdir(candidate).catch((error) => {
420
+ if (error.code !== "ENOENT") throw error;
421
+ });
422
+ }
423
+ }
424
+ var DAEMON_START_TIMEOUT_MS = 6e4;
425
+ var DAEMON_START_TIMEOUT_MAX_MS = 36e5;
426
+ function daemonStartTimeoutMs(env = process.env) {
427
+ const raw = env.ALP_DAEMON_START_TIMEOUT_MS?.trim();
428
+ if (!raw || !/^[0-9]+$/.test(raw)) return DAEMON_START_TIMEOUT_MS;
429
+ const value = Number(raw);
430
+ return value > 0 && value <= DAEMON_START_TIMEOUT_MAX_MS ? value : DAEMON_START_TIMEOUT_MS;
431
+ }
200
432
  async function ensureDaemon({ home = alpHome(), entry = (
201
433
  /** @type {string | undefined} */
202
434
  void 0
203
- ), env = process.env, execPath = process.execPath, timeoutMs = 15e3 } = {}) {
435
+ ), env = process.env, execPath = process.execPath, timeoutMs = daemonStartTimeoutMs(env), lifecycleLocked = false, signal = (
436
+ /** @type {AbortSignal | undefined} */
437
+ void 0
438
+ ) } = {}) {
439
+ signal?.throwIfAborted();
440
+ if (!lifecycleLocked) return withDaemonLifecycle(home, "start", () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true, signal }), { signal });
204
441
  const ready = async () => {
205
442
  const lock = await readLock(home);
206
443
  return lockAlive(lock) && lock.ready ? lock.socket : void 0;
@@ -212,9 +449,13 @@ async function ensureDaemon({ home = alpHome(), entry = (
212
449
  if (!lockAlive(held)) {
213
450
  entry ??= await findDaemonEntry({ home, env });
214
451
  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");
452
+ signal?.throwIfAborted();
215
453
  await new Promise((resolve, reject) => {
216
- const launcher = spawn(execPath, [entry, "--detach"], {
217
- env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: "1" },
454
+ const launch = entryCommand(entry, "daemon", ["--detach", `--startup-timeout=${timeoutMs}`], execPath);
455
+ const launchEnv = { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: "1" };
456
+ if (isNativeDaemonName(launch.command)) delete launchEnv.BUN_BE_BUN;
457
+ const launcher = spawn(launch.command, launch.args, {
458
+ env: launchEnv,
218
459
  stdio: ["ignore", "ignore", "pipe"],
219
460
  windowsHide: true
220
461
  });
@@ -228,6 +469,7 @@ async function ensureDaemon({ home = alpHome(), entry = (
228
469
  }
229
470
  const deadline = Date.now() + timeoutMs;
230
471
  while (Date.now() < deadline) {
472
+ signal?.throwIfAborted();
231
473
  const socket = await ready();
232
474
  if (socket) return socket;
233
475
  await new Promise((resolve) => setTimeout(resolve, 100));
@@ -270,7 +512,7 @@ async function integrationCandidateFromHome(home, name) {
270
512
  return await isFile(legacy) ? legacy : void 0;
271
513
  }
272
514
  function integrationBinaryName(name) {
273
- return name === "web" ? "alp-web-integration" : `alp-${name}-integration`;
515
+ return `alp-${name}-integration`;
274
516
  }
275
517
  async function distributionRoots() {
276
518
  const roots = [];
@@ -289,54 +531,81 @@ async function distributionRoots() {
289
531
  roots.push(process.cwd());
290
532
  return [...new Set(roots)];
291
533
  }
292
- async function discoverIntegration(name = "web", options = {}) {
534
+ async function discoverIntegration(name = "dashboard", options = {}) {
535
+ assertIntegrationName(name);
536
+ if (name === "dashboard" || name === "web") return void 0;
537
+ const { env = process.env, binDirectories = BIN_DIRECTORIES, roots } = options;
293
538
  const envCandidates = [
294
- process.env.ALP_WEB_INTEGRATION,
295
- process.env.ALP_INTEGRATION_ENTRY,
296
- name !== "web" ? process.env[`ALP_${name.toUpperCase()}_INTEGRATION`] : void 0
539
+ env[`ALP_${name.toUpperCase()}_INTEGRATION`],
540
+ name === "paseo" ? env.ALP_WEB_INTEGRATION : void 0,
541
+ env.ALP_INTEGRATION_ENTRY
297
542
  ].filter(Boolean);
298
543
  for (const candidate of envCandidates) if (await isFile(candidate)) return candidate;
299
544
  const home = options?.home ? path.resolve(options.home) : alpHome();
300
545
  const fromHome = await integrationCandidateFromHome(home, name);
301
546
  if (fromHome) return fromHome;
302
- for (const root of await distributionRoots()) {
547
+ for (const root of roots ?? await distributionRoots()) {
303
548
  for (const descriptorPath of [path.join(root, "integrations", `${name}.json`), path.join(root, "integrations", name, "integration.json")]) {
304
549
  const entry = await readIntegrationDescriptor(descriptorPath, [root]);
305
550
  if (entry) return entry;
306
551
  }
307
552
  }
308
553
  const binary = integrationBinaryName(name);
309
- for (const directory of [...(process.env.PATH ?? "").split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
554
+ for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...binDirectories]) {
310
555
  const candidate = await realpath(path.join(directory, binary)).catch(() => void 0);
311
556
  if (candidate && await isFile(candidate)) return candidate;
312
557
  }
313
558
  return void 0;
314
559
  }
315
560
  function integrationAlive(lock) {
316
- if (!lock || !Number.isSafeInteger(lock.pid)) return false;
561
+ if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
317
562
  try {
318
563
  process.kill(lock.pid, 0);
564
+ return true;
319
565
  } catch (error) {
320
566
  return error?.code === "EPERM";
321
567
  }
322
- if (typeof lock.bootTime === "number" && Math.abs(lock.bootTime - bootTime()) > 30) return false;
323
- return true;
324
568
  }
325
- async function startIntegration(nameOrOptions = "web") {
569
+ function integrationText(name, home) {
570
+ const logs = path.join(home, "logs", "integrations");
571
+ if (name === "dashboard") return {
572
+ what: "alp dashboard",
573
+ log: path.join(logs, "alp-dashboard.log"),
574
+ missing: "alp dashboard runs the alp-dashboard service of the ALP CLI, which is started with its entry (packages/cli/dist/alp-dashboard.js); run `alp dashboard`"
575
+ };
576
+ if (name === "paseo") return {
577
+ what: "The Paseo integration",
578
+ log: path.join(logs, "paseo.log"),
579
+ 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."
580
+ };
581
+ return {
582
+ what: `ALP integration ${name}`,
583
+ log: path.join(logs, `${name}.log`),
584
+ missing: `ALP integration ${name} is not installed: no ALP_${name.toUpperCase()}_INTEGRATION, descriptor <home>/integrations/${name}.json or alp-${name}-integration binary was found.`
585
+ };
586
+ }
587
+ async function startIntegration(nameOrOptions = "dashboard") {
326
588
  const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
327
- const name = options.name ?? "web";
589
+ const name = assertIntegrationName(options.name ?? "dashboard");
590
+ if (options.entry !== void 0 && (typeof options.entry !== "string" || !options.entry)) throw new TypeError("startIntegration entry must be a non-empty path");
591
+ const args = options.args ?? [];
592
+ if (!Array.isArray(args) || !args.every((arg) => typeof arg === "string")) throw new TypeError("startIntegration args must be a list of strings");
328
593
  const fs = await import("node:fs/promises");
329
594
  const pathMod = await import("node:path");
330
595
  const home = options.home ? pathMod.resolve(options.home) : alpHome();
596
+ const text = integrationText(name, home);
597
+ const explicit = options.entry !== void 0 ? pathMod.resolve(options.entry) : void 0;
598
+ if (explicit !== void 0 && !await isFile(explicit)) throw new Error(`${text.what}: integration entry not found: ${explicit}`);
331
599
  const lockPath = pathMod.join(home, "integrations", `${name}.lock`);
332
600
  const webPath = pathMod.join(home, `${name}.json`);
333
- let settings = {};
334
- try {
335
- settings = JSON.parse(await fs.readFile(pathMod.join(home, "settings.json"), "utf8"));
336
- } catch {
337
- }
338
- if (settings?.web?.enabled === false) {
339
- throw new Error('ALP web app is disabled by settings ("web.enabled": false).');
601
+ const started = explicit ? ` (entry ${explicit})` : "";
602
+ if (name === "dashboard") {
603
+ let settings = {};
604
+ try {
605
+ settings = JSON.parse(await fs.readFile(pathMod.join(home, "settings.json"), "utf8"));
606
+ } catch {
607
+ }
608
+ if (dashboardSettings(settings).enabled === false) throw new Error('alp dashboard is disabled by settings ("dashboard.enabled": false).');
340
609
  }
341
610
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
342
611
  const readLock2 = async () => {
@@ -361,23 +630,24 @@ async function startIntegration(nameOrOptions = "web") {
361
630
  const info = await readWeb();
362
631
  if (info && info.pid === lock2.pid) return lock2;
363
632
  }
633
+ if (name === "dashboard" && webStartupFailed()) throw new Error(`${text.what}${started} failed to start; see ${text.log}`);
364
634
  await sleep(100);
365
635
  }
366
636
  const lock = await readLock2();
367
- if (lock && !lock.ready) throw new Error("ALP web integration started but did not become ready; see ~/.alp/logs/integrations/paseo.log");
368
- 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.");
369
- throw new Error("ALP web integration did not publish a matching web.json lock");
637
+ if (lock && !lock.ready) throw new Error(`${text.what}${started} started but did not become ready; see ${text.log}`);
638
+ if (!lock) throw new Error(explicit ? `${text.what}${started} did not start; see ${text.log}` : text.missing);
639
+ throw new Error(`${text.what}${started} did not publish a ${name}.json matching its lock; see ${text.log}`);
370
640
  }
641
+ let webStartupFailed = () => false;
371
642
  const existing = await readLock2();
372
643
  if (existing && integrationAlive(existing)) {
373
644
  return waitForReady();
374
645
  }
375
- const entry = await discoverIntegration(name, { home });
376
- if (!entry) {
377
- 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.");
378
- }
646
+ const entry = explicit ?? await discoverIntegration(name, { home });
647
+ if (!entry) throw new Error(text.missing);
379
648
  const { spawn: spawn2 } = await import("node:child_process");
380
- const child = spawn2(process.execPath, [entry, "--service"], { stdio: "ignore", detached: true, env: { ...process.env, ALP_HOME: home } });
649
+ const launch = name === "dashboard" ? entryCommand(entry, "dashboard", ["--service", ...args]) : entryCommand(entry, "dashboard", ["--service", ...args], void 0, { scriptOnly: true });
650
+ const child = spawn2(launch.command, launch.args, { stdio: "ignore", detached: true, env: { ...process.env, ALP_HOME: home } });
381
651
  let spawnError = null;
382
652
  child.on("error", (error) => {
383
653
  spawnError = error;
@@ -387,22 +657,27 @@ async function startIntegration(nameOrOptions = "web") {
387
657
  if (code !== 0 && code !== null) exited = true;
388
658
  });
389
659
  child.unref();
660
+ webStartupFailed = () => exited;
390
661
  if (spawnError) throw spawnError;
391
662
  await sleep(150);
392
663
  if (spawnError) throw spawnError;
393
- if (exited) throw new Error("ALP web integration failed to start; see ~/.alp/logs/integrations/paseo.log");
664
+ if (exited) throw new Error(`${text.what}${explicit ? started : ` (${entry})`} failed to start; see ${text.log}`);
394
665
  return waitForReady();
395
666
  }
396
667
  export {
397
668
  AlpClient,
398
669
  AlpRpcError,
399
670
  CLOSE_CODE,
671
+ DAEMON_START_TIMEOUT_MS,
400
672
  MAX_FRAME,
401
673
  PROTOCOL_VERSION,
674
+ _setBootIdForTest,
402
675
  acquireDaemonLock,
403
676
  alpHome,
677
+ assertIntegrationName,
404
678
  assertPrivateDirectory,
405
679
  assertPrivateSocket,
680
+ bootId,
406
681
  bootTime,
407
682
  connect,
408
683
  connectSocket,
@@ -410,13 +685,18 @@ export {
410
685
  createSocketTransport2 as createSocketTransport,
411
686
  createWebSocketTransport,
412
687
  daemonPaths,
688
+ daemonStartTimeoutMs,
413
689
  discoverIntegration,
414
690
  encodeFrame,
415
691
  ensureDaemon,
416
692
  findDaemonEntry,
693
+ integrationAlive,
694
+ isSameBoot,
417
695
  lockAlive,
696
+ readDaemonLifecycle,
418
697
  readLock,
419
698
  redactUrl,
420
699
  releaseDaemonLock,
421
- startIntegration
700
+ startIntegration,
701
+ withDaemonLifecycle
422
702
  };
@@ -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
+ };