@ipab/cli 0.1.0-rc.8 → 0.1.0-rc.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ipab/cli",
3
- "version": "0.1.0-rc.8",
3
+ "version": "0.1.0-rc.9",
4
4
  "private": false,
5
5
  "description": "Node subprocess IPAB host.",
6
6
  "type": "module",
@@ -0,0 +1,60 @@
1
+ import { join } from "node:path";
2
+ import { bundledSkillSource } from "./skill-source.js";
3
+ import {
4
+ inspectBundledSkill,
5
+ manageSkills,
6
+ officialSkillsPort,
7
+ bundledSkillOrigin,
8
+ type SkillsPort,
9
+ } from "./skills.js";
10
+ import { HostError } from "./errors.js";
11
+
12
+ export async function inspectBundledSkills(
13
+ port: SkillsPort = officialSkillsPort,
14
+ ) {
15
+ return inspectBundledSkill(await bundledSkillSource(), port);
16
+ }
17
+
18
+ export async function installBundledSkills(
19
+ env: NodeJS.ProcessEnv,
20
+ preview: (text: string) => void,
21
+ port: SkillsPort = officialSkillsPort,
22
+ ) {
23
+ const catalog = await port.catalog();
24
+ const agents = catalog.detected
25
+ .filter((agent) =>
26
+ catalog.supported.some(
27
+ (entry) => entry.id === agent.id && entry.globalSkillsDir !== null,
28
+ ),
29
+ )
30
+ .map((agent) => agent.id);
31
+ if (!agents.length)
32
+ throw new HostError(
33
+ "No globally supported agents detected. Install an Agent, then retry ipab doctor --fix.",
34
+ );
35
+ const result = await manageSkills(
36
+ { env, bundledSkill: await bundledSkillSource() },
37
+ bundledSkillOrigin,
38
+ {
39
+ sync: true,
40
+ names: [],
41
+ agents,
42
+ overrideExisting: false,
43
+ dryRun: false,
44
+ yes: true,
45
+ tty: false,
46
+ confirm: () => Promise.resolve(false),
47
+ preview,
48
+ },
49
+ port,
50
+ );
51
+ if (!result.ok)
52
+ throw new HostError(
53
+ [
54
+ "Bundled IPAB Skill installation failed; existing custom content was preserved.",
55
+ ...result.items.flatMap((item) => item.problems),
56
+ ...result.results.flatMap((item) => (item.error ? [item.error] : [])),
57
+ `Inspect ${join(port.home, ".ipab", "skills", "installations.json")} and retry ipab doctor --fix.`,
58
+ ].join("\n"),
59
+ );
60
+ }
package/src/cli.ts CHANGED
@@ -45,6 +45,7 @@ import { initApp } from "./app-authoring.js";
45
45
  import { assembleBundle } from "./assembly.js";
46
46
  import { getBundle } from "./get.js";
47
47
  import { doctorDevice, doctorText } from "./doctor.js";
48
+ import { ensureDaemon, serveDaemon } from "./daemon.js";
48
49
  import { keyId } from "@ipab/bundle/pointer/crypto";
49
50
  import {
50
51
  createSwarm,
@@ -159,7 +160,7 @@ const commands: Record<string, string> = {
159
160
  daemon: "daemon [--swarm URL_OR_ALIAS]",
160
161
  "skills list": "skills list [--refresh | --no-refresh]",
161
162
  "skills sync":
162
- "skills sync [NAMES...] [--agent AGENT]... [--dry-run] [--yes] [--refresh | --no-refresh]",
163
+ "skills sync [NAMES...] [--agent AGENT]... [--override-existing] [--dry-run] [--yes] [--refresh | --no-refresh]",
163
164
  doctor: "doctor [--fix [--yes]]",
164
165
  profile: "profile [--name NAME] [--description TEXT]",
165
166
  "swarm create": "swarm create [--service URL] [--resume OPERATION]",
@@ -236,7 +237,8 @@ const commandHelp: Record<
236
237
  notes: [
237
238
  "Manages all registered Swarms independently, or only the explicitly selected --swarm; ignores the saved default.",
238
239
  "Probes pivot candidates, refreshes approved profiles and retries with cooldown. Diagnostics go to stderr.",
239
- "Ctrl-C / TERM drains operations and releases the device/state-dir lock; Kubo stays running. Run under your own supervisor if desired.",
240
+ "Swarm network operations start one background daemon on demand per state-dir; local commands, doctor and status/members inspections do not. No OS startup service is installed.",
241
+ "Ctrl-C / TERM drains foreground operations and releases the device/state-dir lock; Kubo stays running. An existing background daemon already owns this lock.",
240
242
  "Role and relay candidate changes restart only the verified managed Kubo node.",
241
243
  ],
242
244
  },
@@ -313,9 +315,10 @@ const commandHelp: Record<
313
315
  "NAMES Install identities, e.g. ipab code-review, or full shared Names such as ipab/skills/ipab. Resolved from one verified snapshot; omit for all Skills.",
314
316
  ],
315
317
  options: [
316
- "--agent AGENT Repeatable globally supported agent ID; default is detected agents.",
318
+ "--agent AGENT Repeatable globally supported agent ID; default is universal (~/.agents/skills).",
319
+ "--override-existing Replace non-IPAB-managed Skills and local edits at selected targets.",
317
320
  "--dry-run Preview without invoking npx or changing installed Skills.",
318
- "--yes Skip IPAB consent only; conflicts and local edits remain protected.",
321
+ "--yes Skip IPAB consent only; does not imply --override-existing.",
319
322
  "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
320
323
  ],
321
324
  examples: [
@@ -326,7 +329,7 @@ const commandHelp: Record<
326
329
  "Global installs only, through official skills@1.9.1 with --copy. Requires Node >=22.20.0.",
327
330
  "Non-interactive execution requires --yes. Installer version, source, paths and agents are shown first.",
328
331
  "No Skill hooks/scripts run. The trusted installer is not sandboxed. Telemetry and remote audits are disabled.",
329
- "Non-IPAB installs, local edits, cross-Swarm collisions and symlink/junction aliases are never overwritten. Removed sources are reported, not deleted.",
332
+ "Non-IPAB installs and local edits require --override-existing. Cross-Swarm collisions and symlink/junction aliases remain protected. Removed sources are reported, not deleted.",
330
333
  "Partial failures report individual results, preserve pending attribution and exit nonzero; retry the same sync.",
331
334
  ],
332
335
  },
@@ -362,7 +365,8 @@ const commandHelp: Record<
362
365
  "--yes Authorize planned repairs without prompting; requires --fix.",
363
366
  ],
364
367
  notes: [
365
- "Always checks local state/configuration, managed Kubo, HOME identity, local Swarm registry and compatible updates.",
368
+ "Always checks local state/configuration, managed Kubo, HOME identity, local Swarm registry, compatible updates and the CLI-bundled IPAB Skill for detected Agents.",
369
+ "--fix also installs/updates the bundled IPAB Skill globally using the pinned official installer, without joining a Swarm. Custom content and Swarm-managed Skills are never overwritten.",
366
370
  "Inspection never creates state, locks, credentials or caches. Official release metadata may be queried; unavailable updates are not claimed current.",
367
371
  "Healthy current components are reused without download or confirmation. Fixed protected archive cache is automatic.",
368
372
  "Unverified existing Kubo: --fix may download/cache its exact-version official archive for byte comparison only; never execute it to authenticate itself or overwrite a mismatch.",
@@ -1313,7 +1317,7 @@ export function parse(argv: readonly string[]): Parsed {
1313
1317
  );
1314
1318
  const booleans = result.path.startsWith("skills ")
1315
1319
  ? result.path === "skills sync"
1316
- ? ["dry-run", "yes", "force", "no-force"]
1320
+ ? ["dry-run", "yes", "override-existing", "force", "no-force"]
1317
1321
  : ["force", "no-force"]
1318
1322
  : result.path === "doctor"
1319
1323
  ? ["fix", "yes"]
@@ -1742,6 +1746,24 @@ async function performCli(
1742
1746
  cacheTtl: Number(value("swarm.cacheTtl")),
1743
1747
  listen: value("swarm.listen") === "loopback" ? "loopback" : "lan",
1744
1748
  pivot: Boolean(value("swarm.pivot")),
1749
+ ...(parsed.path === "daemon"
1750
+ ? {
1751
+ daemonReady: () =>
1752
+ serveDaemon(
1753
+ stateLocation(parsed.flags, env).path,
1754
+ parsed.flags.swarm === undefined ? undefined : requireSwarm(),
1755
+ ),
1756
+ }
1757
+ : {
1758
+ ensureDaemon: () =>
1759
+ ensureDaemon(
1760
+ stateLocation(parsed.flags, env).path,
1761
+ env,
1762
+ (text) => {
1763
+ io.err(text);
1764
+ },
1765
+ ),
1766
+ }),
1745
1767
  forceRefresh:
1746
1768
  parsed.options.refresh || parsed.options.force
1747
1769
  ? true
@@ -2174,6 +2196,7 @@ async function performCli(
2174
2196
  sync: parsed.path === "skills sync",
2175
2197
  names: parsed.positional,
2176
2198
  agents: parsed.agents ?? [],
2199
+ overrideExisting: Boolean(parsed.options["override-existing"]),
2177
2200
  dryRun: Boolean(parsed.options["dry-run"]),
2178
2201
  yes: Boolean(parsed.options.yes),
2179
2202
  tty: io.tty,
package/src/daemon.ts ADDED
@@ -0,0 +1,237 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { open, unlink } from "node:fs/promises";
4
+ import { createServer } from "node:http";
5
+ import { join, resolve } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { nodeError } from "./authoring.js";
9
+ import { HostError, object } from "./errors.js";
10
+ import { protectedPath, secureNew } from "./identity.js";
11
+ import {
12
+ privateDirectory,
13
+ readPrivate,
14
+ withPrivateLock,
15
+ writePrivate,
16
+ } from "./swarm-files.js";
17
+
18
+ interface Endpoint {
19
+ pid: number;
20
+ port: number;
21
+ token: string;
22
+ swarm: string | null;
23
+ }
24
+
25
+ export async function daemonResponsive(
26
+ stateDir: string,
27
+ requireAll = false,
28
+ ): Promise<boolean> {
29
+ let raw: unknown;
30
+ try {
31
+ raw = await readPrivate<unknown>(
32
+ join(stateDir, "swarm-daemon"),
33
+ "endpoint.json",
34
+ );
35
+ } catch (cause) {
36
+ if (nodeError(cause, "ENOENT")) return false;
37
+ throw cause;
38
+ }
39
+ if (raw === undefined) return false;
40
+ const endpoint = object(raw, "daemon endpoint");
41
+ if (
42
+ !Number.isSafeInteger(endpoint.pid) ||
43
+ Number(endpoint.pid) < 1 ||
44
+ !Number.isSafeInteger(endpoint.port) ||
45
+ Number(endpoint.port) < 1 ||
46
+ Number(endpoint.port) > 65535 ||
47
+ typeof endpoint.token !== "string" ||
48
+ !/^[a-f0-9]{64}$/.test(endpoint.token) ||
49
+ (endpoint.swarm !== null && typeof endpoint.swarm !== "string")
50
+ )
51
+ throw new HostError(
52
+ "Invalid daemon endpoint; inspect the protected swarm-daemon/endpoint.json before retrying.",
53
+ );
54
+ try {
55
+ const response = await fetch(
56
+ `http://127.0.0.1:${Number(endpoint.port)}/health`,
57
+ {
58
+ headers: { authorization: `Bearer ${endpoint.token}` },
59
+ signal: AbortSignal.timeout(750),
60
+ redirect: "error",
61
+ },
62
+ );
63
+ if (!response.ok) return false;
64
+ const responsive =
65
+ (await response.text()) ===
66
+ JSON.stringify({
67
+ pid: endpoint.pid,
68
+ stateDir: resolve(stateDir),
69
+ swarm: endpoint.swarm,
70
+ });
71
+ if (responsive && requireAll && endpoint.swarm !== null)
72
+ throw new HostError(
73
+ "The existing foreground daemon manages only one Swarm. Stop it and run ipab daemon without --swarm, or retry this network command to start the all-Swarm background manager.",
74
+ );
75
+ return responsive;
76
+ } catch (cause) {
77
+ if (
78
+ cause instanceof TypeError ||
79
+ (cause instanceof Error &&
80
+ ["TimeoutError", "AbortError"].includes(cause.name))
81
+ )
82
+ return false;
83
+ throw cause;
84
+ }
85
+ }
86
+
87
+ // Called only after acquiring the daemon's lifetime lock, before network work.
88
+ export async function serveDaemon(
89
+ stateDir: string,
90
+ selected?: string,
91
+ ): Promise<() => Promise<void>> {
92
+ const directory = await privateDirectory(stateDir, "swarm-daemon");
93
+ const token = randomBytes(32).toString("hex");
94
+ const server = createServer((request, response) => {
95
+ if (
96
+ request.method !== "GET" ||
97
+ request.url !== "/health" ||
98
+ request.headers.authorization !== `Bearer ${token}`
99
+ ) {
100
+ response.writeHead(403).end();
101
+ return;
102
+ }
103
+ response.setHeader("content-type", "application/json");
104
+ response.end(
105
+ JSON.stringify({
106
+ pid: process.pid,
107
+ stateDir: resolve(stateDir),
108
+ swarm: selected ?? null,
109
+ }),
110
+ );
111
+ });
112
+ server.requestTimeout = 1000;
113
+ server.headersTimeout = 1000;
114
+ server.maxConnections = 16;
115
+ const close = () =>
116
+ new Promise<void>((accept, reject) => {
117
+ server.close((error) => {
118
+ if (error) reject(error);
119
+ else accept();
120
+ });
121
+ server.closeAllConnections();
122
+ });
123
+ try {
124
+ await new Promise<void>((accept, reject) => {
125
+ server.once("error", reject);
126
+ server.listen(0, "127.0.0.1", () => {
127
+ server.removeListener("error", reject);
128
+ accept();
129
+ });
130
+ });
131
+ const address = server.address();
132
+ if (!address || typeof address === "string")
133
+ throw new HostError(
134
+ "Daemon did not bind its loopback readiness endpoint.",
135
+ );
136
+ const endpoint: Endpoint = {
137
+ pid: process.pid,
138
+ port: address.port,
139
+ token,
140
+ swarm: selected ?? null,
141
+ };
142
+ await writePrivate(directory, "endpoint.json", endpoint);
143
+ } catch (cause) {
144
+ if (server.listening) await close();
145
+ throw cause;
146
+ }
147
+ return async () => {
148
+ try {
149
+ await unlink(join(directory, "endpoint.json"));
150
+ } finally {
151
+ await close();
152
+ }
153
+ };
154
+ }
155
+
156
+ export async function ensureDaemon(
157
+ stateDir: string,
158
+ env: NodeJS.ProcessEnv,
159
+ diagnostic?: (text: string) => void,
160
+ ): Promise<void> {
161
+ if (await daemonResponsive(stateDir, true)) return;
162
+ const directory = await privateDirectory(stateDir, "swarm-daemon");
163
+ const launch = await privateDirectory(directory, "launch");
164
+ await withPrivateLock(launch, async () => {
165
+ if (await daemonResponsive(stateDir, true)) return;
166
+ const logfile = join(directory, "daemon.log");
167
+ let log;
168
+ let created = false;
169
+ try {
170
+ log = await open(logfile, "ax", 0o600);
171
+ created = true;
172
+ } catch (cause) {
173
+ if (!nodeError(cause, "EEXIST")) throw cause;
174
+ await protectedPath(logfile);
175
+ log = await open(logfile, "a");
176
+ }
177
+ try {
178
+ if (created) await secureNew(logfile);
179
+ } catch (cause) {
180
+ await log.close();
181
+ throw cause;
182
+ }
183
+ const child = spawn(
184
+ process.execPath,
185
+ [
186
+ fileURLToPath(new URL("../dist/main.js", import.meta.url)),
187
+ "--state-dir",
188
+ resolve(stateDir),
189
+ "daemon",
190
+ ],
191
+ {
192
+ env,
193
+ cwd: fileURLToPath(new URL("..", import.meta.url)),
194
+ detached: true,
195
+ windowsHide: true,
196
+ shell: false,
197
+ stdio: ["ignore", log.fd, log.fd],
198
+ },
199
+ );
200
+ child.unref();
201
+ let failure: Error | undefined;
202
+ const onError = (error: Error) => {
203
+ failure = error;
204
+ };
205
+ const onExit = (code: number | null) => {
206
+ failure = new HostError(
207
+ `Daemon exited before readiness (exit ${code ?? "signal"}).`,
208
+ );
209
+ };
210
+ child.once("error", onError);
211
+ child.once("exit", onExit);
212
+ try {
213
+ const deadline = Date.now() + 15_000;
214
+ do {
215
+ if (await daemonResponsive(stateDir, true)) {
216
+ diagnostic?.(
217
+ `IPAB daemon is running in the background. Log: ${logfile}`,
218
+ );
219
+ return;
220
+ }
221
+ if (failure) throw failure;
222
+ await delay(100);
223
+ } while (Date.now() < deadline);
224
+ throw new HostError("Timed out waiting for daemon readiness.");
225
+ } catch (cause) {
226
+ if (child.pid && child.exitCode === null && child.signalCode === null)
227
+ child.kill();
228
+ throw new HostError(
229
+ `Could not start background IPAB daemon. Inspect ${logfile}. ${cause instanceof Error ? cause.message : String(cause)}`,
230
+ );
231
+ } finally {
232
+ child.removeListener("error", onError);
233
+ child.removeListener("exit", onExit);
234
+ await log.close();
235
+ }
236
+ });
237
+ }
package/src/doctor.ts CHANGED
@@ -43,7 +43,12 @@ import {
43
43
  type KuboArchive,
44
44
  type KuboRelease,
45
45
  } from "./kubo-release.js";
46
- import { HostError } from "./errors.js";
46
+ import { HostError, message } from "./errors.js";
47
+ import {
48
+ inspectBundledSkills,
49
+ installBundledSkills,
50
+ } from "./bundled-skills.js";
51
+ import type { SkillsPort } from "./skills.js";
47
52
  import { inspectLocalMembership } from "./swarm.js";
48
53
  import { nodeRecord } from "./kubo.js";
49
54
  import { readPrivate } from "./swarm-files.js";
@@ -70,6 +75,7 @@ export interface DoctorReport {
70
75
  }[];
71
76
  }
72
77
  export interface DoctorOptions extends InstallOptions {
78
+ skillsPort?: SkillsPort;
73
79
  fix?: boolean;
74
80
  yes?: boolean;
75
81
  tty: boolean;
@@ -193,7 +199,7 @@ function check(
193
199
  ): DoctorCheck {
194
200
  return {
195
201
  id,
196
- capability: id === "state" ? "base" : "swarm",
202
+ capability: id === "state" || id === "ipab-skill" ? "base" : "swarm",
197
203
  required: id === "state",
198
204
  status,
199
205
  message,
@@ -295,7 +301,7 @@ async function stateSnapshot(file: string, signal?: AbortSignal) {
295
301
  async function inspect(
296
302
  stateDir: string,
297
303
  env: NodeJS.ProcessEnv,
298
- options: InstallOptions,
304
+ options: InstallOptions & Pick<DoctorOptions, "skillsPort">,
299
305
  verificationFact?: KuboArchive,
300
306
  ): Promise<{
301
307
  report: DoctorReport;
@@ -680,6 +686,29 @@ async function inspect(
680
686
  `Latest verified compatible stable Kubo is ${release.version} (${KUBO_RANGE}); installed ${installed?.version ?? "none"}.`,
681
687
  ),
682
688
  );
689
+ try {
690
+ const skill = await inspectBundledSkills(options.skillsPort);
691
+ checks.push(
692
+ check(
693
+ "ipab-skill",
694
+ skill.status,
695
+ skill.message,
696
+ skill.repairable,
697
+ skill.guidance,
698
+ ),
699
+ );
700
+ } catch (cause) {
701
+ options.signal?.throwIfAborted();
702
+ checks.push(
703
+ check(
704
+ "ipab-skill",
705
+ "invalid",
706
+ `Could not inspect bundled IPAB Skill: ${message(cause)}`,
707
+ false,
708
+ "Inspect Agent directories and the protected Skills ledger; no Skill files were changed.",
709
+ ),
710
+ );
711
+ }
683
712
  report.ready = ready(report);
684
713
  options.signal?.throwIfAborted();
685
714
  return {
@@ -763,7 +792,9 @@ export async function doctorDevice(
763
792
  : `${kubo.status === "blocked" ? "Recover journaled installation using verified managed Kubo" : "Install verified managed Kubo"} ${release!.version}`
764
793
  : item.id === "identity"
765
794
  ? "Create missing protected HOME account identity"
766
- : "Create missing protected local state",
795
+ : item.id === "ipab-skill"
796
+ ? `Install/update bundled IPAB Skill: ${item.message}`
797
+ : "Create missing protected local state",
767
798
  }));
768
799
  if (!actions.length) {
769
800
  report.repairs = blockedRepairs;
@@ -833,6 +864,12 @@ export async function doctorDevice(
833
864
  )
834
865
  throw new Error("Kubo dependency is unavailable.");
835
866
  await accountIdentity(env, true, true);
867
+ } else if (action.id === "ipab-skill") {
868
+ await installBundledSkills(
869
+ env,
870
+ (text) => options.diagnostic?.(text),
871
+ options.skillsPort,
872
+ );
836
873
  } else if (action.id === "kubo" && verification)
837
874
  await verifyExistingKuboArchive(stateDir, verification, {
838
875
  ...options,
@@ -848,7 +885,7 @@ export async function doctorDevice(
848
885
  } catch (cause) {
849
886
  options.signal?.throwIfAborted();
850
887
  options.diagnostic?.(
851
- `Repair failed: ${action.action}. ${cause instanceof HostError && cause.code === "KUBO_SETUP_FAILED" ? cause.message : "Existing resources were not replaced; inspect the protected installation/cache and retry."}`,
888
+ `Repair failed: ${action.action}. ${message(cause)} Existing resources were not replaced; inspect the protected installation/cache and retry.`,
852
889
  );
853
890
  repairs.push({ ...action, status: "failed" });
854
891
  if (action.id === "kubo" || action.id === "kubo-update")
@@ -1,9 +1,10 @@
1
1
  import { fileURLToPath } from "node:url";
2
+ import { buffer } from "node:stream/consumers";
2
3
  import { openBundle } from "@ipab/bundle";
3
4
  import { readCar } from "./authoring.js";
4
5
  import { skillIdentity } from "./skill-definition.js";
5
6
 
6
- export async function seedSkillSource() {
7
+ async function loadSkill() {
7
8
  const car = await readCar(
8
9
  fileURLToPath(new URL("../dist/builtins/skill.ipab.car", import.meta.url)),
9
10
  {},
@@ -11,5 +12,18 @@ export async function seedSkillSource() {
11
12
  const bundle = await openBundle(car.root, { resolveCid: car.resolveCid });
12
13
  if ((await skillIdentity(bundle)) !== "ipab")
13
14
  throw new Error("IPAB Skill seed identity must be ipab.");
14
- return { cid: car.root.toString(), blocks: car.blocks };
15
+ return { cid: car.root.toString(), blocks: car.blocks, bundle };
16
+ }
17
+
18
+ export async function seedSkillSource() {
19
+ const { cid, blocks } = await loadSkill();
20
+ return { cid, blocks };
21
+ }
22
+
23
+ export async function bundledSkillSource() {
24
+ const { cid, bundle } = await loadSkill();
25
+ const files = new Map<string, Uint8Array>();
26
+ for (const path of bundle.files)
27
+ files.set(path, await buffer(await bundle.readFile(path)));
28
+ return { cid, files };
15
29
  }