@ipab/cli 0.1.0-rc.11 → 0.1.0-rc.13

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 (151) hide show
  1. package/README.md +15 -10
  2. package/dist/authoring.d.ts +6 -2
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +65 -18
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/builtins/skill.ipab.car +0 -0
  7. package/dist/cli-daemon.d.ts +14 -0
  8. package/dist/cli-daemon.d.ts.map +1 -0
  9. package/dist/cli-daemon.js +400 -0
  10. package/dist/cli-daemon.js.map +1 -0
  11. package/dist/cli.d.ts +2 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +1631 -1100
  14. package/dist/cli.js.map +1 -1
  15. package/dist/config-secret.js +1 -1
  16. package/dist/config-secret.js.map +1 -1
  17. package/dist/daemon-api.d.ts +80 -0
  18. package/dist/daemon-api.d.ts.map +1 -0
  19. package/dist/daemon-api.js +2411 -0
  20. package/dist/daemon-api.js.map +1 -0
  21. package/dist/daemon-client.d.ts +322 -0
  22. package/dist/daemon-client.d.ts.map +1 -0
  23. package/dist/daemon-client.js +400 -0
  24. package/dist/daemon-client.js.map +1 -0
  25. package/dist/daemon-protocol.d.ts +22 -0
  26. package/dist/daemon-protocol.d.ts.map +1 -0
  27. package/dist/daemon-protocol.js +39 -0
  28. package/dist/daemon-protocol.js.map +1 -0
  29. package/dist/daemon-telemetry.d.ts +86 -0
  30. package/dist/daemon-telemetry.d.ts.map +1 -0
  31. package/dist/daemon-telemetry.js +502 -0
  32. package/dist/daemon-telemetry.js.map +1 -0
  33. package/dist/daemon-ui.d.ts +69 -0
  34. package/dist/daemon-ui.d.ts.map +1 -1
  35. package/dist/daemon-ui.js +285 -4
  36. package/dist/daemon-ui.js.map +1 -1
  37. package/dist/daemon.d.ts +10 -0
  38. package/dist/daemon.d.ts.map +1 -1
  39. package/dist/daemon.js +289 -38
  40. package/dist/daemon.js.map +1 -1
  41. package/dist/history.d.ts +3 -1
  42. package/dist/history.d.ts.map +1 -1
  43. package/dist/history.js +16 -1
  44. package/dist/history.js.map +1 -1
  45. package/dist/identity.d.ts.map +1 -1
  46. package/dist/identity.js +7 -2
  47. package/dist/identity.js.map +1 -1
  48. package/dist/ipc.d.ts +19 -7
  49. package/dist/ipc.d.ts.map +1 -1
  50. package/dist/ipc.js +96 -70
  51. package/dist/ipc.js.map +1 -1
  52. package/dist/kubo-topology.d.ts +2 -0
  53. package/dist/kubo-topology.d.ts.map +1 -1
  54. package/dist/kubo-topology.js +17 -20
  55. package/dist/kubo-topology.js.map +1 -1
  56. package/dist/kubo.d.ts +5 -3
  57. package/dist/kubo.d.ts.map +1 -1
  58. package/dist/kubo.js +83 -13
  59. package/dist/kubo.js.map +1 -1
  60. package/dist/name-reference.d.ts +8 -0
  61. package/dist/name-reference.d.ts.map +1 -0
  62. package/dist/name-reference.js +63 -0
  63. package/dist/name-reference.js.map +1 -0
  64. package/dist/pins.d.ts.map +1 -1
  65. package/dist/pins.js +18 -3
  66. package/dist/pins.js.map +1 -1
  67. package/dist/pivot-rpc.d.ts +37 -2
  68. package/dist/pivot-rpc.d.ts.map +1 -1
  69. package/dist/pivot-rpc.js +188 -8
  70. package/dist/pivot-rpc.js.map +1 -1
  71. package/dist/search-index.d.ts.map +1 -1
  72. package/dist/search-index.js +1 -0
  73. package/dist/search-index.js.map +1 -1
  74. package/dist/skill-definition.d.ts +9 -0
  75. package/dist/skill-definition.d.ts.map +1 -1
  76. package/dist/skill-definition.js +26 -2
  77. package/dist/skill-definition.js.map +1 -1
  78. package/dist/skill-source.d.ts +1 -0
  79. package/dist/skill-source.d.ts.map +1 -1
  80. package/dist/skill-source.js +10 -4
  81. package/dist/skill-source.js.map +1 -1
  82. package/dist/skills.d.ts +8 -2
  83. package/dist/skills.d.ts.map +1 -1
  84. package/dist/skills.js +31 -2
  85. package/dist/skills.js.map +1 -1
  86. package/dist/state-storage.d.ts.map +1 -1
  87. package/dist/state-storage.js +2 -1
  88. package/dist/state-storage.js.map +1 -1
  89. package/dist/state.d.ts +1 -1
  90. package/dist/state.d.ts.map +1 -1
  91. package/dist/state.js +3 -2
  92. package/dist/state.js.map +1 -1
  93. package/dist/swarm-files.d.ts.map +1 -1
  94. package/dist/swarm-files.js +7 -2
  95. package/dist/swarm-files.js.map +1 -1
  96. package/dist/swarm-fs-core.d.ts +217 -0
  97. package/dist/swarm-fs-core.d.ts.map +1 -0
  98. package/dist/swarm-fs-core.js +885 -0
  99. package/dist/swarm-fs-core.js.map +1 -0
  100. package/dist/swarm-fs-path.d.ts +17 -0
  101. package/dist/swarm-fs-path.d.ts.map +1 -0
  102. package/dist/swarm-fs-path.js +46 -0
  103. package/dist/swarm-fs-path.js.map +1 -0
  104. package/dist/swarm-fs.d.ts +9 -0
  105. package/dist/swarm-fs.d.ts.map +1 -0
  106. package/dist/swarm-fs.js +21 -0
  107. package/dist/swarm-fs.js.map +1 -0
  108. package/dist/swarm-observations.d.ts +6 -0
  109. package/dist/swarm-observations.d.ts.map +1 -1
  110. package/dist/swarm-observations.js +28 -8
  111. package/dist/swarm-observations.js.map +1 -1
  112. package/dist/swarm.d.ts +134 -18
  113. package/dist/swarm.d.ts.map +1 -1
  114. package/dist/swarm.js +1293 -484
  115. package/dist/swarm.js.map +1 -1
  116. package/dist/unixfs-tree.d.ts +55 -0
  117. package/dist/unixfs-tree.d.ts.map +1 -1
  118. package/dist/unixfs-tree.js +361 -2
  119. package/dist/unixfs-tree.js.map +1 -1
  120. package/package.json +5 -5
  121. package/src/authoring.ts +88 -28
  122. package/src/cli-daemon.ts +482 -0
  123. package/src/cli.ts +2080 -1464
  124. package/src/config-secret.ts +1 -1
  125. package/src/daemon-api.ts +3148 -0
  126. package/src/daemon-client.ts +975 -0
  127. package/src/daemon-protocol.ts +61 -0
  128. package/src/daemon-telemetry.ts +656 -0
  129. package/src/daemon-ui.ts +364 -4
  130. package/src/daemon.ts +337 -43
  131. package/src/history.ts +26 -1
  132. package/src/identity.ts +10 -2
  133. package/src/ipc.ts +113 -79
  134. package/src/kubo-topology.ts +25 -22
  135. package/src/kubo.ts +127 -9
  136. package/src/name-reference.ts +91 -0
  137. package/src/pins.ts +23 -3
  138. package/src/pivot-rpc.ts +272 -14
  139. package/src/search-index.ts +1 -0
  140. package/src/skill-definition.ts +45 -3
  141. package/src/skill-source.ts +10 -4
  142. package/src/skills.ts +43 -2
  143. package/src/state-storage.ts +5 -1
  144. package/src/state.ts +3 -1
  145. package/src/swarm-files.ts +10 -2
  146. package/src/swarm-fs-core.ts +1461 -0
  147. package/src/swarm-fs-path.ts +68 -0
  148. package/src/swarm-fs.ts +104 -0
  149. package/src/swarm-observations.ts +40 -14
  150. package/src/swarm.ts +2149 -1033
  151. package/src/unixfs-tree.ts +447 -2
package/src/cli.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import { createInterface } from "node:readline/promises";
2
+ import { existsSync } from "node:fs";
2
3
  import { lstat, readFile } from "node:fs/promises";
3
- import { ContentError, IpfsStore } from "@ipab/ipfs-store";
4
- import { ContentBundleError } from "@ipab/bundle";
5
- import { randomUUID } from "node:crypto";
6
- import { CID } from "multiformats/cid";
4
+ import { join, resolve } from "node:path";
5
+ import type { IpfsStore } from "@ipab/ipfs-store";
7
6
  import stringWidth from "string-width";
8
7
  import {
9
8
  LOCAL_SWARM_ALIAS,
@@ -16,95 +15,52 @@ import {
16
15
  storeConfiguration,
17
16
  swarmUrl,
18
17
  visibleConfig,
18
+ type ConfigKey,
19
19
  type GlobalOptions,
20
20
  } from "./config.js";
21
- import { HostError, message, object, syntax } from "./errors.js";
21
+ import { HostError, object, syntax } from "./host-error.js";
22
22
  import {
23
- filters,
24
- listHistory,
25
- selectedIds,
26
- Ownership,
27
- recoverInactive,
28
- removeHistory,
29
- } from "./history.js";
30
- import { execute } from "./runtime.js";
31
- import { validatedBundle } from "./space.js";
32
- import {
33
- createAssociation,
34
23
  exactCid,
35
24
  swarmAlias,
36
25
  State,
37
26
  type Association,
27
+ type RegisteredSwarm,
38
28
  type RunRecord,
39
29
  } from "./state.js";
40
- import {
41
- buildBundle,
42
- inspectBundle,
43
- importBundle,
44
- localBundleDirectory,
45
- nodeError,
46
- snapshotBundle,
47
- } from "./authoring.js";
48
- import { initApp } from "./app-authoring.js";
49
- import { assembleBundle } from "./assembly.js";
50
- import { getBundle } from "./get.js";
51
- import { doctorDevice, doctorText } from "./doctor.js";
52
- import {
53
- daemonEndpoint,
54
- ensureDaemon,
55
- openLoopbackUrl,
56
- serveDaemon,
57
- } from "./daemon.js";
58
- import { keyId } from "@ipab/bundle/pointer/crypto";
59
- import {
60
- createSwarm,
61
- swarmDaemon,
62
- requestMembership,
63
- approveMembership,
64
- grantPivotAuthority,
65
- exportRequest,
66
- removeMember,
67
- resumeRemoval,
68
- updateProfile,
69
- accountProfile,
70
- updateAccountProfile,
71
- swarmMembers,
30
+ import type {
72
31
  inspectSwarmStatus,
73
- verifiedRequest,
74
- verifiedRequestStream,
75
- membershipRequestSummary,
76
- updateSwarm,
77
32
  searchNames,
78
- formatNameReference,
79
- resolveReference,
80
- parseNameReference,
81
- formalName,
82
- publish,
83
- pinNameSubscription,
84
- pinReference,
85
- swarmRegistrations,
86
- swarmAssociation,
87
- setSwarmAssociation,
88
- removeSwarmAssociation,
89
- resolveTemplateSelector,
90
- templateName,
33
+ swarmMembers,
91
34
  swarmTemplates,
35
+ updateAccountProfile,
36
+ updateSwarm,
37
+ replicateSwarm,
38
+ requestMembership,
39
+ grantPivotAuthority,
92
40
  setSwarmTemplate,
93
41
  removeSwarmTemplate,
94
- type SwarmContext,
42
+ setSwarmSkill,
43
+ removeSwarmSkill,
44
+ swarmTypeSkills,
45
+ SwarmContext,
95
46
  } from "./swarm.js";
96
- import { schemaAlias } from "./app-definition.js";
97
- import { unpin, pinDetails } from "./pins.js";
98
- import { publicationSource } from "./publish-source.js";
47
+ import type { manageSkills } from "./skills.js";
48
+ import type { templateOutputTree } from "./template-presentation.js";
99
49
  import {
100
- templateRenderExample,
101
- templateOutputTree,
102
- templateParameterRows,
103
- } from "./template-presentation.js";
104
- import { logFiles } from "./logs.js";
105
- import { builtinContent } from "./builtins.js";
50
+ formatNameReference,
51
+ parseNameReference,
52
+ formalName,
53
+ templateName,
54
+ } from "./name-reference.js";
55
+ import { normalizeSwarmFsPath } from "./swarm-fs-path.js";
106
56
  import { readSecretStream } from "./config-secret.js";
107
- import { manageSkills, syncDaemonSwarm } from "./skills.js";
57
+ import {
58
+ openCliClient,
59
+ resolveLocalPathIfPresent,
60
+ resolveSwarmFromList,
61
+ runPreparedApp,
62
+ type CliClientHandle,
63
+ } from "./cli-daemon.js";
108
64
 
109
65
  export interface IO {
110
66
  out(text: string): void;
@@ -170,6 +126,9 @@ const commands: Record<string, string> = {
170
126
  daemon: "daemon",
171
127
  "daemon ui": "daemon ui [--open]",
172
128
  "skills list": "skills list [--refresh | --no-refresh]",
129
+ "skills show": "skills show SCHEMA_OR_CONTENT [--refresh | --no-refresh]",
130
+ "skills set": "skills set SKILL [--global] [--type SCHEMA]... [--replace]",
131
+ "skills remove": "skills remove [--global NAME] [--type SCHEMA]...",
173
132
  "skills sync":
174
133
  "skills sync [NAMES...] [--agent AGENT]... [--override-existing] [--dry-run] [--yes] [--refresh | --no-refresh]",
175
134
  doctor: "doctor [--fix [--yes]]",
@@ -183,6 +142,7 @@ const commands: Record<string, string> = {
183
142
  "swarm resume": "swarm resume",
184
143
  "swarm profile": "swarm profile [--address MULTIADDR] [--pivot true|false]",
185
144
  "swarm status": "swarm status [--refresh | --no-refresh]",
145
+ "swarm replicate": "swarm replicate [--pivot MEMBER]",
186
146
  "swarm members": "swarm members [--refresh | --no-refresh]",
187
147
  "swarm list": "swarm list",
188
148
  "swarm set": "swarm set ALIAS CONFIG_URL [--yes]",
@@ -197,7 +157,7 @@ const commands: Record<string, string> = {
197
157
  build: "build [SOURCE] [OPTIONS]",
198
158
  "bundle build": "bundle build SOURCE [OPTIONS]",
199
159
  "bundle inspect": "bundle inspect SOURCE",
200
- "bundle import": "bundle import FILE.car",
160
+ "bundle import": "bundle import SOURCE",
201
161
  exec: "exec [--log] [--refresh | --no-refresh] APP [APP_ARGS...]",
202
162
  open: "open [--log] [--raw] [--refresh | --no-refresh] CONTENT",
203
163
  pin: "pin REF [--refresh | --no-refresh]",
@@ -218,18 +178,23 @@ const commands: Record<string, string> = {
218
178
  "config reset": "config reset KEY",
219
179
  "store usage": "store usage",
220
180
  "store gc": "store gc",
181
+ "fs ls": "fs ls [PATH] [--all] [--recursive] [--refresh | --no-refresh]",
182
+ "fs stat": "fs stat PATH [--refresh | --no-refresh]",
183
+ "fs set": "fs set PATH CID [--expect OLD_CID | --replace]",
184
+ "fs rm": "fs rm PATH [--expect OLD_CID]",
221
185
  "history list": "history list [OPTIONS]",
222
186
  "history show": "history show RUN_ID",
223
187
  "history remove":
224
188
  "history remove RUN_ID... [--yes]\n ipab history remove FILTERS [--yes]",
225
189
  };
226
190
  const groups: Record<string, string> = {
227
- skills: "Discover and explicitly synchronize selected Swarm Skills globally",
191
+ skills: "Discover, associate, and synchronize Swarm Skills",
228
192
  swarm: "Create, authorize, select and manage personal swarms",
229
193
  bundle: "Create, inspect and import content bundles",
230
194
  pin: "Retain an exact CID or follow a shared Swarm Name",
231
195
  register: "Associate content types with Apps",
232
196
  templates: "Inspect, render and manage Template Bundles",
197
+ fs: "Inspect and modify paths in a Swarm UnixFS tree",
233
198
  config: "Manage local configuration",
234
199
  store: "Query local storage and collect unreferenced blocks",
235
200
  history: "View and remove execution history",
@@ -269,7 +234,7 @@ const commandHelp: Record<
269
234
  "ipab --json daemon ui",
270
235
  ],
271
236
  notes: [
272
- "Inspects the protected loopback endpoint for the selected state-dir without starting a daemon.",
237
+ "Ensures the local daemon is running for the selected state-dir, then shows or opens its protected loopback status WebUI.",
273
238
  "The WebUI binds strictly to 127.0.0.1, validates Host/Origin headers against DNS rebinding, and never exposes private keys, swarm.key or Kubo Bearer tokens.",
274
239
  ],
275
240
  },
@@ -328,22 +293,81 @@ const commandHelp: Record<
328
293
  ],
329
294
  },
330
295
  "skills list": {
331
- summary: "List typed Skills and local installation status from one Swarm",
296
+ summary:
297
+ "List Global Skills (with local status) and Type Skills from one Swarm",
332
298
  options: [
333
299
  "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
334
- "Global --json Emit machine-readable names, exact payload CIDs and status.",
300
+ "Global --json Emit machine-readable global items, typeSkills, CIDs and status.",
335
301
  ],
336
302
  examples: ["ipab --swarm work skills list", "ipab --json skills list"],
337
303
  notes: [
338
304
  "Select one Swarm with global --swarm or swarm use; there is no --all.",
339
- "Requires skillPath in the exact root State Bundle or legacy Meta type. Older v5 roots require a new seeded Swarm; only legacy v2/v3/v4 Meta can be explicitly replaced with --expect. No silent upgrades.",
305
+ "Reads <skillPath>/global/* and <skillPath>/types/*; missing subdirectories are treated as empty.",
306
+ "Requires skillPath in the exact root State Bundle or legacy Meta type. No silent upgrades.",
307
+ ],
308
+ },
309
+ "skills show": {
310
+ summary: "Show the Skill associated with a Bundle type or content Bundle",
311
+ arguments: [
312
+ "SCHEMA_OR_CONTENT Canonical schema CID, builtin: alias, content Bundle CID, Swarm URI, or local .car/Bundle directory.",
313
+ ],
314
+ options: [
315
+ "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
316
+ "Global --json Emit machine-readable Skill association details.",
317
+ ],
318
+ examples: [
319
+ "ipab skills show SCHEMA_CID",
320
+ "ipab skills show ipab://work/docs/spec",
321
+ "ipab --json skills show ./document.car",
322
+ ],
323
+ notes: [
324
+ "Swarm URIs use the URI's Swarm ahead of --swarm and the default Swarm.",
325
+ "Content Bundle references automatically unwrap Artifacts and resolve their schema CID.",
326
+ "Exits with code 1 (SKILL_NOT_FOUND) when no Skill is associated with the schema.",
327
+ ],
328
+ },
329
+ "skills set": {
330
+ summary: "Associate a Skill Bundle globally and/or with Bundle types",
331
+ arguments: [
332
+ "SKILL Skill Bundle CID, Swarm URI, local .car file, or assembled Skill Bundle directory containing .bundle.yaml.",
333
+ ],
334
+ options: [
335
+ "--global Publish to <skillPath>/global/<skill-name> for global synchronization.",
336
+ "--type SCHEMA Repeatable target Bundle schema CID (writes <skillPath>/types/<schemaCid>).",
337
+ "--replace Overwrite existing targets that point to a different Skill CID.",
338
+ ],
339
+ examples: [
340
+ "ipab skills set SKILL_CID --global",
341
+ "ipab skills set ./skill.car --type SCHEMA_CID",
342
+ "ipab skills set SKILL_CID --global --type SCHEMA_CID --replace",
343
+ ],
344
+ notes: [
345
+ "Requires --global and/or at least one --type SCHEMA. All targets commit atomically in one HEAD CAS.",
346
+ "Writes direct Skill Bundle CIDs. Occupied targets with a different CID fail with exit code 3 unless --replace is set.",
347
+ ],
348
+ },
349
+ "skills remove": {
350
+ summary: "Remove global and/or type Skill associations atomically",
351
+ options: [
352
+ "--global NAME Remove <skillPath>/global/NAME (at most once).",
353
+ "--type SCHEMA Repeatable target Bundle schema CID to remove from <skillPath>/types/.",
354
+ ],
355
+ examples: [
356
+ "ipab skills remove --global my-skill",
357
+ "ipab skills remove --type SCHEMA_CID",
358
+ "ipab skills remove --global my-skill --type SCHEMA_CID",
359
+ ],
360
+ notes: [
361
+ "Requires --global NAME and/or at least one --type SCHEMA. All removals commit atomically in one HEAD CAS.",
362
+ "If any target is missing, the entire batch fails with exit code 1 and nothing is modified.",
363
+ "Does not delete underlying content blocks or locally installed Agent Skill files.",
340
364
  ],
341
365
  },
342
366
  "skills sync": {
343
367
  summary:
344
- "Install reviewed Swarm Skills using the pinned official npx installer",
368
+ "Install reviewed Global Swarm Skills using the pinned official npx installer",
345
369
  arguments: [
346
- "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.",
370
+ "NAMES Install identities, e.g. ipab code-review, or full shared Names such as ipab/skills/global/ipab. Resolved from one verified snapshot; omit for all Global Skills.",
347
371
  ],
348
372
  options: [
349
373
  "--agent AGENT Repeatable globally supported agent ID; default is universal (~/.agents/skills).",
@@ -357,6 +381,7 @@ const commandHelp: Record<
357
381
  "ipab skills sync ipab code-review --agent github-copilot --yes",
358
382
  ],
359
383
  notes: [
384
+ "Scans <skillPath>/global/* only; Type Skills under <skillPath>/types/* are never installed globally.",
360
385
  "Global installs only, through official skills@1.9.1 with --copy. Requires Node >=22.20.0.",
361
386
  "Non-interactive execution requires --yes. Installer version, source, paths and agents are shown first.",
362
387
  "No Skill hooks/scripts run. The trusted installer is not sandboxed. Telemetry and remote audits are disabled.",
@@ -498,6 +523,21 @@ const commandHelp: Record<
498
523
  "Pivot provides backbone connectivity and durable published-content Pin service through daemon. Keep it online with sufficient storage.",
499
524
  ],
500
525
  },
526
+ "swarm replicate": {
527
+ summary: "Replicate the complete local current HEAD to a remote Pivot",
528
+ options: [
529
+ "--pivot MEMBER Target one declared Pivot by exact member name, public key or PeerID.",
530
+ ],
531
+ examples: [
532
+ "ipab --swarm work swarm replicate --pivot scott-office-ubuntu",
533
+ "ipab --json --swarm work swarm replicate",
534
+ ],
535
+ notes: [
536
+ "Requires approved membership and the complete current HEAD locally. Works behind NAT; no source address publication is required.",
537
+ "Checks Pivot readiness and idempotently copies to an unready Pivot. Stops after the first ready replica; --pivot restricts all work to that member. Never changes HEAD or bypasses a write receipt.",
538
+ "Progress goes to stderr; --json returns the HEAD and per-Pivot results. At least one Pivot must confirm readiness for success.",
539
+ ],
540
+ },
501
541
  "swarm members": {
502
542
  summary: "List every public member, including the Owner",
503
543
  options: [
@@ -738,17 +778,25 @@ const commandHelp: Record<
738
778
  notes: ["Does not execute Apps, import content or create pins."],
739
779
  },
740
780
  "bundle import": {
741
- summary: "Validate and import a CAR into the configured Store",
742
- arguments: ["FILE.car Self-contained single-root Bundle or type CAR."],
743
- examples: ["ipab bundle import hello\\dist\\app.car"],
781
+ summary:
782
+ "Validate and import a CAR or Bundle directory into the configured Store",
783
+ arguments: [
784
+ "SOURCE Self-contained single-root CAR or local Content Bundle directory.",
785
+ ],
786
+ examples: [
787
+ "ipab bundle import hello\\dist\\app.car",
788
+ "ipab bundle import .",
789
+ ],
744
790
  notes: [
791
+ "Directories must contain valid Bundle metadata; .bundle-ignore is honored without writing CAR files.",
745
792
  "Repeated imports are safe; no App execution or daemon startup.",
746
793
  "Does not pin or retain content. Use pin CID for persistent retention.",
747
794
  ],
748
795
  },
749
796
  exec: {
750
- summary: "Run an App by exact CID or Swarm IPAB URI",
797
+ summary: "Run an App by CID, Swarm IPAB URI, local CAR or Bundle directory",
751
798
  arguments: [
799
+ "APP App CID, Swarm IPAB URI, local App .car file or assembled App Bundle directory.",
752
800
  "APP_ARGS Everything after APP is passed verbatim, including --help.",
753
801
  ],
754
802
  options: [
@@ -757,12 +805,13 @@ const commandHelp: Record<
757
805
  "--no-refresh Override swarm.forceRefresh; must precede APP.",
758
806
  ],
759
807
  examples: [
760
- "ipab exec reader",
761
- "ipab exec --log reader",
808
+ "ipab exec APP_CID",
809
+ "ipab exec .\\dist\\app.car --help",
762
810
  "ipab exec ipab://work/apps/hello --help",
763
811
  ],
764
812
  notes: [
765
813
  "Apps are NOT sandboxed; run only Apps you trust.",
814
+ "Local App directories must already contain valid assembled Bundle metadata; exec does not compile source, pin or modify the directory.",
766
815
  "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
767
816
  "History stores argv by default; do not put secrets in arguments.",
768
817
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
@@ -772,7 +821,7 @@ const commandHelp: Record<
772
821
  open: {
773
822
  summary: "Open content with its registered App",
774
823
  arguments: [
775
- "CONTENT Local Bundle directory, Bundle CID, packaged builtin reference or Swarm IPAB URI.",
824
+ "CONTENT Local Bundle directory or .car file, Bundle CID, packaged builtin reference or Swarm IPAB URI.",
776
825
  ],
777
826
  options: [
778
827
  "--log Record stdout/stderr; requires history enabled.",
@@ -782,12 +831,12 @@ const commandHelp: Record<
782
831
  ],
783
832
  examples: [
784
833
  "ipab open .",
834
+ "ipab open .\\dist\\bundle.car",
785
835
  "ipab open --log --refresh ipab:///documents/readme",
786
- "ipab open ipab:///",
787
836
  ],
788
837
  notes: [
789
838
  "Requires a saved registration and App support for the exact content type.",
790
- "Local directories must contain valid Bundle metadata; quote paths with spaces. Snapshots honor .bundle-ignore without compiling, publishing, pinning, writing CAR files or updating the source.",
839
+ "Local directories and .car files must contain a valid Content Bundle; quote paths with spaces. Directory snapshots honor .bundle-ignore without compiling, publishing, pinning, writing CAR files or updating the source.",
791
840
  "An empty URI Name (ipab:/// or ipab://ALIAS/) resolves to that Swarm's verified root State CID, not its publication CID. The root binding cannot be overwritten.",
792
841
  "Uses only the content URI's Swarm, otherwise --swarm, otherwise swarm.default. A selected Swarm is required.",
793
842
  "A registered App's retrieval, compatibility or execution failure never triggers fallback.",
@@ -860,7 +909,7 @@ const commandHelp: Record<
860
909
  summary: "Associate a content type with an App",
861
910
  arguments: [
862
911
  "SCHEMA Exact type CID or builtin:node-app.v1.",
863
- "APP App CID or Swarm IPAB URI; the exact CID is saved.",
912
+ "APP App CID, Swarm IPAB URI, local App .car file or assembled App Bundle directory.",
864
913
  ],
865
914
  options: [
866
915
  "--replace Allow changing an existing association.",
@@ -868,10 +917,12 @@ const commandHelp: Record<
868
917
  ],
869
918
  examples: [
870
919
  "ipab register set SCHEMA_CID APP_CID",
920
+ "ipab register set SCHEMA_CID .\\dist\\app.car --swarm work",
871
921
  "ipab register set SCHEMA_CID ipab:///apps/reader --swarm work --swarm team",
872
922
  ],
873
923
  notes: [
874
924
  "Writes the Name META.registryPath/TYPE_CID directly to the App CID. Open passes only the content CID.",
925
+ "Local App .car files or assembled App Bundle directories are snapshotted into the local Store once and published into each selected Swarm registry without compiling or pinning.",
875
926
  "Custom per-association argv is unsupported; adapt the App or use ipab exec APP_CID ARGS.",
876
927
  "Does not verify App type support; open checks it before execution.",
877
928
  "Without explicit --swarm, writes the saved default Swarm. Swarm writes require HEAD write access.",
@@ -893,6 +944,80 @@ const commandHelp: Record<
893
944
  "Does not remove Apps, pins or content.",
894
945
  ],
895
946
  },
947
+ "fs ls": {
948
+ summary: "List entries under a path in the selected Swarm UnixFS tree",
949
+ arguments: [
950
+ "PATH Optional directory path inside the Swarm root (defaults to /).",
951
+ ],
952
+ options: [
953
+ "--all Include protected v7 root metadata files when listing /.",
954
+ "--recursive Traverse subdirectories recursively (bounded depth/nodes).",
955
+ "--refresh Fetch the latest Swarm HEAD before listing.",
956
+ "--no-refresh Use only the cached Swarm HEAD without contacting network.",
957
+ ],
958
+ examples: [
959
+ "ipab fs ls",
960
+ "ipab fs ls ipab/skills --recursive",
961
+ "ipab --json fs ls --all",
962
+ ],
963
+ notes: [
964
+ "On legacy (v2-v6) Swarms, lists a read-only virtual view projected from snapshot names.",
965
+ ],
966
+ },
967
+ "fs stat": {
968
+ summary: "Inspect metadata for a path in the selected Swarm UnixFS tree",
969
+ arguments: ["PATH Path inside the Swarm root (use / or . for root)."],
970
+ options: [
971
+ "--refresh Fetch the latest Swarm HEAD before inspecting.",
972
+ "--no-refresh Use only the cached Swarm HEAD without contacting network.",
973
+ ],
974
+ examples: [
975
+ "ipab fs stat /",
976
+ "ipab fs stat ipab/skills",
977
+ "ipab --json fs stat docs/guide",
978
+ ],
979
+ notes: [
980
+ "On legacy (v2-v6) Swarms, reports a read-only virtual view projected from snapshot names.",
981
+ ],
982
+ },
983
+ "fs set": {
984
+ summary:
985
+ "Mount an existing CID at a path in the selected Swarm UnixFS tree",
986
+ arguments: [
987
+ "PATH Relative path inside the Swarm root (root / and protected metadata are rejected).",
988
+ "CID Canonical CID already present in the local IPFS store.",
989
+ ],
990
+ options: [
991
+ "--expect OLD_CID Require the current path CID to match OLD_CID before replacing.",
992
+ "--replace Allow replacing an existing different CID at PATH.",
993
+ ],
994
+ examples: [
995
+ "ipab fs set docs/guide bafy...",
996
+ "ipab fs set docs/guide bafyNEW --expect bafyOLD",
997
+ "ipab --json fs set docs/guide bafyNEW --replace",
998
+ ],
999
+ notes: [
1000
+ "Requires a State v7 UnixFS Swarm root; legacy (v2-v6) Swarms are not implicitly migrated.",
1001
+ "Protected v7 root metadata files (.bundle.yaml, typeFile, entryFile) cannot be overwritten.",
1002
+ ],
1003
+ },
1004
+ "fs rm": {
1005
+ summary: "Remove a path from the selected Swarm UnixFS tree",
1006
+ arguments: [
1007
+ "PATH Relative path to remove (automatically prunes empty parent directories up to /).",
1008
+ ],
1009
+ options: [
1010
+ "--expect OLD_CID Require the current path CID to match OLD_CID before removing.",
1011
+ ],
1012
+ examples: [
1013
+ "ipab fs rm docs/guide",
1014
+ "ipab fs rm docs/guide --expect bafyOLD",
1015
+ "ipab --json fs rm docs/guide",
1016
+ ],
1017
+ notes: [
1018
+ "Requires a State v7 UnixFS Swarm root; protected root metadata files cannot be removed.",
1019
+ ],
1020
+ },
896
1021
  "config get": {
897
1022
  summary: "Show effective configuration",
898
1023
  arguments: ["KEY Optional configuration key; omit to show all values."],
@@ -986,6 +1111,7 @@ Manage:
986
1111
  doctor ${commandHelp.doctor!.summary}
987
1112
  profile ${commandHelp.profile!.summary}
988
1113
  swarm ${groups.swarm}
1114
+ fs ${groups.fs}
989
1115
  skills ${groups.skills}
990
1116
  search Search formal Names in the current swarm
991
1117
  publish ${commandHelp.publish!.summary}
@@ -1028,6 +1154,7 @@ ${footer}`;
1028
1154
  ...([
1029
1155
  "swarm status",
1030
1156
  "swarm members",
1157
+ "swarm replicate",
1031
1158
  "swarm update",
1032
1159
  "swarm resume",
1033
1160
  "swarm profile",
@@ -1193,6 +1320,7 @@ interface Parsed {
1193
1320
  parameters?: string[];
1194
1321
  registrySwarms?: string[];
1195
1322
  agents?: string[];
1323
+ types?: string[];
1196
1324
  help: boolean;
1197
1325
  version: boolean;
1198
1326
  }
@@ -1210,6 +1338,7 @@ async function closeStore(
1210
1338
  try {
1211
1339
  await store?.close();
1212
1340
  } catch (error) {
1341
+ const { message } = await import("./errors.js");
1213
1342
  throw new HostError(
1214
1343
  `Store cleanup failed: ${message(error)}`,
1215
1344
  appExitCode || 1,
@@ -1331,6 +1460,7 @@ export function parse(argv: readonly string[]): Parsed {
1331
1460
  "store",
1332
1461
  "swarm",
1333
1462
  "skills",
1463
+ "fs",
1334
1464
  ].includes(group)
1335
1465
  )
1336
1466
  syntax(
@@ -1367,6 +1497,10 @@ export function parse(argv: readonly string[]): Parsed {
1367
1497
  syntax(
1368
1498
  "Skills operations select exactly one Swarm; repeated --swarm is not supported.",
1369
1499
  );
1500
+ if (group === "fs" && swarms.length > 1)
1501
+ syntax(
1502
+ "fs operations select at most one Swarm; repeated --swarm is not supported.",
1503
+ );
1370
1504
  const separator = result.path === "register set" ? tokens.indexOf("--") : -1;
1371
1505
  if (separator >= 0) result.template = tokens.splice(separator + 1);
1372
1506
  if (separator >= 0) tokens.splice(separator);
@@ -1385,51 +1519,63 @@ export function parse(argv: readonly string[]): Parsed {
1385
1519
  const booleans = result.path.startsWith("skills ")
1386
1520
  ? result.path === "skills sync"
1387
1521
  ? ["dry-run", "yes", "override-existing", "force", "no-force"]
1388
- : ["force", "no-force"]
1389
- : result.path === "doctor"
1390
- ? ["fix", "yes"]
1391
- : result.path === "bundle build"
1392
- ? ["replace", "schema-only", "no-import"]
1393
- : result.path === "build"
1394
- ? ["replace", "no-import"]
1395
- : result.path === "publish"
1396
- ? ["snapshot"]
1397
- : [
1398
- "get",
1399
- "templates render",
1400
- "templates list",
1401
- "templates show",
1402
- ].includes(result.path)
1403
- ? result.path === "templates render"
1404
- ? ["force", "no-force"]
1405
- : result.path === "get"
1406
- ? ["raw", "force", "no-force"]
1407
- : ["force", "no-force"]
1408
- : result.path === "search"
1409
- ? ["all", "current", "force", "no-force"]
1410
- : result.path === "swarm request"
1411
- ? ["pivot"]
1412
- : result.path === "swarm approve"
1413
- ? ["yes", "again", "pivot"]
1414
- : ["swarm status", "swarm members"].includes(result.path)
1415
- ? ["local", "force", "no-force"]
1416
- : [
1417
- "swarm exclude",
1418
- "swarm set",
1419
- "swarm pivot grant",
1420
- ].includes(result.path)
1421
- ? ["yes"]
1422
- : result.path === "register set"
1423
- ? ["replace"]
1424
- : result.path === "history remove"
1425
- ? ["yes"]
1426
- : result.path === "open"
1427
- ? ["log", "raw", "force", "no-force"]
1428
- : result.path === "pin"
1429
- ? ["force", "no-force"]
1430
- : result.path === "daemon ui"
1431
- ? ["open"]
1432
- : [];
1522
+ : result.path === "skills set"
1523
+ ? ["global", "replace"]
1524
+ : result.path === "skills remove"
1525
+ ? []
1526
+ : ["force", "no-force"]
1527
+ : result.path === "fs ls"
1528
+ ? ["all", "recursive", "force", "no-force"]
1529
+ : result.path === "fs stat"
1530
+ ? ["force", "no-force"]
1531
+ : result.path === "fs set"
1532
+ ? ["replace"]
1533
+ : result.path === "doctor"
1534
+ ? ["fix", "yes"]
1535
+ : result.path === "bundle build"
1536
+ ? ["replace", "schema-only", "no-import"]
1537
+ : result.path === "build"
1538
+ ? ["replace", "no-import"]
1539
+ : result.path === "publish"
1540
+ ? ["snapshot"]
1541
+ : [
1542
+ "get",
1543
+ "templates render",
1544
+ "templates list",
1545
+ "templates show",
1546
+ ].includes(result.path)
1547
+ ? result.path === "templates render"
1548
+ ? ["force", "no-force"]
1549
+ : result.path === "get"
1550
+ ? ["raw", "force", "no-force"]
1551
+ : ["force", "no-force"]
1552
+ : result.path === "search"
1553
+ ? ["all", "current", "force", "no-force"]
1554
+ : result.path === "swarm request"
1555
+ ? ["pivot"]
1556
+ : result.path === "swarm approve"
1557
+ ? ["yes", "again", "pivot"]
1558
+ : ["swarm status", "swarm members"].includes(
1559
+ result.path,
1560
+ )
1561
+ ? ["local", "force", "no-force"]
1562
+ : [
1563
+ "swarm exclude",
1564
+ "swarm set",
1565
+ "swarm pivot grant",
1566
+ ].includes(result.path)
1567
+ ? ["yes"]
1568
+ : result.path === "register set"
1569
+ ? ["replace"]
1570
+ : result.path === "history remove"
1571
+ ? ["yes"]
1572
+ : result.path === "open"
1573
+ ? ["log", "raw", "force", "no-force"]
1574
+ : result.path === "pin"
1575
+ ? ["force", "no-force"]
1576
+ : result.path === "daemon ui"
1577
+ ? ["open"]
1578
+ : [];
1433
1579
  if (booleans.includes("force")) booleans.push("refresh", "no-refresh");
1434
1580
  const values =
1435
1581
  result.path === "swarm create"
@@ -1440,35 +1586,43 @@ export function parse(argv: readonly string[]): Parsed {
1440
1586
  ? ["output"]
1441
1587
  : result.path === "swarm profile"
1442
1588
  ? ["address", "pivot"]
1443
- : result.path === "swarm update" || result.path === "profile"
1444
- ? ["name", "description"]
1445
- : result.path === "swarm approve"
1446
- ? []
1447
- : ["publish", "templates set", "templates remove"].includes(
1448
- result.path,
1449
- )
1450
- ? ["expect"]
1451
- : result.path === "get"
1452
- ? ["output"]
1453
- : result.path === "search"
1454
- ? ["prefix", "kind", "schema", "limit", "offset"]
1455
- : result.path === "templates render"
1456
- ? ["description"]
1457
- : result.path === "bundle build" ||
1458
- result.path === "build"
1459
- ? ["output"]
1460
- : result.path === "history list"
1461
- ? [
1462
- "app",
1463
- "status",
1464
- "since",
1465
- "until",
1466
- "limit",
1467
- "before",
1468
- ]
1469
- : result.path === "history remove"
1470
- ? ["app", "status", "since", "until"]
1471
- : [];
1589
+ : result.path === "swarm replicate"
1590
+ ? ["pivot"]
1591
+ : result.path === "swarm update" || result.path === "profile"
1592
+ ? ["name", "description"]
1593
+ : result.path === "swarm approve"
1594
+ ? []
1595
+ : [
1596
+ "publish",
1597
+ "templates set",
1598
+ "templates remove",
1599
+ "fs set",
1600
+ "fs rm",
1601
+ ].includes(result.path)
1602
+ ? ["expect"]
1603
+ : result.path === "get"
1604
+ ? ["output"]
1605
+ : result.path === "search"
1606
+ ? ["prefix", "kind", "schema", "limit", "offset"]
1607
+ : result.path === "templates render"
1608
+ ? ["description"]
1609
+ : result.path === "bundle build" ||
1610
+ result.path === "build"
1611
+ ? ["output"]
1612
+ : result.path === "history list"
1613
+ ? [
1614
+ "app",
1615
+ "status",
1616
+ "since",
1617
+ "until",
1618
+ "limit",
1619
+ "before",
1620
+ ]
1621
+ : result.path === "history remove"
1622
+ ? ["app", "status", "since", "until"]
1623
+ : result.path === "skills remove"
1624
+ ? ["global"]
1625
+ : [];
1472
1626
  while (tokens.length) {
1473
1627
  const value = tokens.shift()!;
1474
1628
  if (
@@ -1488,6 +1642,21 @@ export function parse(argv: readonly string[]): Parsed {
1488
1642
  (result.agents ??= []).push(input);
1489
1643
  continue;
1490
1644
  }
1645
+ if (
1646
+ (result.path === "skills set" || result.path === "skills remove") &&
1647
+ option === "type"
1648
+ ) {
1649
+ const input = tokens.shift();
1650
+ if (!input || input.startsWith("-")) syntax("--type needs a value.");
1651
+ (result.types ??= []).push(input);
1652
+ continue;
1653
+ }
1654
+ if (
1655
+ result.path === "skills remove" &&
1656
+ option === "global" &&
1657
+ Object.hasOwn(result.options, "global")
1658
+ )
1659
+ syntax("--global may be specified at most once.");
1491
1660
  if (result.path.startsWith("register ") && option === "swarm") {
1492
1661
  const input = tokens.shift();
1493
1662
  if (!input || input.startsWith("-")) syntax("--swarm needs a value.");
@@ -1556,11 +1725,39 @@ export function parse(argv: readonly string[]): Parsed {
1556
1725
  syntax(
1557
1726
  "register list accepts --swarm at most once. Select one Swarm or omit it to use the current Swarm.",
1558
1727
  );
1728
+ if (result.path === "skills set") {
1729
+ if (!result.options.global && !(result.types?.length ?? 0))
1730
+ syntax("skills set requires --global and/or at least one --type SCHEMA.");
1731
+ for (const schema of result.types ?? [])
1732
+ if (!schema.startsWith("builtin:")) exactCid(schema, true);
1733
+ }
1734
+ if (result.path === "skills remove") {
1735
+ if (
1736
+ typeof result.options.global !== "string" &&
1737
+ !(result.types?.length ?? 0)
1738
+ )
1739
+ syntax(
1740
+ "skills remove requires --global NAME and/or at least one --type SCHEMA.",
1741
+ );
1742
+ if (
1743
+ typeof result.options.global === "string" &&
1744
+ (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(result.options.global) ||
1745
+ result.options.global.length > 64)
1746
+ )
1747
+ syntax(
1748
+ `Invalid global Skill name "${result.options.global}". Expected lowercase kebab-case (1..64 characters).`,
1749
+ );
1750
+ for (const schema of result.types ?? [])
1751
+ if (!schema.startsWith("builtin:")) exactCid(schema, true);
1752
+ }
1559
1753
  const counts: Record<string, [number, number]> = {
1560
1754
  daemon: [0, 0],
1561
1755
  "daemon ui": [0, 0],
1562
1756
  doctor: [0, 0],
1563
1757
  "skills list": [0, 0],
1758
+ "skills show": [1, 1],
1759
+ "skills set": [1, 1],
1760
+ "skills remove": [0, 0],
1564
1761
  "skills sync": [0, Number.MAX_SAFE_INTEGER],
1565
1762
  profile: [0, 0],
1566
1763
  "swarm create": [0, 0],
@@ -1572,6 +1769,7 @@ export function parse(argv: readonly string[]): Parsed {
1572
1769
  "swarm resume": [0, 0],
1573
1770
  "swarm profile": [0, 0],
1574
1771
  "swarm status": [0, 0],
1772
+ "swarm replicate": [0, 0],
1575
1773
  "swarm members": [0, 0],
1576
1774
  "swarm list": [0, 0],
1577
1775
  "swarm set": [2, 2],
@@ -1598,6 +1796,10 @@ export function parse(argv: readonly string[]): Parsed {
1598
1796
  "templates show": [1, 1],
1599
1797
  "templates set": [2, 2],
1600
1798
  "templates remove": [1, 1],
1799
+ "fs ls": [0, 1],
1800
+ "fs stat": [1, 1],
1801
+ "fs set": [2, 2],
1802
+ "fs rm": [1, 1],
1601
1803
  "config get": [0, 1],
1602
1804
  "config set": [2, 2],
1603
1805
  "config reset": [1, 1],
@@ -1674,6 +1876,37 @@ export function parse(argv: readonly string[]): Parsed {
1674
1876
  if (result.path === "templates remove" && !result.options.expect)
1675
1877
  syntax("templates remove requires --expect OLD_TARGET_CID.");
1676
1878
  }
1879
+ if (result.path === "fs ls" && result.positional[0] !== undefined) {
1880
+ normalizeSwarmFsPath(result.positional[0], {
1881
+ allowRoot: true,
1882
+ allowTrailingSlash: true,
1883
+ });
1884
+ }
1885
+ if (result.path === "fs stat") {
1886
+ normalizeSwarmFsPath(result.positional[0], {
1887
+ allowRoot: true,
1888
+ allowTrailingSlash: true,
1889
+ });
1890
+ }
1891
+ if (result.path === "fs set") {
1892
+ normalizeSwarmFsPath(result.positional[0], {
1893
+ allowRoot: false,
1894
+ allowTrailingSlash: false,
1895
+ });
1896
+ exactCid(result.positional[1]!);
1897
+ if (typeof result.options.expect === "string")
1898
+ exactCid(result.options.expect);
1899
+ if (result.options.expect !== undefined && result.options.replace)
1900
+ syntax("--expect and --replace are mutually exclusive.");
1901
+ }
1902
+ if (result.path === "fs rm") {
1903
+ normalizeSwarmFsPath(result.positional[0], {
1904
+ allowRoot: false,
1905
+ allowTrailingSlash: false,
1906
+ });
1907
+ if (typeof result.options.expect === "string")
1908
+ exactCid(result.options.expect);
1909
+ }
1677
1910
  if (result.path.startsWith("config ") && result.positional[0]) {
1678
1911
  if (
1679
1912
  !(result.path === "config get" && result.positional[0] === "state-dir") &&
@@ -1704,10 +1937,8 @@ async function performCli(
1704
1937
  io: IO,
1705
1938
  env: NodeJS.ProcessEnv,
1706
1939
  ): Promise<number> {
1707
- let state: State | undefined;
1708
- let store: IpfsStore | undefined;
1709
- let appExitCode: number | undefined;
1710
- let readContext: SwarmContext | undefined;
1940
+ let cliHandle: CliClientHandle | undefined;
1941
+ let daemonStore: IpfsStore | undefined;
1711
1942
  try {
1712
1943
  const parsed = parse(argv);
1713
1944
  if (parsed.help) {
@@ -1728,7 +1959,12 @@ async function performCli(
1728
1959
  }
1729
1960
  if (parsed.path === "history remove" && !parsed.options.yes && !io.tty)
1730
1961
  syntax("Non-interactive history remove requires --yes.");
1962
+
1963
+ const stateDir = stateLocation(parsed.flags, env).path;
1964
+
1965
+ // Exempt command #3: doctor (never auto-starts Daemon)
1731
1966
  if (parsed.path === "doctor") {
1967
+ const { doctorDevice, doctorText } = await import("./doctor.js");
1732
1968
  const controller = new AbortController();
1733
1969
  const interrupt = () => {
1734
1970
  controller.abort(new HostError("Doctor interrupted.", 130, "ABORTED"));
@@ -1739,20 +1975,16 @@ async function performCli(
1739
1975
  process.once("SIGINT", interrupt);
1740
1976
  process.once("SIGTERM", terminate);
1741
1977
  try {
1742
- const result = await doctorDevice(
1743
- stateLocation(parsed.flags, env).path,
1744
- env,
1745
- {
1746
- diagnostic: (text, progress) => {
1747
- io.err(text, progress);
1748
- },
1749
- signal: controller.signal,
1750
- fix: Boolean(parsed.options.fix),
1751
- yes: Boolean(parsed.options.yes),
1752
- tty: io.tty,
1753
- confirm: (text, signal) => io.confirm(text, signal),
1978
+ const result = await doctorDevice(stateDir, env, {
1979
+ diagnostic: (text, progress) => {
1980
+ io.err(text, progress);
1754
1981
  },
1755
- );
1982
+ signal: controller.signal,
1983
+ fix: Boolean(parsed.options.fix),
1984
+ yes: Boolean(parsed.options.yes),
1985
+ tty: io.tty,
1986
+ confirm: (text, signal) => io.confirm(text, signal),
1987
+ });
1756
1988
  io.out(parsed.flags.json ? JSON.stringify(result) : doctorText(result));
1757
1989
  return result.ready ? 0 : 1;
1758
1990
  } finally {
@@ -1760,35 +1992,110 @@ async function performCli(
1760
1992
  process.removeListener("SIGTERM", terminate);
1761
1993
  }
1762
1994
  }
1763
- if (parsed.path === "daemon ui") {
1764
- const stateDir = stateLocation(parsed.flags, env).path;
1765
- const endpoint = await daemonEndpoint(stateDir);
1766
- if (!endpoint)
1767
- throw new HostError(
1768
- "IPAB daemon is not running for this state directory. Start it with `ipab daemon` or run a Swarm network command.",
1995
+
1996
+ // Exempt command #4: daemon (foreground daemon host itself)
1997
+ if (parsed.path === "daemon") {
1998
+ if (parsed.flags.json)
1999
+ syntax(
2000
+ "--json is not supported for daemon; diagnostics are written to stderr.",
1769
2001
  );
1770
- const opened = Boolean(parsed.options.open);
1771
- if (opened) openLoopbackUrl(endpoint.url);
1772
- io.out(
1773
- parsed.flags.json
1774
- ? JSON.stringify({ ...endpoint, opened })
1775
- : opened
1776
- ? `Opened daemon status UI: ${endpoint.url}`
1777
- : endpoint.url,
2002
+ const [
2003
+ { IpfsStore },
2004
+ { builtinContent },
2005
+ { serveDaemon },
2006
+ { swarmDaemon },
2007
+ { syncDaemonSwarm },
2008
+ ] = await Promise.all([
2009
+ import("@ipab/ipfs-store"),
2010
+ import("./builtins.js"),
2011
+ import("./daemon.js"),
2012
+ import("./swarm.js"),
2013
+ import("./skills.js"),
2014
+ ]);
2015
+ const builtins = await builtinContent();
2016
+ const bootState = new State(stateDir, builtins.pins, env);
2017
+ let items;
2018
+ try {
2019
+ items = effectiveConfig(
2020
+ bootState.config({ includeSecrets: true }),
2021
+ parsed.flags,
2022
+ env,
2023
+ (reference) => bootState.resolveSwarm(reference),
2024
+ );
2025
+ } finally {
2026
+ bootState.close();
2027
+ }
2028
+ const val = (key: ConfigKey) =>
2029
+ items.find((item) => item.key === key)!.value;
2030
+ daemonStore = new IpfsStore(
2031
+ await storeConfiguration(val("store.gateway")),
1778
2032
  );
2033
+ const context: SwarmContext = {
2034
+ get store() {
2035
+ return daemonStore!;
2036
+ },
2037
+ set store(next) {
2038
+ daemonStore = next;
2039
+ },
2040
+ env,
2041
+ stateDir,
2042
+ cacheTtl: Number(val("swarm.cacheTtl")),
2043
+ syncInterval: Number(val("swarm.syncInterval")),
2044
+ listen: val("swarm.listen") === "loopback" ? "loopback" : "lan",
2045
+ ...(items.find((item) => item.key === "swarm.pivot")!.source ===
2046
+ "default"
2047
+ ? {}
2048
+ : { pivot: Boolean(val("swarm.pivot")) }),
2049
+ daemonReady: (status, onListen, extra) =>
2050
+ serveDaemon(stateDir, {
2051
+ port: Number(val("daemon.uiPort")),
2052
+ env,
2053
+ ...(status ? { status } : {}),
2054
+ ...(onListen ? { onListen } : {}),
2055
+ ...(extra ?? {}),
2056
+ }),
2057
+ forceRefresh: Boolean(val("swarm.forceRefresh")),
2058
+ diagnostic: (text) => {
2059
+ io.err(text);
2060
+ },
2061
+ ...(typeof val("pointers.service") === "string"
2062
+ ? { pointerService: String(val("pointers.service")) }
2063
+ : {}),
2064
+ ...(typeof val("pointers.apiKey") === "string"
2065
+ ? { pointerApiKey: String(val("pointers.apiKey")) }
2066
+ : {}),
2067
+ };
2068
+ const controller = new AbortController();
2069
+ const interrupt = () => {
2070
+ controller.abort();
2071
+ };
2072
+ process.once("SIGINT", interrupt);
2073
+ process.once("SIGTERM", interrupt);
2074
+ try {
2075
+ await swarmDaemon(context, controller.signal, (ctx, url, report) =>
2076
+ syncDaemonSwarm(ctx, url, undefined, report),
2077
+ );
2078
+ } catch (cause) {
2079
+ if (!controller.signal.aborted) throw cause;
2080
+ } finally {
2081
+ process.removeListener("SIGINT", interrupt);
2082
+ process.removeListener("SIGTERM", interrupt);
2083
+ }
1779
2084
  return 0;
1780
2085
  }
1781
- const builtins = await builtinContent();
1782
- state = new State(
1783
- stateLocation(parsed.flags, env).path,
1784
- builtins.pins,
1785
- env,
1786
- );
2086
+
2087
+ // Exempt recovery: config reset store.rpc runs directly on local State so
2088
+ // legacy store.rpc recovery is never blocked by Daemon startup calling state.config().
1787
2089
  if (
1788
2090
  parsed.path === "config reset" &&
1789
2091
  parsed.positional[0] === "store.rpc"
1790
2092
  ) {
1791
- state.resetConfig("store.rpc");
2093
+ const localState = new State(stateDir, [], env);
2094
+ try {
2095
+ localState.resetConfig("store.rpc");
2096
+ } finally {
2097
+ localState.close();
2098
+ }
1792
2099
  io.out(
1793
2100
  parsed.flags.json
1794
2101
  ? JSON.stringify({ reset: ["store.rpc"] })
@@ -1796,29 +2103,251 @@ async function performCli(
1796
2103
  );
1797
2104
  return 0;
1798
2105
  }
1799
- const items = effectiveConfig(
1800
- state.config({
1801
- includeSecrets: ![
1802
- "swarm members",
1803
- "profile",
1804
- "swarm status",
1805
- "swarm set",
1806
- ].includes(parsed.path),
2106
+
2107
+ // Stateless local build when --no-import is set (never touches IpfsStore or spawns a Daemon).
2108
+ if (
2109
+ (parsed.path === "build" || parsed.path === "bundle build") &&
2110
+ Boolean(parsed.options["no-import"])
2111
+ ) {
2112
+ const [{ assembleBundle }, { buildBundle }, { message }] =
2113
+ await Promise.all([
2114
+ import("./assembly.js"),
2115
+ import("./authoring.js"),
2116
+ import("./errors.js"),
2117
+ ]);
2118
+ let savedConfig: Partial<
2119
+ Record<ConfigKey, string | number | boolean | null>
2120
+ > = {};
2121
+ if (existsSync(join(stateDir, "state.sqlite"))) {
2122
+ const localState = new State(stateDir, [], env);
2123
+ try {
2124
+ savedConfig = localState.config({ includeSecrets: false });
2125
+ } finally {
2126
+ localState.close();
2127
+ }
2128
+ }
2129
+ const outputDirOpt = String(
2130
+ effectiveConfig(savedConfig, parsed.flags, env).find(
2131
+ (item) => item.key === "bundle.outputDir",
2132
+ )!.value,
2133
+ );
2134
+ const outputOpt =
2135
+ typeof parsed.options.output === "string"
2136
+ ? resolve(parsed.options.output)
2137
+ : undefined;
2138
+ const controller = new AbortController();
2139
+ let cancelled = 0;
2140
+ const interrupt = () => {
2141
+ cancelled = 130;
2142
+ controller.abort(new Error("Interrupted."));
2143
+ };
2144
+ const terminate = () => {
2145
+ cancelled = 143;
2146
+ controller.abort(new Error("Terminated."));
2147
+ };
2148
+ process.once("SIGINT", interrupt);
2149
+ process.once("SIGTERM", terminate);
2150
+ try {
2151
+ const commonOpts = {
2152
+ signal: controller.signal,
2153
+ diagnostic: (text: string) => {
2154
+ io.err(text);
2155
+ },
2156
+ replace: Boolean(parsed.options.replace),
2157
+ ...(outputOpt !== undefined ? { output: outputOpt } : {}),
2158
+ outputDir: outputDirOpt,
2159
+ };
2160
+ let built;
2161
+ if (parsed.path === "build") {
2162
+ const sourcePath = parsed.positional[0]
2163
+ ? resolve(parsed.positional[0])
2164
+ : process.cwd();
2165
+ io.err("Assembling and validating Bundle (no compilation)...");
2166
+ built = await assembleBundle(sourcePath, commonOpts);
2167
+ } else {
2168
+ const sourcePath = await resolveLocalPathIfPresent(
2169
+ parsed.positional[0]!,
2170
+ );
2171
+ io.err("Validating and building bundle...");
2172
+ built = await buildBundle(sourcePath, {
2173
+ ...commonOpts,
2174
+ schemaOnly: Boolean(parsed.options["schema-only"]),
2175
+ });
2176
+ }
2177
+ controller.signal.throwIfAborted();
2178
+ const result = { ...built, imported: false };
2179
+ const validation = (
2180
+ result as { validation?: { status?: string } | null }
2181
+ ).validation;
2182
+ const human = `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${validation !== undefined ? `\nEntry validation: ${validation?.status ?? "not-applicable"}` : ""}\nStore: not imported (--no-import)`;
2183
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
2184
+ return 0;
2185
+ } catch (cause) {
2186
+ if (cancelled) {
2187
+ io.err(message(cause));
2188
+ return cancelled;
2189
+ }
2190
+ throw cause;
2191
+ } finally {
2192
+ process.removeListener("SIGINT", interrupt);
2193
+ process.removeListener("SIGTERM", terminate);
2194
+ }
2195
+ }
2196
+
2197
+ // Stateless local CAR inspection (never touches state.sqlite, IpfsStore, or spawns a Daemon).
2198
+ if (parsed.path === "bundle inspect") {
2199
+ const target = parsed.positional[0]!;
2200
+ const looksLikeCarPath =
2201
+ !target.startsWith("ipab://") &&
2202
+ !target.startsWith("builtin:") &&
2203
+ target.toLowerCase().endsWith(".car");
2204
+ if (looksLikeCarPath) {
2205
+ const resolvedCar = resolve(target);
2206
+ let isLocalFile = false;
2207
+ try {
2208
+ isLocalFile = (await lstat(resolvedCar)).isFile();
2209
+ } catch {
2210
+ isLocalFile = false;
2211
+ }
2212
+ if (isLocalFile) {
2213
+ const [{ inspectBundle }, { message }] = await Promise.all([
2214
+ import("./authoring.js"),
2215
+ import("./errors.js"),
2216
+ ]);
2217
+ const controller = new AbortController();
2218
+ let cancelled = 0;
2219
+ const interrupt = () => {
2220
+ cancelled = 130;
2221
+ controller.abort(new Error("Interrupted."));
2222
+ };
2223
+ const terminate = () => {
2224
+ cancelled = 143;
2225
+ controller.abort(new Error("Terminated."));
2226
+ };
2227
+ process.once("SIGINT", interrupt);
2228
+ process.once("SIGTERM", terminate);
2229
+ try {
2230
+ const result = await inspectBundle(resolvedCar, {
2231
+ signal: controller.signal,
2232
+ diagnostic: (text: string) => {
2233
+ io.err(text);
2234
+ },
2235
+ });
2236
+ controller.signal.throwIfAborted();
2237
+ const manifest = result.manifest;
2238
+ const human = `Kind: ${result.kind}\n${manifest ? `Title: ${printable(manifest.title)}\nEntry: ${manifest.entry}\nType file: ${manifest.type}\n` : ""}Type CID: ${result.schemaCid}\nContent type: ${result.type.contentType}\nDefinition validation: passed\nStorage verification: ${result.validation.storage}\nEntry validation: ${result.validation.entry?.status ?? "not-applicable"}`;
2239
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
2240
+ return 0;
2241
+ } catch (cause) {
2242
+ if (cancelled) {
2243
+ io.err(message(cause));
2244
+ return cancelled;
2245
+ }
2246
+ throw cause;
2247
+ } finally {
2248
+ process.removeListener("SIGINT", interrupt);
2249
+ process.removeListener("SIGTERM", terminate);
2250
+ }
2251
+ }
2252
+ }
2253
+ }
2254
+
2255
+ // All remaining commands go through the local Daemon HTTP loopback API.
2256
+ cliHandle = await openCliClient(
2257
+ stateDir,
2258
+ env,
2259
+ parsed.flags,
2260
+ (text, prog) => {
2261
+ io.err(text, prog);
2262
+ },
2263
+ { lightweight: parsed.path === "swarm list" },
2264
+ );
2265
+ const { client } = cliHandle;
2266
+ const emit = (result: unknown, human: string) => {
2267
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
2268
+ };
2269
+
2270
+ if (parsed.path === "daemon ui") {
2271
+ const { openLoopbackUrl } = await import("./daemon.js");
2272
+ const live = await client.resolveEndpoint();
2273
+ const endpoint = {
2274
+ pid: live.pid,
2275
+ port: live.port,
2276
+ url: live.url,
2277
+ stateDir: live.stateDir,
2278
+ };
2279
+ const opened = Boolean(parsed.options.open);
2280
+ if (opened) openLoopbackUrl(endpoint.url);
2281
+ emit(
2282
+ { ...endpoint, opened },
2283
+ opened ? `Opened daemon status UI: ${endpoint.url}` : endpoint.url,
2284
+ );
2285
+ return 0;
2286
+ }
2287
+
2288
+ const includeConfigSecrets = ![
2289
+ "swarm members",
2290
+ "profile",
2291
+ "swarm status",
2292
+ "swarm set",
2293
+ ].includes(parsed.path);
2294
+ const [configSnapshot, swarmsSnapshot] = await Promise.all([
2295
+ client.host.getConfig(undefined, {
2296
+ includeSecrets: includeConfigSecrets,
1807
2297
  }),
2298
+ client.swarms.list(),
2299
+ ]);
2300
+ const registeredSwarms: RegisteredSwarm[] = swarmsSnapshot.swarms;
2301
+ const resolveSwarm = (reference: string) =>
2302
+ resolveSwarmFromList(registeredSwarms, reference);
2303
+
2304
+ const savedConfig = configSnapshot.saved ?? {};
2305
+ const computedItems = effectiveConfig(
2306
+ savedConfig,
1808
2307
  parsed.flags,
1809
2308
  env,
1810
- (reference) => state!.resolveSwarm(reference),
2309
+ resolveSwarm,
1811
2310
  );
1812
- const value = (key: string) =>
2311
+ const items = computedItems.map((item) => {
2312
+ if (item.key === "pointers.apiKey") {
2313
+ const fromDaemon = configSnapshot.items.find(
2314
+ (entry) => entry.key === "pointers.apiKey",
2315
+ );
2316
+ if (fromDaemon && item.source === "default") return fromDaemon;
2317
+ }
2318
+ return visibleConfig(item);
2319
+ });
2320
+ const value = (key: ConfigKey) =>
1813
2321
  items.find((item) => item.key === key)!.value;
1814
- const emit = (result: unknown, human: string) => {
1815
- io.out(parsed.flags.json ? JSON.stringify(result) : human);
2322
+
2323
+ const selection = (
2324
+ savedOverride?: string | null,
2325
+ ): {
2326
+ savedCurrent: string | null;
2327
+ effectiveCurrent: string | null;
2328
+ source: string;
2329
+ } => {
2330
+ const saved =
2331
+ savedOverride !== undefined
2332
+ ? { ...savedConfig, "swarm.default": savedOverride }
2333
+ : savedConfig;
2334
+ const current = effectiveConfig(
2335
+ saved,
2336
+ parsed.flags,
2337
+ env,
2338
+ resolveSwarm,
2339
+ ).find((item) => item.key === "swarm.default")!;
2340
+ return {
2341
+ savedCurrent:
2342
+ saved["swarm.default"] === undefined
2343
+ ? null
2344
+ : (saved["swarm.default"] as string | null),
2345
+ effectiveCurrent: current.value === null ? null : String(current.value),
2346
+ source: current.source,
2347
+ };
1816
2348
  };
1817
- const [first, second] = parsed.positional;
1818
- const selectedSwarm =
1819
- value("swarm.default") === null
1820
- ? undefined
1821
- : String(value("swarm.default"));
2349
+
2350
+ const selectedSwarm = selection().effectiveCurrent ?? undefined;
1822
2351
  const requireSwarm = () => {
1823
2352
  if (!selectedSwarm)
1824
2353
  syntax(
@@ -1826,199 +2355,195 @@ async function performCli(
1826
2355
  );
1827
2356
  return selectedSwarm;
1828
2357
  };
1829
- const swarmContext = (): SwarmContext => ({
1830
- get store() {
1831
- return store!;
1832
- },
1833
- set store(next) {
1834
- store = next;
1835
- },
1836
- state: state!,
1837
- env,
1838
- stateDir: stateLocation(parsed.flags, env).path,
1839
- cacheTtl: Number(value("swarm.cacheTtl")),
1840
- syncInterval: Number(value("swarm.syncInterval")),
1841
- listen: value("swarm.listen") === "loopback" ? "loopback" : "lan",
1842
- ...(items.find((item) => item.key === "swarm.pivot")!.source === "default"
1843
- ? {}
1844
- : { pivot: Boolean(value("swarm.pivot")) }),
1845
- ...(parsed.path === "daemon"
1846
- ? {
1847
- daemonReady: (status, onListen) =>
1848
- serveDaemon(stateLocation(parsed.flags, env).path, {
1849
- port: Number(value("daemon.uiPort")),
1850
- ...(status ? { status } : {}),
1851
- ...(onListen ? { onListen } : {}),
1852
- }),
1853
- }
1854
- : {
1855
- ensureDaemon: () =>
1856
- ensureDaemon(
1857
- stateLocation(parsed.flags, env).path,
1858
- env,
1859
- (text) => {
1860
- io.err(text);
1861
- },
1862
- ),
1863
- }),
1864
- forceRefresh:
1865
- parsed.options.refresh || parsed.options.force
1866
- ? true
1867
- : parsed.options["no-refresh"] || parsed.options["no-force"]
1868
- ? false
1869
- : Boolean(value("swarm.forceRefresh")),
1870
- diagnostic: (text) => {
1871
- io.err(text);
1872
- },
1873
- ...(typeof value("pointers.service") === "string"
1874
- ? { pointerService: String(value("pointers.service")) }
1875
- : {}),
1876
- ...(typeof value("pointers.apiKey") === "string"
1877
- ? { pointerApiKey: String(value("pointers.apiKey")) }
1878
- : {}),
1879
- });
1880
- const filter = parsed.path.startsWith("history ")
1881
- ? filters(state, parsed.options)
1882
- : {};
1883
- const selection = () => {
1884
- const saved = state!.config({ includeSecrets: false });
1885
- const current = effectiveConfig(saved, parsed.flags, env, (reference) =>
1886
- state!.resolveSwarm(reference),
1887
- ).find((item) => item.key === "swarm.default")!;
1888
- return {
1889
- savedCurrent: saved["swarm.default"] ?? null,
1890
- effectiveCurrent: current.value,
1891
- source: current.source,
1892
- };
1893
- };
2358
+
2359
+ const explicitRefresh: boolean | undefined =
2360
+ parsed.options.refresh || parsed.options.force
2361
+ ? true
2362
+ : parsed.options["no-refresh"] || parsed.options["no-force"]
2363
+ ? false
2364
+ : undefined;
2365
+
2366
+ const stateDirectory = configSnapshot.stateDir ?? stateDir;
1894
2367
  if (parsed.path === "open" || parsed.path.startsWith("register ")) {
1895
- if (state.legacyRegistrationCount)
2368
+ if (configSnapshot.legacyRegistrationCount)
1896
2369
  io.err(
1897
- `Legacy User registrations are inactive. ${state.legacyRegistrationCount} entries are preserved in legacy_user_registrations in the state database under ${state.directory}; nothing was uploaded or deleted. Custom per-association argv is unsupported. Review the archived values and explicitly run ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS to publish only intended associations.`,
2370
+ `Legacy User registrations are inactive. ${configSnapshot.legacyRegistrationCount} entries are preserved in legacy_user_registrations in the state database under ${stateDirectory}; nothing was uploaded or deleted. Custom per-association argv is unsupported. Review the archived values and explicitly run ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS to publish only intended associations.`,
1898
2371
  );
1899
2372
  }
1900
- if (state.legacyPinCount)
2373
+ if (configSnapshot.legacyPinCount)
1901
2374
  io.err(
1902
- `Legacy local pin names are inactive: ${state.legacyPinCount} records are preserved in legacy_named_pins under ${state.directory}. Retention and original Store owners are unchanged; inspect ipab pin list and release intended archived holders with ipab unpin EXACT_CID.`,
2375
+ `Legacy local pin names are inactive: ${configSnapshot.legacyPinCount} records are preserved in legacy_named_pins under ${stateDirectory}. Retention and original Store owners are unchanged; inspect ipab pin list and release intended archived holders with ipab unpin EXACT_CID.`,
1903
2376
  );
2377
+
2378
+ const [first, second] = parsed.positional;
2379
+
2380
+ if (parsed.path === "swarm list") {
2381
+ const result = { swarms: registeredSwarms, ...selection() };
2382
+ emit(
2383
+ {
2384
+ ...result,
2385
+ swarms: result.swarms.map((entry) => ({
2386
+ configUrl: entry.cid,
2387
+ alias: entry.alias,
2388
+ local: Boolean(entry.local),
2389
+ })),
2390
+ },
2391
+ [
2392
+ ...alignedRows(
2393
+ result.swarms.map((entry) => [
2394
+ `${entry.cid === result.effectiveCurrent ? "*" : " "} ${entry.alias ?? entry.cid}${entry.local ? " [local]" : ""}`,
2395
+ entry.cid,
2396
+ ]),
2397
+ ),
2398
+ ...(result.source === "flag" &&
2399
+ result.effectiveCurrent !== result.savedCurrent
2400
+ ? [
2401
+ `Selected via --swarm: ${printable(String(result.swarms.find((entry) => entry.cid === result.effectiveCurrent)?.alias ?? result.effectiveCurrent ?? "(none)"))}; saved default: ${printable(String(result.swarms.find((entry) => entry.cid === result.savedCurrent)?.alias ?? result.savedCurrent ?? "(none)"))}.`,
2402
+ ]
2403
+ : []),
2404
+ ].join("\n"),
2405
+ );
2406
+ return 0;
2407
+ }
2408
+
1904
2409
  if (
1905
2410
  parsed.path.startsWith("templates ") &&
1906
2411
  parsed.path !== "templates render"
1907
2412
  ) {
1908
2413
  const configUrl = requireSwarm();
1909
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1910
- const context = swarmContext();
1911
2414
  const expected =
1912
2415
  typeof parsed.options.expect === "string"
1913
2416
  ? parsed.options.expect
1914
2417
  : undefined;
1915
- try {
1916
- if (parsed.path === "templates list") {
1917
- const items = await swarmTemplates(context, configUrl);
1918
- const alias = state
1919
- .allSwarms()
1920
- .find((swarm) => swarm.cid === configUrl)?.alias;
1921
- emit(
1922
- { items },
1923
- `Swarm: ${alias ? printable(alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nTemplates: ${items.length}\n\n${table(
1924
- ["NAME", "TITLE", "TARGET CID", "TEMPLATE CID"],
1925
- items.map((item) => [
1926
- item.selector,
1927
- item.title,
1928
- item.targetCid,
1929
- item.templateCid,
1930
- ]),
1931
- "No templates registered in this Swarm.\nAdd a template: ipab templates set NAME SOURCE",
1932
- )}`,
1933
- );
1934
- } else if (parsed.path === "templates show") {
1935
- const item = (await swarmTemplates(context, configUrl, first))[0]!;
1936
- if (parsed.flags.json) io.out(JSON.stringify(item));
1937
- else {
1938
- const alias = state
1939
- .allSwarms()
1940
- .find((swarm) => swarm.cid === configUrl)?.alias;
1941
- const swarm = alias ?? configUrl;
1942
- const reference = formatNameReference(swarm, item.name);
1943
- const tree = await templateOutputTree(
1944
- context.store,
2418
+ if (parsed.path === "templates list") {
2419
+ const response = (await client.swarms.fsLs(
2420
+ {
2421
+ swarm: configUrl,
2422
+ kind: "templates",
2423
+ refresh: explicitRefresh,
2424
+ },
2425
+ { ndjson: true },
2426
+ )) as unknown as {
2427
+ items: Awaited<ReturnType<typeof swarmTemplates>>;
2428
+ alias: string | null;
2429
+ };
2430
+ emit(
2431
+ { items: response.items },
2432
+ `Swarm: ${response.alias ? printable(response.alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nTemplates: ${response.items.length}\n\n${table(
2433
+ ["NAME", "TITLE", "TARGET CID", "TEMPLATE CID"],
2434
+ response.items.map((item) => [
2435
+ item.selector,
2436
+ item.title,
2437
+ item.targetCid,
1945
2438
  item.templateCid,
1946
- );
1947
- const shell = process.platform === "win32" ? "powershell" : "posix";
1948
- io.out(
1949
- [
1950
- `${printable(item.selector)} — ${printable(item.title)}`,
1951
- printable(item.description) || "(No description.)",
1952
- "",
1953
- "Location",
1954
- ` Swarm: ${printable(swarm)}`,
1955
- ` Name: ${printable(item.name)}`,
1956
- "",
1957
- `Create a project (${shell === "powershell" ? "PowerShell" : "POSIX shell"})`,
1958
- ` ${templateRenderExample(reference, swarm, item.definition, shell)}`,
1959
- " Replace example parameter values as needed. No code is run by show.",
1960
- "",
1961
- "Parameters",
1962
- table(
1963
- ["NAME", "TYPE", "REQUIRED", "DEFAULT", "INPUT"],
1964
- templateParameterRows(item.definition),
1965
- "No parameters declared.",
1966
- ),
1967
- "Required means an input is needed when no default is declared.",
1968
- "",
1969
- "Output files (from project/)",
1970
- " my-project/",
1971
- ...tree.entries.map(
1972
- (entry) =>
1973
- `${" ".repeat(entry.path.split("/").length + 1)}${printable(entry.path.split("/").at(-1)!)}${entry.kind === "directory" ? "/" : ""}`,
1974
- ),
1975
- ...(tree.truncated
1976
- ? [
1977
- ` ... truncated: ${tree.truncated}; more files may exist.`,
1978
- ]
1979
- : tree.entries.length
1980
- ? []
1981
- : [" (no output files)"]),
1982
- "",
1983
- "Versions",
1984
- ` Template CID: ${item.templateCid}`,
1985
- ` Reference: ${reference}`,
1986
- ...(item.targetCid !== item.templateCid
1987
- ? [` Target CID (--expect): ${item.targetCid}`]
1988
- : []),
1989
- ].join("\n"),
1990
- );
1991
- }
1992
- } else if (parsed.path === "templates set") {
1993
- const item = await setSwarmTemplate(
1994
- context,
1995
- configUrl,
1996
- first!,
1997
- second!,
1998
- expected,
1999
- );
2000
- emit(
2001
- item,
2002
- `${item.reference} → ${item.targetCid} (Template ${item.templateCid})`,
2003
- );
2004
- } else {
2005
- const item = await removeSwarmTemplate(
2006
- context,
2007
- configUrl,
2008
- first!,
2009
- expected!,
2010
- );
2011
- emit(
2012
- { removed: item },
2013
- `Removed ${item.reference}; content and history are retained.`,
2439
+ ]),
2440
+ "No templates registered in this Swarm.\nAdd a template: ipab templates set NAME SOURCE",
2441
+ )}`,
2442
+ );
2443
+ } else if (parsed.path === "templates show") {
2444
+ const { templateRenderExample, templateParameterRows } =
2445
+ await import("./template-presentation.js");
2446
+ const response = (await client.swarms.fsStat(
2447
+ {
2448
+ swarm: configUrl,
2449
+ kind: "template",
2450
+ name: first!,
2451
+ includeTree: !parsed.flags.json,
2452
+ refresh: explicitRefresh,
2453
+ },
2454
+ { ndjson: true },
2455
+ )) as unknown as {
2456
+ item: Awaited<ReturnType<typeof swarmTemplates>>[number];
2457
+ tree?: Awaited<ReturnType<typeof templateOutputTree>>;
2458
+ alias: string | null;
2459
+ };
2460
+ const { item, tree, alias } = response;
2461
+ if (parsed.flags.json) io.out(JSON.stringify(item));
2462
+ else {
2463
+ const previewTree = tree ?? { entries: [], truncated: null };
2464
+ const swarm = alias ?? configUrl;
2465
+ const reference = formatNameReference(swarm, item.name);
2466
+ const shell = process.platform === "win32" ? "powershell" : "posix";
2467
+ io.out(
2468
+ [
2469
+ `${printable(item.selector)} — ${printable(item.title)}`,
2470
+ printable(item.description) || "(No description.)",
2471
+ "",
2472
+ "Location",
2473
+ ` Swarm: ${printable(swarm)}`,
2474
+ ` Name: ${printable(item.name)}`,
2475
+ "",
2476
+ `Create a project (${shell === "powershell" ? "PowerShell" : "POSIX shell"})`,
2477
+ ` ${templateRenderExample(reference, swarm, item.definition, shell)}`,
2478
+ " Replace example parameter values as needed. No code is run by show.",
2479
+ "",
2480
+ "Parameters",
2481
+ table(
2482
+ ["NAME", "TYPE", "REQUIRED", "DEFAULT", "INPUT"],
2483
+ templateParameterRows(item.definition),
2484
+ "No parameters declared.",
2485
+ ),
2486
+ "Required means an input is needed when no default is declared.",
2487
+ "",
2488
+ "Output files (from project/)",
2489
+ " my-project/",
2490
+ ...previewTree.entries.map(
2491
+ (entry) =>
2492
+ `${" ".repeat(entry.path.split("/").length + 1)}${printable(entry.path.split("/").at(-1)!)}${entry.kind === "directory" ? "/" : ""}`,
2493
+ ),
2494
+ ...(previewTree.truncated
2495
+ ? [
2496
+ ` ... truncated: ${previewTree.truncated}; more files may exist.`,
2497
+ ]
2498
+ : previewTree.entries.length
2499
+ ? []
2500
+ : [" (no output files)"]),
2501
+ "",
2502
+ "Versions",
2503
+ ` Template CID: ${item.templateCid}`,
2504
+ ` Reference: ${reference}`,
2505
+ ...(item.targetCid !== item.templateCid
2506
+ ? [` Target CID (--expect): ${item.targetCid}`]
2507
+ : []),
2508
+ ].join("\n"),
2014
2509
  );
2015
2510
  }
2016
- } finally {
2017
- await context.finishRead?.();
2511
+ } else if (parsed.path === "templates set") {
2512
+ const source = await resolveLocalPathIfPresent(second!);
2513
+ const item = (await client.swarms.fsSet(
2514
+ {
2515
+ swarm: configUrl,
2516
+ kind: "template",
2517
+ name: first!,
2518
+ source,
2519
+ expect: expected,
2520
+ },
2521
+ { ndjson: true },
2522
+ )) as unknown as Awaited<ReturnType<typeof setSwarmTemplate>>;
2523
+ emit(
2524
+ item,
2525
+ `${item.reference} → ${item.targetCid} (Template ${item.templateCid})`,
2526
+ );
2527
+ } else {
2528
+ const item = (await client.swarms.fsRm(
2529
+ {
2530
+ swarm: configUrl,
2531
+ kind: "template",
2532
+ name: first!,
2533
+ expect: expected!,
2534
+ },
2535
+ { ndjson: true },
2536
+ )) as unknown as Awaited<ReturnType<typeof removeSwarmTemplate>>;
2537
+ emit(
2538
+ { removed: item },
2539
+ `Removed ${item.reference}; content and history are retained.`,
2540
+ );
2018
2541
  }
2019
2542
  return 0;
2020
2543
  }
2544
+
2021
2545
  if (parsed.path.startsWith("register ")) {
2546
+ const { message } = await import("./errors.js");
2022
2547
  const references = parsed.registrySwarms?.length
2023
2548
  ? parsed.registrySwarms
2024
2549
  : selectedSwarm
@@ -2029,72 +2554,90 @@ async function performCli(
2029
2554
  "Register requires a selected Swarm. Pass --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.",
2030
2555
  );
2031
2556
  const targets = [
2032
- ...new Set(
2033
- references.map((reference) => state!.resolveSwarm(reference)),
2034
- ),
2557
+ ...new Set(references.map((reference) => resolveSwarm(reference))),
2035
2558
  ];
2036
- const schema = first
2037
- ? state.resolve(schemaAlias(first), true)
2038
- : undefined;
2039
2559
  const results: (
2040
- | {
2041
- items: Association[];
2042
- }
2043
- | {
2044
- association: Association;
2045
- }
2046
- | {
2047
- removed: string[];
2048
- }
2560
+ | { items: Association[] }
2561
+ | { association: Association }
2562
+ | { removed: string[] }
2049
2563
  )[] = [];
2050
2564
  const completed: string[] = [];
2051
2565
  const human: string[] = [];
2052
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2566
+ const resolvedApp =
2567
+ parsed.path === "register set"
2568
+ ? await resolveLocalPathIfPresent(second!)
2569
+ : undefined;
2570
+ if (parsed.path === "register set" && targets.length > 1) {
2571
+ const batch = (await client.swarms.fsSet(
2572
+ {
2573
+ swarm: targets[0]!,
2574
+ swarms: targets,
2575
+ kind: "register",
2576
+ schema: first!,
2577
+ app: resolvedApp!,
2578
+ argv: parsed.template ?? ["%"],
2579
+ replace: Boolean(parsed.options.replace),
2580
+ },
2581
+ { ndjson: true },
2582
+ )) as unknown as { associations: Association[] };
2583
+ for (let i = 0; i < targets.length; i++) {
2584
+ const association = batch.associations[i]!;
2585
+ results.push({ association });
2586
+ human.push(
2587
+ `${targets[i]}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`,
2588
+ );
2589
+ }
2590
+ emit(
2591
+ {
2592
+ swarms: results.map((result, index) => ({
2593
+ configUrl: targets[index],
2594
+ ...result,
2595
+ })),
2596
+ },
2597
+ human.join("\n\n"),
2598
+ );
2599
+ return 0;
2600
+ }
2053
2601
  for (const configUrl of targets) {
2054
- const context = swarmContext();
2055
2602
  try {
2056
2603
  if (parsed.path === "register list") {
2057
- const items = await swarmRegistrations(context, configUrl);
2058
- const alias = state
2059
- .allSwarms()
2060
- .find((swarm) => swarm.cid === configUrl)?.alias;
2061
- results.push({ items });
2604
+ const response = (await client.swarms.fsLs(
2605
+ { swarm: configUrl, kind: "register" },
2606
+ { ndjson: true },
2607
+ )) as unknown as { items: Association[]; alias: string | null };
2608
+ results.push({ items: response.items });
2062
2609
  human.push(
2063
- `Swarm: ${alias ? printable(alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nAssociations: ${items.length}\n\n${table(
2610
+ `Swarm: ${response.alias ? printable(response.alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nAssociations: ${response.items.length}\n\n${table(
2064
2611
  ["TYPE CID", "APP CID"],
2065
- items.map((item) => [item.schemaCid, item.appCid]),
2612
+ response.items.map((item) => [item.schemaCid, item.appCid]),
2066
2613
  "No associations registered in this Swarm.\nRegister an App: ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS",
2067
2614
  )}`,
2068
2615
  );
2069
2616
  } else if (parsed.path === "register set") {
2070
- const appCid = parseNameReference(second!)
2071
- ? (
2072
- await resolveReference(
2073
- context,
2074
- second!,
2075
- configUrl,
2076
- (reference) => state!.resolve(reference),
2077
- )
2078
- ).cid
2079
- : state.resolve(second!);
2080
- const association = await setSwarmAssociation(
2081
- context,
2082
- configUrl,
2083
- createAssociation(schema!, appCid, parsed.template ?? ["%"]),
2084
- Boolean(parsed.options.replace),
2085
- );
2617
+ const association = (await client.swarms.fsSet(
2618
+ {
2619
+ swarm: configUrl,
2620
+ kind: "register",
2621
+ schema: first!,
2622
+ app: resolvedApp!,
2623
+ argv: parsed.template ?? ["%"],
2624
+ replace: Boolean(parsed.options.replace),
2625
+ },
2626
+ { ndjson: true },
2627
+ )) as unknown as Association;
2086
2628
  results.push({ association });
2087
2629
  human.push(
2088
2630
  `${configUrl}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`,
2089
2631
  );
2090
2632
  } else {
2091
- const removed = await removeSwarmAssociation(
2092
- context,
2093
- configUrl,
2094
- schema!,
2633
+ const response = (await client.swarms.fsRm(
2634
+ { swarm: configUrl, kind: "register", schema: first! },
2635
+ { ndjson: true },
2636
+ )) as unknown as { removed: string };
2637
+ results.push({ removed: [response.removed] });
2638
+ human.push(
2639
+ `${configUrl}: removed association for ${response.removed}.`,
2095
2640
  );
2096
- results.push({ removed: [removed] });
2097
- human.push(`${configUrl}: removed association for ${removed}.`);
2098
2641
  }
2099
2642
  completed.push(configUrl);
2100
2643
  } catch (cause) {
@@ -2106,8 +2649,6 @@ async function performCli(
2106
2649
  cause instanceof HostError ? cause.code : "REGISTRY_FAILED",
2107
2650
  "publication",
2108
2651
  );
2109
- } finally {
2110
- await context.finishRead?.();
2111
2652
  }
2112
2653
  }
2113
2654
  emit(
@@ -2121,10 +2662,9 @@ async function performCli(
2121
2662
  );
2122
2663
  return 0;
2123
2664
  }
2665
+
2124
2666
  switch (parsed.path) {
2125
2667
  case "profile": {
2126
- const context = swarmContext();
2127
- readContext = context;
2128
2668
  const changes = {
2129
2669
  ...(typeof parsed.options.name === "string"
2130
2670
  ? { name: parsed.options.name }
@@ -2134,13 +2674,22 @@ async function performCli(
2134
2674
  : {}),
2135
2675
  };
2136
2676
  if (!Object.keys(changes).length) {
2137
- const profile = await accountProfile(context);
2677
+ const profile = (await client.swarms.identity({
2678
+ ndjson: true,
2679
+ })) as {
2680
+ name: string;
2681
+ description: string;
2682
+ publicKey: string;
2683
+ updatedAt: string | null;
2684
+ };
2138
2685
  emit(
2139
2686
  { profile, localPersisted: profile.updatedAt !== null },
2140
2687
  `Name: ${printable(profile.name)}\nDescription: ${printable(profile.description)}\nPublic key: ${profile.publicKey}`,
2141
2688
  );
2142
2689
  } else {
2143
- const result = await updateAccountProfile(context, changes);
2690
+ const result = (await client.swarms.governance("profile", changes, {
2691
+ ndjson: true,
2692
+ })) as Awaited<ReturnType<typeof updateAccountProfile>>;
2144
2693
  emit(
2145
2694
  result,
2146
2695
  [
@@ -2162,37 +2711,20 @@ async function performCli(
2162
2711
  }
2163
2712
  break;
2164
2713
  }
2165
- case "swarm list": {
2166
- const result = { swarms: state.allSwarms(), ...selection() };
2167
- emit(
2168
- {
2169
- ...result,
2170
- swarms: result.swarms.map((entry) => ({
2171
- configUrl: entry.cid,
2172
- alias: entry.alias,
2173
- local: Boolean(entry.local),
2174
- })),
2175
- },
2176
- [
2177
- ...alignedRows(
2178
- result.swarms.map((entry) => [
2179
- `${entry.cid === result.effectiveCurrent ? "*" : " "} ${entry.alias ?? entry.cid}${entry.local ? " [local]" : ""}`,
2180
- entry.cid,
2181
- ]),
2182
- ),
2183
- ...(result.source === "flag" &&
2184
- result.effectiveCurrent !== result.savedCurrent
2185
- ? [
2186
- `Selected via --swarm: ${printable(String(result.swarms.find((entry) => entry.cid === result.effectiveCurrent)?.alias ?? result.effectiveCurrent ?? "(none)"))}; saved default: ${printable(String(result.swarms.find((entry) => entry.cid === result.savedCurrent)?.alias ?? result.savedCurrent ?? "(none)"))}.`,
2187
- ]
2188
- : []),
2189
- ].join("\n"),
2190
- );
2191
- break;
2192
- }
2193
2714
  case "swarm use": {
2194
- state.useSwarm(first!);
2195
- const result = selection();
2715
+ const resolvedUrl = resolveSwarm(first!);
2716
+ const registered = registeredSwarms.some(
2717
+ (entry) => entry.cid === resolvedUrl,
2718
+ );
2719
+ if (!registered) {
2720
+ throw new HostError(
2721
+ `Unknown Swarm "${first!}". Run ipab swarm list or register it with ipab swarm set ALIAS CONFIG_URL.`,
2722
+ );
2723
+ }
2724
+ await client.host.setConfig("swarm.default", resolvedUrl, {
2725
+ fromString: true,
2726
+ });
2727
+ const result = selection(resolvedUrl);
2196
2728
  emit(result, `Saved current swarm: ${result.savedCurrent}`);
2197
2729
  if (result.source === "flag" || result.source === "env")
2198
2730
  io.err(
@@ -2201,21 +2733,19 @@ async function performCli(
2201
2733
  break;
2202
2734
  }
2203
2735
  case "swarm remove": {
2204
- const removed = state.removeSwarm(first!);
2736
+ const result = await client.swarms.remove({ swarm: first! });
2205
2737
  emit(
2206
- {
2207
- removed,
2208
- savedCurrent:
2209
- state.config({ includeSecrets: false })["swarm.default"] ?? null,
2210
- },
2211
- `Removed registration ${removed}. Credentials, content and remote membership are unchanged.`,
2738
+ result,
2739
+ `Removed registration ${result.removed}. Credentials, content and remote membership are unchanged.`,
2212
2740
  );
2213
2741
  break;
2214
2742
  }
2215
2743
  case "swarm set": {
2216
2744
  swarmAlias(first!);
2217
2745
  const cid = swarmUrl(second!);
2218
- const previous = state.swarms().find((entry) => entry.alias === first);
2746
+ const previous = registeredSwarms.find(
2747
+ (entry) => entry.alias === first,
2748
+ );
2219
2749
  if (previous && previous.cid !== cid) {
2220
2750
  io.err(`Swarm alias ${first}: ${previous.cid} -> ${cid}`);
2221
2751
  if (
@@ -2229,613 +2759,888 @@ async function performCli(
2229
2759
  "Alias unchanged. Retargeting requires --yes or interactive confirmation.",
2230
2760
  );
2231
2761
  }
2232
- const entry = state.setSwarm(first!, cid, previous?.cid ?? null);
2762
+ const entry = await client.swarms.set({
2763
+ alias: first!,
2764
+ url: cid,
2765
+ expectedTarget: previous?.cid ?? null,
2766
+ });
2767
+ emit(entry, `Set local swarm alias ${entry.alias} (${cid}).`);
2768
+ break;
2769
+ }
2770
+ case "fs ls": {
2771
+ const result = await client.swarms.fsLs(
2772
+ {
2773
+ swarm: requireSwarm(),
2774
+ path: first,
2775
+ all: Boolean(parsed.options.all),
2776
+ recursive: Boolean(parsed.options.recursive),
2777
+ refresh: explicitRefresh,
2778
+ },
2779
+ { ndjson: true },
2780
+ );
2781
+ const text = result.entries.length
2782
+ ? result.entries
2783
+ .map(
2784
+ (entry) =>
2785
+ `${result.recursive ? entry.path : entry.name}\t${entry.cid ?? "<dir>"}\t${entry.size !== null ? String(entry.size) : entry.kind}`,
2786
+ )
2787
+ .join("\n")
2788
+ : "No entries.";
2789
+ emit(result, text);
2790
+ if (result.truncated || result.skippedSubtrees > 0) {
2791
+ io.err(
2792
+ `Listing incomplete: truncated=${String(result.truncated)}, skippedSubtrees=${String(result.skippedSubtrees)}.`,
2793
+ );
2794
+ }
2795
+ break;
2796
+ }
2797
+ case "fs stat": {
2798
+ const result = await client.swarms.fsStat(
2799
+ {
2800
+ swarm: requireSwarm(),
2801
+ path: first!,
2802
+ ...(explicitRefresh !== undefined
2803
+ ? { refresh: explicitRefresh }
2804
+ : {}),
2805
+ },
2806
+ { ndjson: true },
2807
+ );
2808
+ const lines = [
2809
+ `Path: ${result.path || "/"}`,
2810
+ `CID: ${result.cid ?? "(virtual)"}`,
2811
+ `Kind: ${result.kind}`,
2812
+ `Size: ${result.size !== null ? String(result.size) : "unavailable"}`,
2813
+ ...(result.kind === "directory" && result.isBundle !== undefined
2814
+ ? [`Bundle: ${result.isBundle ? "yes" : "no"}`]
2815
+ : []),
2816
+ ...(result.kind === "directory" && result.entryCount !== undefined
2817
+ ? [`Entries: ${result.entryCount}`]
2818
+ : []),
2819
+ `Swarm: ${result.swarm}`,
2820
+ `Snapshot: ${result.snapshotVersion === "legacy" ? "legacy (read-only virtual)" : "v7"}`,
2821
+ ];
2822
+ emit(result, lines.join("\n"));
2823
+ break;
2824
+ }
2825
+ case "fs set": {
2826
+ const result = await client.swarms.fsSet(
2827
+ {
2828
+ swarm: requireSwarm(),
2829
+ path: first!,
2830
+ cid: second!,
2831
+ ...(typeof parsed.options.expect === "string"
2832
+ ? { expect: parsed.options.expect }
2833
+ : {}),
2834
+ ...(parsed.options.replace ? { replace: true } : {}),
2835
+ },
2836
+ { ndjson: true },
2837
+ );
2838
+ emit(
2839
+ result,
2840
+ result.changed
2841
+ ? `Set ${result.path} -> ${result.cid} (HEAD ${result.headCid})`
2842
+ : `Unchanged ${result.path} -> ${result.cid} (HEAD ${result.headCid})`,
2843
+ );
2844
+ break;
2845
+ }
2846
+ case "fs rm": {
2847
+ const result = await client.swarms.fsRm(
2848
+ {
2849
+ swarm: requireSwarm(),
2850
+ path: first!,
2851
+ ...(typeof parsed.options.expect === "string"
2852
+ ? { expect: parsed.options.expect }
2853
+ : {}),
2854
+ },
2855
+ { ndjson: true },
2856
+ );
2233
2857
  emit(
2858
+ result,
2859
+ `Removed ${result.path} (was ${result.removedCid}, HEAD ${result.headCid})`,
2860
+ );
2861
+ break;
2862
+ }
2863
+ case "swarm replicate": {
2864
+ const result = (await client.swarms.replicate(
2234
2865
  {
2235
- configUrl: entry.cid,
2236
- alias: entry.alias,
2237
- savedCurrent:
2238
- state.config({ includeSecrets: false })["swarm.default"] ?? null,
2866
+ swarm: requireSwarm(),
2867
+ ...(typeof parsed.options.pivot === "string"
2868
+ ? { pivot: parsed.options.pivot }
2869
+ : {}),
2239
2870
  },
2240
- `Set local swarm alias ${entry.alias} (${cid}).`,
2871
+ { ndjson: true },
2872
+ )) as Awaited<ReturnType<typeof replicateSwarm>>;
2873
+ emit(
2874
+ result,
2875
+ [
2876
+ `HEAD: ${result.headCid}`,
2877
+ ...result.results.map(
2878
+ (entry) =>
2879
+ `${entry.peerId}: ${entry.status}${entry.error ? ` (${entry.error})` : ""}`,
2880
+ ),
2881
+ ].join("\n"),
2241
2882
  );
2242
2883
  break;
2243
2884
  }
2244
- case "daemon": {
2245
- if (parsed.flags.json)
2246
- syntax(
2247
- "--json is not supported for daemon; diagnostics are written to stderr.",
2248
- );
2249
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2250
- const controller = new AbortController();
2251
- const interrupt = () => {
2252
- controller.abort();
2885
+ case "skills show": {
2886
+ const named = parseNameReference(first!);
2887
+ const targetSwarm = named?.swarm
2888
+ ? resolveSwarm(named.swarm)
2889
+ : requireSwarm();
2890
+ const ref = await resolveLocalPathIfPresent(first!);
2891
+ const payload = (await client.swarms.fsStat(
2892
+ {
2893
+ swarm: targetSwarm,
2894
+ kind: "skill",
2895
+ ref,
2896
+ ...(explicitRefresh !== undefined
2897
+ ? { refresh: explicitRefresh }
2898
+ : {}),
2899
+ },
2900
+ { ndjson: true },
2901
+ )) as unknown as {
2902
+ swarm: string;
2903
+ schemaCid: string;
2904
+ resolvedFrom: string;
2905
+ contentCid?: string;
2906
+ reference?: string;
2907
+ name: string;
2908
+ cid: string;
2909
+ identity: string;
2910
+ description: string;
2253
2911
  };
2254
- process.once("SIGINT", interrupt);
2255
- process.once("SIGTERM", interrupt);
2256
- try {
2257
- await swarmDaemon(
2258
- swarmContext(),
2259
- controller.signal,
2260
- (ctx, url, report) => syncDaemonSwarm(ctx, url, undefined, report),
2261
- );
2262
- } catch (cause) {
2263
- if (!controller.signal.aborted) throw cause;
2264
- } finally {
2265
- process.removeListener("SIGINT", interrupt);
2266
- process.removeListener("SIGTERM", interrupt);
2267
- }
2912
+ const lines = [
2913
+ `Swarm: ${payload.swarm}`,
2914
+ `Schema: ${payload.schemaCid}`,
2915
+ ...(payload.contentCid ? [`Content CID: ${payload.contentCid}`] : []),
2916
+ `Skill: ${payload.identity}`,
2917
+ `Skill CID: ${payload.cid}`,
2918
+ `Path: ${payload.name}`,
2919
+ `Description: ${payload.description}`,
2920
+ ];
2921
+ emit(payload, lines.join("\n"));
2268
2922
  break;
2269
2923
  }
2270
- case "swarm update":
2271
- case "search":
2272
- case "skills list":
2273
- case "skills sync":
2274
- case "swarm create":
2275
- case "swarm request":
2276
- case "swarm approve":
2277
- case "swarm pivot grant":
2278
- case "swarm export":
2279
- case "swarm exclude":
2280
- case "swarm resume":
2281
- case "swarm profile":
2282
- case "swarm members":
2283
- case "swarm status":
2284
- case "publish":
2285
- case "pin":
2286
- case "get": {
2287
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2288
- const context = swarmContext();
2289
- readContext = context;
2290
- if (parsed.path.startsWith("skills ")) {
2291
- const result = await manageSkills(context, requireSwarm(), {
2292
- sync: parsed.path === "skills sync",
2924
+ case "skills set": {
2925
+ const targetSwarm = requireSwarm();
2926
+ const skill = await resolveLocalPathIfPresent(first!);
2927
+ const result = (await client.swarms.fsSet(
2928
+ {
2929
+ swarm: targetSwarm,
2930
+ kind: "skill",
2931
+ skill,
2932
+ global: Boolean(parsed.options.global),
2933
+ types: parsed.types ?? [],
2934
+ replace: Boolean(parsed.options.replace),
2935
+ },
2936
+ { ndjson: true },
2937
+ )) as unknown as Awaited<ReturnType<typeof setSwarmSkill>>;
2938
+ const text = result.changed
2939
+ ? [
2940
+ `Skill: ${result.identity} (${result.cid})`,
2941
+ `HEAD: ${result.headCid}`,
2942
+ ...result.targets.map((target) => {
2943
+ const status = !target.changed
2944
+ ? "unchanged"
2945
+ : target.previousCid
2946
+ ? "updated"
2947
+ : "created";
2948
+ return target.scope === "global"
2949
+ ? ` global -> ${target.name} (${status})`
2950
+ : ` type ${target.schemaCid} -> ${target.name} (${status})`;
2951
+ }),
2952
+ ].join("\n")
2953
+ : `Unchanged: ${result.identity} (${result.cid}) (HEAD ${result.headCid})`;
2954
+ emit(result, text);
2955
+ break;
2956
+ }
2957
+ case "skills remove": {
2958
+ const targetSwarm = requireSwarm();
2959
+ const globalName =
2960
+ typeof parsed.options.global === "string"
2961
+ ? parsed.options.global
2962
+ : undefined;
2963
+ const result = (await client.swarms.fsRm(
2964
+ {
2965
+ swarm: targetSwarm,
2966
+ kind: "skill",
2967
+ ...(globalName !== undefined ? { globalName } : {}),
2968
+ types: parsed.types ?? [],
2969
+ },
2970
+ { ndjson: true },
2971
+ )) as unknown as Awaited<ReturnType<typeof removeSwarmSkill>>;
2972
+ const lines = [
2973
+ `Removed ${result.removed.length} Skill association(s) (HEAD ${result.headCid}):`,
2974
+ ...result.removed.map((entry) =>
2975
+ entry.scope === "global"
2976
+ ? ` global ${entry.name} (was ${entry.removedCid})`
2977
+ : ` type ${entry.schemaCid} ${entry.name} (was ${entry.removedCid})`,
2978
+ ),
2979
+ ];
2980
+ emit(result, lines.join("\n"));
2981
+ break;
2982
+ }
2983
+ case "skills list": {
2984
+ const targetSwarm = requireSwarm();
2985
+ const result = (await client.swarms.fsLs(
2986
+ {
2987
+ swarm: targetSwarm,
2988
+ kind: "skills",
2293
2989
  names: parsed.positional,
2294
2990
  agents: parsed.agents ?? [],
2295
- overrideExisting: Boolean(parsed.options["override-existing"]),
2296
- dryRun: Boolean(parsed.options["dry-run"]),
2297
- yes: Boolean(parsed.options.yes),
2298
- tty: io.tty,
2299
- confirm: (text) => io.confirm(text),
2300
- preview: (text) => {
2301
- io.err(text);
2991
+ refresh: explicitRefresh,
2992
+ },
2993
+ { ndjson: true },
2994
+ )) as unknown as Awaited<ReturnType<typeof manageSkills>> & {
2995
+ typeSkills: Awaited<ReturnType<typeof swarmTypeSkills>>;
2996
+ };
2997
+ const globalLines = [
2998
+ table(
2999
+ ["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"],
3000
+ result.items.map((skill) => [
3001
+ skill.name,
3002
+ skill.cid,
3003
+ skill.identity,
3004
+ skill.status,
3005
+ ]),
3006
+ "No Global Skills.",
3007
+ ),
3008
+ ...result.items.flatMap((skill) => skill.problems),
3009
+ ...result.orphaned.map(
3010
+ (skill) =>
3011
+ `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`,
3012
+ ),
3013
+ ];
3014
+ const typeLines = [
3015
+ "Type Skills:",
3016
+ table(
3017
+ ["TYPE CID", "SKILL NAME", "SKILL CID"],
3018
+ result.typeSkills.map((entry) => [
3019
+ entry.schemaCid,
3020
+ entry.identity,
3021
+ entry.cid,
3022
+ ]),
3023
+ "No Type Skills.",
3024
+ ),
3025
+ ];
3026
+ emit(result, [...globalLines, "", ...typeLines].join("\n"));
3027
+ if (!result.ok) return 1;
3028
+ break;
3029
+ }
3030
+ case "skills sync": {
3031
+ const targetSwarm = requireSwarm();
3032
+ const syncParams = {
3033
+ swarm: targetSwarm,
3034
+ names: parsed.positional,
3035
+ agents: parsed.agents ?? [],
3036
+ overrideExisting: Boolean(parsed.options["override-existing"]),
3037
+ refresh: explicitRefresh,
3038
+ };
3039
+ let result: Awaited<ReturnType<typeof manageSkills>>;
3040
+ if (parsed.options["dry-run"] || parsed.options.yes || !io.tty) {
3041
+ result = (await client.host.syncSkills(
3042
+ {
3043
+ ...syncParams,
3044
+ dryRun: Boolean(parsed.options["dry-run"]),
3045
+ yes: Boolean(parsed.options.yes),
2302
3046
  },
2303
- });
2304
- store = context.store;
2305
- emit(
2306
- result,
2307
- [
2308
- table(
2309
- ["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"],
2310
- result.items.map((skill) => [
2311
- skill.name,
2312
- skill.cid,
2313
- skill.identity,
2314
- skill.status,
2315
- ]),
2316
- "No Skills.",
2317
- ),
2318
- ...result.items.flatMap((skill) => skill.problems),
2319
- ...result.orphaned.map(
2320
- (skill) =>
2321
- `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`,
2322
- ),
2323
- ...result.results.map(
2324
- (entry) =>
2325
- `${entry.name} / ${entry.agent}: ${entry.status}${entry.error ? `: ${entry.error}` : ""}`,
2326
- ),
2327
- ].join("\n"),
2328
- );
2329
- if (!result.ok) return 1;
2330
- break;
2331
- }
2332
- if (parsed.path === "pin") {
2333
- io.err("Fetching, verifying and retaining content...");
2334
- const result = await pinNameSubscription(
2335
- context,
2336
- first!,
2337
- selectedSwarm,
2338
- );
2339
- store = context.store;
2340
- emit(
2341
- result,
2342
- `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`,
2343
- );
2344
- break;
2345
- }
2346
- if (parsed.path === "swarm members") {
2347
- const result = await swarmMembers(
2348
- context,
2349
- requireSwarm(),
2350
- Boolean(parsed.options.refresh || parsed.options.force),
2351
- );
2352
- if (result.mode === "local") {
2353
- emit(
2354
- result,
2355
- [
2356
- "Swarm: local (Built-in single-machine Swarm)",
2357
- "Mode: local",
2358
- "Members: local user only (single-machine; no remote collaborators or HOME identity required)",
2359
- ].join("\n"),
3047
+ { ndjson: true },
3048
+ )) as Awaited<ReturnType<typeof manageSkills>>;
3049
+ } else {
3050
+ const preview = (await client.host.syncSkills(
3051
+ {
3052
+ ...syncParams,
3053
+ dryRun: true,
3054
+ yes: false,
3055
+ },
3056
+ { ndjson: true },
3057
+ )) as Awaited<ReturnType<typeof manageSkills>>;
3058
+ if (!preview.ok) {
3059
+ result = preview;
3060
+ } else {
3061
+ const selected = preview.items.filter(
3062
+ (skill) =>
3063
+ !parsed.positional.length ||
3064
+ parsed.positional.includes(skill.name) ||
3065
+ parsed.positional.includes(skill.identity),
3066
+ );
3067
+ const hasChanges = selected.some((skill) =>
3068
+ skill.agents.some((agent) => agent.status !== "current"),
2360
3069
  );
2361
- break;
3070
+ if (!selected.length) {
3071
+ result = { ...preview, dryRun: false };
3072
+ } else {
3073
+ if (
3074
+ hasChanges &&
3075
+ !(await io.confirm(
3076
+ `Authorize ${preview.installer} and the changes above?`,
3077
+ ))
3078
+ ) {
3079
+ throw new HostError(
3080
+ "Skill sync requires --yes or interactive consent. Use --override-existing to authorize replacing existing Skills; source and link conflicts remain protected.",
3081
+ );
3082
+ }
3083
+ result = (await client.host.syncSkills(
3084
+ {
3085
+ ...syncParams,
3086
+ dryRun: false,
3087
+ yes: true,
3088
+ quietPreview: true,
3089
+ },
3090
+ { ndjson: true },
3091
+ )) as Awaited<ReturnType<typeof manageSkills>>;
3092
+ }
2362
3093
  }
3094
+ }
3095
+ emit(
3096
+ result,
3097
+ [
3098
+ table(
3099
+ ["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"],
3100
+ result.items.map((skill) => [
3101
+ skill.name,
3102
+ skill.cid,
3103
+ skill.identity,
3104
+ skill.status,
3105
+ ]),
3106
+ "No Skills.",
3107
+ ),
3108
+ ...result.items.flatMap((skill) => skill.problems),
3109
+ ...result.orphaned.map(
3110
+ (skill) =>
3111
+ `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`,
3112
+ ),
3113
+ ...result.results.map(
3114
+ (entry) =>
3115
+ `${entry.name} / ${entry.agent}: ${entry.status}${entry.error ? `: ${entry.error}` : ""}`,
3116
+ ),
3117
+ ].join("\n"),
3118
+ );
3119
+ if (!result.ok) return 1;
3120
+ break;
3121
+ }
3122
+ case "pin": {
3123
+ io.err("Fetching, verifying and retaining content...");
3124
+ const result = await client.store.addPin(
3125
+ {
3126
+ ref: first!,
3127
+ swarm: selectedSwarm,
3128
+ refresh: explicitRefresh,
3129
+ },
3130
+ { ndjson: true },
3131
+ );
3132
+ emit(
3133
+ result,
3134
+ `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`,
3135
+ );
3136
+ break;
3137
+ }
3138
+ case "swarm members": {
3139
+ const result = (await client.swarms.members(
3140
+ {
3141
+ swarm: requireSwarm(),
3142
+ refresh: Boolean(parsed.options.refresh || parsed.options.force),
3143
+ },
3144
+ { ndjson: true },
3145
+ )) as Awaited<ReturnType<typeof swarmMembers>>;
3146
+ if (result.mode === "local") {
2363
3147
  emit(
2364
3148
  result,
2365
3149
  [
2366
- `Directory: ${result.cache.source} (${result.cache.freshness}), observed ${result.cache.updatedAt}`,
2367
- `Daemon: ${result.local.status}, observed ${result.local.updatedAt ?? "unknown"}; control-plane verified ${result.local.verifiedAt ?? "unknown"}`,
2368
- table(
2369
- ["NAME", "DESCRIPTION", "ROLE", "PIVOT", "PUBLIC KEY"],
2370
- result.members.map((member) => [
2371
- member.name,
2372
- member.description,
2373
- member.role,
2374
- member.pivot ? (member.localStatus ?? "candidate") : "-",
2375
- member.publicKey,
2376
- ]),
2377
- "No members.",
2378
- ),
3150
+ "Swarm: local (Built-in single-machine Swarm)",
3151
+ "Mode: local",
3152
+ "Members: local user only (single-machine; no remote collaborators or HOME identity required)",
2379
3153
  ].join("\n"),
2380
3154
  );
2381
- if (result.local.error)
2382
- io.err(
2383
- `Local Pivot observations (${result.local.status}): ${printable(result.local.error)}`,
2384
- );
2385
3155
  break;
2386
3156
  }
2387
- if (parsed.path === "swarm export") {
2388
- const member = await exportRequest(
2389
- context,
2390
- requireSwarm(),
2391
- String(parsed.options.output ?? ""),
2392
- );
2393
- emit({ member }, member);
2394
- break;
2395
- }
2396
- if (parsed.path === "swarm pivot grant") {
2397
- const url = requireSwarm();
2398
- if (!parsed.options.yes)
2399
- syntax(
2400
- "Granting Pivot HEAD receipt authority requires --yes; revoking it requires swarm exclude.",
2401
- );
2402
- const result = await grantPivotAuthority(context, url, first!);
2403
- store = context.store;
2404
- emit(
2405
- result,
2406
- `Granted Pivot HEAD authority to ${result.member} on ${result.configUrl} (HEAD ${result.headId}). Revoking Pivot HEAD authority requires swarm exclude.`,
3157
+ emit(
3158
+ result,
3159
+ [
3160
+ `Directory: ${result.cache.source} (${result.cache.freshness}), observed ${result.cache.updatedAt}`,
3161
+ `Daemon: ${result.local.status}, observed ${result.local.updatedAt ?? "unknown"}; control-plane verified ${result.local.verifiedAt ?? "unknown"}`,
3162
+ table(
3163
+ ["NAME", "DESCRIPTION", "ROLE", "PIVOT", "PUBLIC KEY"],
3164
+ result.members.map((member) => [
3165
+ member.name,
3166
+ member.description,
3167
+ member.role,
3168
+ member.pivot ? (member.localStatus ?? "candidate") : "-",
3169
+ member.publicKey,
3170
+ ]),
3171
+ "No members.",
3172
+ ),
3173
+ ].join("\n"),
3174
+ );
3175
+ if (result.local.error)
3176
+ io.err(
3177
+ `Local Pivot observations (${result.local.status}): ${printable(result.local.error)}`,
2407
3178
  );
2408
- break;
2409
- }
2410
- if (
2411
- ["swarm exclude", "swarm resume", "swarm profile"].includes(
2412
- parsed.path,
2413
- )
2414
- ) {
2415
- const url = requireSwarm();
2416
- if (parsed.path === "swarm exclude") {
2417
- if (!parsed.options.yes)
2418
- syntax("Member removal is irreversible; --yes required.");
2419
- await removeMember(context, url, first!);
2420
- } else if (parsed.path === "swarm resume")
2421
- await resumeRemoval(context, url);
2422
- else {
2423
- const profile = await updateProfile(context, url, {
2424
- ...(typeof parsed.options.address === "string"
2425
- ? { addresses: [parsed.options.address] }
2426
- : {}),
2427
- ...(typeof parsed.options.pivot === "string"
2428
- ? {
2429
- pivot: Boolean(
2430
- parseValue("swarm.pivot", parsed.options.pivot, true),
2431
- ),
2432
- }
2433
- : {}),
2434
- });
2435
- emit(profile, JSON.stringify(profile));
2436
- store = context.store;
2437
- break;
2438
- }
2439
- store = context.store;
2440
- emit(
2441
- { url, completed: true },
2442
- `Organization switch complete: ${url}`,
3179
+ break;
3180
+ }
3181
+ case "swarm export": {
3182
+ const output =
3183
+ typeof parsed.options.output === "string"
3184
+ ? resolve(parsed.options.output)
3185
+ : "";
3186
+ const result = (await client.swarms.governance(
3187
+ "export",
3188
+ { swarm: requireSwarm(), output },
3189
+ { ndjson: true },
3190
+ )) as { member: string };
3191
+ emit({ member: result.member }, result.member);
3192
+ break;
3193
+ }
3194
+ case "swarm pivot grant": {
3195
+ const url = requireSwarm();
3196
+ if (!parsed.options.yes)
3197
+ syntax(
3198
+ "Granting Pivot HEAD receipt authority requires --yes; revoking it requires swarm exclude.",
2443
3199
  );
2444
- break;
2445
- }
2446
- if (parsed.path === "swarm update") {
2447
- const cid = requireSwarm();
2448
- const result = await updateSwarm(context, cid, {
3200
+ const result = (await client.swarms.governance(
3201
+ "pivot-grant",
3202
+ { swarm: url, member: first! },
3203
+ { ndjson: true },
3204
+ )) as Awaited<ReturnType<typeof grantPivotAuthority>>;
3205
+ emit(
3206
+ result,
3207
+ `Granted Pivot HEAD authority to ${result.member} on ${result.configUrl} (HEAD ${result.headId}). Revoking Pivot HEAD authority requires swarm exclude.`,
3208
+ );
3209
+ break;
3210
+ }
3211
+ case "swarm exclude": {
3212
+ const url = requireSwarm();
3213
+ if (!parsed.options.yes)
3214
+ syntax("Member removal is irreversible; --yes required.");
3215
+ await client.swarms.governance(
3216
+ "exclude",
3217
+ { swarm: url, member: first! },
3218
+ { ndjson: true },
3219
+ );
3220
+ emit({ url, completed: true }, `Organization switch complete: ${url}`);
3221
+ break;
3222
+ }
3223
+ case "swarm resume": {
3224
+ const url = requireSwarm();
3225
+ await client.swarms.governance(
3226
+ "resume",
3227
+ { swarm: url },
3228
+ { ndjson: true },
3229
+ );
3230
+ emit({ url, completed: true }, `Organization switch complete: ${url}`);
3231
+ break;
3232
+ }
3233
+ case "swarm profile": {
3234
+ const url = requireSwarm();
3235
+ const profile = await client.swarms.governance(
3236
+ "profile",
3237
+ {
3238
+ swarm: url,
3239
+ ...(typeof parsed.options.address === "string"
3240
+ ? { addresses: [parsed.options.address] }
3241
+ : {}),
3242
+ ...(typeof parsed.options.pivot === "string"
3243
+ ? {
3244
+ pivot: Boolean(
3245
+ parseValue("swarm.pivot", parsed.options.pivot, true),
3246
+ ),
3247
+ }
3248
+ : {}),
3249
+ },
3250
+ { ndjson: true },
3251
+ );
3252
+ emit(profile, JSON.stringify(profile));
3253
+ break;
3254
+ }
3255
+ case "swarm update": {
3256
+ const cid = requireSwarm();
3257
+ const result = (await client.swarms.update(
3258
+ {
3259
+ swarm: cid,
2449
3260
  ...(typeof parsed.options.name === "string"
2450
3261
  ? { name: parsed.options.name }
2451
3262
  : {}),
2452
3263
  ...(typeof parsed.options.description === "string"
2453
3264
  ? { description: parsed.options.description }
2454
3265
  : {}),
2455
- });
2456
- emit(
2457
- result,
2458
- `Swarm: ${result.configUrl}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD ID: ${result.headId}\nConfig content CID: ${result.valueCid}`,
2459
- );
2460
- break;
2461
- }
2462
- if (parsed.path === "search") {
2463
- const registrations = state.allSwarms();
2464
- const scope = parsed.options.all
2465
- ? registrations
2466
- : [
2467
- {
2468
- cid: requireSwarm(),
2469
- alias:
2470
- registrations.find((entry) => entry.cid === selectedSwarm)
2471
- ?.alias ?? null,
2472
- },
2473
- ];
2474
- const searchOptions: Parameters<typeof searchNames>[3] = {};
2475
- if (typeof parsed.options.prefix === "string")
2476
- searchOptions.prefix = parsed.options.prefix;
2477
- if (typeof parsed.options.kind === "string")
2478
- searchOptions.kind = parsed.options.kind as Exclude<
2479
- NonNullable<Parameters<typeof searchNames>[3]>["kind"],
2480
- undefined
2481
- >;
2482
- if (typeof parsed.options.schema === "string")
2483
- searchOptions.schemaCid = parsed.options.schema;
2484
- if (typeof parsed.options.limit === "string")
2485
- searchOptions.limit = /^\d+$/.test(parsed.options.limit)
2486
- ? Number(parsed.options.limit)
2487
- : Number.NaN;
2488
- if (typeof parsed.options.offset === "string")
2489
- searchOptions.offset = /^\d+$/.test(parsed.options.offset)
2490
- ? Number(parsed.options.offset)
2491
- : Number.NaN;
2492
- const result = Object.keys(searchOptions).length
2493
- ? await searchNames(context, first!, scope, searchOptions)
2494
- : await searchNames(context, first!, scope);
2495
- emit(result, formatSearchResults(result.matches));
2496
- break;
2497
- }
2498
- if (parsed.path === "swarm status") {
2499
- const cid = requireSwarm();
2500
- const status = await inspectSwarmStatus(
2501
- context,
2502
- cid,
2503
- Boolean(parsed.options.refresh || parsed.options.force),
2504
- );
2505
- store = context.store;
2506
- if (status.mode === "local") {
2507
- emit(
2508
- {
2509
- mode: "local",
2510
- configUrl: cid,
2511
- root: status.head.root,
2512
- valueCid: status.head.cid,
2513
- properties: {
2514
- name: status.config.name,
2515
- description: status.config.description,
2516
- },
2517
- local: status.local,
2518
- },
2519
- [
2520
- "Swarm",
2521
- " Mode: local (built-in single-machine Swarm)",
2522
- ` Name: ${printable(status.config.name)}`,
2523
- ` Description: ${printable(status.config.description)}`,
2524
- " Config URL:",
2525
- ` ${cid}`,
2526
- "",
2527
- "Content",
2528
- " HEAD (publication root):",
2529
- ` ${status.head.root}`,
2530
- " Content CID (HEAD value):",
2531
- ` ${status.head.cid}`,
2532
- ` Names: ${status.local.names} (Templates: ${status.local.templates}, Skills: ${status.local.skills}, Registrations: ${status.local.registrations})`,
2533
- ].join("\n"),
2534
- );
2535
- break;
2536
- }
2537
- const {
2538
- head,
2539
- config,
2540
- networking,
2541
- cache,
2542
- lastWriter,
2543
- state: contentState,
2544
- } = status;
2545
- const fingerprint = await keyId(config.owner);
2546
- emit(
2547
- {
2548
- configUrl: cid,
2549
- owner: config.owner,
2550
- ownerFingerprint: fingerprint,
2551
- epoch: config.epoch,
2552
- scopeId: config.scopeId,
2553
- headId: config.headId,
2554
- cache,
2555
- state: contentState,
2556
- networking,
2557
- root: head.root,
2558
- valueCid: head.cid,
2559
- lastWriter,
2560
- properties: {
2561
- name: config.name,
2562
- description: config.description,
2563
- },
2564
- },
2565
- [
2566
- "Swarm",
2567
- ` Directory: ${cache.source} (${cache.freshness}), observed ${cache.updatedAt}`,
2568
- ` Name: ${printable(config.name)}`,
2569
- ` Description: ${config.description ? printable(config.description) : "(none)"}`,
2570
- " Config URL:",
2571
- ` ${cid}`,
2572
- "",
2573
- "Identity",
2574
- " Owner fingerprint:",
2575
- ` ${fingerprint}`,
2576
- "",
2577
- "Content",
2578
- " HEAD (publication root):",
2579
- ` ${head.root}`,
2580
- " Content CID (HEAD value):",
2581
- ` ${head.cid}`,
2582
- ...(lastWriter
2583
- ? [
2584
- ` Last HEAD writer: ${lastWriter.name ? printable(lastWriter.name) : "(profile name unavailable)"}`,
2585
- ` Public key: ${lastWriter.subject}`,
2586
- ` PeerID: ${lastWriter.peerId ?? "unknown"}`,
2587
- ` Updated: ${lastWriter.updatedAt} (service time)`,
2588
- " Last writer is not a confirmed content holder or the only copy.",
2589
- ]
2590
- : [
2591
- " Last HEAD writer/time: unknown (legacy record or service without update metadata).",
2592
- ]),
2593
- ` State: ${contentState.status}. ${contentState.error}`,
2594
- "",
2595
- "Local networking",
2596
- ` Daemon observations: ${networking.daemon.status}`,
2597
- ` Updated: ${networking.daemon.updatedAt ?? "unknown"}`,
2598
- ` Control-plane verified: ${networking.daemon.verifiedAt ?? "unknown"}`,
2599
- ...(networking.daemon.error
2600
- ? [` Observation error: ${printable(networking.daemon.error)}`]
2601
- : []),
2602
- ` Connections observed: ${networking.connections.observedAt ?? "unknown"} (${networking.connections.freshness})`,
2603
- ...(networking.connections.error
2604
- ? [
2605
- ` Connection error: ${printable(networking.connections.error)}`,
2606
- ]
2607
- : []),
2608
- table(
2609
- [
2610
- "PIVOT PEER ID",
2611
- "LOCAL",
2612
- "PROBE",
2613
- "PROBED AT",
2614
- "FAILURES",
2615
- "RETRY AT",
2616
- "CONNECTION",
2617
- ],
2618
- networking.pivots.map((pivot) => [
2619
- pivot.peerId,
2620
- pivot.localStatus ?? "unknown",
2621
- `${pivot.probe.result} (${pivot.probe.freshness})`,
2622
- pivot.probe.at ?? "-",
2623
- pivot.failures === null ? "-" : String(pivot.failures),
2624
- pivot.retryAt ?? "-",
2625
- pivot.connection.status,
2626
- ]),
2627
- "No declared Pivots.",
2628
- ),
2629
- ...networking.pivots.flatMap((pivot) =>
2630
- pivot.probe.error
2631
- ? [
2632
- ` ${pivot.peerId} probe error: ${printable(pivot.probe.error)}`,
2633
- ]
2634
- : [],
2635
- ),
2636
- ...(networking.connections.error
2637
- ? []
2638
- : [
2639
- table(
2640
- ["CONNECTED PEER ID", "TRANSPORT", "ADDRESS"],
2641
- networking.connections.peers.map((peer) => [
2642
- peer.peerId,
2643
- peer.transport,
2644
- peer.address,
2645
- ]),
2646
- "No observed peer connections.",
2647
- ),
2648
- ]),
2649
- " Selected is configuration, not connection success. Relay connectivity does not guarantee content availability.",
2650
- ].join("\n"),
2651
- );
2652
- break;
2653
- }
2654
- if (parsed.path === "get") {
2655
- const localCid = /^(ipab|name):/i.test(first!)
2656
- ? undefined
2657
- : state.resolve(first!);
2658
- const builtin = builtins.pins.find((pin) => pin.cid === localCid);
2659
- const selected = builtin
2660
- ? { cid: builtin.cid, targetCid: builtin.cid }
2661
- : await resolveReference(
2662
- context,
2663
- first!,
2664
- selectedSwarm,
2665
- (reference) => state!.resolve(reference),
2666
- Boolean(parsed.options.raw),
2667
- "local-first",
2668
- );
2669
- const contentStore = context.store;
2670
- const source = IpfsStore.fromClient(
3266
+ },
3267
+ { ndjson: true },
3268
+ )) as Awaited<ReturnType<typeof updateSwarm>>;
3269
+ emit(
3270
+ result,
3271
+ `Swarm: ${result.configUrl}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD ID: ${result.headId}\nConfig content CID: ${result.valueCid}`,
3272
+ );
3273
+ break;
3274
+ }
3275
+ case "search": {
3276
+ const result = (await client.swarms.search(
3277
+ {
3278
+ ...(parsed.options.all
3279
+ ? { swarms: registeredSwarms.map((entry) => entry.cid) }
3280
+ : { swarm: requireSwarm() }),
3281
+ q: first!,
3282
+ ...(typeof parsed.options.prefix === "string"
3283
+ ? { prefix: parsed.options.prefix }
3284
+ : {}),
3285
+ ...(typeof parsed.options.kind === "string"
3286
+ ? {
3287
+ kind: parsed.options.kind as
3288
+ "all" | "bundle" | "dir" | "file",
3289
+ }
3290
+ : {}),
3291
+ ...(typeof parsed.options.schema === "string"
3292
+ ? { schemaCid: parsed.options.schema }
3293
+ : {}),
3294
+ ...(typeof parsed.options.limit === "string"
3295
+ ? { limit: parsed.options.limit }
3296
+ : {}),
3297
+ ...(typeof parsed.options.offset === "string"
3298
+ ? { offset: parsed.options.offset }
3299
+ : {}),
3300
+ refresh: explicitRefresh,
3301
+ },
3302
+ { ndjson: true },
3303
+ )) as Awaited<ReturnType<typeof searchNames>>;
3304
+ emit(result, formatSearchResults(result.matches));
3305
+ break;
3306
+ }
3307
+ case "swarm status": {
3308
+ const { keyId } = await import("@ipab/bundle/pointer/crypto");
3309
+ const cid = requireSwarm();
3310
+ const status = (await client.swarms.status(
3311
+ {
3312
+ swarm: cid,
3313
+ refresh: Boolean(parsed.options.refresh || parsed.options.force),
3314
+ },
3315
+ { ndjson: true },
3316
+ )) as Awaited<ReturnType<typeof inspectSwarmStatus>>;
3317
+ if (status.mode === "local") {
3318
+ emit(
2671
3319
  {
2672
- block: {
2673
- get: (key, options) => {
2674
- options?.signal?.throwIfAborted();
2675
- const builtin = builtins.blocks.get(
2676
- CID.parse(key).toV1().toString(),
2677
- );
2678
- return builtin
2679
- ? Promise.resolve(builtin.slice())
2680
- : contentStore.block.get(key, options);
2681
- },
3320
+ mode: "local",
3321
+ configUrl: cid,
3322
+ root: status.head.root,
3323
+ valueCid: status.head.cid,
3324
+ properties: {
3325
+ name: status.config.name,
3326
+ description: status.config.description,
2682
3327
  },
3328
+ local: status.local,
2683
3329
  },
2684
- contentStore.limits,
3330
+ [
3331
+ "Swarm",
3332
+ " Mode: local (built-in single-machine Swarm)",
3333
+ ` Name: ${printable(status.config.name)}`,
3334
+ ` Description: ${printable(status.config.description)}`,
3335
+ " Config URL:",
3336
+ ` ${cid}`,
3337
+ "",
3338
+ "Content",
3339
+ " HEAD (publication root):",
3340
+ ` ${status.head.root}`,
3341
+ " Content CID (HEAD value):",
3342
+ ` ${status.head.cid}`,
3343
+ ` Names: ${status.local.names} (Templates: ${status.local.templates}, Skills: ${status.local.skills} [global: ${status.local.globalSkills}, types: ${status.local.typeSkills}], Registrations: ${status.local.registrations})`,
3344
+ ].join("\n"),
2685
3345
  );
2686
- let directory: string;
2687
- try {
2688
- directory = await getBundle(
2689
- source,
2690
- selected.cid,
2691
- typeof parsed.options.output === "string"
2692
- ? parsed.options.output
2693
- : undefined,
2694
- );
2695
- } finally {
2696
- await source.close();
2697
- }
2698
- try {
2699
- await context.finishRead?.();
2700
- } finally {
2701
- readContext = undefined;
2702
- }
2703
- const closing = store;
2704
- store = undefined;
2705
- await closeStore(closing, undefined);
2706
- state.close();
2707
- state = undefined;
2708
- emit({ ...selected, directory }, directory);
2709
3346
  break;
2710
3347
  }
2711
- let cid: string;
2712
- let contentCid: string | undefined;
2713
- if (parsed.path === "swarm create") {
2714
- cid = await createSwarm(context, {
3348
+ const {
3349
+ head,
3350
+ config,
3351
+ networking,
3352
+ cache,
3353
+ lastWriter,
3354
+ state: contentState,
3355
+ } = status;
3356
+ const fingerprint = await keyId(config.owner);
3357
+ emit(
3358
+ {
3359
+ configUrl: cid,
3360
+ owner: config.owner,
3361
+ ownerFingerprint: fingerprint,
3362
+ epoch: config.epoch,
3363
+ scopeId: config.scopeId,
3364
+ headId: config.headId,
3365
+ cache,
3366
+ state: contentState,
3367
+ networking,
3368
+ root: head.root,
3369
+ valueCid: head.cid,
3370
+ lastWriter,
3371
+ properties: {
3372
+ name: config.name,
3373
+ description: config.description,
3374
+ },
3375
+ },
3376
+ [
3377
+ "Swarm",
3378
+ ` Directory: ${cache.source} (${cache.freshness}), observed ${cache.updatedAt}`,
3379
+ ` Name: ${printable(config.name)}`,
3380
+ ` Description: ${config.description ? printable(config.description) : "(none)"}`,
3381
+ " Config URL:",
3382
+ ` ${cid}`,
3383
+ "",
3384
+ "Identity",
3385
+ " Owner fingerprint:",
3386
+ ` ${fingerprint}`,
3387
+ "",
3388
+ "Content",
3389
+ " HEAD (publication root):",
3390
+ ` ${head.root}`,
3391
+ " Content CID (HEAD value):",
3392
+ ` ${head.cid}`,
3393
+ ...(lastWriter
3394
+ ? [
3395
+ ` Last HEAD writer: ${lastWriter.name ? printable(lastWriter.name) : "(profile name unavailable)"}`,
3396
+ ` Public key: ${lastWriter.subject}`,
3397
+ ` PeerID: ${lastWriter.peerId ?? "unknown"}`,
3398
+ ` Updated: ${lastWriter.updatedAt} (service time)`,
3399
+ " Last writer is not a confirmed content holder or the only copy.",
3400
+ ]
3401
+ : [
3402
+ " Last HEAD writer/time: unknown (legacy record or service without update metadata).",
3403
+ ]),
3404
+ ` State: ${contentState.status}. ${contentState.error}`,
3405
+ "",
3406
+ "Local networking",
3407
+ ` Daemon observations: ${networking.daemon.status}`,
3408
+ ` Updated: ${networking.daemon.updatedAt ?? "unknown"}`,
3409
+ ` Control-plane verified: ${networking.daemon.verifiedAt ?? "unknown"}`,
3410
+ ...(networking.daemon.error
3411
+ ? [` Observation error: ${printable(networking.daemon.error)}`]
3412
+ : []),
3413
+ ` Connections observed: ${networking.connections.observedAt ?? "unknown"} (${networking.connections.freshness})`,
3414
+ ...(networking.connections.error
3415
+ ? [
3416
+ ` Connection error: ${printable(networking.connections.error)}`,
3417
+ ]
3418
+ : []),
3419
+ table(
3420
+ [
3421
+ "PIVOT PEER ID",
3422
+ "LOCAL",
3423
+ "PROBE",
3424
+ "PROBED AT",
3425
+ "FAILURES",
3426
+ "RETRY AT",
3427
+ "CONNECTION",
3428
+ "READINESS",
3429
+ ],
3430
+ networking.pivots.map((pivot) => [
3431
+ pivot.peerId,
3432
+ pivot.localStatus ?? "unknown",
3433
+ `${pivot.probe.result} (${pivot.probe.freshness})`,
3434
+ pivot.probe.at ?? "-",
3435
+ pivot.failures === null ? "-" : String(pivot.failures),
3436
+ pivot.retryAt ?? "-",
3437
+ pivot.connection.status,
3438
+ pivot.readiness.status,
3439
+ ]),
3440
+ "No declared Pivots.",
3441
+ ),
3442
+ ...networking.pivots.flatMap((pivot) =>
3443
+ pivot.probe.error
3444
+ ? [
3445
+ ` ${pivot.peerId} probe error: ${printable(pivot.probe.error)}`,
3446
+ ]
3447
+ : [],
3448
+ ),
3449
+ ...(networking.connections.error
3450
+ ? []
3451
+ : [
3452
+ table(
3453
+ ["CONNECTED PEER ID", "TRANSPORT", "ADDRESS"],
3454
+ networking.connections.peers.map((peer) => [
3455
+ peer.peerId,
3456
+ peer.transport,
3457
+ peer.address,
3458
+ ]),
3459
+ "No observed peer connections.",
3460
+ ),
3461
+ ]),
3462
+ " Selected is configuration, not connection success. Relay connectivity does not guarantee content availability.",
3463
+ ].join("\n"),
3464
+ );
3465
+ break;
3466
+ }
3467
+ case "get": {
3468
+ const destination =
3469
+ typeof parsed.options.output === "string"
3470
+ ? resolve(parsed.options.output)
3471
+ : undefined;
3472
+ const result = (await client.store.export(
3473
+ {
3474
+ mode: "get",
3475
+ ref: first!,
3476
+ ...(destination !== undefined ? { destination } : {}),
3477
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3478
+ raw: Boolean(parsed.options.raw),
3479
+ ...(explicitRefresh !== undefined
3480
+ ? { refresh: explicitRefresh }
3481
+ : {}),
3482
+ },
3483
+ { ndjson: true },
3484
+ )) as unknown as Record<string, unknown> & { directory: string };
3485
+ const payload = { ...result };
3486
+ delete payload.destination;
3487
+ const closing = cliHandle;
3488
+ cliHandle = undefined;
3489
+ await closing.close();
3490
+ emit(payload, result.directory);
3491
+ break;
3492
+ }
3493
+ case "swarm create": {
3494
+ const created = (await client.swarms.governance(
3495
+ "create",
3496
+ {
2715
3497
  ...(typeof parsed.options.service === "string"
2716
3498
  ? { service: parsed.options.service }
2717
3499
  : {}),
2718
3500
  ...(typeof parsed.options.resume === "string"
2719
3501
  ? { resume: parsed.options.resume }
2720
3502
  : {}),
2721
- properties: {
2722
- name: String(parsed.options.name ?? ""),
2723
- description: String(parsed.options.description ?? ""),
2724
- },
3503
+ name: String(parsed.options.name ?? ""),
3504
+ description: String(parsed.options.description ?? ""),
2725
3505
  ...(typeof parsed.options.alias === "string"
2726
3506
  ? { alias: parsed.options.alias }
2727
3507
  : {}),
2728
- });
2729
- } else if (parsed.path === "swarm request") {
2730
- const result = await requestMembership(
2731
- context,
2732
- state.resolveSwarm(first!),
2733
- {
2734
- ...(typeof parsed.options.output === "string"
2735
- ? { output: parsed.options.output }
2736
- : {}),
2737
- ...(parsed.options.pivot ? { role: "pivot" as const } : {}),
2738
- },
3508
+ },
3509
+ { ndjson: true },
3510
+ )) as {
3511
+ configUrl: string;
3512
+ alias: string | null;
3513
+ savedCurrent: string | null;
3514
+ };
3515
+ io.err(
3516
+ `Registered swarm ${created.alias ?? created.configUrl}. Saved current: ${created.savedCurrent ?? "(none)"}.`,
3517
+ );
3518
+ io.err(
3519
+ "Pivot replication is not yet confirmed. Keep this member online until a Pivot is ready; daemon will replicate automatically. Manual retry: ipab swarm replicate. Inspect readiness with ipab swarm status.",
3520
+ );
3521
+ emit({ configUrl: created.configUrl }, created.configUrl);
3522
+ break;
3523
+ }
3524
+ case "swarm request": {
3525
+ const output =
3526
+ typeof parsed.options.output === "string"
3527
+ ? parsed.options.output
3528
+ : undefined;
3529
+ const result = (await client.swarms.governance(
3530
+ "request",
3531
+ {
3532
+ swarm: first!,
3533
+ ...(output !== undefined ? { output, cwd: process.cwd() } : {}),
3534
+ ...(parsed.options.pivot ? { role: "pivot" } : {}),
3535
+ },
3536
+ { ndjson: true },
3537
+ )) as Awaited<ReturnType<typeof requestMembership>>;
3538
+ io.err(
3539
+ `Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`,
3540
+ );
3541
+ if (result.file === undefined)
3542
+ io.out(JSON.stringify(result.request, null, 2));
3543
+ else {
3544
+ io.err(`Request saved to: ${result.file}`);
3545
+ if (parsed.flags.json)
3546
+ emit(
3547
+ {
3548
+ file: result.file,
3549
+ member: result.request.member,
3550
+ ownerFingerprint: result.ownerFingerprint,
3551
+ },
3552
+ "",
3553
+ );
3554
+ }
3555
+ break;
3556
+ }
3557
+ case "swarm approve": {
3558
+ const {
3559
+ verifiedRequest,
3560
+ verifiedRequestStream,
3561
+ membershipRequestSummary,
3562
+ } = await import("./swarm.js");
3563
+ const selected = requireSwarm();
3564
+ if (isLocalSwarm(selected))
3565
+ throw new HostError(
3566
+ `The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support swarm approve.`,
2739
3567
  );
2740
- store = context.store;
2741
- io.err(
2742
- `Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`,
3568
+ if (first === "-" && !parsed.options.yes)
3569
+ syntax(
3570
+ "Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.",
2743
3571
  );
2744
- if (result.file === undefined)
2745
- io.out(JSON.stringify(result.request, null, 2));
2746
- else {
2747
- io.err(`Request saved to: ${result.file}`);
2748
- if (parsed.flags.json)
2749
- emit(
2750
- {
2751
- file: result.file,
2752
- member: result.request.member,
2753
- ownerFingerprint: result.ownerFingerprint,
2754
- },
2755
- "",
2756
- );
2757
- }
2758
- break;
2759
- } else if (parsed.path === "swarm approve") {
2760
- const selected = requireSwarm();
2761
- if (isLocalSwarm(selected))
2762
- throw new HostError(
2763
- `The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support swarm approve.`,
2764
- );
2765
- if (first === "-" && !parsed.options.yes)
2766
- syntax(
2767
- "Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.",
2768
- );
2769
- const request =
2770
- first === "-"
2771
- ? await verifiedRequestStream(
2772
- (io.requestInput ?? processIO.requestInput!)(),
2773
- )
2774
- : await verifiedRequest(first!);
2775
- if (request.configUrl !== selected)
2776
- syntax(
2777
- `Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`,
2778
- );
2779
- io.err(await membershipRequestSummary(request));
2780
- if (
2781
- !parsed.options.yes &&
2782
- (!io.tty ||
2783
- !(await io.confirm(
2784
- `Approve the verified ${parsed.options.pivot || request.role === "pivot" ? "pivot" : "ordinary"} Request from ${request.member} above? This grants ${parsed.options.pivot || request.role === "pivot" ? "current HEAD and " : ""}the member's profile write access; all reads are public.`,
2785
- )))
2786
- )
2787
- throw new HostError(
2788
- "Approval requires explicit --yes or interactive confirmation.",
2789
- );
2790
- cid = await approveMembership(context, request, {
3572
+ const request =
3573
+ first === "-"
3574
+ ? await verifiedRequestStream(
3575
+ (io.requestInput ?? processIO.requestInput!)(),
3576
+ )
3577
+ : await verifiedRequest(resolve(first!));
3578
+ if (request.configUrl !== selected)
3579
+ syntax(
3580
+ `Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`,
3581
+ );
3582
+ io.err(await membershipRequestSummary(request));
3583
+ if (
3584
+ !parsed.options.yes &&
3585
+ (!io.tty ||
3586
+ !(await io.confirm(
3587
+ `Approve the verified ${parsed.options.pivot || request.role === "pivot" ? "pivot" : "ordinary"} Request from ${request.member} above? This grants ${parsed.options.pivot || request.role === "pivot" ? "current HEAD and " : ""}the member's profile write access; all reads are public.`,
3588
+ )))
3589
+ )
3590
+ throw new HostError(
3591
+ "Approval requires explicit --yes or interactive confirmation.",
3592
+ );
3593
+ const result = (await client.swarms.governance(
3594
+ "approve",
3595
+ {
3596
+ request,
2791
3597
  again: Boolean(parsed.options.again),
2792
3598
  pivot: Boolean(parsed.options.pivot),
2793
- });
2794
- } else {
2795
- const content = await publicationSource(second!, store);
2796
- contentCid = content;
2797
- cid = await publish(context, content, {
2798
- ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3599
+ },
3600
+ { ndjson: true },
3601
+ )) as { approved: string };
3602
+ emit({ configUrl: result.approved }, result.approved);
3603
+ break;
3604
+ }
3605
+ case "publish": {
3606
+ const named = parseNameReference(first!);
3607
+ const targetSwarm = named?.swarm
3608
+ ? resolveSwarm(named.swarm)
3609
+ : requireSwarm();
3610
+ const source = await resolveLocalPathIfPresent(second!);
3611
+ const result = (await client.swarms.fsSet(
3612
+ {
3613
+ swarm: targetSwarm,
3614
+ kind: "publish",
2799
3615
  name: first!,
3616
+ source,
2800
3617
  ...(typeof parsed.options.expect === "string"
2801
3618
  ? { expect: parsed.options.expect }
2802
3619
  : {}),
2803
3620
  snapshot: Boolean(parsed.options.snapshot),
2804
- });
2805
- }
2806
- store = context.store;
2807
- if (parsed.path === "swarm create")
2808
- io.err(
2809
- `Registered swarm ${state.registeredSwarm(cid).alias ?? cid}. Saved current: ${state.config({ includeSecrets: false })["swarm.default"] ?? "(none)"}.`,
2810
- );
2811
- if (contentCid)
2812
- io.err(
2813
- `Locally protected payload: ${contentCid}. Use ipab unpin ${contentCid} to release this CID pin only; Name subscriptions and publication/history owners remain. --snapshot links payloads directly into retained publication history, so unpin cannot release that protection.`,
2814
- );
3621
+ },
3622
+ { ndjson: true },
3623
+ )) as unknown as { cid: string; contentCid: string };
3624
+ io.err(
3625
+ `Locally protected payload: ${result.contentCid}. Use ipab unpin ${result.contentCid} to release this CID pin only; Name subscriptions and publication/history owners remain. --snapshot links payloads directly into retained publication history, so unpin cannot release that protection.`,
3626
+ );
3627
+ emit(result, result.cid);
3628
+ break;
3629
+ }
3630
+ case "store usage": {
3631
+ const result = await client.store.usage();
2815
3632
  emit(
2816
- parsed.path === "swarm create" || parsed.path === "swarm approve"
2817
- ? { configUrl: cid }
2818
- : { cid, ...(contentCid ? { contentCid } : {}) },
2819
- cid,
3633
+ result,
3634
+ `Cached blocks: ${storageBytes(result.cachedBytes)}\nPinned blocks (deduplicated): ${storageBytes(result.pinnedBytes)}`,
2820
3635
  );
2821
3636
  break;
2822
3637
  }
2823
- case "store usage":
2824
3638
  case "store gc": {
2825
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2826
- if (parsed.path === "store usage") {
2827
- const result = await store.usage();
2828
- emit(
2829
- result,
2830
- `Cached blocks: ${storageBytes(result.cachedBytes)}\nPinned blocks (deduplicated): ${storageBytes(result.pinnedBytes)}`,
2831
- );
2832
- } else {
2833
- const result = await store.gc();
2834
- emit(
2835
- result,
2836
- `Removed ${result.removedBlocks} blocks; reclaimed ${storageBytes(result.reclaimedBytes)}.`,
2837
- );
2838
- }
3639
+ const result = await client.store.gc({ ndjson: true });
3640
+ emit(
3641
+ result,
3642
+ `Removed ${result.removedBlocks} blocks; reclaimed ${storageBytes(result.reclaimedBytes)}.`,
3643
+ );
2839
3644
  break;
2840
3645
  }
2841
3646
  case "templates render":
@@ -2843,6 +3648,7 @@ async function performCli(
2843
3648
  case "bundle build":
2844
3649
  case "bundle inspect":
2845
3650
  case "bundle import": {
3651
+ const { message } = await import("./errors.js");
2846
3652
  const controller = new AbortController();
2847
3653
  let cancelled = 0;
2848
3654
  const interrupt = () => {
@@ -2856,188 +3662,131 @@ async function performCli(
2856
3662
  process.once("SIGINT", interrupt);
2857
3663
  process.once("SIGTERM", terminate);
2858
3664
  try {
2859
- let pendingStore: Promise<IpfsStore> | undefined;
2860
- const getStore = () => {
2861
- pendingStore ??= storeConfiguration(value("store.gateway")).then(
2862
- (configuration) => {
2863
- store = new IpfsStore(configuration);
2864
- return store;
2865
- },
2866
- );
2867
- return pendingStore;
2868
- };
2869
- const request = {
2870
- signal: controller.signal,
2871
- diagnostic: (text: string) => {
2872
- io.err(text);
2873
- },
2874
- resolveCid: async (cid: CID, options: { signal?: AbortSignal }) => {
2875
- options.signal?.throwIfAborted();
2876
- const builtin = builtins.blocks.get(cid.toV1().toString());
2877
- if (builtin) return builtin.slice();
2878
- return (store ?? (await getStore())).block.get(
2879
- cid.toString(),
2880
- options,
2881
- );
2882
- },
2883
- };
2884
- const builtinSource = first ? state.pin(first) : undefined;
2885
- const source =
2886
- builtinSource?.builtin && builtinSource.metadata?.kind === "bundle"
2887
- ? builtinSource.cid
2888
- : first;
2889
- let selectedTemplate: string | undefined;
3665
+ const requestOpts = { signal: controller.signal, ndjson: true };
3666
+ const outputOpt =
3667
+ typeof parsed.options.output === "string"
3668
+ ? resolve(parsed.options.output)
3669
+ : undefined;
3670
+ const outputDirOpt = String(value("bundle.outputDir"));
3671
+ let result: Record<string, unknown>;
2890
3672
  if (parsed.path === "templates render") {
2891
- const selector = first!;
2892
- selectedTemplate = selector;
2893
- if (parseNameReference(selector)) {
2894
- await getStore();
2895
- const context = swarmContext();
2896
- readContext = context;
2897
- selectedTemplate = (
2898
- await resolveReference(
2899
- context,
2900
- selector,
2901
- selectedSwarm,
2902
- (reference) => state!.resolve(reference),
2903
- false,
2904
- "local-first",
2905
- )
2906
- ).cid;
2907
- store = context.store;
2908
- } else {
2909
- let explicit = false;
2910
- try {
2911
- CID.parse(selector);
2912
- explicit = true;
2913
- } catch {
2914
- /* Not a CID. */
2915
- }
2916
- explicit ||= selector.toLowerCase().endsWith(".car");
2917
- if (!explicit) {
2918
- try {
2919
- await lstat(selector);
2920
- explicit = true;
2921
- } catch (cause) {
2922
- if (
2923
- !nodeError(cause, "ENOENT") &&
2924
- !nodeError(cause, "ENOTDIR")
2925
- )
2926
- throw cause;
2927
- }
2928
- }
2929
- if (!explicit) {
2930
- templateName(selector);
2931
- if (!selectedSwarm)
2932
- throw new HostError(
2933
- "Template selectors require a selected Swarm. Use --swarm or swarm use, or supply an explicit Bundle directory, CAR, exact CID or IPAB URI.",
2934
- );
2935
- await getStore();
2936
- const context = swarmContext();
2937
- readContext = context;
2938
- selectedTemplate = await resolveTemplateSelector(
2939
- context,
2940
- selector,
2941
- selectedSwarm,
2942
- );
2943
- store = context.store;
2944
- }
2945
- }
2946
- }
2947
- if (parsed.path === "bundle build" || parsed.path === "build")
2948
- io.err(
2949
- parsed.path === "build"
2950
- ? "Assembling and validating Bundle (no compilation)..."
2951
- : "Validating and building bundle...",
3673
+ const template = await resolveLocalPathIfPresent(first!);
3674
+ const destination = resolve(parsed.positional[2] ?? second!);
3675
+ const parameters = [
3676
+ ...(parsed.parameters ?? []),
3677
+ ...(typeof parsed.options.description === "string"
3678
+ ? [`description=${parsed.options.description}`]
3679
+ : []),
3680
+ ];
3681
+ result = await client.store.export(
3682
+ {
3683
+ mode: "render-template",
3684
+ template,
3685
+ name: second!,
3686
+ destination,
3687
+ parameters,
3688
+ swarm: selectedSwarm,
3689
+ refresh: explicitRefresh,
3690
+ },
3691
+ requestOpts,
2952
3692
  );
2953
- if (parsed.path === "bundle import")
2954
- io.err("Validating and importing CAR into Store...");
2955
- const result =
2956
- parsed.path === "templates render"
2957
- ? await initApp(second!, parsed.positional[2], {
2958
- ...request,
2959
- ...(selectedTemplate ? { template: selectedTemplate } : {}),
2960
- parameters: [
2961
- ...(parsed.parameters ?? []),
2962
- ...(typeof parsed.options.description === "string"
2963
- ? [`description=${parsed.options.description}`]
2964
- : []),
2965
- ],
2966
- })
2967
- : parsed.path === "build"
2968
- ? await assembleBundle(first, {
2969
- ...request,
2970
- replace: Boolean(parsed.options.replace),
2971
- ...(typeof parsed.options.output === "string"
2972
- ? { output: parsed.options.output }
2973
- : {}),
2974
- outputDir: String(value("bundle.outputDir")),
2975
- })
2976
- : parsed.path === "bundle build"
2977
- ? await buildBundle(source!, {
2978
- ...request,
2979
- schemaOnly: Boolean(parsed.options["schema-only"]),
2980
- replace: Boolean(parsed.options.replace),
2981
- ...(typeof parsed.options.output === "string"
2982
- ? { output: parsed.options.output }
2983
- : {}),
2984
- outputDir: String(value("bundle.outputDir")),
2985
- })
2986
- : parsed.path === "bundle import"
2987
- ? await importBundle(first!, getStore, request)
2988
- : await inspectBundle(source!, request);
2989
- const importing = "output" in result && !parsed.options["no-import"];
2990
- if (importing) {
2991
- io.err("Importing build result into Store (without pinning)...");
2992
- try {
2993
- await importBundle(result.output, getStore, request);
2994
- } catch (cause) {
2995
- throw new HostError(
2996
- `${message(cause)} CAR remains at ${JSON.stringify(result.output)}; retry with ipab bundle import ${JSON.stringify(result.output)}, or build with --no-import.`,
2997
- 1,
2998
- "IMPORT_FAILED",
2999
- "authoring",
3000
- );
3001
- }
3693
+ } else if (parsed.path === "build") {
3694
+ const sourcePath = first ? resolve(first) : process.cwd();
3695
+ result = (await client.store.import(
3696
+ {
3697
+ mode: "assemble",
3698
+ path: sourcePath,
3699
+ replace: Boolean(parsed.options.replace),
3700
+ output: outputOpt,
3701
+ outputDir: outputDirOpt,
3702
+ autoImport: !parsed.options["no-import"],
3703
+ },
3704
+ requestOpts,
3705
+ )) as Record<string, unknown>;
3706
+ } else if (parsed.path === "bundle build") {
3707
+ const sourcePath = await resolveLocalPathIfPresent(first!);
3708
+ result = (await client.store.import(
3709
+ {
3710
+ mode: "build",
3711
+ path: sourcePath,
3712
+ schemaOnly: Boolean(parsed.options["schema-only"]),
3713
+ replace: Boolean(parsed.options.replace),
3714
+ output: outputOpt,
3715
+ outputDir: outputDirOpt,
3716
+ autoImport: !parsed.options["no-import"],
3717
+ },
3718
+ requestOpts,
3719
+ )) as Record<string, unknown>;
3720
+ } else if (parsed.path === "bundle import") {
3721
+ const sourcePath = resolve(first!);
3722
+ result = (await client.store.import(
3723
+ { mode: "car", path: sourcePath },
3724
+ requestOpts,
3725
+ )) as Record<string, unknown>;
3726
+ } else {
3727
+ const sourceRef = await resolveLocalPathIfPresent(first!);
3728
+ result = (await client.store.inspect(
3729
+ {
3730
+ ref: sourceRef,
3731
+ swarm: selectedSwarm,
3732
+ },
3733
+ requestOpts,
3734
+ )) as Record<string, unknown>;
3002
3735
  }
3003
- const closing = store;
3004
- store = undefined;
3005
- await closeStore(closing, undefined);
3006
- state.close();
3007
- state = undefined;
3736
+
3008
3737
  controller.signal.throwIfAborted();
3009
- if ("output" in result)
3738
+
3739
+ if ("output" in result) {
3740
+ const importing = Boolean(result.imported);
3741
+ const validation = result.validation as
3742
+ { status?: string } | null | undefined;
3010
3743
  emit(
3011
- { ...result, imported: importing },
3012
- `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${result.validation !== undefined ? `\nEntry validation: ${result.validation?.status ?? "not-applicable"}` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`,
3744
+ result,
3745
+ `CID: ${String(result.cid)}\nSchema CID: ${String(result.schemaCid)}\nCAR: ${String(result.output)}${validation !== undefined ? `\nEntry validation: ${validation?.status ?? "not-applicable"}` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`,
3013
3746
  );
3014
- else if (result.kind === "bundle-import")
3747
+ } else if (result.kind === "bundle-import") {
3748
+ const source = String(result.source);
3749
+ const validation = result.validation as
3750
+ { status?: string } | null | undefined;
3015
3751
  emit(
3016
3752
  result,
3017
- `Imported CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nBlocks: ${result.blocks}\nCAR: ${result.source}\nEntry validation: ${result.validation?.status ?? "not-applicable"}`,
3753
+ `Imported CID: ${String(result.cid)}\nSchema CID: ${String(result.schemaCid)}\nBlocks: ${String(result.blocks)}\n${source.toLowerCase().endsWith(".car") ? "CAR" : "Source"}: ${source}\nEntry validation: ${validation?.status ?? "not-applicable"}`,
3018
3754
  );
3019
- else if (result.kind === "project-init") {
3755
+ } else if (result.kind === "project-init") {
3756
+ const directory = String(result.directory);
3757
+ const files = Array.isArray(result.files)
3758
+ ? (result.files as string[])
3759
+ : [];
3760
+ const templateCid =
3761
+ typeof result.templateCid === "string"
3762
+ ? result.templateCid
3763
+ : undefined;
3020
3764
  emit(
3021
3765
  result,
3022
- `Created project: ${result.directory}${result.templateCid ? `\nTemplate CID: ${result.templateCid}` : ""}`,
3766
+ `Created project: ${directory}${templateCid ? `\nTemplate CID: ${templateCid}` : ""}`,
3023
3767
  );
3024
3768
  if (
3025
- result.files.includes("package.json") &&
3026
- (result.files.includes("ipab.yaml") ||
3027
- result.files.includes("ipab.json"))
3769
+ files.includes("package.json") &&
3770
+ (files.includes("ipab.yaml") || files.includes("ipab.json"))
3028
3771
  )
3029
3772
  io.err(
3030
- `Next: install declared dependencies in ${JSON.stringify(result.directory)}; if your template does not declare @ipab/cli, add or link it as a development dependency. Run pnpm build to prepare and package the App. Root ipab build does not compile.`,
3031
- );
3032
- else if (result.files.includes(".bundle.yaml"))
3033
- io.err(
3034
- `Next: ipab bundle build ${JSON.stringify(result.directory)}`,
3773
+ `Next: install declared dependencies in ${JSON.stringify(directory)}; if your template does not declare @ipab/cli, add or link it as a development dependency. Run pnpm build to prepare and package the App. Root ipab build does not compile.`,
3035
3774
  );
3036
- } else
3775
+ else if (files.includes(".bundle.yaml"))
3776
+ io.err(`Next: ipab bundle build ${JSON.stringify(directory)}`);
3777
+ } else {
3778
+ const manifest = result.manifest as
3779
+ { title: string; entry: string; type: string } | undefined;
3780
+ const type = result.type as { contentType: string };
3781
+ const validation = result.validation as {
3782
+ storage: string;
3783
+ entry?: { status: string } | null;
3784
+ };
3037
3785
  emit(
3038
3786
  result,
3039
- `Kind: ${result.kind}\n${result.manifest ? `Title: ${printable(result.manifest.title)}\nEntry: ${result.manifest.entry}\nType file: ${result.manifest.type}\n` : ""}Type CID: ${result.schemaCid}\nContent type: ${result.type.contentType}\nDefinition validation: passed\nStorage verification: ${result.validation.storage}\nEntry validation: ${result.validation.entry?.status ?? "not-applicable"}`,
3787
+ `Kind: ${String(result.kind)}\n${manifest ? `Title: ${printable(manifest.title)}\nEntry: ${manifest.entry}\nType file: ${manifest.type}\n` : ""}Type CID: ${String(result.schemaCid)}\nContent type: ${type.contentType}\nDefinition validation: passed\nStorage verification: ${validation.storage}\nEntry validation: ${validation.entry?.status ?? "not-applicable"}`,
3040
3788
  );
3789
+ }
3041
3790
  } catch (cause) {
3042
3791
  if (cancelled)
3043
3792
  throw new HostError(
@@ -3054,27 +3803,29 @@ async function performCli(
3054
3803
  break;
3055
3804
  }
3056
3805
  case "pin list": {
3057
- const listed = state.contentPins();
3058
- const archived = state.archivedPins();
3059
- const builtins = state.pins().map(pinDetails);
3806
+ const listed = await client.store.listPins();
3060
3807
  emit(
3061
- { items: listed, builtins, archived },
3808
+ {
3809
+ items: listed.pins,
3810
+ builtins: listed.builtins,
3811
+ archived: listed.archived,
3812
+ },
3062
3813
  table(
3063
3814
  ["REFERENCE", "CID", "STATUS", "SOURCE"],
3064
3815
  [
3065
- ...listed.map((pin) => [
3816
+ ...listed.pins.map((pin) => [
3066
3817
  pin.reference,
3067
3818
  pin.cid ?? "(none)",
3068
3819
  `${pin.status}/${pin.freshness}${pin.error ? `: ${pin.error}` : ""}`,
3069
3820
  pin.swarm ? "following shared Name" : "fixed CID",
3070
3821
  ]),
3071
- ...builtins.map((pin) => [
3072
- pin.name,
3073
- pin.cid,
3822
+ ...listed.builtins.map((pin) => [
3823
+ String(pin.name),
3824
+ String(pin.cid),
3074
3825
  "read-only",
3075
3826
  "built-in",
3076
3827
  ]),
3077
- ...archived.map((pin) => [
3828
+ ...listed.archived.map((pin) => [
3078
3829
  pin.cid,
3079
3830
  pin.cid,
3080
3831
  pin.status,
@@ -3087,47 +3838,27 @@ async function performCli(
3087
3838
  break;
3088
3839
  }
3089
3840
  case "unpin": {
3090
- const canonical = pinReference(state, first!, selectedSwarm);
3091
- const result = await unpin(state, canonical.reference);
3841
+ const result = await client.store.removePin(first!, {
3842
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3843
+ });
3092
3844
  emit(
3093
3845
  result,
3094
- `Unpinned ${canonical.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`,
3846
+ `Unpinned ${result.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`,
3095
3847
  );
3096
3848
  break;
3097
3849
  }
3098
3850
  case "pin show": {
3099
- const builtin = first!.startsWith("builtin:")
3100
- ? state.pin(first!)
3101
- : undefined;
3102
- const canonical = builtin
3103
- ? undefined
3104
- : pinReference(state, first!, selectedSwarm);
3105
- const pin = canonical
3106
- ? state.contentPin(canonical.reference)
3107
- : undefined;
3108
- const archived = canonical
3109
- ? state
3110
- .archivedPins()
3111
- .filter((pin) => pin.cid === canonical.reference)
3112
- : [];
3113
- if (!pin && !builtin && !archived.length)
3114
- throw new HostError(
3115
- `Pin "${first}" does not exist. Run ipab pin list.`,
3116
- );
3117
- const result = builtin
3118
- ? pinDetails(builtin)
3119
- : {
3120
- pin: pin ?? null,
3121
- roots: pin ? state.hold(pin.owner)?.roots : [],
3122
- archived,
3123
- };
3851
+ const result = await client.store.getPin(first!, {
3852
+ details: true,
3853
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3854
+ });
3124
3855
  emit(result, JSON.stringify(result, null, 2));
3125
3856
  break;
3126
3857
  }
3127
3858
  case "config get": {
3128
- const selected = (
3129
- first ? items.filter((item) => item.key === first) : items
3130
- ).map(visibleConfig);
3859
+ const selected = first
3860
+ ? items.filter((item) => item.key === first)
3861
+ : items;
3131
3862
  emit(
3132
3863
  { items: selected },
3133
3864
  table(
@@ -3140,50 +3871,69 @@ async function performCli(
3140
3871
  }
3141
3872
  case "config set": {
3142
3873
  const key = configKey(first!);
3143
- const saved = parseValue(
3144
- key,
3874
+ const rawInput =
3145
3875
  key === "pointers.apiKey"
3146
3876
  ? await (io.readSecret ?? processIO.readSecret!)()
3147
- : second,
3148
- true,
3149
- );
3150
- state.setConfig(key, saved);
3151
- const source = items.find((item) => item.key === key)!.source;
3152
- if (source === "env" || source === "flag")
3153
- io.err(`Warning: saved user value is masked by ${source}.`);
3154
- const display = visibleConfig({ key, value: saved, source: "user" });
3877
+ : second!;
3878
+ parseValue(key, rawInput, true);
3879
+ const updated = await client.host.setConfig(key, rawInput, {
3880
+ fromString: true,
3881
+ });
3882
+ const currentSource = items.find((item) => item.key === key)!.source;
3883
+ const maskSource =
3884
+ currentSource === "env" || currentSource === "flag"
3885
+ ? currentSource
3886
+ : updated.effectiveSource === "env" ||
3887
+ updated.effectiveSource === "flag"
3888
+ ? updated.effectiveSource
3889
+ : undefined;
3890
+ if (maskSource)
3891
+ io.err(`Warning: saved user value is masked by ${maskSource}.`);
3892
+ const display = {
3893
+ key: updated.key,
3894
+ value: updated.value,
3895
+ source: updated.source,
3896
+ };
3155
3897
  emit(
3156
3898
  display,
3157
3899
  `Saved ${key} = ${printable(String(display.value))} (user).`,
3158
3900
  );
3159
3901
  break;
3160
3902
  }
3161
- case "config reset":
3162
- state.resetConfig(configKey(first!));
3903
+ case "config reset": {
3904
+ await client.host.resetConfig(configKey(first!));
3163
3905
  emit({ reset: [first] }, `Reset user override: ${first}.`);
3164
3906
  break;
3907
+ }
3165
3908
  case "history list": {
3166
- const page = listHistory(
3167
- state,
3168
- filter,
3169
- Number(parsed.options.limit ?? value("history.limit")),
3170
- typeof parsed.options.before === "string"
3171
- ? state.resolveRunId(parsed.options.before)
3172
- : undefined,
3173
- );
3909
+ const page = await client.runs.list({
3910
+ ...(typeof parsed.options.app === "string"
3911
+ ? { app: parsed.options.app }
3912
+ : {}),
3913
+ ...(typeof parsed.options.status === "string"
3914
+ ? { status: parsed.options.status as RunRecord["status"] }
3915
+ : {}),
3916
+ ...(typeof parsed.options.since === "string"
3917
+ ? { since: parsed.options.since }
3918
+ : {}),
3919
+ ...(typeof parsed.options.until === "string"
3920
+ ? { until: parsed.options.until }
3921
+ : {}),
3922
+ limit: Number(parsed.options.limit ?? value("history.limit")),
3923
+ ...(typeof parsed.options.before === "string"
3924
+ ? { before: parsed.options.before }
3925
+ : {}),
3926
+ });
3927
+ const jsonPage = { items: page.items, nextBefore: page.nextBefore };
3174
3928
  if (parsed.flags.json) {
3175
- emit(page, "");
3929
+ emit(jsonPage, "");
3176
3930
  break;
3177
3931
  }
3178
- const names = new Map<string, string>();
3179
- for (const pin of state.pins())
3180
- if (pin.status === "ready" && !names.has(pin.cid))
3181
- names.set(pin.cid, pin.name);
3932
+ const pinNames = page.pinNames ?? {};
3182
3933
  const reference = (cid: string | null): string =>
3183
3934
  cid === null
3184
3935
  ? "none"
3185
- : cid + (names.has(cid) ? ` (${names.get(cid)!})` : "");
3186
- const shortId = state.shortRunId.bind(state);
3936
+ : cid + (pinNames[cid] ? ` (${pinNames[cid]})` : "");
3187
3937
  const rows = page.items.length
3188
3938
  ? page.items
3189
3939
  .map((record) =>
@@ -3203,21 +3953,19 @@ async function performCli(
3203
3953
  .join("\n\n")
3204
3954
  : "No ended executions.";
3205
3955
  emit(
3206
- page,
3956
+ jsonPage,
3207
3957
  rows +
3208
3958
  (page.nextBefore
3209
- ? `\nMore matches; use --before ${shortId(page.nextBefore)} with the same filters.`
3959
+ ? `\nMore matches; use --before ${page.shortNextBefore ?? page.nextBefore} with the same filters.`
3210
3960
  : ""),
3211
3961
  );
3212
3962
  break;
3213
3963
  }
3214
3964
  case "history show": {
3215
- const record = state.run(state.resolveRunId(first!));
3216
- const logs = record.log
3217
- ? await logFiles(state.directory, record.id)
3218
- : undefined;
3965
+ const record = await client.runs.show(first!);
3966
+ const logs = record.logs;
3219
3967
  emit(
3220
- logs ? { ...record, logs } : record,
3968
+ record,
3221
3969
  runDetails(record) +
3222
3970
  (logs
3223
3971
  ? `\nLog recording: ${record.log!}\nStdout log: ${printable(logs.stdout ?? "unavailable")}\nStderr log: ${printable(logs.stderr ?? "unavailable")}`
@@ -3226,24 +3974,46 @@ async function performCli(
3226
3974
  break;
3227
3975
  }
3228
3976
  case "history remove": {
3229
- const ids = parsed.positional.length
3230
- ? [...new Set(parsed.positional.map(state.resolveRunId.bind(state)))]
3231
- : selectedIds(state, filter);
3232
- for (const id of ids) state.run(id);
3233
- if (
3234
- ids.length &&
3235
- !parsed.options.yes &&
3236
- !(await io.confirm(
3237
- `Remove ${ids.length} ended records selected by ${JSON.stringify(
3238
- parsed.positional.length ? { ids } : parsed.options,
3239
- )}? Release only their retention; no GC or disk reclamation is guaranteed.`,
3240
- ))
3241
- )
3242
- throw new HostError("History removal cancelled.");
3243
- const result = await removeHistory(state, ids);
3977
+ const removeParams = parsed.positional.length
3978
+ ? { ids: parsed.positional }
3979
+ : {
3980
+ ...(typeof parsed.options.app === "string"
3981
+ ? { app: parsed.options.app }
3982
+ : {}),
3983
+ ...(typeof parsed.options.status === "string"
3984
+ ? { status: parsed.options.status as RunRecord["status"] }
3985
+ : {}),
3986
+ ...(typeof parsed.options.since === "string"
3987
+ ? { since: parsed.options.since }
3988
+ : {}),
3989
+ ...(typeof parsed.options.until === "string"
3990
+ ? { until: parsed.options.until }
3991
+ : {}),
3992
+ };
3993
+ let idsToRemove: string[] | undefined;
3994
+ if (!parsed.options.yes) {
3995
+ const preview = await client.runs.remove({
3996
+ ...removeParams,
3997
+ dryRun: true,
3998
+ });
3999
+ const ids = preview.ids ?? [];
4000
+ if (
4001
+ ids.length &&
4002
+ !(await io.confirm(
4003
+ `Remove ${ids.length} ended records selected by ${JSON.stringify(
4004
+ parsed.positional.length ? { ids } : parsed.options,
4005
+ )}? Release only their retention; no GC or disk reclamation is guaranteed.`,
4006
+ ))
4007
+ )
4008
+ throw new HostError("History removal cancelled.");
4009
+ idsToRemove = ids;
4010
+ }
4011
+ const result = await client.runs.remove(
4012
+ idsToRemove !== undefined ? { ids: idsToRemove } : removeParams,
4013
+ );
3244
4014
  emit(
3245
4015
  result,
3246
- `Removed ${result.removed.length} records; garbage collection is not guaranteed.`,
4016
+ `Removed ${(result.removed ?? []).length} records; garbage collection is not guaranteed.`,
3247
4017
  );
3248
4018
  break;
3249
4019
  }
@@ -3252,7 +4022,7 @@ async function performCli(
3252
4022
  const named =
3253
4023
  parsed.path === "open" ? parseNameReference(first!) : undefined;
3254
4024
  const registrySwarm = named?.swarm
3255
- ? state.resolveSwarm(named.swarm)
4025
+ ? resolveSwarm(named.swarm)
3256
4026
  : selectedSwarm;
3257
4027
  if (parsed.path === "open" && !registrySwarm)
3258
4028
  throw new HostError(
@@ -3262,194 +4032,39 @@ async function performCli(
3262
4032
  throw new HostError(
3263
4033
  "Execution logging requires history.enabled=true.",
3264
4034
  );
3265
- await recoverInactive(state);
3266
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
3267
- const context = swarmContext();
3268
- readContext = context;
3269
- const directory =
3270
- parsed.path === "open"
3271
- ? await localBundleDirectory(first!)
3272
- : undefined;
3273
- const target = directory
3274
- ? undefined
3275
- : (
3276
- await resolveReference(
3277
- context,
3278
- first!,
3279
- selectedSwarm,
3280
- (reference) => state!.resolve(reference),
3281
- Boolean(parsed.options.raw),
3282
- "local-first",
3283
- )
3284
- ).cid;
3285
- store = context.store;
3286
- const resolveBundleReference = async (
3287
- reference: string,
3288
- signal: AbortSignal,
3289
- preferredSwarm?: string,
3290
- ) => {
3291
- signal.throwIfAborted();
3292
- const lookup: SwarmContext = {
3293
- ...swarmContext(),
3294
- store: new IpfsStore(
3295
- await storeConfiguration(value("store.gateway")),
3296
- ),
3297
- };
3298
- try {
3299
- const named = parseNameReference(reference);
3300
- const swarm = named?.swarm
3301
- ? state!.resolveSwarm(named.swarm)
3302
- : preferredSwarm
3303
- ? state!.resolveSwarm(preferredSwarm)
3304
- : selectedSwarm;
3305
- const resolve = (source: string | undefined) =>
3306
- resolveReference(
3307
- lookup,
3308
- reference,
3309
- source,
3310
- (input) => state!.resolve(input),
3311
- false,
3312
- "local-first",
3313
- );
3314
- let resolved;
3315
- try {
3316
- resolved = await resolve(named ? swarm : undefined);
3317
- } catch (cause) {
3318
- let failure: unknown = cause;
3319
- for (
3320
- let depth = 0;
3321
- depth < 8 && failure instanceof ContentBundleError;
3322
- depth++
3323
- )
3324
- failure = failure.cause;
3325
- if (
3326
- named ||
3327
- !swarm ||
3328
- !(failure instanceof ContentError) ||
3329
- failure.code !== "missing_block"
3330
- )
3331
- throw cause;
3332
- signal.throwIfAborted();
3333
- resolved = await resolve(swarm);
3334
- }
3335
- signal.throwIfAborted();
3336
- return { ...resolved, ...(swarm ? { swarm } : {}) };
3337
- } finally {
3338
- try {
3339
- await lookup.finishRead?.();
3340
- } finally {
3341
- await lookup.store.close();
3342
- }
3343
- }
3344
- };
3345
- let appCid: string;
3346
- let appArgv: string[];
3347
- if (parsed.path === "open") {
3348
- const session = directory ? `open:${randomUUID()}` : null;
3349
- const owner = await Ownership.create(
3350
- state,
3351
- store,
3352
- `open:${randomUUID()}`,
3353
- session,
3354
- );
3355
- try {
3356
- const root = directory
3357
- ? await snapshotBundle(directory, owner, session!)
3358
- : target!;
3359
- const content = await validatedBundle(root, store, owner);
3360
- const schema = content.schemaKey;
3361
- let association: Association | undefined;
3362
- if (registrySwarm) {
3363
- const lookup: SwarmContext = {
3364
- ...swarmContext(),
3365
- store: new IpfsStore(
3366
- await storeConfiguration(value("store.gateway")),
3367
- ),
3368
- };
3369
- try {
3370
- association = await swarmAssociation(
3371
- lookup,
3372
- registrySwarm,
3373
- schema,
3374
- "local-first",
3375
- );
3376
- } finally {
3377
- try {
3378
- await lookup.finishRead?.();
3379
- } finally {
3380
- await lookup.store.close();
3381
- }
3382
- }
3383
- }
3384
- if (!association)
3385
- throw new HostError(
3386
- `No App registered for Schema ${schema} in Swarm ${registrySwarm}. Use ipab register set ${schema} APP_CID --swarm ${registrySwarm} or ipab exec.`,
3387
- );
3388
- appCid = association.appCid;
3389
- if (association.argv.length !== 1 || association.argv[0] !== "%")
3390
- throw new HostError(
3391
- "Custom per-association argv is unsupported; adapt the App to accept only the content CID or use ipab exec APP_CID ARGS.",
3392
- );
3393
- appArgv = [root];
3394
- // execute owns the App/input context before this validation owner's eventual release.
3395
- const result = await execute(
3396
- state,
3397
- store,
3398
- { origin: "open", appCid, argv: appArgv },
3399
- {
3400
- inputSchema: schema,
3401
- resolveBundleReference,
3402
- history: Boolean(value("history.enabled")),
3403
- retain: value("output.retention") === "history",
3404
- log: Boolean(parsed.options.log),
3405
- diagnostic: (text) => {
3406
- io.err(text);
3407
- },
3408
- },
3409
- );
3410
- appExitCode = result.exitCode;
3411
- return appExitCode;
3412
- } finally {
3413
- await owner.release();
3414
- }
3415
- } else {
3416
- appCid = target!;
3417
- appArgv = parsed.positional.slice(1);
3418
- }
3419
- appExitCode = (
3420
- await execute(
3421
- state,
3422
- store,
3423
- { origin: "exec", appCid, argv: appArgv },
3424
- {
3425
- resolveBundleReference,
3426
- history: Boolean(value("history.enabled")),
3427
- retain: value("output.retention") === "history",
3428
- log: Boolean(parsed.options.log),
3429
- diagnostic: (text) => {
3430
- io.err(text);
3431
- },
3432
- },
3433
- )
3434
- ).exitCode;
3435
- return appExitCode;
4035
+ const resolvedFirst = await resolveLocalPathIfPresent(first!);
4036
+ const prepared = await client.runs.prepare(
4037
+ {
4038
+ origin: parsed.path,
4039
+ ...(parsed.path === "open"
4040
+ ? { target: resolvedFirst }
4041
+ : { appCid: resolvedFirst, argv: parsed.positional.slice(1) }),
4042
+ swarm: selectedSwarm,
4043
+ history: Boolean(value("history.enabled")),
4044
+ retain: value("output.retention") === "history",
4045
+ log: Boolean(parsed.options.log),
4046
+ raw: Boolean(parsed.options.raw),
4047
+ refresh: explicitRefresh,
4048
+ },
4049
+ { ndjson: true },
4050
+ );
4051
+ return await runPreparedApp(client, prepared, (text, prog) => {
4052
+ io.err(text, prog);
4053
+ });
3436
4054
  }
3437
4055
  default:
3438
4056
  syntax("Unknown command.");
3439
4057
  }
3440
4058
  return 0;
3441
4059
  } catch (error) {
4060
+ const { message } = await import("./errors.js");
3442
4061
  io.err(`Error: ${message(error)}`);
3443
4062
  return error instanceof HostError ? error.exitCode : 1;
3444
4063
  } finally {
3445
4064
  try {
3446
- try {
3447
- await readContext?.finishRead?.();
3448
- } finally {
3449
- await closeStore(store, appExitCode);
3450
- }
4065
+ await cliHandle?.close();
3451
4066
  } finally {
3452
- state?.close();
4067
+ await closeStore(daemonStore, undefined);
3453
4068
  }
3454
4069
  }
3455
4070
  }
@@ -3462,6 +4077,7 @@ export async function runCli(
3462
4077
  try {
3463
4078
  return await performCli(argv, io, env);
3464
4079
  } catch (error) {
4080
+ const { message } = await import("./errors.js");
3465
4081
  io.err(`Error: ${message(error)}`);
3466
4082
  return error instanceof HostError ? error.exitCode : 1;
3467
4083
  }