@anhlp/alp-cli 0.0.1-beta.3 → 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.
Files changed (69) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +51 -1
  2. package/dist/acp/main.js +1 -1
  3. package/dist/acp.js +300 -92
  4. package/dist/alp-web/THIRD-PARTY-NOTICES.txt +3256 -0
  5. package/dist/alp-web/alp-boundary.json +16 -0
  6. package/dist/alp-web/apple-touch-icon.png +0 -0
  7. package/dist/alp-web/assets/TerminalPanel-CqTsgY-W.js +22 -0
  8. package/dist/alp-web/assets/TerminalPanel-DLuoa74B.css +1 -0
  9. package/dist/alp-web/assets/highlighter-BnicKQ_d.js +18 -0
  10. package/dist/alp-web/assets/index-BMbDUCHW.css +1 -0
  11. package/dist/alp-web/assets/index-B_RFaj2C.js +59 -0
  12. package/dist/alp-web/favicon-attention.svg +6 -0
  13. package/dist/alp-web/favicon-running.svg +6 -0
  14. package/dist/alp-web/favicon.svg +5 -0
  15. package/dist/alp-web/index.html +20 -0
  16. package/dist/alp-web.js +10119 -0
  17. package/dist/alpd.js +30333 -15153
  18. package/dist/backup.js +2 -2
  19. package/dist/build-manifest.json +120 -2
  20. package/dist/cli.js +34 -3
  21. package/dist/daemon.d.ts +1 -1
  22. package/dist/daemon.js +5 -0
  23. package/dist/interfaces.d.ts +22 -2
  24. package/dist/interfaces.js +182 -37
  25. package/dist/paths.d.ts +1 -0
  26. package/dist/paths.js +2 -1
  27. package/dist/roles.d.ts +15 -0
  28. package/dist/roles.js +18 -0
  29. package/dist/schedules.d.ts +2 -0
  30. package/dist/schedules.js +45 -0
  31. package/dist/self-update.d.ts +152 -0
  32. package/dist/self-update.js +390 -0
  33. package/dist/sessions.d.ts +7 -1
  34. package/dist/sessions.js +44 -12
  35. package/dist/tasks.js +22 -8
  36. package/dist/terminal-native/README.md +201 -0
  37. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  38. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  39. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  40. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  41. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  42. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  43. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  44. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  45. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  46. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  48. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  49. package/dist/terminal-native/terminal-owner.c +389 -0
  50. package/dist/terminal.d.ts +13 -0
  51. package/dist/terminal.js +80 -0
  52. package/dist/usage.d.ts +1 -1
  53. package/dist/usage.js +22 -7
  54. package/dist/web-service.d.ts +56 -0
  55. package/dist/web-service.js +143 -0
  56. package/package.json +11 -4
  57. package/src/backup.js +1 -1
  58. package/src/cli.js +40 -4
  59. package/src/daemon.js +3 -0
  60. package/src/interfaces.js +227 -32
  61. package/src/paths.js +3 -1
  62. package/src/roles.js +28 -0
  63. package/src/schedules.js +38 -0
  64. package/src/self-update.js +406 -0
  65. package/src/sessions.js +44 -13
  66. package/src/tasks.js +22 -8
  67. package/src/terminal.js +78 -0
  68. package/src/usage.js +22 -7
  69. package/src/web-service.js +187 -0
package/dist/acp.js CHANGED
@@ -820,10 +820,10 @@ function mergeDefs(...defs) {
820
820
  function cloneDef(schema) {
821
821
  return mergeDefs(schema._zod.def);
822
822
  }
823
- function getElementAtPath(obj, path5) {
824
- if (!path5)
823
+ function getElementAtPath(obj, path6) {
824
+ if (!path6)
825
825
  return obj;
826
- return path5.reduce((acc, key) => acc?.[key], obj);
826
+ return path6.reduce((acc, key) => acc?.[key], obj);
827
827
  }
828
828
  function promiseAllObject(promisesObj) {
829
829
  const keys = Object.keys(promisesObj);
@@ -1232,11 +1232,11 @@ function explicitlyAborted(x, startIndex = 0) {
1232
1232
  }
1233
1233
  return false;
1234
1234
  }
1235
- function prefixIssues(path5, issues) {
1235
+ function prefixIssues(path6, issues) {
1236
1236
  return issues.map((iss) => {
1237
1237
  var _a3;
1238
1238
  (_a3 = iss).path ?? (_a3.path = []);
1239
- iss.path.unshift(path5);
1239
+ iss.path.unshift(path6);
1240
1240
  return iss;
1241
1241
  });
1242
1242
  }
@@ -1383,16 +1383,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1383
1383
  }
1384
1384
  function formatError(error51, mapper = (issue2) => issue2.message) {
1385
1385
  const fieldErrors = { _errors: [] };
1386
- const processError = (error52, path5 = []) => {
1386
+ const processError = (error52, path6 = []) => {
1387
1387
  for (const issue2 of error52.issues) {
1388
1388
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1389
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
1389
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
1390
1390
  } else if (issue2.code === "invalid_key") {
1391
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
1391
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
1392
1392
  } else if (issue2.code === "invalid_element") {
1393
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
1393
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
1394
1394
  } else {
1395
- const fullpath = [...path5, ...issue2.path];
1395
+ const fullpath = [...path6, ...issue2.path];
1396
1396
  if (fullpath.length === 0) {
1397
1397
  fieldErrors._errors.push(mapper(issue2));
1398
1398
  } else {
@@ -1419,17 +1419,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1419
1419
  }
1420
1420
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1421
1421
  const result = { errors: [] };
1422
- const processError = (error52, path5 = []) => {
1422
+ const processError = (error52, path6 = []) => {
1423
1423
  var _a3, _b;
1424
1424
  for (const issue2 of error52.issues) {
1425
1425
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1426
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
1426
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
1427
1427
  } else if (issue2.code === "invalid_key") {
1428
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
1428
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
1429
1429
  } else if (issue2.code === "invalid_element") {
1430
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
1430
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
1431
1431
  } else {
1432
- const fullpath = [...path5, ...issue2.path];
1432
+ const fullpath = [...path6, ...issue2.path];
1433
1433
  if (fullpath.length === 0) {
1434
1434
  result.errors.push(mapper(issue2));
1435
1435
  continue;
@@ -1461,8 +1461,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1461
1461
  }
1462
1462
  function toDotPath(_path) {
1463
1463
  const segs = [];
1464
- const path5 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1465
- for (const seg of path5) {
1464
+ const path6 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1465
+ for (const seg of path6) {
1466
1466
  if (typeof seg === "number")
1467
1467
  segs.push(`[${seg}]`);
1468
1468
  else if (typeof seg === "symbol")
@@ -14154,13 +14154,13 @@ function resolveRef(ref, ctx) {
14154
14154
  if (!ref.startsWith("#")) {
14155
14155
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14156
14156
  }
14157
- const path5 = ref.slice(1).split("/").filter(Boolean);
14158
- if (path5.length === 0) {
14157
+ const path6 = ref.slice(1).split("/").filter(Boolean);
14158
+ if (path6.length === 0) {
14159
14159
  return ctx.rootSchema;
14160
14160
  }
14161
14161
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14162
- if (path5[0] === defsKey) {
14163
- const key = path5[1];
14162
+ if (path6[0] === defsKey) {
14163
+ const key = path6[1];
14164
14164
  if (!key || !ctx.defs[key]) {
14165
14165
  throw new Error(`Reference not found: ${ref}`);
14166
14166
  }
@@ -18418,12 +18418,14 @@ var legacyClientNotificationMethods = /* @__PURE__ */ new Set([
18418
18418
  import { Readable, Writable } from "node:stream";
18419
18419
 
18420
18420
  // packages/client/src/index.js
18421
- import { spawn } from "node:child_process";
18421
+ import { setTimeout as delay } from "node:timers/promises";
18422
+ import { execFileSync, spawn } from "node:child_process";
18422
18423
  import { createHash, randomUUID } from "node:crypto";
18424
+ import { readFileSync as readFileSync2 } from "node:fs";
18423
18425
  import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, rename, rmdir, link } from "node:fs/promises";
18424
18426
  import net from "node:net";
18425
18427
  import os from "node:os";
18426
- import path from "node:path";
18428
+ import path2 from "node:path";
18427
18429
 
18428
18430
  // packages/core/src/log.js
18429
18431
  var LEVELS = Object.freeze({ debug: 10, info: 20, warn: 30, error: 40 });
@@ -18540,6 +18542,60 @@ function createLogger({ component, level, context = {}, write = stderrSink, now
18540
18542
  }
18541
18543
  var TAIL_BYTES = 256 * 1024;
18542
18544
 
18545
+ // packages/core/src/packaged.js
18546
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
18547
+ import path from "node:path";
18548
+ var KEY = Symbol.for("alp.packaged");
18549
+ var ROLE_ARGS = Object.freeze({
18550
+ daemon: Object.freeze(["daemon", "run"]),
18551
+ web: Object.freeze(["web", "serve"]),
18552
+ "bridge-acp": Object.freeze(["bridge", "acp"]),
18553
+ "bridge-antigravity": Object.freeze(["bridge", "antigravity"])
18554
+ });
18555
+ function packagedInfo() {
18556
+ return (
18557
+ /** @type {any} */
18558
+ globalThis[KEY]
18559
+ );
18560
+ }
18561
+ function isPackaged() {
18562
+ return packagedInfo() !== void 0;
18563
+ }
18564
+ var EXECUTABLE_MARKER = "alp-standalone-executable:v1:2b6f0c1e";
18565
+ var isExecutableName = (file2) => /^alp(\.exe)?$/i.test(file2.split(/[\\/]/).pop() ?? "");
18566
+ var isSelf = (file2) => isPackaged() && typeof file2 === "string" && samePath(file2, process.execPath);
18567
+ var canonical = (file2) => {
18568
+ let resolved = path.resolve(file2);
18569
+ try {
18570
+ resolved = realpathSync.native(resolved);
18571
+ } catch {
18572
+ }
18573
+ return process.platform === "darwin" || process.platform === "win32" ? resolved.toLowerCase() : resolved;
18574
+ };
18575
+ var samePath = (a, b) => canonical(a) === canonical(b);
18576
+ var isScript = (file2) => /\.[cm]?js$/i.test(file2);
18577
+ function roleArgs(role) {
18578
+ const args = ROLE_ARGS[role];
18579
+ if (!args) throw new TypeError(`Unknown ALP role: ${role}`);
18580
+ return [...args];
18581
+ }
18582
+ function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
18583
+ if (scriptOnly || isScript(entry) || !(isExecutableName(entry) || isSelf(entry))) {
18584
+ if (isPackaged() && execPath === process.execPath) return { command: "node", args: [entry, ...args] };
18585
+ return { command: execPath, args: [entry, ...args] };
18586
+ }
18587
+ return { command: entry, args: [...roleArgs(role), ...args] };
18588
+ }
18589
+ function scriptCommand(script, args = []) {
18590
+ if (isPackaged()) return { command: process.execPath, args: [script, ...args], env: { BUN_BE_BUN: "1" } };
18591
+ return { command: process.execPath, args: [script, ...args] };
18592
+ }
18593
+ function executablePath() {
18594
+ return isPackaged() ? process.execPath : void 0;
18595
+ }
18596
+ var STALE_MS = 60 * 60 * 1e3;
18597
+ var SWEEP_MIN_MS = 10 * 60 * 1e3;
18598
+
18543
18599
  // packages/protocol/src/wire.js
18544
18600
  var PROTOCOL_VERSION2 = 1;
18545
18601
  var MAX_FRAME = 16 * 1024 * 1024;
@@ -18552,10 +18608,40 @@ var AlpRpcError = class extends Error {
18552
18608
  };
18553
18609
  var ERROR = Object.freeze({ failed: 1e3, notFound: 1001, forbidden: 1003, conflict: 1004, unavailable: 1005, protocol: 1006 });
18554
18610
  var RPC_ERROR = Object.freeze({ parseError: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602 });
18555
- var CAPABILITY = Object.freeze({ attachAfter: "attach.after", promptReceipts: "prompt.receipts", extensionMethods: "extension.methods", team: "team", task: "task", library: "library", libraryProjectWrite: "library.project.write", settingsLanguage: "settings.language", sessionListPage: "session.list.page", questionWatch: "question.watch", questionWatchTurns: "question.watch.turns", workspaceFiles: "workspace.files", workspaceFilesRead: "workspace.files.read", promptImages: "prompt.images" });
18611
+ var CAPABILITY = Object.freeze({ sessionInterruptTurn: "session.interrupt.turn", catalogLive: "catalog.live", attachAfter: "attach.after", sessionHistory: "session.history", workspaceRegistry: "workspace.registry", workspaceWorktree: "workspace.worktree", workspaceGit: "workspace.git", workspaceGitFacts: "workspace.git.facts", promptReceipts: "prompt.receipts", extensionMethods: "extension.methods", team: "team", task: "task", library: "library", libraryProjectWrite: "library.project.write", settingsLanguage: "settings.language", sessionListPage: "session.list.page", questionWatch: "question.watch", questionWatchTurns: "question.watch.turns", sessionAttention: "session.attention", workspaceFiles: "workspace.files", workspaceFilesRead: "workspace.files.read", workspaceFilesBrowse: "workspace.files.browse", hostDirectories: "host.directories", promptImages: "prompt.images", schedule: "schedule", attachments: "attachments", sessionFork: "session.fork", sessionRewind: "session.rewind", sessionReload: "session.reload", sessionResumeCommand: "session.resumeCommand", sessionConfigureLive: "session.configure.live", terminal: "terminal", terminalCapture: "terminal.capture", terminalWatch: "terminal.watch" });
18556
18612
  var PROMPT_IMAGES = Object.freeze({ mimeTypes: Object.freeze(["image/png", "image/jpeg", "image/gif", "image/webp"]), maxCount: 8, maxBytes: 5 * 1024 * 1024, maxTotalBytes: 11 * 1024 * 1024 });
18557
- var RPC_METHODS = Object.freeze(["assignment.recall", "board.list", "catalog.get", "daemon.hello", "daemon.pause", "daemon.pauses", "daemon.resume", "daemon.shutdown", "daemon.status", "daemon.usage", "extension.register", "extension.unregister", "library.delete", "library.duplicate", "library.get", "library.list", "library.models", "library.rename", "library.save", "library.skills.set", "question.answer", "question.list", "question.watch", "session.archive", "session.attach", "session.close", "session.configure", "session.create", "session.get", "session.interrupt", "session.list", "session.log", "session.message", "session.preview", "session.prompt", "session.release", "session.rename", "session.status", "settings.language.get", "settings.language.set", "task.create", "task.gate.resolve", "task.list", "task.update", "team.list", "workspace.files.list", "workspace.files.read", "workspace.files.search"]);
18558
- var WORKSPACE_FILES = Object.freeze({ maxReadBytes: 1024 * 1024, maxListEntries: 1e3, maxPathLength: 4096 });
18613
+ var RPC_METHODS = Object.freeze(["assignment.recall", "attachment.abort", "attachment.begin", "attachment.chunk", "attachment.commit", "attachment.delete", "attachment.get", "board.list", "catalog.get", "catalog.refresh", "daemon.hello", "daemon.pause", "daemon.pauses", "daemon.resume", "daemon.shutdown", "daemon.status", "daemon.usage", "extension.register", "extension.unregister", "host.directories.search", "library.delete", "library.duplicate", "library.get", "library.list", "library.models", "library.rename", "library.save", "library.skills.set", "project.list", "project.register", "project.remove", "question.answer", "question.list", "question.watch", "registry.owner", "registry.worktree", "schedule.cancel", "schedule.create", "schedule.get", "schedule.list", "session.archive", "session.attach", "session.attention.clear", "session.close", "session.compact", "session.configure", "session.configure.preview", "session.create", "session.fork", "session.get", "session.history", "session.interrupt", "session.list", "session.log", "session.message", "session.preview", "session.prompt", "session.release", "session.reload", "session.rename", "session.resumeCommand", "session.rewind", "session.status", "settings.language.get", "settings.language.set", "task.create", "task.gate.resolve", "task.list", "task.update", "team.list", "terminal.attach", "terminal.close", "terminal.capture", "terminal.create", "terminal.input", "terminal.list", "terminal.watch", "terminal.unwatch", "terminal.resize", "terminal.revoke", "workspace.files.find", "workspace.files.list", "workspace.files.preview", "workspace.files.read", "workspace.files.search", "workspace.get", "workspace.git.diff", "workspace.git.facts", "workspace.git.status", "workspace.list", "workspace.update", "workspace.worktree.create", "workspace.worktree.options", "workspace.worktree.remove"]);
18614
+ var WORKSPACE_FILES = Object.freeze({ maxReadBytes: 1024 * 1024, maxListEntries: 1e3, maxPathLength: 4096, maxPreviewBytes: 50 * 1024 * 1024, maxPreviewChunkBytes: 8 * 1024 * 1024, maxFindEntries: 1e3 });
18615
+ var WORKSPACE_GIT = Object.freeze({ maxFileBytes: 1024 * 1024, maxTotalBytes: 2 * 1024 * 1024, maxUntracked: 200, maxStatusFiles: 1e3, maxRefLength: 255 });
18616
+ var ATTACHMENTS = Object.freeze({
18617
+ maxObjectBytes: 20 * 1024 * 1024,
18618
+ maxPerPrompt: 8,
18619
+ maxPromptBytes: 40 * 1024 * 1024,
18620
+ maxChunkBytes: 256 * 1024,
18621
+ maxActiveUploads: 2,
18622
+ maxPrincipalBytes: 200 * 1024 * 1024,
18623
+ maxDaemonBytes: 1024 * 1024 * 1024,
18624
+ uploadTimeoutMs: 60 * 60 * 1e3,
18625
+ unreferencedRetentionMs: 24 * 60 * 60 * 1e3,
18626
+ releasedGraceMs: 7 * 24 * 60 * 60 * 1e3,
18627
+ maxNameBytes: 255
18628
+ });
18629
+ var TERMINAL = Object.freeze({
18630
+ maxPerPrincipal: 4,
18631
+ maxPerDaemon: 16,
18632
+ maxInputBytes: 64 * 1024,
18633
+ maxOutputFrameBytes: 64 * 1024,
18634
+ replayBytes: 1024 * 1024,
18635
+ idleMs: 30 * 60 * 1e3,
18636
+ maxLifetimeMs: 8 * 60 * 60 * 1e3,
18637
+ reconnectMs: 60 * 1e3,
18638
+ minCols: 2,
18639
+ maxCols: 500,
18640
+ minRows: 1,
18641
+ maxRows: 200
18642
+ });
18643
+ var TERMINAL_LIMIT_KEYS = Object.freeze(["maxPerPrincipal", "maxPerDaemon", "maxInputBytes", "maxOutputFrameBytes", "replayBytes", "idleMs", "maxLifetimeMs", "reconnectMs"]);
18644
+ var ATTACHMENT_CHUNK_OVERHEAD = 64 * 1024;
18559
18645
 
18560
18646
  // packages/client/src/rpc/errors.js
18561
18647
  var BRAND = Symbol.for("@anhlp/alp-client/AlpClientError");
@@ -18784,9 +18870,9 @@ var AlpRpcClient = class {
18784
18870
  if (this.#closeError) return Promise.reject(new AlpClientError(CLOSED, { reason: this.#closeError.reason === "closed" ? "closed" : "disconnected", cause: this.#closeError }));
18785
18871
  if (signal?.aborted) return Promise.reject(abortError(signal));
18786
18872
  if (this.#pending.size >= this.#maxPending) return Promise.reject(new AlpClientError(`Too many ALP requests waiting for an answer (${this.#maxPending})`, { reason: "overloaded" }));
18787
- let delay;
18873
+ let delay2;
18788
18874
  try {
18789
- delay = timerDelay(timeoutMs);
18875
+ delay2 = timerDelay(timeoutMs);
18790
18876
  } catch (error51) {
18791
18877
  return Promise.reject(error51);
18792
18878
  }
@@ -18814,12 +18900,12 @@ var AlpRpcClient = class {
18814
18900
  signal?.removeEventListener("abort", onAbort);
18815
18901
  };
18816
18902
  this.#pending.set(id, { resolve, reject, cleanup });
18817
- if (delay !== void 0) {
18903
+ if (delay2 !== void 0) {
18818
18904
  timer = setTimeout(() => {
18819
18905
  if (!this.#pending.delete(id)) return;
18820
18906
  cleanup();
18821
18907
  reject(new AlpClientError(`ALP request ${method} timed out after ${timeoutMs} ms`, { reason: "timeout" }));
18822
- }, delay);
18908
+ }, delay2);
18823
18909
  }
18824
18910
  signal?.addEventListener("abort", onAbort, { once: true });
18825
18911
  try {
@@ -18994,8 +19080,9 @@ var AlpRpcClient = class {
18994
19080
  };
18995
19081
 
18996
19082
  // packages/client/src/rpc/handshake.js
18997
- function hello(client, info = { name: "alp", version: "0" }, options) {
18998
- return client.request("daemon.hello", { protocolVersion: PROTOCOL_VERSION2, client: info }, options);
19083
+ var AGENT_CAPABILITY = "principal.agent";
19084
+ function hello(client, info = { name: "alp", version: "0" }, options, { agent: agent2 = false } = {}) {
19085
+ return client.request("daemon.hello", { protocolVersion: PROTOCOL_VERSION2, client: info, ...agent2 ? { capabilities: [AGENT_CAPABILITY] } : {} }, options);
18999
19086
  }
19000
19087
 
19001
19088
  // packages/client/src/websocket.js
@@ -19003,27 +19090,27 @@ var CLOSE_CODE = Object.freeze({ unsupportedData: 4003, tooLarge: 4009 });
19003
19090
 
19004
19091
  // packages/client/src/index.js
19005
19092
  function alpHome(env = process.env) {
19006
- return path.resolve(env.ALP_HOME || path.join(os.homedir(), ".alp"));
19093
+ return path2.resolve(env.ALP_HOME || path2.join(os.homedir(), ".alp"));
19007
19094
  }
19008
19095
  function daemonPaths(home) {
19009
- const preferred = path.join(home, "alpd.sock");
19010
- const socket = process.platform === "win32" ? `\\\\.\\pipe\\alpd-${createHash("sha256").update(home).digest("hex").slice(0, 24)}` : Buffer.byteLength(preferred) < 100 ? preferred : path.join(os.tmpdir(), `alpd-${process.getuid?.() ?? "user"}-${createHash("sha256").update(home).digest("hex").slice(0, 12)}`, "rpc.sock");
19011
- return { home, lock: path.join(home, "alpd.lock"), socket, log: path.join(home, "logs", "alpd.log"), install: path.join(home, "alpd.json") };
19096
+ const preferred = path2.join(home, "alpd.sock");
19097
+ const socket = process.platform === "win32" ? `\\\\.\\pipe\\alpd-${createHash("sha256").update(home).digest("hex").slice(0, 24)}` : Buffer.byteLength(preferred) < 100 ? preferred : path2.join(os.tmpdir(), `alpd-${process.getuid?.() ?? "user"}-${createHash("sha256").update(home).digest("hex").slice(0, 12)}`, "rpc.sock");
19098
+ return { home, lock: path2.join(home, "alpd.lock"), socket, log: path2.join(home, "logs", "alpd.log"), install: path2.join(home, "alpd.json") };
19012
19099
  }
19013
19100
  async function assertSafeAncestors(directory) {
19014
19101
  if (process.platform === "win32") return;
19015
- const absolute = path.isAbsolute(directory) ? directory : `${process.cwd()}/${directory}`;
19016
- let current = path.parse(absolute).root;
19102
+ const absolute = path2.isAbsolute(directory) ? directory : `${process.cwd()}/${directory}`;
19103
+ let current = path2.parse(absolute).root;
19017
19104
  const pending = absolute.slice(current.length).split("/");
19018
19105
  let links = 0;
19019
19106
  while (pending.length) {
19020
19107
  const part = pending.shift();
19021
19108
  if (!part || part === ".") continue;
19022
19109
  if (part === "..") {
19023
- current = path.dirname(current);
19110
+ current = path2.dirname(current);
19024
19111
  continue;
19025
19112
  }
19026
- const candidate = path.join(current, part);
19113
+ const candidate = path2.join(current, part);
19027
19114
  const info = await lstat(candidate).catch((error51) => {
19028
19115
  if (error51.code !== "ENOENT") throw error51;
19029
19116
  });
@@ -19036,8 +19123,8 @@ async function assertSafeAncestors(directory) {
19036
19123
  if (info.isSymbolicLink()) {
19037
19124
  if (++links > 40) throw new Error("IPC ancestor symlink loop");
19038
19125
  const target = await readlink(candidate);
19039
- if (path.isAbsolute(target)) current = path.parse(target).root;
19040
- pending.unshift(...target.slice(path.isAbsolute(target) ? path.parse(target).root.length : 0).split("/"));
19126
+ if (path2.isAbsolute(target)) current = path2.parse(target).root;
19127
+ pending.unshift(...target.slice(path2.isAbsolute(target) ? path2.parse(target).root.length : 0).split("/"));
19041
19128
  continue;
19042
19129
  }
19043
19130
  if (!info.isDirectory() || info.mode & 18 && !(info.mode & 512)) {
@@ -19057,7 +19144,7 @@ async function assertPrivateDirectory(directory, { create = false } = {}) {
19057
19144
  }
19058
19145
  async function assertPrivateSocket(socketPath) {
19059
19146
  if (process.platform === "win32") return;
19060
- await assertPrivateDirectory(path.dirname(socketPath));
19147
+ await assertPrivateDirectory(path2.dirname(socketPath));
19061
19148
  const info = await lstat(socketPath);
19062
19149
  if (!info.isSocket() || info.uid !== process.getuid?.() || (info.mode & 63) !== 0) {
19063
19150
  throw new Error("IPC socket must be owned by the current user with private permissions (0600)");
@@ -19065,31 +19152,109 @@ async function assertPrivateSocket(socketPath) {
19065
19152
  return info;
19066
19153
  }
19067
19154
  var isFile = (file2) => stat(file2).then((info) => info.isFile(), () => false);
19068
- var BIN_DIRECTORIES = [path.join(os.homedir(), ".npm-global", "bin"), path.join(os.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin"];
19155
+ async function isAlpExecutable(file2) {
19156
+ if (isScript(file2) || !isExecutableName(file2) || !await isFile(file2)) return false;
19157
+ const handle = await open(file2, "r").catch(() => void 0);
19158
+ if (!handle) return false;
19159
+ try {
19160
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(4), 0, 4, 0);
19161
+ if (bytesRead < 4) return false;
19162
+ const magic = buffer.readUInt32BE(0);
19163
+ const native = buffer.toString("latin1") === "\x7FELF" || buffer.subarray(0, 2).toString("latin1") === "MZ" || [4277009102, 4277009103, 3472551422, 3489328638, 3405691582].includes(magic);
19164
+ if (!native) return false;
19165
+ const marker = Buffer.from(EXECUTABLE_MARKER, "latin1");
19166
+ const chunk = Buffer.alloc(1 << 20);
19167
+ let tail2 = Buffer.alloc(0);
19168
+ for (let position = 0; ; ) {
19169
+ const { bytesRead: read } = await handle.read(chunk, 0, chunk.length, position);
19170
+ if (!read) return false;
19171
+ const window = Buffer.concat([tail2, chunk.subarray(0, read)]);
19172
+ if (window.includes(marker)) return true;
19173
+ tail2 = window.subarray(Math.max(0, window.length - marker.length + 1));
19174
+ position += read;
19175
+ }
19176
+ } finally {
19177
+ await handle.close();
19178
+ }
19179
+ }
19180
+ var BIN_DIRECTORIES = [path2.join(os.homedir(), ".alp", "bin"), path2.join(os.homedir(), ".npm-global", "bin"), path2.join(os.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin"];
19069
19181
  var CLI_PACKAGES = ["@anhlp/alp", "@anhlp/alp-cli"];
19182
+ async function npmWrapperExecutable(launcher, platform = process.platform, arch = process.arch) {
19183
+ if (path2.basename(launcher) !== "alp.js") return void 0;
19184
+ const root = path2.resolve(path2.dirname(launcher), "..");
19185
+ const name = await readFile(path2.join(root, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
19186
+ if (name !== "@anhlp/alp") return void 0;
19187
+ const id = `alp-${platform}-${arch}`;
19188
+ const file2 = path2.join("bin", platform === "win32" ? "alp.exe" : "alp");
19189
+ for (const candidate of [path2.join(root, "node_modules", "@anhlp", id, file2), path2.join(root, "..", id, file2)]) {
19190
+ if (await isAlpExecutable(candidate)) return candidate;
19191
+ }
19192
+ return void 0;
19193
+ }
19070
19194
  async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = (
19071
19195
  /** @type {Array<string | undefined>} */
19072
19196
  []
19073
19197
  ) } = {}) {
19074
19198
  for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
19199
+ const own2 = executablePath();
19200
+ if (own2) return own2;
19075
19201
  try {
19076
19202
  const { entry } = JSON.parse(await readFile(daemonPaths(home).install, "utf8"));
19077
19203
  if (typeof entry === "string" && await isFile(entry)) return entry;
19078
19204
  } catch {
19079
19205
  }
19080
- for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
19081
- const cli = await realpath(path.join(directory, "alp")).catch(() => void 0);
19082
- if (!cli || path.basename(cli) !== "cli.js") continue;
19083
- const root = path.resolve(path.dirname(cli), "..");
19084
- const name = await readFile(path.join(root, "package.json"), "utf8").then((text) => JSON.parse(text).name, () => void 0);
19085
- const entry = path.join(root, "dist", "alpd.js");
19206
+ for (const directory of [...(env.PATH ?? "").split(path2.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
19207
+ const cli = await realpath(path2.join(directory, process.platform === "win32" ? "alp.exe" : "alp")).catch(() => void 0);
19208
+ if (cli && await isAlpExecutable(cli)) return cli;
19209
+ const npmExecutable = cli && await npmWrapperExecutable(cli);
19210
+ if (npmExecutable) return npmExecutable;
19211
+ if (!cli || path2.basename(cli) !== "cli.js") continue;
19212
+ const root = path2.resolve(path2.dirname(cli), "..");
19213
+ const name = await readFile(path2.join(root, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
19214
+ const entry = path2.join(root, "dist", "alpd.js");
19086
19215
  if (CLI_PACKAGES.includes(name) && await isFile(entry)) return entry;
19087
19216
  }
19088
19217
  return void 0;
19089
19218
  }
19219
+ var cachedBootId = null;
19220
+ function bootId() {
19221
+ if (cachedBootId !== null) return cachedBootId;
19222
+ try {
19223
+ if (process.platform === "linux") {
19224
+ const id = readFileSync2("/proc/sys/kernel/random/boot_id", "utf8").trim();
19225
+ if (id.length > 0) {
19226
+ cachedBootId = id;
19227
+ return cachedBootId;
19228
+ }
19229
+ } else if (process.platform === "darwin") {
19230
+ const id = execFileSync("sysctl", ["-n", "kern.bootsessionuuid"], {
19231
+ encoding: "utf8",
19232
+ stdio: ["ignore", "pipe", "ignore"],
19233
+ timeout: 2e3
19234
+ }).trim();
19235
+ if (id.length > 0) {
19236
+ cachedBootId = id;
19237
+ return cachedBootId;
19238
+ }
19239
+ }
19240
+ } catch {
19241
+ }
19242
+ cachedBootId = void 0;
19243
+ return cachedBootId;
19244
+ }
19090
19245
  function bootTime() {
19091
19246
  return Math.round((Date.now() - os.uptime() * 1e3) / 1e3);
19092
19247
  }
19248
+ function isSameBoot(lock, { bootId: curBootId = bootId(), bootTime: curBootTime = bootTime() } = {}) {
19249
+ if (!lock) return false;
19250
+ if (typeof lock.bootId === "string" && lock.bootId.length > 0 && typeof curBootId === "string" && curBootId.length > 0) {
19251
+ return lock.bootId === curBootId;
19252
+ }
19253
+ if (typeof lock.bootTime === "number" && Number.isFinite(lock.bootTime) && Number.isFinite(curBootTime)) {
19254
+ return Math.abs(lock.bootTime - curBootTime) <= 30;
19255
+ }
19256
+ return false;
19257
+ }
19093
19258
  async function readLock(home) {
19094
19259
  try {
19095
19260
  return JSON.parse(await readFile(daemonPaths(home).lock, "utf8"));
@@ -19099,7 +19264,7 @@ async function readLock(home) {
19099
19264
  }
19100
19265
  }
19101
19266
  function lockAlive(lock) {
19102
- if (!lock || !Number.isSafeInteger(lock.pid) || Math.abs((lock.bootTime ?? 0) - bootTime()) > 30) return false;
19267
+ if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
19103
19268
  try {
19104
19269
  process.kill(lock.pid, 0);
19105
19270
  return true;
@@ -19108,6 +19273,14 @@ function lockAlive(lock) {
19108
19273
  }
19109
19274
  }
19110
19275
  var AlpClient = class extends AlpRpcClient {
19276
+ /** Host features captured by connect's handshake. @type {readonly string[]} */
19277
+ capabilities = [];
19278
+ /** Limits captured by connect's handshake. @type {import('@anhlp/alp-protocol').AttachmentLimits | undefined} */
19279
+ attachmentLimits;
19280
+ /** @type {{ readonly maxCount: number; readonly maxBytes: number; readonly maxTotalBytes: number } | undefined} */
19281
+ promptImageLimits;
19282
+ /** @type {import('@anhlp/alp-protocol').TerminalLimits | undefined} */
19283
+ terminalLimits;
19111
19284
  /**
19112
19285
  * @param {import('node:net').Socket} socket a connected or connecting socket; the client owns it
19113
19286
  * @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
@@ -19133,7 +19306,17 @@ async function openSocket(socketPath) {
19133
19306
  async function connect(socketPath, client = { name: "alp", version: "0" }, options = {}) {
19134
19307
  const connection = new AlpClient(await openSocket(socketPath), options);
19135
19308
  try {
19136
- await hello(connection, client);
19309
+ const greeting = await hello(connection, client, void 0, { agent: typeof process.env.ALP_AGENT_SESSION === "string" && process.env.ALP_AGENT_SESSION !== "" });
19310
+ connection.capabilities = Object.freeze(Array.isArray(greeting.capabilities) ? greeting.capabilities.filter((value) => typeof value === "string") : []);
19311
+ if (greeting.attachmentLimits && typeof greeting.attachmentLimits === "object") {
19312
+ connection.attachmentLimits = Object.freeze({ ...greeting.attachmentLimits });
19313
+ }
19314
+ if (greeting.promptImageLimits && typeof greeting.promptImageLimits === "object") {
19315
+ connection.promptImageLimits = Object.freeze({ ...greeting.promptImageLimits });
19316
+ }
19317
+ if (greeting.terminalLimits && typeof greeting.terminalLimits === "object") {
19318
+ connection.terminalLimits = Object.freeze({ ...greeting.terminalLimits });
19319
+ }
19137
19320
  } catch (error51) {
19138
19321
  connection.close();
19139
19322
  throw error51;
@@ -19159,7 +19342,7 @@ async function tail(file2, lines = 30) {
19159
19342
  }
19160
19343
  }
19161
19344
  async function lifecycleOwners(home) {
19162
- const directory = path.join(home, "state", "alpd.starting");
19345
+ const directory = path2.join(home, "state", "alpd.starting");
19163
19346
  const names = await readdir(directory).catch((error51) => {
19164
19347
  if (error51.code === "ENOENT") return [];
19165
19348
  throw error51;
@@ -19173,26 +19356,37 @@ async function lifecycleOwners(home) {
19173
19356
  async function readDaemonLifecycle(home) {
19174
19357
  return (await lifecycleOwners(home)).find((owner) => lockAlive(owner));
19175
19358
  }
19176
- async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}) {
19359
+ async function withDaemonLifecycle(home, action, run, { joinStart = false, signal = (
19360
+ /** @type {AbortSignal | undefined} */
19361
+ void 0
19362
+ ) } = {}) {
19363
+ signal?.throwIfAborted();
19177
19364
  try {
19178
19365
  await assertPrivateDirectory(home, { create: true });
19179
19366
  } catch (cause) {
19180
19367
  throw Object.assign(new Error(`ALP_HOME_UNUSABLE, alpd failed to start while preparing its home: ${cause.message}`, { cause }), { code: "ALP_HOME_UNUSABLE" });
19181
19368
  }
19182
- const state = path.join(home, "state");
19369
+ const state = path2.join(home, "state");
19183
19370
  await assertPrivateDirectory(state, { create: true });
19184
- const directory = path.join(state, "alpd.starting");
19371
+ const directory = path2.join(state, "alpd.starting");
19372
+ const currentBootId = bootId();
19185
19373
  const token = `owner-${process.pid}-${bootTime()}-${action}-${randomUUID()}`;
19186
- const candidate = path.join(state, `alpd.starting-${token}`);
19374
+ const candidate = path2.join(state, `alpd.starting-${token}`);
19187
19375
  await mkdir(candidate, { mode: 448 });
19188
- await writeFile(path.join(candidate, token), JSON.stringify({ pid: process.pid, bootTime: bootTime(), action }), { mode: 384 });
19376
+ await writeFile(path2.join(candidate, token), JSON.stringify({
19377
+ pid: process.pid,
19378
+ bootTime: bootTime(),
19379
+ ...currentBootId ? { bootId: currentBootId } : {},
19380
+ startedUptime: Math.floor(os.uptime()),
19381
+ action
19382
+ }), { mode: 384 });
19189
19383
  try {
19190
19384
  let joined = false;
19191
19385
  if (joinStart) {
19192
19386
  const owner = await readDaemonLifecycle(home);
19193
19387
  if (owner?.action === "start") {
19194
19388
  try {
19195
- await link(path.join(directory, owner.token), path.join(directory, token));
19389
+ await link(path2.join(directory, owner.token), path2.join(directory, token));
19196
19390
  joined = true;
19197
19391
  } catch (error51) {
19198
19392
  if (error51.code !== "ENOENT") throw error51;
@@ -19200,32 +19394,34 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
19200
19394
  }
19201
19395
  }
19202
19396
  while (!joined) {
19397
+ signal?.throwIfAborted();
19203
19398
  try {
19204
19399
  await rename(candidate, directory);
19205
19400
  break;
19206
19401
  } catch (error51) {
19207
19402
  if (!["EEXIST", "ENOTEMPTY", "EPERM", "EACCES"].includes(error51.code)) throw error51;
19208
19403
  for (const owner of await lifecycleOwners(home)) {
19209
- if (!lockAlive(owner)) await unlink(path.join(directory, owner.token)).catch((error52) => {
19404
+ if (!lockAlive(owner)) await unlink(path2.join(directory, owner.token)).catch((error52) => {
19210
19405
  if (error52.code !== "ENOENT") throw error52;
19211
19406
  });
19212
19407
  }
19213
19408
  await rmdir(directory).catch((error52) => {
19214
19409
  if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error52.code)) throw error52;
19215
19410
  });
19216
- await new Promise((resolve) => setTimeout(resolve, 25));
19411
+ await delay(25, void 0, { signal });
19217
19412
  }
19218
19413
  }
19219
19414
  try {
19415
+ signal?.throwIfAborted();
19220
19416
  return await run();
19221
19417
  } finally {
19222
- await unlink(path.join(directory, token));
19418
+ await unlink(path2.join(directory, token));
19223
19419
  await rmdir(directory).catch((error51) => {
19224
19420
  if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error51.code)) throw error51;
19225
19421
  });
19226
19422
  }
19227
19423
  } finally {
19228
- await unlink(path.join(candidate, token)).catch((error51) => {
19424
+ await unlink(path2.join(candidate, token)).catch((error51) => {
19229
19425
  if (error51.code !== "ENOENT") throw error51;
19230
19426
  });
19231
19427
  await rmdir(candidate).catch((error51) => {
@@ -19236,8 +19432,12 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
19236
19432
  async function ensureDaemon({ home = alpHome(), entry = (
19237
19433
  /** @type {string | undefined} */
19238
19434
  void 0
19239
- ), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false } = {}) {
19240
- if (!lifecycleLocked) return withDaemonLifecycle(home, "start", () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true }));
19435
+ ), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false, signal = (
19436
+ /** @type {AbortSignal | undefined} */
19437
+ void 0
19438
+ ) } = {}) {
19439
+ signal?.throwIfAborted();
19440
+ if (!lifecycleLocked) return withDaemonLifecycle(home, "start", () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true, signal }), { signal });
19241
19441
  const ready = async () => {
19242
19442
  const lock = await readLock(home);
19243
19443
  return lockAlive(lock) && lock.ready ? lock.socket : void 0;
@@ -19249,8 +19449,10 @@ async function ensureDaemon({ home = alpHome(), entry = (
19249
19449
  if (!lockAlive(held)) {
19250
19450
  entry ??= await findDaemonEntry({ home, env });
19251
19451
  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");
19452
+ signal?.throwIfAborted();
19252
19453
  await new Promise((resolve, reject) => {
19253
- const launcher = spawn(execPath, [entry, "--detach", `--startup-timeout=${timeoutMs}`], {
19454
+ const launch = entryCommand(entry, "daemon", ["--detach", `--startup-timeout=${timeoutMs}`], execPath);
19455
+ const launcher = spawn(launch.command, launch.args, {
19254
19456
  env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: "1" },
19255
19457
  stdio: ["ignore", "ignore", "pipe"],
19256
19458
  windowsHide: true
@@ -19265,6 +19467,7 @@ async function ensureDaemon({ home = alpHome(), entry = (
19265
19467
  }
19266
19468
  const deadline = Date.now() + timeoutMs;
19267
19469
  while (Date.now() < deadline) {
19470
+ signal?.throwIfAborted();
19268
19471
  const socket = await ready();
19269
19472
  if (socket) return socket;
19270
19473
  await new Promise((resolve) => setTimeout(resolve, 100));
@@ -19276,13 +19479,13 @@ ${log}` : ""}`);
19276
19479
 
19277
19480
  // packages/client/src/supervise.js
19278
19481
  import { mkdir as mkdir3, unlink as unlink3, writeFile as writeFile3, stat as stat2 } from "node:fs/promises";
19279
- import path3 from "node:path";
19482
+ import path4 from "node:path";
19280
19483
 
19281
19484
  // packages/client/src/service.js
19282
19485
  import { createHash as createHash2 } from "node:crypto";
19283
19486
  import { mkdir as mkdir2, readFile as readFile2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
19284
19487
  import os2 from "node:os";
19285
- import path2 from "node:path";
19488
+ import path3 from "node:path";
19286
19489
 
19287
19490
  // packages/client/src/command.js
19288
19491
  import { spawn as spawn2 } from "node:child_process";
@@ -19290,8 +19493,9 @@ function runCommand(command, args, { cwd, env = process.env, timeoutMs = 15e3 }
19290
19493
  return new Promise((resolve) => {
19291
19494
  let child;
19292
19495
  const script = process.platform === "win32" && /\.[cm]?js$/i.test(command);
19496
+ const run = script ? scriptCommand(command, args) : { command, args };
19293
19497
  try {
19294
- child = spawn2(script ? process.execPath : command, script ? [command, ...args] : args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
19498
+ child = spawn2(run.command, run.args, { cwd, env: run.env ? { ...env, ...run.env } : env, stdio: ["ignore", "pipe", "pipe"] });
19295
19499
  } catch (error51) {
19296
19500
  resolve({ code: -1, stdout: "", stderr: error51.message });
19297
19501
  return;
@@ -19317,14 +19521,14 @@ function runCommand(command, args, { cwd, env = process.env, timeoutMs = 15e3 }
19317
19521
 
19318
19522
  // packages/client/src/service.js
19319
19523
  function serviceFor({ home, env = process.env, platform = process.platform, uid = process.getuid?.() ?? 0 }) {
19320
- const custom2 = path2.resolve(home) !== path2.join(os2.homedir(), ".alp");
19321
- const suffix = custom2 ? createHash2("sha256").update(path2.resolve(home)).digest("hex").slice(0, 8) : "";
19524
+ const custom2 = path3.resolve(home) !== path3.join(os2.homedir(), ".alp");
19525
+ const suffix = custom2 ? createHash2("sha256").update(path3.resolve(home)).digest("hex").slice(0, 8) : "";
19322
19526
  if (platform === "darwin") {
19323
19527
  const label = `com.alp.alpd${suffix ? `.${suffix}` : ""}`;
19324
- const directory = env.ALP_SERVICE_DIR || path2.join(os2.homedir(), "Library", "LaunchAgents");
19528
+ const directory = env.ALP_SERVICE_DIR || path3.join(os2.homedir(), "Library", "LaunchAgents");
19325
19529
  const launchctl = env.ALP_LAUNCHCTL || "launchctl";
19326
19530
  const target = `gui/${uid}/${label}`;
19327
- const file2 = path2.join(directory, `${label}.plist`);
19531
+ const file2 = path3.join(directory, `${label}.plist`);
19328
19532
  return {
19329
19533
  kind: "launchd",
19330
19534
  name: label,
@@ -19336,12 +19540,12 @@ function serviceFor({ home, env = process.env, platform = process.platform, uid
19336
19540
  }
19337
19541
  if (platform === "linux") {
19338
19542
  const name = `alpd${suffix ? `-${suffix}` : ""}`;
19339
- const directory = env.ALP_SERVICE_DIR || path2.join(env.XDG_CONFIG_HOME || path2.join(os2.homedir(), ".config"), "systemd", "user");
19543
+ const directory = env.ALP_SERVICE_DIR || path3.join(env.XDG_CONFIG_HOME || path3.join(os2.homedir(), ".config"), "systemd", "user");
19340
19544
  const systemctl = env.ALP_SYSTEMCTL || "systemctl";
19341
19545
  return {
19342
19546
  kind: "systemd",
19343
19547
  name,
19344
- file: path2.join(directory, `${name}.service`),
19548
+ file: path3.join(directory, `${name}.service`),
19345
19549
  install: [[systemctl, ["--user", "daemon-reload"]], [systemctl, ["--user", "enable", "--now", `${name}.service`]]],
19346
19550
  start: [[systemctl, ["--user", "start", `${name}.service`]]],
19347
19551
  uninstall: [[systemctl, ["--user", "disable", "--now", `${name}.service`], { ignore: true }]],
@@ -19372,7 +19576,7 @@ async function startService(service, run = runCommand) {
19372
19576
  }
19373
19577
 
19374
19578
  // packages/client/src/supervise.js
19375
- var holdFile = (home) => path3.join(home, "state", "alpd.held");
19579
+ var holdFile = (home) => path4.join(home, "state", "alpd.held");
19376
19580
  async function releaseHold(home) {
19377
19581
  await unlink3(holdFile(home)).catch(() => {
19378
19582
  });
@@ -19380,34 +19584,38 @@ async function releaseHold(home) {
19380
19584
  async function daemonHeld(home) {
19381
19585
  return stat2(holdFile(home)).then(() => true, () => false);
19382
19586
  }
19383
- async function whenReady(home, timeoutMs) {
19587
+ async function whenReady(home, timeoutMs, signal) {
19384
19588
  const deadline = Date.now() + timeoutMs;
19385
19589
  while (Date.now() < deadline) {
19590
+ signal?.throwIfAborted();
19386
19591
  const lock = await readLock(home);
19387
19592
  if (lockAlive(lock) && lock.ready) return lock.socket;
19388
19593
  await new Promise((resolve) => setTimeout(resolve, 100));
19389
19594
  }
19390
- throw new Error(`alpd did not become ready within ${timeoutMs / 1e3} s; see ${path3.join(home, "logs")}`);
19595
+ throw new Error(`alpd did not become ready within ${timeoutMs / 1e3} s; see ${path4.join(home, "logs")}`);
19391
19596
  }
19392
- async function startDaemon({ home, entry, env = process.env, timeoutMs = 15e3, automatic = false }) {
19597
+ async function startDaemon({ home, entry, env = process.env, timeoutMs = 15e3, automatic = false, signal }) {
19393
19598
  return withDaemonLifecycle(home, "start", async () => {
19599
+ signal?.throwIfAborted();
19394
19600
  if (automatic) {
19395
19601
  if (await daemonHeld(home)) return;
19396
19602
  } else await releaseHold(home);
19397
19603
  const lock = await readLock(home);
19398
- if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs);
19604
+ signal?.throwIfAborted();
19605
+ if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs, signal);
19399
19606
  const service = serviceFor({ home, env });
19400
19607
  if (service && await installedProgram(service)) {
19608
+ signal?.throwIfAborted();
19401
19609
  await startService(service);
19402
- return whenReady(home, timeoutMs);
19610
+ return whenReady(home, timeoutMs, signal);
19403
19611
  }
19404
- return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true });
19405
- });
19612
+ return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true, signal });
19613
+ }, { signal });
19406
19614
  }
19407
19615
 
19408
19616
  // packages/cli/src/acp/agent.ts
19409
19617
  import { randomUUID as randomUUID2 } from "node:crypto";
19410
- import path4 from "node:path";
19618
+ import path5 from "node:path";
19411
19619
  var unlistedOf = ({ teams, team, teamLabel }) => teams.some((entry) => entry.id === team) ? void 0 : { id: team, label: teamLabel ?? (team === "custom" ? "Custom" : team) };
19412
19620
  var MODES = [
19413
19621
  { id: "read-only", name: "Read only", description: "Agents read and search; nothing is changed" },
@@ -19451,9 +19659,9 @@ ${resource.text}
19451
19659
  return text.trim();
19452
19660
  }
19453
19661
  function shown(file2, cwd) {
19454
- if (!cwd || !path4.isAbsolute(file2)) return file2;
19455
- const relative = path4.relative(cwd, file2);
19456
- return relative && !relative.startsWith("..") && !path4.isAbsolute(relative) ? relative : file2;
19662
+ if (!cwd || !path5.isAbsolute(file2)) return file2;
19663
+ const relative = path5.relative(cwd, file2);
19664
+ return relative && !relative.startsWith("..") && !path5.isAbsolute(relative) ? relative : file2;
19457
19665
  }
19458
19666
  function toolKind(item) {
19459
19667
  const detail = item.detail;
@@ -19790,8 +19998,8 @@ ${item2.text}`;
19790
19998
  return preview2;
19791
19999
  }
19792
20000
  const absolute = (cwd) => {
19793
- if (!path4.isAbsolute(cwd)) throw RequestError.invalidParams(void 0, "cwd must be an absolute path");
19794
- return path4.resolve(cwd);
20001
+ if (!path5.isAbsolute(cwd)) throw RequestError.invalidParams(void 0, "cwd must be an absolute path");
20002
+ return path5.resolve(cwd);
19795
20003
  };
19796
20004
  return agent({ name: "alp" }).onConnect((connection) => {
19797
20005
  editor = connection.client;
@@ -19817,7 +20025,7 @@ ${item2.text}`;
19817
20025
  const { session: record2 } = await request("session.get", { sessionId: params.sessionId }).catch(() => {
19818
20026
  throw RequestError.resourceNotFound(params.sessionId);
19819
20027
  });
19820
- if (record2.parentId || path4.resolve(record2.projectRoot) !== cwd) throw RequestError.invalidParams(void 0, "That ALP session belongs to another project");
20028
+ if (record2.parentId || path5.resolve(record2.projectRoot) !== cwd) throw RequestError.invalidParams(void 0, "That ALP session belongs to another project");
19821
20029
  const session = track(params.sessionId, cwd, hostServers(params.mcpServers), {
19822
20030
  teams: [{ id: record2.workflow?.mode ?? "pho", label: record2.teamLabel ?? record2.workflow?.mode ?? "pho" }],
19823
20031
  team: record2.workflow?.mode ?? "pho",
@@ -19835,7 +20043,7 @@ ${item2.text}`;
19835
20043
  send(session, { sessionUpdate: "available_commands_update", availableCommands: COMMANDS });
19836
20044
  return { configOptions: configOptions(session), modes: modeState(session) };
19837
20045
  }).onRequest("session/list", async ({ params }) => {
19838
- const { sessions: rows } = await request("session.list", { ...params.cwd ? { projectRoot: path4.resolve(params.cwd) } : {}, rootsOnly: true, includeClosed: true });
20046
+ const { sessions: rows } = await request("session.list", { ...params.cwd ? { projectRoot: path5.resolve(params.cwd) } : {}, rootsOnly: true, includeClosed: true });
19839
20047
  return {
19840
20048
  sessions: rows.filter((row) => row.persistent).slice(0, 100).map((row) => ({
19841
20049
  sessionId: row.id,
@@ -19886,7 +20094,7 @@ ${item2.text}`;
19886
20094
 
19887
20095
  // packages/cli/src/acp/main.ts
19888
20096
  async function runAcp({ daemonEntry }) {
19889
- const version2 = true ? "0.0.1-beta.3" : "0.0.0";
20097
+ const version2 = true ? "0.0.1-beta.6" : "0.0.0";
19890
20098
  const logger = createLogger({ component: "acp" });
19891
20099
  const log = (message, fields) => logger.warn(message, fields);
19892
20100
  const app = createAcpAgent({