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

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/README.md CHANGED
@@ -32,6 +32,7 @@ Public imports use the package root and its explicitly exported subpaths. See [a
32
32
  `session.fork`, `session.rewind`, `session.reload`, `session.resumeCommand` and
33
33
  `session.configure.live`; docs/protocol/alp-json-rpc-v1.md §12.7–§12.9): `fork`, `rewind`, `reload`,
34
34
  `resumeCommand`, `configure` and `configurePreview`. They change only the conversation, never a file.
35
+ `commands` (capability `session.commands`, §12.12) lists the slash commands and skills a composer offers after "/".
35
36
  Each mutation is sent once: keep its `requestId` and `ifGeneration` (the generation `session.history`
36
37
  answered) and send the identical request again only after a lost answer, which alpd answers with the
37
38
  first result and `duplicate: true`. After a rewind, attached clients get `history.reset`: drop the
@@ -5,7 +5,7 @@
5
5
  * it also opens a session in `cwd`, as Paseo does, to read the models and modes the agent
6
6
  * offers (ALPD §65); an agent that offers none leaves them out.
7
7
  * @param {{ command: string, args?: string[], env?: Record<string, string>, label?: string, id?: string }} provider
8
- * @param {{ cwd?: string, timeoutMs?: number, discover?: boolean }} [options]
8
+ * @param {{ cwd?: string, timeoutMs?: number, discover?: boolean, signal?: AbortSignal }} [options]
9
9
  * @returns {Promise<{ protocolVersion: number, agent?: { name?: string, title?: string, version?: string }, loadSession: boolean, mcpHttp: boolean, authMethods: string[],
10
10
  * models?: Array<{ id: string, label: string, description?: string }>, currentModel?: string, modes?: Array<{ id: string, label: string, description?: string }>, currentMode?: string }>}
11
11
  */
@@ -15,10 +15,11 @@ export function probeAcp(provider: {
15
15
  env?: Record<string, string>;
16
16
  label?: string;
17
17
  id?: string;
18
- }, { cwd, timeoutMs, discover }?: {
18
+ }, { cwd, timeoutMs, discover, signal }?: {
19
19
  cwd?: string;
20
20
  timeoutMs?: number;
21
21
  discover?: boolean;
22
+ signal?: AbortSignal;
22
23
  }): Promise<{
23
24
  protocolVersion: number;
24
25
  agent?: {
package/dist/acp-probe.js CHANGED
@@ -1,7 +1,14 @@
1
1
  // packages/client/src/acp-probe.js
2
2
  import { stdioSession } from "./mcp-probe.js";
3
- async function probeAcp(provider, { cwd, timeoutMs = 2e4, discover = false } = {}) {
3
+ async function probeAcp(provider, { cwd, timeoutMs = 2e4, discover = false, signal } = {}) {
4
+ signal?.throwIfAborted();
4
5
  const session = stdioSession({ command: provider.command, args: provider.args ?? [], env: provider.env ?? {} }, cwd, timeoutMs);
6
+ let closing;
7
+ const abort = () => {
8
+ closing ??= session.close();
9
+ };
10
+ signal?.addEventListener("abort", abort, { once: true });
11
+ if (signal?.aborted) abort();
5
12
  try {
6
13
  const result = await session.request("initialize", {
7
14
  protocolVersion: 1,
@@ -29,7 +36,9 @@ async function probeAcp(provider, { cwd, timeoutMs = 2e4, discover = false } = {
29
36
  authMethods: (result.authMethods ?? []).map((method) => method?.name ?? method?.id).filter(Boolean)
30
37
  };
31
38
  } finally {
32
- await session.close();
39
+ signal?.removeEventListener("abort", abort);
40
+ await (closing ?? session.close());
41
+ signal?.throwIfAborted();
33
42
  }
34
43
  }
35
44
  export {
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Probes Antigravity CLI for version, status and available models.
3
- * @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string}} [provider] readOnlyMode, if set, is a legacy setting with no effect: agy enforces read-only itself.
3
+ * @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string}} [provider]
4
4
  * @param {{ cwd?: string, timeoutMs?: number }} [options]
5
5
  */
6
6
  export function probeAntigravity(provider?: {
package/dist/doctor.d.ts CHANGED
@@ -10,5 +10,12 @@ export type CommandResult = { code: number; stdout: string; stderr: string };
10
10
  export type CommandRunner = (command: string, args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number }) => Promise<CommandResult>;
11
11
  export const runCommand: CommandRunner;
12
12
  export function diagnose(options?: { home?: string; project?: string; env?: NodeJS.ProcessEnv; run?: CommandRunner; sandbox?: boolean; daemonEntry?: string; timeoutMs?: number }): Promise<DoctorCheck[]>;
13
- export function diskCheck(home: string, options?: { run?: CommandRunner; env?: NodeJS.ProcessEnv; free?: number; tempDirs?: string[] }): Promise<DoctorCheck>;
13
+ export type LeftoverState = 'clean-pushed' | 'dirty' | 'local-only' | 'unpushed' | 'in-use' | 'unknown';
14
+ export type Leftover = { path: string; state: LeftoverState; reason?: string; command?: string };
15
+ export const LEFTOVER_STATES: Record<LeftoverState, string>;
16
+ /** An absolute path of ASCII letters, digits, space and . _ - / \ : in single quotes, for sh or PowerShell; undefined for any other path. */
17
+ export function shellQuote(text: string, platform?: NodeJS.Platform): string | undefined;
18
+ /** A path as alp doctor prints it in a comment line: escaped injectively, on one line. */
19
+ export function printable(text: unknown): string;
20
+ export function diskCheck(home: string, options?: { run?: CommandRunner; env?: NodeJS.ProcessEnv; free?: number; tempDirs?: string[]; cwd?: string; classifyMs?: number; recentMs?: number; platform?: NodeJS.Platform }): Promise<DoctorCheck & { leftovers?: Leftover[] }>;
14
21
  export function repair(checks: DoctorCheck[]): Promise<Array<{ id: string; result: string }>>;
package/dist/doctor.js CHANGED
@@ -9,6 +9,7 @@ import { installedProgram, serviceFor } from "./service.js";
9
9
  import { jsonObject, agentSources, resolveAgent } from "@anhlp/alp-core/resolver";
10
10
  import { loadHooks } from "@anhlp/alp-core/hooks";
11
11
  import { isTrusted } from "@anhlp/alp-core/trust";
12
+ import { validateSkill } from "@anhlp/alp-core/skill-validate";
12
13
  import { listProviders } from "@anhlp/alp-core/providers";
13
14
  import { settingsWarnings, validateSettings, validateUserSettings } from "@anhlp/alp-core/validation";
14
15
  import { readLogTail, scrubText } from "@anhlp/alp-core/log";
@@ -408,6 +409,29 @@ async function providersCheck(home, env) {
408
409
  ]
409
410
  };
410
411
  }
412
+ async function skillFormatCheck(home) {
413
+ const directory = path.join(home, "skills");
414
+ const entries2 = await readdir(directory, { withFileTypes: true }).catch(() => []);
415
+ const failed = [];
416
+ const warned = [];
417
+ let checked = 0;
418
+ for (const entry of entries2) {
419
+ if (!entry.isDirectory() && !entry.isSymbolicLink() || !/^[\w.-]+$/.test(entry.name) || entry.name.startsWith(".")) continue;
420
+ if (!await lstat(path.join(directory, entry.name, "SKILL.md")).then(() => true, () => false)) continue;
421
+ checked++;
422
+ try {
423
+ const report = await validateSkill(path.join(directory, entry.name));
424
+ if (!report.ok) failed.push(`${entry.name}: ${report.errors.map((finding) => finding.message).join("; ")}`);
425
+ else if (report.warnings.length) warned.push(`${entry.name}: ${report.warnings.map((finding) => finding.code).join(", ")}`);
426
+ } catch (error) {
427
+ failed.push(`${entry.name}: could not be checked: ${error.message}`);
428
+ }
429
+ }
430
+ if (!checked) return void 0;
431
+ if (failed.length) return { id: "skill-format", status: "fail", summary: `${failed.length} library skill${failed.length > 1 ? "s have" : " has"} an unsafe link or an unreadable file (alp skill check <name> explains)`, details: [...failed, ...warned] };
432
+ if (warned.length) return { id: "skill-format", status: "warn", summary: `${warned.length} library skill${warned.length > 1 ? "s do" : " does"} not fully meet the skill format; they still load (alp skill check <name> explains)`, details: warned };
433
+ return { id: "skill-format", status: "ok", summary: `the library's skills meet the skill format (${directory})` };
434
+ }
411
435
  async function librarySkillsCheck(home) {
412
436
  const file = path.join(home, "role-skills.json");
413
437
  let roles;
@@ -580,7 +604,137 @@ async function entries(directory, prefix = "") {
580
604
  const names = await readdir(directory).catch(() => []);
581
605
  return names.filter((name) => name.startsWith(prefix)).map((name) => path.join(directory, name));
582
606
  }
583
- async function diskCheck(home, { run = runCommand, env = process.env, free, tempDirs = [.../* @__PURE__ */ new Set([os.tmpdir(), ...process.platform === "win32" ? [] : ["/tmp"]])] } = {}) {
607
+ var QUOTABLE = /^[A-Za-z0-9._\-/\\: ]+$/;
608
+ function shellQuote(text, platform = process.platform) {
609
+ const value = String(text);
610
+ const absolute = platform === "win32" ? path.win32.isAbsolute(value) : path.posix.isAbsolute(value);
611
+ return absolute && QUOTABLE.test(value) ? `'${value}'` : void 0;
612
+ }
613
+ var printable = (text) => String(text).replace(new RegExp("\\\\|[\\p{C}\\p{Zl}\\p{Zp}]|(?! )\\p{Zs}", "gu"), (char) => char === "\\" ? "\\\\" : `\\u{${char.codePointAt(0).toString(16)}}`);
614
+ var UNQUOTABLE = "no command: its path holds characters other than ASCII letters, digits, space and . _ - / \\ :, which a pasted command might not carry safely; check it and remove it by hand";
615
+ var LEFTOVER_STATES = {
616
+ "clean-pushed": "clean and pushed (no changes, no untracked or ignored files, and every commit and, for a clone, every ref on a remote it last fetched; remove by hand with the command shown, given only for a plain ASCII path)",
617
+ dirty: "dirty (uncommitted changes or untracked files, or a merge or rebase in progress; keep)",
618
+ "local-only": "local-only data (ignored files such as .env, local config, node_modules or build output, which exist only here; keep)",
619
+ unpushed: "unpushed (commits, or for a clone tags, branches or other refs, that no remote-tracking ref mirrors; keep)",
620
+ "in-use": "in use (a running assignment, a retained result, this shell, or changed in the last day; keep)",
621
+ unknown: "unknown (not a git checkout of its own, or git could not tell; check by hand)"
622
+ };
623
+ async function ownedPaths(home) {
624
+ const owned = /* @__PURE__ */ new Set();
625
+ const read = async (file) => JSON.parse(await readFile(file, "utf8"));
626
+ const live = await read(path.join(home, "state", "live.json")).catch(() => []);
627
+ for (const entry of Array.isArray(live) ? live : []) if (typeof entry?.worktree?.path === "string") owned.add(realpathOr(entry.worktree.path));
628
+ const ledger = await read(path.join(home, "state", "assignment-results.json")).catch(() => void 0);
629
+ for (const entry of Array.isArray(ledger?.results) ? ledger.results : []) {
630
+ if (entry?.handled) continue;
631
+ for (const where of [entry?.worktree, entry?.checkout]) if (typeof where === "string") owned.add(realpathOr(where));
632
+ }
633
+ return owned;
634
+ }
635
+ var NOT_CHECKED = "not checked: alp doctor ran out of time; run it again, or check by hand";
636
+ var OutOfTime = class extends Error {
637
+ };
638
+ async function classifyLeftover(directory, { run, env, owned, here, recentMs, deadline, platform }) {
639
+ const real = realpathOr(directory);
640
+ const inside = (outer, inner) => inner === outer || inner.startsWith(outer.endsWith(path.sep) ? outer : outer + path.sep);
641
+ if ([...owned].some((owner) => inside(real, owner) || inside(owner, real)) || inside(real, here)) return { path: directory, state: "in-use" };
642
+ const git = async (args) => {
643
+ const left = deadline - Date.now();
644
+ if (left <= 0) throw new OutOfTime();
645
+ const result = await run("git", ["-C", directory, ...args], { env, timeoutMs: Math.min(1e4, left) });
646
+ if (Date.now() >= deadline) throw new OutOfTime();
647
+ return result;
648
+ };
649
+ const unknown = (reason) => ({ path: directory, state: "unknown", reason });
650
+ if (!await lstat(path.join(directory, ".git")).then(() => true, () => false)) return unknown("not a git checkout");
651
+ const where = await git(["rev-parse", "--show-toplevel", "--absolute-git-dir", "--git-common-dir"]);
652
+ if (where.code !== 0) return unknown("not a git checkout");
653
+ const [top, gitDir, common] = where.stdout.trim().split("\n");
654
+ if (!top || !gitDir || !common || realpathOr(top) !== real) return unknown("not the top of a git checkout");
655
+ const commonDir = realpathOr(path.resolve(top, common));
656
+ const status = await git(["-c", "status.showUntrackedFiles=all", "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching"]);
657
+ if (status.code !== 0) return unknown("git status failed");
658
+ const rows = status.stdout.split("\0").filter(Boolean);
659
+ if (rows.some((row) => !row.startsWith("!! "))) return { path: directory, state: "dirty" };
660
+ const ignored = rows.map((row) => row.slice(3));
661
+ if (ignored.length) return { path: directory, state: "local-only", reason: `ignored files: ${ignored.slice(0, 3).join(", ")}${ignored.length > 3 ? `, \u2026 ${ignored.length - 3} more` : ""}` };
662
+ const index = await git(["ls-files", "-z", "-v", "--stage"]);
663
+ if (index.code !== 0) return unknown("git could not list its index");
664
+ const tracked = index.stdout.split("\0").filter(Boolean);
665
+ if (tracked.some((row) => row[0] === "S" || /[a-z]/.test(row[0]))) return unknown("some files are marked assume-unchanged or skip-worktree, which git status does not check");
666
+ if (tracked.some((row) => row.slice(2).startsWith("160000 "))) return unknown("it has submodules, whose own changes and commits this check does not read");
667
+ for (const name of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply"]) {
668
+ if (await lstat(path.join(gitDir, name)).then(() => true, () => false)) return { path: directory, state: "dirty" };
669
+ }
670
+ const touched = Math.max(...await Promise.all([directory, path.join(gitDir, "index"), path.join(gitDir, "HEAD")].map((file) => lstat(file).then((info) => info.mtimeMs, () => 0))));
671
+ if (Date.now() - touched < recentMs) return { path: directory, state: "in-use", reason: "changed in the last day" };
672
+ const linked = realpathOr(gitDir) !== commonDir;
673
+ const ahead = await git(["rev-list", "-n", "1", ...linked ? ["HEAD"] : ["HEAD", "--all"], "--not", "--remotes"]);
674
+ if (ahead.code !== 0) return unknown("git could not compare HEAD with the remotes");
675
+ if (ahead.stdout.trim()) return { path: directory, state: "unpushed" };
676
+ if (!linked) {
677
+ const refs = await git(["for-each-ref", "--format=%(objectname) %(refname)"]);
678
+ if (refs.code !== 0) return unknown("git could not list its refs");
679
+ const all = refs.stdout.split("\n").filter(Boolean).map((line) => {
680
+ const at = line.indexOf(" ");
681
+ return [line.slice(at + 1), line.slice(0, at)];
682
+ });
683
+ const remotes = await git(["remote"]);
684
+ if (remotes.code !== 0) return unknown("git could not list its remotes");
685
+ const remoteNames = remotes.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
686
+ const mirrors = new Map(all.filter(([name]) => name.startsWith("refs/remotes/")));
687
+ const mirrored = ([name, object]) => {
688
+ const branch = name.startsWith("refs/heads/");
689
+ const rest = branch ? name.slice("refs/heads/".length) : name.slice("refs/".length);
690
+ return remoteNames.some((remote) => {
691
+ const target = mirrors.get(`refs/remotes/${remote}/${rest}`);
692
+ return target !== void 0 && (branch || target === object);
693
+ });
694
+ };
695
+ const local = all.filter((entry) => !entry[0].startsWith("refs/remotes/") && !mirrored(entry));
696
+ if (local.length) return { path: directory, state: "unpushed", reason: `local refs no remote-tracking ref mirrors: ${local.slice(0, 3).map(([name]) => name).join(", ")}${local.length > 3 ? `, \u2026 ${local.length - 3} more` : ""}` };
697
+ }
698
+ const list = await git(["worktree", "list", "--porcelain"]);
699
+ if (list.code !== 0) return unknown("git could not list its worktrees");
700
+ if (!linked) {
701
+ if ((list.stdout.match(/^worktree /gm) ?? []).length > 1) return { path: directory, state: "in-use", reason: "other worktrees use its repository" };
702
+ const quoted2 = shellQuote(directory, platform);
703
+ if (quoted2 === void 0) return { path: directory, state: "clean-pushed", reason: UNQUOTABLE };
704
+ return { path: directory, state: "clean-pushed", command: platform === "win32" ? `Remove-Item -LiteralPath ${quoted2} -Recurse -Force` : `rm -rf ${quoted2}` };
705
+ }
706
+ const main = list.stdout.match(/^worktree (.*)$/m)?.[1];
707
+ if (!main) return unknown("git could not name its main worktree");
708
+ const [quotedMain, quoted] = [shellQuote(main, platform), shellQuote(directory, platform)];
709
+ if (quotedMain === void 0 || quoted === void 0) return { path: directory, state: "clean-pushed", reason: UNQUOTABLE };
710
+ return { path: directory, state: "clean-pushed", command: `git -C ${quotedMain} worktree remove ${quoted}` };
711
+ }
712
+ async function classifyLeftovers(paths, { budgetMs, ...options }) {
713
+ const results = paths.map((directory) => ({ path: directory, state: "unknown", reason: NOT_CHECKED }));
714
+ const deadline = Date.now() + budgetMs;
715
+ let next = 0, done = false;
716
+ const worker = async () => {
717
+ while (!done && next < paths.length && Date.now() < deadline) {
718
+ const index = next++;
719
+ try {
720
+ const result = await classifyLeftover(paths[index], { ...options, deadline });
721
+ if (!done && Date.now() < deadline) results[index] = result;
722
+ } catch (error) {
723
+ if (!(error instanceof OutOfTime)) results[index] = { path: paths[index], state: "unknown", reason: `could not check: ${error?.message ?? error}` };
724
+ }
725
+ }
726
+ };
727
+ let timer;
728
+ const expired = new Promise((resolve) => {
729
+ timer = setTimeout(resolve, Math.max(0, budgetMs));
730
+ });
731
+ await Promise.race([Promise.all(Array.from({ length: Math.min(8, paths.length) }, worker)), expired]);
732
+ clearTimeout(timer);
733
+ done = true;
734
+ return results;
735
+ }
736
+ var SHOWN_COMMANDS = 20;
737
+ async function diskCheck(home, { run = runCommand, env = process.env, free, tempDirs = [.../* @__PURE__ */ new Set([os.tmpdir(), ...process.platform === "win32" ? [] : ["/tmp"]])], cwd = process.cwd(), classifyMs = 1e4, recentMs = 24 * 60 * 60 * 1e3, platform = process.platform } = {}) {
584
738
  let bytes = free;
585
739
  if (bytes === void 0) {
586
740
  try {
@@ -605,17 +759,27 @@ async function diskCheck(home, { run = runCommand, env = process.env, free, temp
605
759
  const total = result.stdout.split("\n").reduce((sum, line) => sum + (Number(line.split(/\s+/)[0]) || 0), 0);
606
760
  return total * 1024;
607
761
  }
608
- const details = [];
609
- for (const [label, paths] of [[`${path.join(home, "worktrees")}`, worktrees], [`${tempDirs.map((directory) => path.join(directory, "alp-*")).join(", ")}`, temp]]) {
610
- if (!paths.length) continue;
611
- const used = await size(paths);
612
- details.push(`${paths.length} left in ${label}${used === void 0 ? "" : `, ${formatSize(used)}`}`);
613
- }
614
- const hint = details.length ? "ALP deletes none of these: some may belong to running assignments or hold uncommitted work. Remove those you no longer need (git worktree remove, or rm -rf)." : void 0;
762
+ const gitEnv = { ...Object.fromEntries(Object.entries(env).filter(([name]) => !/^GIT_(DIR|WORK_TREE|INDEX_FILE|COMMON_DIR|OBJECT_DIRECTORY|NAMESPACE|CEILING_DIRECTORIES)$/.test(name))), GIT_OPTIONAL_LOCKS: "0" };
763
+ const groups = [[`${path.join(home, "worktrees")}`, worktrees], [`${tempDirs.map((directory) => path.join(directory, "alp-*")).join(", ")}`, temp]].filter(([, paths]) => paths.length);
764
+ const [sizes, leftovers] = await Promise.all([
765
+ Promise.all(groups.map(([, paths]) => size(paths))),
766
+ ownedPaths(home).then((owned) => classifyLeftovers([.../* @__PURE__ */ new Set([...worktrees, ...temp])], { run, env: gitEnv, owned, here: realpathOr(cwd), budgetMs: classifyMs, recentMs, platform }))
767
+ ]);
768
+ const details = groups.map(([label, paths], index) => `${paths.length} left in ${label}${sizes[index] === void 0 ? "" : `, ${formatSize(sizes[index])}`}`);
769
+ for (const [state, meaning] of Object.entries(LEFTOVER_STATES)) {
770
+ const count = leftovers.filter((entry) => entry.state === state).length;
771
+ if (count) details.push(`${count} ${meaning}`);
772
+ }
773
+ const unchecked = leftovers.filter((entry) => entry.reason === NOT_CHECKED).length;
774
+ if (unchecked) details.push(` ${unchecked} of the unknown were not checked within ${classifyMs < 1e3 ? `${classifyMs} ms` : `${Math.round(classifyMs / 1e3)} s`}`);
775
+ const commands = leftovers.filter((entry) => entry.state === "clean-pushed").map((entry) => entry.command ?? `# remove by hand after checking (no safe command): ${printable(entry.path)}`);
776
+ for (const command of commands.slice(0, SHOWN_COMMANDS)) details.push(` ${command}`);
777
+ if (commands.length > SHOWN_COMMANDS) details.push(` \u2026 ${commands.length - SHOWN_COMMANDS} more; alp doctor --json lists every one`);
778
+ const hint = details.length ? "ALP deletes none of these, and --fix does not either. Only a clean and pushed leftover gets a command, for you to run by hand, and only when its path is plain ASCII; inspect the others before removing anything." : void 0;
615
779
  const where = bytes === void 0 ? "free space unknown" : `${formatSize(bytes)} free`;
616
780
  const status = bytes !== void 0 && bytes < 2 * GIB ? "warn" : "ok";
617
781
  const summary = bytes !== void 0 && bytes < 2 * GIB ? `${where} where ALP_HOME lives; when the disk is full, alpd pauses all work until space returns` : `${where} where ALP_HOME lives`;
618
- return { id: "disk", status, summary, ...details.length ? { details } : {}, ...hint ? { hint } : {} };
782
+ return { id: "disk", status, summary, ...details.length ? { details } : {}, ...hint ? { hint } : {}, ...leftovers.length ? { leftovers } : {} };
619
783
  }
620
784
  function realpathOr(file) {
621
785
  try {
@@ -650,6 +814,8 @@ async function diagnose({ home, project, env = process.env, run = runCommand, sa
650
814
  checks.push(await userSettingsCheck(home));
651
815
  const skills = await librarySkillsCheck(home);
652
816
  if (skills) checks.push(skills);
817
+ const skillFormat = await skillFormatCheck(home);
818
+ if (skillFormat) checks.push(skillFormat);
653
819
  const providers = await providersCheck(home, env);
654
820
  if (providers) checks.push(providers);
655
821
  const live = await liveCheck(home, running);
@@ -674,8 +840,11 @@ async function repair(checks) {
674
840
  return done;
675
841
  }
676
842
  export {
843
+ LEFTOVER_STATES,
677
844
  diagnose,
678
845
  diskCheck,
846
+ printable,
679
847
  repair,
680
- runCommand
848
+ runCommand,
849
+ shellQuote
681
850
  };
package/dist/index.d.ts CHANGED
@@ -14,13 +14,15 @@ export function assertPrivateSocket(socketPath: any): Promise<import("fs").Stats
14
14
  /**
15
15
  * Finds alpd.js for a client that cannot locate it beside itself, such as the Paseo
16
16
  * plugin, which Paseo re-bundles: the first existing candidate, then where alpd last
17
- * recorded itself ($ALP_HOME/alpd.json), then the ALP CLI (`alp`) on PATH.
17
+ * recorded itself ($ALP_HOME/alpd.json), then the ALP CLI (`alp`) on PATH and in the usual install
18
+ * directories (`binDirectories`; a test passes [] so the caller's own install is not found).
18
19
  */
19
- export function findDaemonEntry({ home, env, candidates }?: {
20
+ export function findDaemonEntry({ home, env, candidates, binDirectories }?: {
20
21
  home?: string | undefined;
21
22
  env?: NodeJS.ProcessEnv | undefined;
22
23
  candidates?: (string | undefined)[] | undefined;
23
- }): Promise<string | undefined>;
24
+ binDirectories?: string[] | undefined;
25
+ }): Promise<any>;
24
26
  /**
25
27
  * Integration names are single lowercase path segments: they name `<home>/integrations/<name>.lock`,
26
28
  * its guard and `<home>/<name>.json`. Returns the name, or throws a TypeError.
@@ -128,6 +130,12 @@ export function withDaemonLifecycle(home: any, action: any, run: any, { joinStar
128
130
  joinStart?: boolean | undefined;
129
131
  signal?: AbortSignal | undefined;
130
132
  }): Promise<any>;
133
+ /**
134
+ * The time a start of alpd waits for it to become ready, in ms: ALP_DAEMON_START_TIMEOUT_MS when it
135
+ * is a positive whole number of at most one hour, else DAEMON_START_TIMEOUT_MS.
136
+ * @param {NodeJS.ProcessEnv} [env]
137
+ */
138
+ export function daemonStartTimeoutMs(env?: NodeJS.ProcessEnv): number;
131
139
  /**
132
140
  * Returns the socket of a ready daemon, starting one when none runs.
133
141
  * `entry` is the daemon script; it is started through its own detaching launcher so the
@@ -151,10 +159,13 @@ export function ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleL
151
159
  * rename to `paseo`, which must never run under the web lock. `ALP_WEB_INTEGRATION` is read for
152
160
  * `paseo` only, after `ALP_PASEO_INTEGRATION`, for one release (like the alp-web-integration alias).
153
161
  * @param {string} [name]
154
- * @param {{ home?: string }} [options]
162
+ * @param {{ home?: string, env?: NodeJS.ProcessEnv, binDirectories?: string[], roots?: string[] }} [options]
155
163
  */
156
164
  export function discoverIntegration(name?: string, options?: {
157
165
  home?: string;
166
+ env?: NodeJS.ProcessEnv;
167
+ binDirectories?: string[];
168
+ roots?: string[];
158
169
  }): Promise<string | undefined>;
159
170
  export function integrationAlive(lock: any): boolean;
160
171
  /**
@@ -197,6 +208,8 @@ export class AlpClient extends AlpRpcClient {
197
208
  /** @type {import('@anhlp/alp-protocol').TerminalLimits | undefined} */
198
209
  terminalLimits: import("@anhlp/alp-protocol").TerminalLimits | undefined;
199
210
  }
211
+ /** How long a start waits for alpd to be ready by default: generous, as a loaded host can take a while. */
212
+ export const DAEMON_START_TIMEOUT_MS: 60000;
200
213
  import { AlpRpcClient } from './rpc/client.js';
201
214
  export { PROTOCOL_VERSION, MAX_FRAME, AlpRpcError, encodeFrame } from "@anhlp/alp-protocol";
202
215
  export { connectWebSocket, createWebSocketTransport, redactUrl, CLOSE_CODE } from "./websocket.js";
package/dist/index.js CHANGED
@@ -2,13 +2,13 @@
2
2
  import { setTimeout as delay } from "node:timers/promises";
3
3
  import { execFileSync, spawn } from "node:child_process";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
- import { readFileSync } from "node:fs";
6
- import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, rename, rmdir, link } from "node:fs/promises";
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";
7
7
  import net from "node:net";
8
8
  import os from "node:os";
9
9
  import path from "node:path";
10
10
  import { scrubText } from "@anhlp/alp-core/log";
11
- import { EXECUTABLE_MARKER, entryCommand, executablePath, isExecutableName, isScript } from "@anhlp/alp-core/packaged";
11
+ import { entryCommand } from "@anhlp/alp-core/packaged";
12
12
  import { createSocketTransport } from "./ipc.js";
13
13
  import { AlpRpcClient } from "./rpc/client.js";
14
14
  import { hello } from "./rpc/handshake.js";
@@ -63,11 +63,21 @@ async function assertSafeAncestors(directory) {
63
63
  async function assertPrivateDirectory(directory, { create = false } = {}) {
64
64
  await assertSafeAncestors(directory);
65
65
  if (create) await mkdir(directory, { recursive: true, mode: 448 });
66
- const info = await lstat(directory);
66
+ let info = await lstat(directory);
67
67
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("IPC requires a private directory, not a symlink");
68
- if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 63) !== 0)) {
69
- throw new Error("IPC directory must be owned by the current user with private permissions (0700)");
68
+ if (process.platform === "win32") return;
69
+ const shown = JSON.stringify(directory);
70
+ const mine = (entry) => entry.isDirectory() && !entry.isSymbolicLink() && entry.uid === process.getuid?.();
71
+ 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`);
72
+ if ((info.mode & 63) === 0) return;
73
+ if (create && (await readdir(directory)).length === 0) {
74
+ await chmod(directory, 448).catch(() => {
75
+ });
70
76
  }
77
+ info = await lstat(directory);
78
+ if (mine(info) && (info.mode & 63) === 0) return;
79
+ const quoted = `'${directory.replaceAll("'", "'\\''")}'`;
80
+ 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}`);
71
81
  }
72
82
  async function assertPrivateSocket(socketPath) {
73
83
  if (process.platform === "win32") return;
@@ -79,67 +89,52 @@ async function assertPrivateSocket(socketPath) {
79
89
  return info;
80
90
  }
81
91
  var isFile = (file) => stat(file).then((info) => info.isFile(), () => false);
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
92
  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"];
108
93
  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;
94
+ async function cliDaemonEntry(cli, depth = 0) {
95
+ const base = path.basename(cli).toLowerCase();
96
+ const root = path.resolve(path.dirname(cli), "..");
97
+ const alpd = (directory) => path.join(directory, "dist", "alpd.js");
98
+ const named = async (directory) => readFile(path.join(directory, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
99
+ let candidates = [];
100
+ if (base === "alp.cmd" && depth < 1 && !await isFile(path.join(root, "alp-bundle.json"))) {
101
+ const text = await stat(cli).then((info) => info.size <= 64 * 1024 ? readFile(cli, "utf8") : "", () => "");
102
+ for (const [, quoted] of text.matchAll(/"([^"\r\n]+\.js)"/gi)) {
103
+ const script = quoted.replace(/^%~?dp0%?[\\/]?/i, `${path.dirname(cli)}${path.sep}`);
104
+ const entry = path.isAbsolute(script) && await isFile(script) ? await cliDaemonEntry(script, depth + 1) : void 0;
105
+ if (entry) return entry;
106
+ }
107
+ return void 0;
118
108
  }
109
+ if (base === "alp" || base === "alp.cmd") {
110
+ if (!await isFile(path.join(root, "alp-bundle.json"))) return void 0;
111
+ const current = path.join(path.dirname(root), "current");
112
+ const viaCurrent = await realpath(current).then((real) => real === root, () => false);
113
+ candidates = [alpd(path.join(viaCurrent ? current : root, "lib", "node_modules", "@anhlp", "alp-cli"))];
114
+ } else if (base === "cli.js" && CLI_PACKAGES.includes(await named(root))) {
115
+ candidates = [alpd(root)];
116
+ } else if (base === "alp.js" && await named(root) === "@anhlp/alp") {
117
+ candidates = [alpd(path.join(root, "node_modules", "@anhlp", "alp-cli")), alpd(path.join(root, "..", "alp-cli"))];
118
+ }
119
+ for (const candidate of candidates) if (await isFile(candidate)) return candidate;
119
120
  return void 0;
120
121
  }
121
122
  async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = (
122
123
  /** @type {Array<string | undefined>} */
123
124
  []
124
- ) } = {}) {
125
+ ), binDirectories = BIN_DIRECTORIES } = {}) {
125
126
  for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
126
- const own = executablePath();
127
- if (own) return own;
128
127
  try {
129
128
  const { entry } = JSON.parse(await readFile(daemonPaths(home).install, "utf8"));
130
129
  if (typeof entry === "string" && await isFile(entry)) return entry;
131
130
  } catch {
132
131
  }
133
- for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
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;
138
- if (!cli || path.basename(cli) !== "cli.js") continue;
139
- const root = path.resolve(path.dirname(cli), "..");
140
- const name = await readFile(path.join(root, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
141
- const entry = path.join(root, "dist", "alpd.js");
142
- if (CLI_PACKAGES.includes(name) && await isFile(entry)) return entry;
132
+ for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...binDirectories]) {
133
+ for (const name of process.platform === "win32" ? ["alp.cmd", "alp"] : ["alp"]) {
134
+ const cli = await realpath(path.join(directory, name)).catch(() => void 0);
135
+ const entry = cli && await cliDaemonEntry(cli);
136
+ if (entry) return entry;
137
+ }
143
138
  }
144
139
  return void 0;
145
140
  }
@@ -222,7 +217,24 @@ async function acquireDaemonLock(home, contents) {
222
217
  for (let attempt = 0; attempt < 2; attempt++) {
223
218
  try {
224
219
  const handle = await open(file, "wx", 384);
225
- await handle.writeFile(JSON.stringify(lock));
220
+ let ours;
221
+ try {
222
+ ours = await handle.stat();
223
+ await handle.writeFile(JSON.stringify(lock));
224
+ } catch (error) {
225
+ if (!ours) {
226
+ try {
227
+ ours = fstatSync(handle.fd);
228
+ } catch {
229
+ }
230
+ }
231
+ await handle.close().catch(() => {
232
+ });
233
+ const there = await lstat(file).catch(() => void 0);
234
+ if (ours && there && ours.ino === there.ino && ours.dev === there.dev) await unlink(file).catch(() => {
235
+ });
236
+ throw error;
237
+ }
226
238
  await handle.close();
227
239
  return lock;
228
240
  } catch (error) {
@@ -230,7 +242,13 @@ async function acquireDaemonLock(home, contents) {
230
242
  const current = await readLock(home);
231
243
  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})`);
232
244
  const again = await readFile(file, "utf8").catch(() => void 0);
233
- if (again === void 0 || JSON.stringify(current) === again || !lockAlive(JSON.parse(again))) await unlink(file).catch(() => {
245
+ let parsed;
246
+ try {
247
+ parsed = again === void 0 ? void 0 : JSON.parse(again);
248
+ } catch {
249
+ 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`);
250
+ }
251
+ if (again === void 0 || JSON.stringify(current) === again || !lockAlive(parsed)) await unlink(file).catch(() => {
234
252
  });
235
253
  }
236
254
  }
@@ -401,10 +419,18 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false, signa
401
419
  });
402
420
  }
403
421
  }
422
+ var DAEMON_START_TIMEOUT_MS = 6e4;
423
+ var DAEMON_START_TIMEOUT_MAX_MS = 36e5;
424
+ function daemonStartTimeoutMs(env = process.env) {
425
+ const raw = env.ALP_DAEMON_START_TIMEOUT_MS?.trim();
426
+ if (!raw || !/^[0-9]+$/.test(raw)) return DAEMON_START_TIMEOUT_MS;
427
+ const value = Number(raw);
428
+ return value > 0 && value <= DAEMON_START_TIMEOUT_MAX_MS ? value : DAEMON_START_TIMEOUT_MS;
429
+ }
404
430
  async function ensureDaemon({ home = alpHome(), entry = (
405
431
  /** @type {string | undefined} */
406
432
  void 0
407
- ), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false, signal = (
433
+ ), env = process.env, execPath = process.execPath, timeoutMs = daemonStartTimeoutMs(env), lifecycleLocked = false, signal = (
408
434
  /** @type {AbortSignal | undefined} */
409
435
  void 0
410
436
  ) } = {}) {
@@ -504,23 +530,24 @@ async function distributionRoots() {
504
530
  async function discoverIntegration(name = "web", options = {}) {
505
531
  assertIntegrationName(name);
506
532
  if (name === "web") return void 0;
533
+ const { env = process.env, binDirectories = BIN_DIRECTORIES, roots } = options;
507
534
  const envCandidates = [
508
- process.env[`ALP_${name.toUpperCase()}_INTEGRATION`],
509
- name === "paseo" ? process.env.ALP_WEB_INTEGRATION : void 0,
510
- process.env.ALP_INTEGRATION_ENTRY
535
+ env[`ALP_${name.toUpperCase()}_INTEGRATION`],
536
+ name === "paseo" ? env.ALP_WEB_INTEGRATION : void 0,
537
+ env.ALP_INTEGRATION_ENTRY
511
538
  ].filter(Boolean);
512
539
  for (const candidate of envCandidates) if (await isFile(candidate)) return candidate;
513
540
  const home = options?.home ? path.resolve(options.home) : alpHome();
514
541
  const fromHome = await integrationCandidateFromHome(home, name);
515
542
  if (fromHome) return fromHome;
516
- for (const root of await distributionRoots()) {
543
+ for (const root of roots ?? await distributionRoots()) {
517
544
  for (const descriptorPath of [path.join(root, "integrations", `${name}.json`), path.join(root, "integrations", name, "integration.json")]) {
518
545
  const entry = await readIntegrationDescriptor(descriptorPath, [root]);
519
546
  if (entry) return entry;
520
547
  }
521
548
  }
522
549
  const binary = integrationBinaryName(name);
523
- for (const directory of [...(process.env.PATH ?? "").split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
550
+ for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...binDirectories]) {
524
551
  const candidate = await realpath(path.join(directory, binary)).catch(() => void 0);
525
552
  if (candidate && await isFile(candidate)) return candidate;
526
553
  }
@@ -637,6 +664,7 @@ export {
637
664
  AlpClient,
638
665
  AlpRpcError,
639
666
  CLOSE_CODE,
667
+ DAEMON_START_TIMEOUT_MS,
640
668
  MAX_FRAME,
641
669
  PROTOCOL_VERSION,
642
670
  _setBootIdForTest,
@@ -653,6 +681,7 @@ export {
653
681
  createSocketTransport2 as createSocketTransport,
654
682
  createWebSocketTransport,
655
683
  daemonPaths,
684
+ daemonStartTimeoutMs,
656
685
  discoverIntegration,
657
686
  encodeFrame,
658
687
  ensureDaemon,
package/dist/render.js CHANGED
@@ -75,6 +75,9 @@ function renderLog(rootId, entries) {
75
75
  case "skill":
76
76
  text = Array.isArray(entry.roles) ? `\u2726 ${entry.agent} saved skill ${entry.name} for ${entry.roles.join(", ")}` : `\u2726 ${entry.agent} uses skill ${entry.skill}${entry.via === "skill" ? " (Skill tool)" : ""}`;
77
77
  break;
78
+ case "skill-resource":
79
+ text = `\u2726 ${entry.agent} ${entry.action === "run" ? "runs" : "reads"} ${entry.skill}/${entry.resource}`;
80
+ break;
78
81
  case "compacted":
79
82
  text = entry.failed ? `\u2717 ${entry.agent}'s context could not be compacted${entry.error ? `: ${entry.error}` : ""}` : `\u25D1 ${entry.agent}'s context compacted${entry.preTokens !== void 0 ? ` from ${tokens(entry.preTokens)}` : ""}${entry.postTokens !== void 0 ? ` to ${tokens(entry.postTokens)}` : ""}${entry.trigger === "manual" ? " on request" : ""}`;
80
83
  break;