@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/dist/cli.js CHANGED
@@ -1,32 +1,15 @@
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";
7
5
  import stringWidth from "string-width";
8
6
  import { LOCAL_SWARM_ALIAS, configKey, effectiveConfig, isLocalSwarm, parseValue, publicUrl, stateLocation, storeConfiguration, swarmUrl, visibleConfig, } from "./config.js";
9
- import { HostError, message, object, syntax } from "./errors.js";
10
- import { filters, listHistory, selectedIds, Ownership, recoverInactive, removeHistory, } from "./history.js";
11
- import { execute } from "./runtime.js";
12
- import { validatedBundle } from "./space.js";
13
- import { createAssociation, exactCid, swarmAlias, State, } from "./state.js";
14
- import { buildBundle, inspectBundle, importBundle, localBundleDirectory, nodeError, snapshotBundle, } from "./authoring.js";
15
- import { initApp } from "./app-authoring.js";
16
- import { assembleBundle } from "./assembly.js";
17
- import { getBundle } from "./get.js";
18
- import { doctorDevice, doctorText } from "./doctor.js";
19
- import { daemonEndpoint, ensureDaemon, openLoopbackUrl, serveDaemon, } from "./daemon.js";
20
- import { keyId } from "@ipab/bundle/pointer/crypto";
21
- import { createSwarm, swarmDaemon, requestMembership, approveMembership, grantPivotAuthority, exportRequest, removeMember, resumeRemoval, updateProfile, accountProfile, updateAccountProfile, swarmMembers, inspectSwarmStatus, verifiedRequest, verifiedRequestStream, membershipRequestSummary, updateSwarm, searchNames, formatNameReference, resolveReference, parseNameReference, formalName, publish, pinNameSubscription, pinReference, swarmRegistrations, swarmAssociation, setSwarmAssociation, removeSwarmAssociation, resolveTemplateSelector, templateName, swarmTemplates, setSwarmTemplate, removeSwarmTemplate, } from "./swarm.js";
22
- import { schemaAlias } from "./app-definition.js";
23
- import { unpin, pinDetails } from "./pins.js";
24
- import { publicationSource } from "./publish-source.js";
25
- import { templateRenderExample, templateOutputTree, templateParameterRows, } from "./template-presentation.js";
26
- import { logFiles } from "./logs.js";
27
- import { builtinContent } from "./builtins.js";
7
+ import { HostError, object, syntax } from "./host-error.js";
8
+ import { exactCid, swarmAlias, State, } from "./state.js";
9
+ import { formatNameReference, parseNameReference, formalName, templateName, } from "./name-reference.js";
10
+ import { normalizeSwarmFsPath } from "./swarm-fs-path.js";
28
11
  import { readSecretStream } from "./config-secret.js";
29
- import { manageSkills, syncDaemonSwarm } from "./skills.js";
12
+ import { openCliClient, resolveLocalPathIfPresent, resolveSwarmFromList, runPreparedApp, } from "./cli-daemon.js";
30
13
  let progressLine = false;
31
14
  export const processIO = {
32
15
  out(text) {
@@ -75,6 +58,9 @@ const commands = {
75
58
  daemon: "daemon",
76
59
  "daemon ui": "daemon ui [--open]",
77
60
  "skills list": "skills list [--refresh | --no-refresh]",
61
+ "skills show": "skills show SCHEMA_OR_CONTENT [--refresh | --no-refresh]",
62
+ "skills set": "skills set SKILL [--global] [--type SCHEMA]... [--replace]",
63
+ "skills remove": "skills remove [--global NAME] [--type SCHEMA]...",
78
64
  "skills sync": "skills sync [NAMES...] [--agent AGENT]... [--override-existing] [--dry-run] [--yes] [--refresh | --no-refresh]",
79
65
  doctor: "doctor [--fix [--yes]]",
80
66
  profile: "profile [--name NAME] [--description TEXT]",
@@ -87,6 +73,7 @@ const commands = {
87
73
  "swarm resume": "swarm resume",
88
74
  "swarm profile": "swarm profile [--address MULTIADDR] [--pivot true|false]",
89
75
  "swarm status": "swarm status [--refresh | --no-refresh]",
76
+ "swarm replicate": "swarm replicate [--pivot MEMBER]",
90
77
  "swarm members": "swarm members [--refresh | --no-refresh]",
91
78
  "swarm list": "swarm list",
92
79
  "swarm set": "swarm set ALIAS CONFIG_URL [--yes]",
@@ -100,7 +87,7 @@ const commands = {
100
87
  build: "build [SOURCE] [OPTIONS]",
101
88
  "bundle build": "bundle build SOURCE [OPTIONS]",
102
89
  "bundle inspect": "bundle inspect SOURCE",
103
- "bundle import": "bundle import FILE.car",
90
+ "bundle import": "bundle import SOURCE",
104
91
  exec: "exec [--log] [--refresh | --no-refresh] APP [APP_ARGS...]",
105
92
  open: "open [--log] [--raw] [--refresh | --no-refresh] CONTENT",
106
93
  pin: "pin REF [--refresh | --no-refresh]",
@@ -119,17 +106,22 @@ const commands = {
119
106
  "config reset": "config reset KEY",
120
107
  "store usage": "store usage",
121
108
  "store gc": "store gc",
109
+ "fs ls": "fs ls [PATH] [--all] [--recursive] [--refresh | --no-refresh]",
110
+ "fs stat": "fs stat PATH [--refresh | --no-refresh]",
111
+ "fs set": "fs set PATH CID [--expect OLD_CID | --replace]",
112
+ "fs rm": "fs rm PATH [--expect OLD_CID]",
122
113
  "history list": "history list [OPTIONS]",
123
114
  "history show": "history show RUN_ID",
124
115
  "history remove": "history remove RUN_ID... [--yes]\n ipab history remove FILTERS [--yes]",
125
116
  };
126
117
  const groups = {
127
- skills: "Discover and explicitly synchronize selected Swarm Skills globally",
118
+ skills: "Discover, associate, and synchronize Swarm Skills",
128
119
  swarm: "Create, authorize, select and manage personal swarms",
129
120
  bundle: "Create, inspect and import content bundles",
130
121
  pin: "Retain an exact CID or follow a shared Swarm Name",
131
122
  register: "Associate content types with Apps",
132
123
  templates: "Inspect, render and manage Template Bundles",
124
+ fs: "Inspect and modify paths in a Swarm UnixFS tree",
133
125
  config: "Manage local configuration",
134
126
  store: "Query local storage and collect unreferenced blocks",
135
127
  history: "View and remove execution history",
@@ -159,7 +151,7 @@ const commandHelp = {
159
151
  "ipab --json daemon ui",
160
152
  ],
161
153
  notes: [
162
- "Inspects the protected loopback endpoint for the selected state-dir without starting a daemon.",
154
+ "Ensures the local daemon is running for the selected state-dir, then shows or opens its protected loopback status WebUI.",
163
155
  "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.",
164
156
  ],
165
157
  },
@@ -217,21 +209,79 @@ const commandHelp = {
217
209
  ],
218
210
  },
219
211
  "skills list": {
220
- summary: "List typed Skills and local installation status from one Swarm",
212
+ summary: "List Global Skills (with local status) and Type Skills from one Swarm",
221
213
  options: [
222
214
  "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
223
- "Global --json Emit machine-readable names, exact payload CIDs and status.",
215
+ "Global --json Emit machine-readable global items, typeSkills, CIDs and status.",
224
216
  ],
225
217
  examples: ["ipab --swarm work skills list", "ipab --json skills list"],
226
218
  notes: [
227
219
  "Select one Swarm with global --swarm or swarm use; there is no --all.",
228
- "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.",
220
+ "Reads <skillPath>/global/* and <skillPath>/types/*; missing subdirectories are treated as empty.",
221
+ "Requires skillPath in the exact root State Bundle or legacy Meta type. No silent upgrades.",
222
+ ],
223
+ },
224
+ "skills show": {
225
+ summary: "Show the Skill associated with a Bundle type or content Bundle",
226
+ arguments: [
227
+ "SCHEMA_OR_CONTENT Canonical schema CID, builtin: alias, content Bundle CID, Swarm URI, or local .car/Bundle directory.",
228
+ ],
229
+ options: [
230
+ "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
231
+ "Global --json Emit machine-readable Skill association details.",
232
+ ],
233
+ examples: [
234
+ "ipab skills show SCHEMA_CID",
235
+ "ipab skills show ipab://work/docs/spec",
236
+ "ipab --json skills show ./document.car",
237
+ ],
238
+ notes: [
239
+ "Swarm URIs use the URI's Swarm ahead of --swarm and the default Swarm.",
240
+ "Content Bundle references automatically unwrap Artifacts and resolve their schema CID.",
241
+ "Exits with code 1 (SKILL_NOT_FOUND) when no Skill is associated with the schema.",
242
+ ],
243
+ },
244
+ "skills set": {
245
+ summary: "Associate a Skill Bundle globally and/or with Bundle types",
246
+ arguments: [
247
+ "SKILL Skill Bundle CID, Swarm URI, local .car file, or assembled Skill Bundle directory containing .bundle.yaml.",
248
+ ],
249
+ options: [
250
+ "--global Publish to <skillPath>/global/<skill-name> for global synchronization.",
251
+ "--type SCHEMA Repeatable target Bundle schema CID (writes <skillPath>/types/<schemaCid>).",
252
+ "--replace Overwrite existing targets that point to a different Skill CID.",
253
+ ],
254
+ examples: [
255
+ "ipab skills set SKILL_CID --global",
256
+ "ipab skills set ./skill.car --type SCHEMA_CID",
257
+ "ipab skills set SKILL_CID --global --type SCHEMA_CID --replace",
258
+ ],
259
+ notes: [
260
+ "Requires --global and/or at least one --type SCHEMA. All targets commit atomically in one HEAD CAS.",
261
+ "Writes direct Skill Bundle CIDs. Occupied targets with a different CID fail with exit code 3 unless --replace is set.",
262
+ ],
263
+ },
264
+ "skills remove": {
265
+ summary: "Remove global and/or type Skill associations atomically",
266
+ options: [
267
+ "--global NAME Remove <skillPath>/global/NAME (at most once).",
268
+ "--type SCHEMA Repeatable target Bundle schema CID to remove from <skillPath>/types/.",
269
+ ],
270
+ examples: [
271
+ "ipab skills remove --global my-skill",
272
+ "ipab skills remove --type SCHEMA_CID",
273
+ "ipab skills remove --global my-skill --type SCHEMA_CID",
274
+ ],
275
+ notes: [
276
+ "Requires --global NAME and/or at least one --type SCHEMA. All removals commit atomically in one HEAD CAS.",
277
+ "If any target is missing, the entire batch fails with exit code 1 and nothing is modified.",
278
+ "Does not delete underlying content blocks or locally installed Agent Skill files.",
229
279
  ],
230
280
  },
231
281
  "skills sync": {
232
- summary: "Install reviewed Swarm Skills using the pinned official npx installer",
282
+ summary: "Install reviewed Global Swarm Skills using the pinned official npx installer",
233
283
  arguments: [
234
- "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.",
284
+ "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.",
235
285
  ],
236
286
  options: [
237
287
  "--agent AGENT Repeatable globally supported agent ID; default is universal (~/.agents/skills).",
@@ -245,6 +295,7 @@ const commandHelp = {
245
295
  "ipab skills sync ipab code-review --agent github-copilot --yes",
246
296
  ],
247
297
  notes: [
298
+ "Scans <skillPath>/global/* only; Type Skills under <skillPath>/types/* are never installed globally.",
248
299
  "Global installs only, through official skills@1.9.1 with --copy. Requires Node >=22.20.0.",
249
300
  "Non-interactive execution requires --yes. Installer version, source, paths and agents are shown first.",
250
301
  "No Skill hooks/scripts run. The trusted installer is not sandboxed. Telemetry and remote audits are disabled.",
@@ -385,6 +436,21 @@ const commandHelp = {
385
436
  "Pivot provides backbone connectivity and durable published-content Pin service through daemon. Keep it online with sufficient storage.",
386
437
  ],
387
438
  },
439
+ "swarm replicate": {
440
+ summary: "Replicate the complete local current HEAD to a remote Pivot",
441
+ options: [
442
+ "--pivot MEMBER Target one declared Pivot by exact member name, public key or PeerID.",
443
+ ],
444
+ examples: [
445
+ "ipab --swarm work swarm replicate --pivot scott-office-ubuntu",
446
+ "ipab --json --swarm work swarm replicate",
447
+ ],
448
+ notes: [
449
+ "Requires approved membership and the complete current HEAD locally. Works behind NAT; no source address publication is required.",
450
+ "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.",
451
+ "Progress goes to stderr; --json returns the HEAD and per-Pivot results. At least one Pivot must confirm readiness for success.",
452
+ ],
453
+ },
388
454
  "swarm members": {
389
455
  summary: "List every public member, including the Owner",
390
456
  options: [
@@ -625,17 +691,24 @@ const commandHelp = {
625
691
  notes: ["Does not execute Apps, import content or create pins."],
626
692
  },
627
693
  "bundle import": {
628
- summary: "Validate and import a CAR into the configured Store",
629
- arguments: ["FILE.car Self-contained single-root Bundle or type CAR."],
630
- examples: ["ipab bundle import hello\\dist\\app.car"],
694
+ summary: "Validate and import a CAR or Bundle directory into the configured Store",
695
+ arguments: [
696
+ "SOURCE Self-contained single-root CAR or local Content Bundle directory.",
697
+ ],
698
+ examples: [
699
+ "ipab bundle import hello\\dist\\app.car",
700
+ "ipab bundle import .",
701
+ ],
631
702
  notes: [
703
+ "Directories must contain valid Bundle metadata; .bundle-ignore is honored without writing CAR files.",
632
704
  "Repeated imports are safe; no App execution or daemon startup.",
633
705
  "Does not pin or retain content. Use pin CID for persistent retention.",
634
706
  ],
635
707
  },
636
708
  exec: {
637
- summary: "Run an App by exact CID or Swarm IPAB URI",
709
+ summary: "Run an App by CID, Swarm IPAB URI, local CAR or Bundle directory",
638
710
  arguments: [
711
+ "APP App CID, Swarm IPAB URI, local App .car file or assembled App Bundle directory.",
639
712
  "APP_ARGS Everything after APP is passed verbatim, including --help.",
640
713
  ],
641
714
  options: [
@@ -644,12 +717,13 @@ const commandHelp = {
644
717
  "--no-refresh Override swarm.forceRefresh; must precede APP.",
645
718
  ],
646
719
  examples: [
647
- "ipab exec reader",
648
- "ipab exec --log reader",
720
+ "ipab exec APP_CID",
721
+ "ipab exec .\\dist\\app.car --help",
649
722
  "ipab exec ipab://work/apps/hello --help",
650
723
  ],
651
724
  notes: [
652
725
  "Apps are NOT sandboxed; run only Apps you trust.",
726
+ "Local App directories must already contain valid assembled Bundle metadata; exec does not compile source, pin or modify the directory.",
653
727
  "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
654
728
  "History stores argv by default; do not put secrets in arguments.",
655
729
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
@@ -659,7 +733,7 @@ const commandHelp = {
659
733
  open: {
660
734
  summary: "Open content with its registered App",
661
735
  arguments: [
662
- "CONTENT Local Bundle directory, Bundle CID, packaged builtin reference or Swarm IPAB URI.",
736
+ "CONTENT Local Bundle directory or .car file, Bundle CID, packaged builtin reference or Swarm IPAB URI.",
663
737
  ],
664
738
  options: [
665
739
  "--log Record stdout/stderr; requires history enabled.",
@@ -669,12 +743,12 @@ const commandHelp = {
669
743
  ],
670
744
  examples: [
671
745
  "ipab open .",
746
+ "ipab open .\\dist\\bundle.car",
672
747
  "ipab open --log --refresh ipab:///documents/readme",
673
- "ipab open ipab:///",
674
748
  ],
675
749
  notes: [
676
750
  "Requires a saved registration and App support for the exact content type.",
677
- "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.",
751
+ "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.",
678
752
  "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.",
679
753
  "Uses only the content URI's Swarm, otherwise --swarm, otherwise swarm.default. A selected Swarm is required.",
680
754
  "A registered App's retrieval, compatibility or execution failure never triggers fallback.",
@@ -747,7 +821,7 @@ const commandHelp = {
747
821
  summary: "Associate a content type with an App",
748
822
  arguments: [
749
823
  "SCHEMA Exact type CID or builtin:node-app.v1.",
750
- "APP App CID or Swarm IPAB URI; the exact CID is saved.",
824
+ "APP App CID, Swarm IPAB URI, local App .car file or assembled App Bundle directory.",
751
825
  ],
752
826
  options: [
753
827
  "--replace Allow changing an existing association.",
@@ -755,10 +829,12 @@ const commandHelp = {
755
829
  ],
756
830
  examples: [
757
831
  "ipab register set SCHEMA_CID APP_CID",
832
+ "ipab register set SCHEMA_CID .\\dist\\app.car --swarm work",
758
833
  "ipab register set SCHEMA_CID ipab:///apps/reader --swarm work --swarm team",
759
834
  ],
760
835
  notes: [
761
836
  "Writes the Name META.registryPath/TYPE_CID directly to the App CID. Open passes only the content CID.",
837
+ "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.",
762
838
  "Custom per-association argv is unsupported; adapt the App or use ipab exec APP_CID ARGS.",
763
839
  "Does not verify App type support; open checks it before execution.",
764
840
  "Without explicit --swarm, writes the saved default Swarm. Swarm writes require HEAD write access.",
@@ -780,6 +856,79 @@ const commandHelp = {
780
856
  "Does not remove Apps, pins or content.",
781
857
  ],
782
858
  },
859
+ "fs ls": {
860
+ summary: "List entries under a path in the selected Swarm UnixFS tree",
861
+ arguments: [
862
+ "PATH Optional directory path inside the Swarm root (defaults to /).",
863
+ ],
864
+ options: [
865
+ "--all Include protected v7 root metadata files when listing /.",
866
+ "--recursive Traverse subdirectories recursively (bounded depth/nodes).",
867
+ "--refresh Fetch the latest Swarm HEAD before listing.",
868
+ "--no-refresh Use only the cached Swarm HEAD without contacting network.",
869
+ ],
870
+ examples: [
871
+ "ipab fs ls",
872
+ "ipab fs ls ipab/skills --recursive",
873
+ "ipab --json fs ls --all",
874
+ ],
875
+ notes: [
876
+ "On legacy (v2-v6) Swarms, lists a read-only virtual view projected from snapshot names.",
877
+ ],
878
+ },
879
+ "fs stat": {
880
+ summary: "Inspect metadata for a path in the selected Swarm UnixFS tree",
881
+ arguments: ["PATH Path inside the Swarm root (use / or . for root)."],
882
+ options: [
883
+ "--refresh Fetch the latest Swarm HEAD before inspecting.",
884
+ "--no-refresh Use only the cached Swarm HEAD without contacting network.",
885
+ ],
886
+ examples: [
887
+ "ipab fs stat /",
888
+ "ipab fs stat ipab/skills",
889
+ "ipab --json fs stat docs/guide",
890
+ ],
891
+ notes: [
892
+ "On legacy (v2-v6) Swarms, reports a read-only virtual view projected from snapshot names.",
893
+ ],
894
+ },
895
+ "fs set": {
896
+ summary: "Mount an existing CID at a path in the selected Swarm UnixFS tree",
897
+ arguments: [
898
+ "PATH Relative path inside the Swarm root (root / and protected metadata are rejected).",
899
+ "CID Canonical CID already present in the local IPFS store.",
900
+ ],
901
+ options: [
902
+ "--expect OLD_CID Require the current path CID to match OLD_CID before replacing.",
903
+ "--replace Allow replacing an existing different CID at PATH.",
904
+ ],
905
+ examples: [
906
+ "ipab fs set docs/guide bafy...",
907
+ "ipab fs set docs/guide bafyNEW --expect bafyOLD",
908
+ "ipab --json fs set docs/guide bafyNEW --replace",
909
+ ],
910
+ notes: [
911
+ "Requires a State v7 UnixFS Swarm root; legacy (v2-v6) Swarms are not implicitly migrated.",
912
+ "Protected v7 root metadata files (.bundle.yaml, typeFile, entryFile) cannot be overwritten.",
913
+ ],
914
+ },
915
+ "fs rm": {
916
+ summary: "Remove a path from the selected Swarm UnixFS tree",
917
+ arguments: [
918
+ "PATH Relative path to remove (automatically prunes empty parent directories up to /).",
919
+ ],
920
+ options: [
921
+ "--expect OLD_CID Require the current path CID to match OLD_CID before removing.",
922
+ ],
923
+ examples: [
924
+ "ipab fs rm docs/guide",
925
+ "ipab fs rm docs/guide --expect bafyOLD",
926
+ "ipab --json fs rm docs/guide",
927
+ ],
928
+ notes: [
929
+ "Requires a State v7 UnixFS Swarm root; protected root metadata files cannot be removed.",
930
+ ],
931
+ },
783
932
  "config get": {
784
933
  summary: "Show effective configuration",
785
934
  arguments: ["KEY Optional configuration key; omit to show all values."],
@@ -871,6 +1020,7 @@ Manage:
871
1020
  doctor ${commandHelp.doctor.summary}
872
1021
  profile ${commandHelp.profile.summary}
873
1022
  swarm ${groups.swarm}
1023
+ fs ${groups.fs}
874
1024
  skills ${groups.skills}
875
1025
  search Search formal Names in the current swarm
876
1026
  publish ${commandHelp.publish.summary}
@@ -907,6 +1057,7 @@ ${footer}`;
907
1057
  ...([
908
1058
  "swarm status",
909
1059
  "swarm members",
1060
+ "swarm replicate",
910
1061
  "swarm update",
911
1062
  "swarm resume",
912
1063
  "swarm profile",
@@ -1053,6 +1204,7 @@ async function closeStore(store, appExitCode) {
1053
1204
  await store?.close();
1054
1205
  }
1055
1206
  catch (error) {
1207
+ const { message } = await import("./errors.js");
1056
1208
  throw new HostError(`Store cleanup failed: ${message(error)}`, appExitCode || 1, "CLEANUP_FAILED", "cleanup");
1057
1209
  }
1058
1210
  }
@@ -1164,6 +1316,7 @@ export function parse(argv) {
1164
1316
  "store",
1165
1317
  "swarm",
1166
1318
  "skills",
1319
+ "fs",
1167
1320
  ].includes(group))
1168
1321
  syntax(`Unknown command "${group}".${group === "setup" ? " Run ipab doctor to inspect, or ipab doctor --fix to prepare this device." : " Run ipab --help."}`);
1169
1322
  if (group === "pin" && !["list", "show"].includes(tokens[0] ?? "")) {
@@ -1198,6 +1351,8 @@ export function parse(argv) {
1198
1351
  syntax(`Unknown command "${result.path}".`);
1199
1352
  if (group === "skills" && swarms.length > 1)
1200
1353
  syntax("Skills operations select exactly one Swarm; repeated --swarm is not supported.");
1354
+ if (group === "fs" && swarms.length > 1)
1355
+ syntax("fs operations select at most one Swarm; repeated --swarm is not supported.");
1201
1356
  const separator = result.path === "register set" ? tokens.indexOf("--") : -1;
1202
1357
  if (separator >= 0)
1203
1358
  result.template = tokens.splice(separator + 1);
@@ -1214,51 +1369,61 @@ export function parse(argv) {
1214
1369
  const booleans = result.path.startsWith("skills ")
1215
1370
  ? result.path === "skills sync"
1216
1371
  ? ["dry-run", "yes", "override-existing", "force", "no-force"]
1217
- : ["force", "no-force"]
1218
- : result.path === "doctor"
1219
- ? ["fix", "yes"]
1220
- : result.path === "bundle build"
1221
- ? ["replace", "schema-only", "no-import"]
1222
- : result.path === "build"
1223
- ? ["replace", "no-import"]
1224
- : result.path === "publish"
1225
- ? ["snapshot"]
1226
- : [
1227
- "get",
1228
- "templates render",
1229
- "templates list",
1230
- "templates show",
1231
- ].includes(result.path)
1232
- ? result.path === "templates render"
1233
- ? ["force", "no-force"]
1234
- : result.path === "get"
1235
- ? ["raw", "force", "no-force"]
1236
- : ["force", "no-force"]
1237
- : result.path === "search"
1238
- ? ["all", "current", "force", "no-force"]
1239
- : result.path === "swarm request"
1240
- ? ["pivot"]
1241
- : result.path === "swarm approve"
1242
- ? ["yes", "again", "pivot"]
1243
- : ["swarm status", "swarm members"].includes(result.path)
1244
- ? ["local", "force", "no-force"]
1245
- : [
1246
- "swarm exclude",
1247
- "swarm set",
1248
- "swarm pivot grant",
1249
- ].includes(result.path)
1250
- ? ["yes"]
1251
- : result.path === "register set"
1252
- ? ["replace"]
1253
- : result.path === "history remove"
1254
- ? ["yes"]
1255
- : result.path === "open"
1256
- ? ["log", "raw", "force", "no-force"]
1257
- : result.path === "pin"
1258
- ? ["force", "no-force"]
1259
- : result.path === "daemon ui"
1260
- ? ["open"]
1261
- : [];
1372
+ : result.path === "skills set"
1373
+ ? ["global", "replace"]
1374
+ : result.path === "skills remove"
1375
+ ? []
1376
+ : ["force", "no-force"]
1377
+ : result.path === "fs ls"
1378
+ ? ["all", "recursive", "force", "no-force"]
1379
+ : result.path === "fs stat"
1380
+ ? ["force", "no-force"]
1381
+ : result.path === "fs set"
1382
+ ? ["replace"]
1383
+ : result.path === "doctor"
1384
+ ? ["fix", "yes"]
1385
+ : result.path === "bundle build"
1386
+ ? ["replace", "schema-only", "no-import"]
1387
+ : result.path === "build"
1388
+ ? ["replace", "no-import"]
1389
+ : result.path === "publish"
1390
+ ? ["snapshot"]
1391
+ : [
1392
+ "get",
1393
+ "templates render",
1394
+ "templates list",
1395
+ "templates show",
1396
+ ].includes(result.path)
1397
+ ? result.path === "templates render"
1398
+ ? ["force", "no-force"]
1399
+ : result.path === "get"
1400
+ ? ["raw", "force", "no-force"]
1401
+ : ["force", "no-force"]
1402
+ : result.path === "search"
1403
+ ? ["all", "current", "force", "no-force"]
1404
+ : result.path === "swarm request"
1405
+ ? ["pivot"]
1406
+ : result.path === "swarm approve"
1407
+ ? ["yes", "again", "pivot"]
1408
+ : ["swarm status", "swarm members"].includes(result.path)
1409
+ ? ["local", "force", "no-force"]
1410
+ : [
1411
+ "swarm exclude",
1412
+ "swarm set",
1413
+ "swarm pivot grant",
1414
+ ].includes(result.path)
1415
+ ? ["yes"]
1416
+ : result.path === "register set"
1417
+ ? ["replace"]
1418
+ : result.path === "history remove"
1419
+ ? ["yes"]
1420
+ : result.path === "open"
1421
+ ? ["log", "raw", "force", "no-force"]
1422
+ : result.path === "pin"
1423
+ ? ["force", "no-force"]
1424
+ : result.path === "daemon ui"
1425
+ ? ["open"]
1426
+ : [];
1262
1427
  if (booleans.includes("force"))
1263
1428
  booleans.push("refresh", "no-refresh");
1264
1429
  const values = result.path === "swarm create"
@@ -1269,33 +1434,43 @@ export function parse(argv) {
1269
1434
  ? ["output"]
1270
1435
  : result.path === "swarm profile"
1271
1436
  ? ["address", "pivot"]
1272
- : result.path === "swarm update" || result.path === "profile"
1273
- ? ["name", "description"]
1274
- : result.path === "swarm approve"
1275
- ? []
1276
- : ["publish", "templates set", "templates remove"].includes(result.path)
1277
- ? ["expect"]
1278
- : result.path === "get"
1279
- ? ["output"]
1280
- : result.path === "search"
1281
- ? ["prefix", "kind", "schema", "limit", "offset"]
1282
- : result.path === "templates render"
1283
- ? ["description"]
1284
- : result.path === "bundle build" ||
1285
- result.path === "build"
1286
- ? ["output"]
1287
- : result.path === "history list"
1288
- ? [
1289
- "app",
1290
- "status",
1291
- "since",
1292
- "until",
1293
- "limit",
1294
- "before",
1295
- ]
1296
- : result.path === "history remove"
1297
- ? ["app", "status", "since", "until"]
1298
- : [];
1437
+ : result.path === "swarm replicate"
1438
+ ? ["pivot"]
1439
+ : result.path === "swarm update" || result.path === "profile"
1440
+ ? ["name", "description"]
1441
+ : result.path === "swarm approve"
1442
+ ? []
1443
+ : [
1444
+ "publish",
1445
+ "templates set",
1446
+ "templates remove",
1447
+ "fs set",
1448
+ "fs rm",
1449
+ ].includes(result.path)
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
+ : result.path === "skills remove"
1472
+ ? ["global"]
1473
+ : [];
1299
1474
  while (tokens.length) {
1300
1475
  const value = tokens.shift();
1301
1476
  if (result.path === "swarm exclude" &&
@@ -1313,6 +1488,18 @@ export function parse(argv) {
1313
1488
  (result.agents ??= []).push(input);
1314
1489
  continue;
1315
1490
  }
1491
+ if ((result.path === "skills set" || result.path === "skills remove") &&
1492
+ option === "type") {
1493
+ const input = tokens.shift();
1494
+ if (!input || input.startsWith("-"))
1495
+ syntax("--type needs a value.");
1496
+ (result.types ??= []).push(input);
1497
+ continue;
1498
+ }
1499
+ if (result.path === "skills remove" &&
1500
+ option === "global" &&
1501
+ Object.hasOwn(result.options, "global"))
1502
+ syntax("--global may be specified at most once.");
1316
1503
  if (result.path.startsWith("register ") && option === "swarm") {
1317
1504
  const input = tokens.shift();
1318
1505
  if (!input || input.startsWith("-"))
@@ -1367,11 +1554,33 @@ export function parse(argv) {
1367
1554
  if (result.path === "register list" &&
1368
1555
  (result.registrySwarms?.length ?? 0) > 1)
1369
1556
  syntax("register list accepts --swarm at most once. Select one Swarm or omit it to use the current Swarm.");
1557
+ if (result.path === "skills set") {
1558
+ if (!result.options.global && !(result.types?.length ?? 0))
1559
+ syntax("skills set requires --global and/or at least one --type SCHEMA.");
1560
+ for (const schema of result.types ?? [])
1561
+ if (!schema.startsWith("builtin:"))
1562
+ exactCid(schema, true);
1563
+ }
1564
+ if (result.path === "skills remove") {
1565
+ if (typeof result.options.global !== "string" &&
1566
+ !(result.types?.length ?? 0))
1567
+ syntax("skills remove requires --global NAME and/or at least one --type SCHEMA.");
1568
+ if (typeof result.options.global === "string" &&
1569
+ (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(result.options.global) ||
1570
+ result.options.global.length > 64))
1571
+ syntax(`Invalid global Skill name "${result.options.global}". Expected lowercase kebab-case (1..64 characters).`);
1572
+ for (const schema of result.types ?? [])
1573
+ if (!schema.startsWith("builtin:"))
1574
+ exactCid(schema, true);
1575
+ }
1370
1576
  const counts = {
1371
1577
  daemon: [0, 0],
1372
1578
  "daemon ui": [0, 0],
1373
1579
  doctor: [0, 0],
1374
1580
  "skills list": [0, 0],
1581
+ "skills show": [1, 1],
1582
+ "skills set": [1, 1],
1583
+ "skills remove": [0, 0],
1375
1584
  "skills sync": [0, Number.MAX_SAFE_INTEGER],
1376
1585
  profile: [0, 0],
1377
1586
  "swarm create": [0, 0],
@@ -1383,6 +1592,7 @@ export function parse(argv) {
1383
1592
  "swarm resume": [0, 0],
1384
1593
  "swarm profile": [0, 0],
1385
1594
  "swarm status": [0, 0],
1595
+ "swarm replicate": [0, 0],
1386
1596
  "swarm members": [0, 0],
1387
1597
  "swarm list": [0, 0],
1388
1598
  "swarm set": [2, 2],
@@ -1409,6 +1619,10 @@ export function parse(argv) {
1409
1619
  "templates show": [1, 1],
1410
1620
  "templates set": [2, 2],
1411
1621
  "templates remove": [1, 1],
1622
+ "fs ls": [0, 1],
1623
+ "fs stat": [1, 1],
1624
+ "fs set": [2, 2],
1625
+ "fs rm": [1, 1],
1412
1626
  "config get": [0, 1],
1413
1627
  "config set": [2, 2],
1414
1628
  "config reset": [1, 1],
@@ -1468,6 +1682,37 @@ export function parse(argv) {
1468
1682
  if (result.path === "templates remove" && !result.options.expect)
1469
1683
  syntax("templates remove requires --expect OLD_TARGET_CID.");
1470
1684
  }
1685
+ if (result.path === "fs ls" && result.positional[0] !== undefined) {
1686
+ normalizeSwarmFsPath(result.positional[0], {
1687
+ allowRoot: true,
1688
+ allowTrailingSlash: true,
1689
+ });
1690
+ }
1691
+ if (result.path === "fs stat") {
1692
+ normalizeSwarmFsPath(result.positional[0], {
1693
+ allowRoot: true,
1694
+ allowTrailingSlash: true,
1695
+ });
1696
+ }
1697
+ if (result.path === "fs set") {
1698
+ normalizeSwarmFsPath(result.positional[0], {
1699
+ allowRoot: false,
1700
+ allowTrailingSlash: false,
1701
+ });
1702
+ exactCid(result.positional[1]);
1703
+ if (typeof result.options.expect === "string")
1704
+ exactCid(result.options.expect);
1705
+ if (result.options.expect !== undefined && result.options.replace)
1706
+ syntax("--expect and --replace are mutually exclusive.");
1707
+ }
1708
+ if (result.path === "fs rm") {
1709
+ normalizeSwarmFsPath(result.positional[0], {
1710
+ allowRoot: false,
1711
+ allowTrailingSlash: false,
1712
+ });
1713
+ if (typeof result.options.expect === "string")
1714
+ exactCid(result.options.expect);
1715
+ }
1471
1716
  if (result.path.startsWith("config ") && result.positional[0]) {
1472
1717
  if (!(result.path === "config get" && result.positional[0] === "state-dir") &&
1473
1718
  !(result.path === "config reset" && result.positional[0] === "store.rpc"))
@@ -1490,10 +1735,8 @@ export function parse(argv) {
1490
1735
  return result;
1491
1736
  }
1492
1737
  async function performCli(argv, io, env) {
1493
- let state;
1494
- let store;
1495
- let appExitCode;
1496
- let readContext;
1738
+ let cliHandle;
1739
+ let daemonStore;
1497
1740
  try {
1498
1741
  const parsed = parse(argv);
1499
1742
  if (parsed.help) {
@@ -1509,7 +1752,10 @@ async function performCli(argv, io, env) {
1509
1752
  }
1510
1753
  if (parsed.path === "history remove" && !parsed.options.yes && !io.tty)
1511
1754
  syntax("Non-interactive history remove requires --yes.");
1755
+ const stateDir = stateLocation(parsed.flags, env).path;
1756
+ // Exempt command #3: doctor (never auto-starts Daemon)
1512
1757
  if (parsed.path === "doctor") {
1758
+ const { doctorDevice, doctorText } = await import("./doctor.js");
1513
1759
  const controller = new AbortController();
1514
1760
  const interrupt = () => {
1515
1761
  controller.abort(new HostError("Doctor interrupted.", 130, "ABORTED"));
@@ -1520,7 +1766,7 @@ async function performCli(argv, io, env) {
1520
1766
  process.once("SIGINT", interrupt);
1521
1767
  process.once("SIGTERM", terminate);
1522
1768
  try {
1523
- const result = await doctorDevice(stateLocation(parsed.flags, env).path, env, {
1769
+ const result = await doctorDevice(stateDir, env, {
1524
1770
  diagnostic: (text, progress) => {
1525
1771
  io.err(text, progress);
1526
1772
  },
@@ -1538,198 +1784,434 @@ async function performCli(argv, io, env) {
1538
1784
  process.removeListener("SIGTERM", terminate);
1539
1785
  }
1540
1786
  }
1541
- if (parsed.path === "daemon ui") {
1542
- const stateDir = stateLocation(parsed.flags, env).path;
1543
- const endpoint = await daemonEndpoint(stateDir);
1544
- if (!endpoint)
1545
- throw new HostError("IPAB daemon is not running for this state directory. Start it with `ipab daemon` or run a Swarm network command.");
1546
- const opened = Boolean(parsed.options.open);
1547
- if (opened)
1548
- openLoopbackUrl(endpoint.url);
1549
- io.out(parsed.flags.json
1550
- ? JSON.stringify({ ...endpoint, opened })
1551
- : opened
1552
- ? `Opened daemon status UI: ${endpoint.url}`
1553
- : endpoint.url);
1787
+ // Exempt command #4: daemon (foreground daemon host itself)
1788
+ if (parsed.path === "daemon") {
1789
+ if (parsed.flags.json)
1790
+ syntax("--json is not supported for daemon; diagnostics are written to stderr.");
1791
+ const [{ IpfsStore }, { builtinContent }, { serveDaemon }, { swarmDaemon }, { syncDaemonSwarm },] = await Promise.all([
1792
+ import("@ipab/ipfs-store"),
1793
+ import("./builtins.js"),
1794
+ import("./daemon.js"),
1795
+ import("./swarm.js"),
1796
+ import("./skills.js"),
1797
+ ]);
1798
+ const builtins = await builtinContent();
1799
+ const bootState = new State(stateDir, builtins.pins, env);
1800
+ let items;
1801
+ try {
1802
+ items = effectiveConfig(bootState.config({ includeSecrets: true }), parsed.flags, env, (reference) => bootState.resolveSwarm(reference));
1803
+ }
1804
+ finally {
1805
+ bootState.close();
1806
+ }
1807
+ const val = (key) => items.find((item) => item.key === key).value;
1808
+ daemonStore = new IpfsStore(await storeConfiguration(val("store.gateway")));
1809
+ const context = {
1810
+ get store() {
1811
+ return daemonStore;
1812
+ },
1813
+ set store(next) {
1814
+ daemonStore = next;
1815
+ },
1816
+ env,
1817
+ stateDir,
1818
+ cacheTtl: Number(val("swarm.cacheTtl")),
1819
+ syncInterval: Number(val("swarm.syncInterval")),
1820
+ listen: val("swarm.listen") === "loopback" ? "loopback" : "lan",
1821
+ ...(items.find((item) => item.key === "swarm.pivot").source ===
1822
+ "default"
1823
+ ? {}
1824
+ : { pivot: Boolean(val("swarm.pivot")) }),
1825
+ daemonReady: (status, onListen, extra) => serveDaemon(stateDir, {
1826
+ port: Number(val("daemon.uiPort")),
1827
+ env,
1828
+ ...(status ? { status } : {}),
1829
+ ...(onListen ? { onListen } : {}),
1830
+ ...(extra ?? {}),
1831
+ }),
1832
+ forceRefresh: Boolean(val("swarm.forceRefresh")),
1833
+ diagnostic: (text) => {
1834
+ io.err(text);
1835
+ },
1836
+ ...(typeof val("pointers.service") === "string"
1837
+ ? { pointerService: String(val("pointers.service")) }
1838
+ : {}),
1839
+ ...(typeof val("pointers.apiKey") === "string"
1840
+ ? { pointerApiKey: String(val("pointers.apiKey")) }
1841
+ : {}),
1842
+ };
1843
+ const controller = new AbortController();
1844
+ const interrupt = () => {
1845
+ controller.abort();
1846
+ };
1847
+ process.once("SIGINT", interrupt);
1848
+ process.once("SIGTERM", interrupt);
1849
+ try {
1850
+ await swarmDaemon(context, controller.signal, (ctx, url, report) => syncDaemonSwarm(ctx, url, undefined, report));
1851
+ }
1852
+ catch (cause) {
1853
+ if (!controller.signal.aborted)
1854
+ throw cause;
1855
+ }
1856
+ finally {
1857
+ process.removeListener("SIGINT", interrupt);
1858
+ process.removeListener("SIGTERM", interrupt);
1859
+ }
1554
1860
  return 0;
1555
1861
  }
1556
- const builtins = await builtinContent();
1557
- state = new State(stateLocation(parsed.flags, env).path, builtins.pins, env);
1862
+ // Exempt recovery: config reset store.rpc runs directly on local State so
1863
+ // legacy store.rpc recovery is never blocked by Daemon startup calling state.config().
1558
1864
  if (parsed.path === "config reset" &&
1559
1865
  parsed.positional[0] === "store.rpc") {
1560
- state.resetConfig("store.rpc");
1866
+ const localState = new State(stateDir, [], env);
1867
+ try {
1868
+ localState.resetConfig("store.rpc");
1869
+ }
1870
+ finally {
1871
+ localState.close();
1872
+ }
1561
1873
  io.out(parsed.flags.json
1562
1874
  ? JSON.stringify({ reset: ["store.rpc"] })
1563
1875
  : "Removed legacy store.rpc configuration. Existing Kubo pins and content are unchanged.");
1564
1876
  return 0;
1565
1877
  }
1566
- const items = effectiveConfig(state.config({
1567
- includeSecrets: ![
1568
- "swarm members",
1569
- "profile",
1570
- "swarm status",
1571
- "swarm set",
1572
- ].includes(parsed.path),
1573
- }), parsed.flags, env, (reference) => state.resolveSwarm(reference));
1574
- const value = (key) => items.find((item) => item.key === key).value;
1878
+ // Stateless local build when --no-import is set (never touches IpfsStore or spawns a Daemon).
1879
+ if ((parsed.path === "build" || parsed.path === "bundle build") &&
1880
+ Boolean(parsed.options["no-import"])) {
1881
+ const [{ assembleBundle }, { buildBundle }, { message }] = await Promise.all([
1882
+ import("./assembly.js"),
1883
+ import("./authoring.js"),
1884
+ import("./errors.js"),
1885
+ ]);
1886
+ let savedConfig = {};
1887
+ if (existsSync(join(stateDir, "state.sqlite"))) {
1888
+ const localState = new State(stateDir, [], env);
1889
+ try {
1890
+ savedConfig = localState.config({ includeSecrets: false });
1891
+ }
1892
+ finally {
1893
+ localState.close();
1894
+ }
1895
+ }
1896
+ const outputDirOpt = String(effectiveConfig(savedConfig, parsed.flags, env).find((item) => item.key === "bundle.outputDir").value);
1897
+ const outputOpt = typeof parsed.options.output === "string"
1898
+ ? resolve(parsed.options.output)
1899
+ : undefined;
1900
+ const controller = new AbortController();
1901
+ let cancelled = 0;
1902
+ const interrupt = () => {
1903
+ cancelled = 130;
1904
+ controller.abort(new Error("Interrupted."));
1905
+ };
1906
+ const terminate = () => {
1907
+ cancelled = 143;
1908
+ controller.abort(new Error("Terminated."));
1909
+ };
1910
+ process.once("SIGINT", interrupt);
1911
+ process.once("SIGTERM", terminate);
1912
+ try {
1913
+ const commonOpts = {
1914
+ signal: controller.signal,
1915
+ diagnostic: (text) => {
1916
+ io.err(text);
1917
+ },
1918
+ replace: Boolean(parsed.options.replace),
1919
+ ...(outputOpt !== undefined ? { output: outputOpt } : {}),
1920
+ outputDir: outputDirOpt,
1921
+ };
1922
+ let built;
1923
+ if (parsed.path === "build") {
1924
+ const sourcePath = parsed.positional[0]
1925
+ ? resolve(parsed.positional[0])
1926
+ : process.cwd();
1927
+ io.err("Assembling and validating Bundle (no compilation)...");
1928
+ built = await assembleBundle(sourcePath, commonOpts);
1929
+ }
1930
+ else {
1931
+ const sourcePath = await resolveLocalPathIfPresent(parsed.positional[0]);
1932
+ io.err("Validating and building bundle...");
1933
+ built = await buildBundle(sourcePath, {
1934
+ ...commonOpts,
1935
+ schemaOnly: Boolean(parsed.options["schema-only"]),
1936
+ });
1937
+ }
1938
+ controller.signal.throwIfAborted();
1939
+ const result = { ...built, imported: false };
1940
+ const validation = result.validation;
1941
+ 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)`;
1942
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
1943
+ return 0;
1944
+ }
1945
+ catch (cause) {
1946
+ if (cancelled) {
1947
+ io.err(message(cause));
1948
+ return cancelled;
1949
+ }
1950
+ throw cause;
1951
+ }
1952
+ finally {
1953
+ process.removeListener("SIGINT", interrupt);
1954
+ process.removeListener("SIGTERM", terminate);
1955
+ }
1956
+ }
1957
+ // Stateless local CAR inspection (never touches state.sqlite, IpfsStore, or spawns a Daemon).
1958
+ if (parsed.path === "bundle inspect") {
1959
+ const target = parsed.positional[0];
1960
+ const looksLikeCarPath = !target.startsWith("ipab://") &&
1961
+ !target.startsWith("builtin:") &&
1962
+ target.toLowerCase().endsWith(".car");
1963
+ if (looksLikeCarPath) {
1964
+ const resolvedCar = resolve(target);
1965
+ let isLocalFile = false;
1966
+ try {
1967
+ isLocalFile = (await lstat(resolvedCar)).isFile();
1968
+ }
1969
+ catch {
1970
+ isLocalFile = false;
1971
+ }
1972
+ if (isLocalFile) {
1973
+ const [{ inspectBundle }, { message }] = await Promise.all([
1974
+ import("./authoring.js"),
1975
+ import("./errors.js"),
1976
+ ]);
1977
+ const controller = new AbortController();
1978
+ let cancelled = 0;
1979
+ const interrupt = () => {
1980
+ cancelled = 130;
1981
+ controller.abort(new Error("Interrupted."));
1982
+ };
1983
+ const terminate = () => {
1984
+ cancelled = 143;
1985
+ controller.abort(new Error("Terminated."));
1986
+ };
1987
+ process.once("SIGINT", interrupt);
1988
+ process.once("SIGTERM", terminate);
1989
+ try {
1990
+ const result = await inspectBundle(resolvedCar, {
1991
+ signal: controller.signal,
1992
+ diagnostic: (text) => {
1993
+ io.err(text);
1994
+ },
1995
+ });
1996
+ controller.signal.throwIfAborted();
1997
+ const manifest = result.manifest;
1998
+ 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"}`;
1999
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
2000
+ return 0;
2001
+ }
2002
+ catch (cause) {
2003
+ if (cancelled) {
2004
+ io.err(message(cause));
2005
+ return cancelled;
2006
+ }
2007
+ throw cause;
2008
+ }
2009
+ finally {
2010
+ process.removeListener("SIGINT", interrupt);
2011
+ process.removeListener("SIGTERM", terminate);
2012
+ }
2013
+ }
2014
+ }
2015
+ }
2016
+ // All remaining commands go through the local Daemon HTTP loopback API.
2017
+ cliHandle = await openCliClient(stateDir, env, parsed.flags, (text, prog) => {
2018
+ io.err(text, prog);
2019
+ }, { lightweight: parsed.path === "swarm list" });
2020
+ const { client } = cliHandle;
1575
2021
  const emit = (result, human) => {
1576
2022
  io.out(parsed.flags.json ? JSON.stringify(result) : human);
1577
2023
  };
1578
- const [first, second] = parsed.positional;
1579
- const selectedSwarm = value("swarm.default") === null
1580
- ? undefined
1581
- : String(value("swarm.default"));
1582
- const requireSwarm = () => {
1583
- if (!selectedSwarm)
1584
- syntax("Select a Swarm with ipab --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.");
1585
- return selectedSwarm;
1586
- };
1587
- const swarmContext = () => ({
1588
- get store() {
1589
- return store;
1590
- },
1591
- set store(next) {
1592
- store = next;
1593
- },
1594
- state: state,
1595
- env,
1596
- stateDir: stateLocation(parsed.flags, env).path,
1597
- cacheTtl: Number(value("swarm.cacheTtl")),
1598
- syncInterval: Number(value("swarm.syncInterval")),
1599
- listen: value("swarm.listen") === "loopback" ? "loopback" : "lan",
1600
- ...(items.find((item) => item.key === "swarm.pivot").source === "default"
1601
- ? {}
1602
- : { pivot: Boolean(value("swarm.pivot")) }),
1603
- ...(parsed.path === "daemon"
1604
- ? {
1605
- daemonReady: (status, onListen) => serveDaemon(stateLocation(parsed.flags, env).path, {
1606
- port: Number(value("daemon.uiPort")),
1607
- ...(status ? { status } : {}),
1608
- ...(onListen ? { onListen } : {}),
1609
- }),
1610
- }
1611
- : {
1612
- ensureDaemon: () => ensureDaemon(stateLocation(parsed.flags, env).path, env, (text) => {
1613
- io.err(text);
1614
- }),
1615
- }),
1616
- forceRefresh: parsed.options.refresh || parsed.options.force
1617
- ? true
1618
- : parsed.options["no-refresh"] || parsed.options["no-force"]
1619
- ? false
1620
- : Boolean(value("swarm.forceRefresh")),
1621
- diagnostic: (text) => {
1622
- io.err(text);
1623
- },
1624
- ...(typeof value("pointers.service") === "string"
1625
- ? { pointerService: String(value("pointers.service")) }
1626
- : {}),
1627
- ...(typeof value("pointers.apiKey") === "string"
1628
- ? { pointerApiKey: String(value("pointers.apiKey")) }
1629
- : {}),
2024
+ if (parsed.path === "daemon ui") {
2025
+ const { openLoopbackUrl } = await import("./daemon.js");
2026
+ const live = await client.resolveEndpoint();
2027
+ const endpoint = {
2028
+ pid: live.pid,
2029
+ port: live.port,
2030
+ url: live.url,
2031
+ stateDir: live.stateDir,
2032
+ };
2033
+ const opened = Boolean(parsed.options.open);
2034
+ if (opened)
2035
+ openLoopbackUrl(endpoint.url);
2036
+ emit({ ...endpoint, opened }, opened ? `Opened daemon status UI: ${endpoint.url}` : endpoint.url);
2037
+ return 0;
2038
+ }
2039
+ const includeConfigSecrets = ![
2040
+ "swarm members",
2041
+ "profile",
2042
+ "swarm status",
2043
+ "swarm set",
2044
+ ].includes(parsed.path);
2045
+ const [configSnapshot, swarmsSnapshot] = await Promise.all([
2046
+ client.host.getConfig(undefined, {
2047
+ includeSecrets: includeConfigSecrets,
2048
+ }),
2049
+ client.swarms.list(),
2050
+ ]);
2051
+ const registeredSwarms = swarmsSnapshot.swarms;
2052
+ const resolveSwarm = (reference) => resolveSwarmFromList(registeredSwarms, reference);
2053
+ const savedConfig = configSnapshot.saved ?? {};
2054
+ const computedItems = effectiveConfig(savedConfig, parsed.flags, env, resolveSwarm);
2055
+ const items = computedItems.map((item) => {
2056
+ if (item.key === "pointers.apiKey") {
2057
+ const fromDaemon = configSnapshot.items.find((entry) => entry.key === "pointers.apiKey");
2058
+ if (fromDaemon && item.source === "default")
2059
+ return fromDaemon;
2060
+ }
2061
+ return visibleConfig(item);
1630
2062
  });
1631
- const filter = parsed.path.startsWith("history ")
1632
- ? filters(state, parsed.options)
1633
- : {};
1634
- const selection = () => {
1635
- const saved = state.config({ includeSecrets: false });
1636
- const current = effectiveConfig(saved, parsed.flags, env, (reference) => state.resolveSwarm(reference)).find((item) => item.key === "swarm.default");
2063
+ const value = (key) => items.find((item) => item.key === key).value;
2064
+ const selection = (savedOverride) => {
2065
+ const saved = savedOverride !== undefined
2066
+ ? { ...savedConfig, "swarm.default": savedOverride }
2067
+ : savedConfig;
2068
+ const current = effectiveConfig(saved, parsed.flags, env, resolveSwarm).find((item) => item.key === "swarm.default");
1637
2069
  return {
1638
- savedCurrent: saved["swarm.default"] ?? null,
1639
- effectiveCurrent: current.value,
2070
+ savedCurrent: saved["swarm.default"] === undefined
2071
+ ? null
2072
+ : saved["swarm.default"],
2073
+ effectiveCurrent: current.value === null ? null : String(current.value),
1640
2074
  source: current.source,
1641
2075
  };
1642
2076
  };
2077
+ const selectedSwarm = selection().effectiveCurrent ?? undefined;
2078
+ const requireSwarm = () => {
2079
+ if (!selectedSwarm)
2080
+ syntax("Select a Swarm with ipab --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.");
2081
+ return selectedSwarm;
2082
+ };
2083
+ const explicitRefresh = parsed.options.refresh || parsed.options.force
2084
+ ? true
2085
+ : parsed.options["no-refresh"] || parsed.options["no-force"]
2086
+ ? false
2087
+ : undefined;
2088
+ const stateDirectory = configSnapshot.stateDir ?? stateDir;
1643
2089
  if (parsed.path === "open" || parsed.path.startsWith("register ")) {
1644
- if (state.legacyRegistrationCount)
1645
- io.err(`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.`);
2090
+ if (configSnapshot.legacyRegistrationCount)
2091
+ io.err(`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.`);
2092
+ }
2093
+ if (configSnapshot.legacyPinCount)
2094
+ io.err(`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.`);
2095
+ const [first, second] = parsed.positional;
2096
+ if (parsed.path === "swarm list") {
2097
+ const result = { swarms: registeredSwarms, ...selection() };
2098
+ emit({
2099
+ ...result,
2100
+ swarms: result.swarms.map((entry) => ({
2101
+ configUrl: entry.cid,
2102
+ alias: entry.alias,
2103
+ local: Boolean(entry.local),
2104
+ })),
2105
+ }, [
2106
+ ...alignedRows(result.swarms.map((entry) => [
2107
+ `${entry.cid === result.effectiveCurrent ? "*" : " "} ${entry.alias ?? entry.cid}${entry.local ? " [local]" : ""}`,
2108
+ entry.cid,
2109
+ ])),
2110
+ ...(result.source === "flag" &&
2111
+ result.effectiveCurrent !== result.savedCurrent
2112
+ ? [
2113
+ `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)"))}.`,
2114
+ ]
2115
+ : []),
2116
+ ].join("\n"));
2117
+ return 0;
1646
2118
  }
1647
- if (state.legacyPinCount)
1648
- io.err(`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.`);
1649
2119
  if (parsed.path.startsWith("templates ") &&
1650
2120
  parsed.path !== "templates render") {
1651
2121
  const configUrl = requireSwarm();
1652
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1653
- const context = swarmContext();
1654
2122
  const expected = typeof parsed.options.expect === "string"
1655
2123
  ? parsed.options.expect
1656
2124
  : undefined;
1657
- try {
1658
- if (parsed.path === "templates list") {
1659
- const items = await swarmTemplates(context, configUrl);
1660
- const alias = state
1661
- .allSwarms()
1662
- .find((swarm) => swarm.cid === configUrl)?.alias;
1663
- emit({ items }, `Swarm: ${alias ? printable(alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nTemplates: ${items.length}\n\n${table(["NAME", "TITLE", "TARGET CID", "TEMPLATE CID"], items.map((item) => [
1664
- item.selector,
1665
- item.title,
1666
- item.targetCid,
1667
- item.templateCid,
1668
- ]), "No templates registered in this Swarm.\nAdd a template: ipab templates set NAME SOURCE")}`);
1669
- }
1670
- else if (parsed.path === "templates show") {
1671
- const item = (await swarmTemplates(context, configUrl, first))[0];
1672
- if (parsed.flags.json)
1673
- io.out(JSON.stringify(item));
1674
- else {
1675
- const alias = state
1676
- .allSwarms()
1677
- .find((swarm) => swarm.cid === configUrl)?.alias;
1678
- const swarm = alias ?? configUrl;
1679
- const reference = formatNameReference(swarm, item.name);
1680
- const tree = await templateOutputTree(context.store, item.templateCid);
1681
- const shell = process.platform === "win32" ? "powershell" : "posix";
1682
- io.out([
1683
- `${printable(item.selector)} — ${printable(item.title)}`,
1684
- printable(item.description) || "(No description.)",
1685
- "",
1686
- "Location",
1687
- ` Swarm: ${printable(swarm)}`,
1688
- ` Name: ${printable(item.name)}`,
1689
- "",
1690
- `Create a project (${shell === "powershell" ? "PowerShell" : "POSIX shell"})`,
1691
- ` ${templateRenderExample(reference, swarm, item.definition, shell)}`,
1692
- " Replace example parameter values as needed. No code is run by show.",
1693
- "",
1694
- "Parameters",
1695
- table(["NAME", "TYPE", "REQUIRED", "DEFAULT", "INPUT"], templateParameterRows(item.definition), "No parameters declared."),
1696
- "Required means an input is needed when no default is declared.",
1697
- "",
1698
- "Output files (from project/)",
1699
- " my-project/",
1700
- ...tree.entries.map((entry) => `${" ".repeat(entry.path.split("/").length + 1)}${printable(entry.path.split("/").at(-1))}${entry.kind === "directory" ? "/" : ""}`),
1701
- ...(tree.truncated
1702
- ? [
1703
- ` ... truncated: ${tree.truncated}; more files may exist.`,
1704
- ]
1705
- : tree.entries.length
1706
- ? []
1707
- : [" (no output files)"]),
1708
- "",
1709
- "Versions",
1710
- ` Template CID: ${item.templateCid}`,
1711
- ` Reference: ${reference}`,
1712
- ...(item.targetCid !== item.templateCid
1713
- ? [` Target CID (--expect): ${item.targetCid}`]
1714
- : []),
1715
- ].join("\n"));
1716
- }
1717
- }
1718
- else if (parsed.path === "templates set") {
1719
- const item = await setSwarmTemplate(context, configUrl, first, second, expected);
1720
- emit(item, `${item.reference} → ${item.targetCid} (Template ${item.templateCid})`);
1721
- }
2125
+ if (parsed.path === "templates list") {
2126
+ const response = (await client.swarms.fsLs({
2127
+ swarm: configUrl,
2128
+ kind: "templates",
2129
+ refresh: explicitRefresh,
2130
+ }, { ndjson: true }));
2131
+ emit({ items: response.items }, `Swarm: ${response.alias ? printable(response.alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nTemplates: ${response.items.length}\n\n${table(["NAME", "TITLE", "TARGET CID", "TEMPLATE CID"], response.items.map((item) => [
2132
+ item.selector,
2133
+ item.title,
2134
+ item.targetCid,
2135
+ item.templateCid,
2136
+ ]), "No templates registered in this Swarm.\nAdd a template: ipab templates set NAME SOURCE")}`);
2137
+ }
2138
+ else if (parsed.path === "templates show") {
2139
+ const { templateRenderExample, templateParameterRows } = await import("./template-presentation.js");
2140
+ const response = (await client.swarms.fsStat({
2141
+ swarm: configUrl,
2142
+ kind: "template",
2143
+ name: first,
2144
+ includeTree: !parsed.flags.json,
2145
+ refresh: explicitRefresh,
2146
+ }, { ndjson: true }));
2147
+ const { item, tree, alias } = response;
2148
+ if (parsed.flags.json)
2149
+ io.out(JSON.stringify(item));
1722
2150
  else {
1723
- const item = await removeSwarmTemplate(context, configUrl, first, expected);
1724
- emit({ removed: item }, `Removed ${item.reference}; content and history are retained.`);
2151
+ const previewTree = tree ?? { entries: [], truncated: null };
2152
+ const swarm = alias ?? configUrl;
2153
+ const reference = formatNameReference(swarm, item.name);
2154
+ const shell = process.platform === "win32" ? "powershell" : "posix";
2155
+ io.out([
2156
+ `${printable(item.selector)} — ${printable(item.title)}`,
2157
+ printable(item.description) || "(No description.)",
2158
+ "",
2159
+ "Location",
2160
+ ` Swarm: ${printable(swarm)}`,
2161
+ ` Name: ${printable(item.name)}`,
2162
+ "",
2163
+ `Create a project (${shell === "powershell" ? "PowerShell" : "POSIX shell"})`,
2164
+ ` ${templateRenderExample(reference, swarm, item.definition, shell)}`,
2165
+ " Replace example parameter values as needed. No code is run by show.",
2166
+ "",
2167
+ "Parameters",
2168
+ table(["NAME", "TYPE", "REQUIRED", "DEFAULT", "INPUT"], templateParameterRows(item.definition), "No parameters declared."),
2169
+ "Required means an input is needed when no default is declared.",
2170
+ "",
2171
+ "Output files (from project/)",
2172
+ " my-project/",
2173
+ ...previewTree.entries.map((entry) => `${" ".repeat(entry.path.split("/").length + 1)}${printable(entry.path.split("/").at(-1))}${entry.kind === "directory" ? "/" : ""}`),
2174
+ ...(previewTree.truncated
2175
+ ? [
2176
+ ` ... truncated: ${previewTree.truncated}; more files may exist.`,
2177
+ ]
2178
+ : previewTree.entries.length
2179
+ ? []
2180
+ : [" (no output files)"]),
2181
+ "",
2182
+ "Versions",
2183
+ ` Template CID: ${item.templateCid}`,
2184
+ ` Reference: ${reference}`,
2185
+ ...(item.targetCid !== item.templateCid
2186
+ ? [` Target CID (--expect): ${item.targetCid}`]
2187
+ : []),
2188
+ ].join("\n"));
1725
2189
  }
1726
2190
  }
1727
- finally {
1728
- await context.finishRead?.();
2191
+ else if (parsed.path === "templates set") {
2192
+ const source = await resolveLocalPathIfPresent(second);
2193
+ const item = (await client.swarms.fsSet({
2194
+ swarm: configUrl,
2195
+ kind: "template",
2196
+ name: first,
2197
+ source,
2198
+ expect: expected,
2199
+ }, { ndjson: true }));
2200
+ emit(item, `${item.reference} → ${item.targetCid} (Template ${item.templateCid})`);
2201
+ }
2202
+ else {
2203
+ const item = (await client.swarms.fsRm({
2204
+ swarm: configUrl,
2205
+ kind: "template",
2206
+ name: first,
2207
+ expect: expected,
2208
+ }, { ndjson: true }));
2209
+ emit({ removed: item }, `Removed ${item.reference}; content and history are retained.`);
1729
2210
  }
1730
2211
  return 0;
1731
2212
  }
1732
2213
  if (parsed.path.startsWith("register ")) {
2214
+ const { message } = await import("./errors.js");
1733
2215
  const references = parsed.registrySwarms?.length
1734
2216
  ? parsed.registrySwarms
1735
2217
  : selectedSwarm
@@ -1738,38 +2220,60 @@ async function performCli(argv, io, env) {
1738
2220
  if (!references.length)
1739
2221
  throw new HostError("Register requires a selected Swarm. Pass --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.");
1740
2222
  const targets = [
1741
- ...new Set(references.map((reference) => state.resolveSwarm(reference))),
2223
+ ...new Set(references.map((reference) => resolveSwarm(reference))),
1742
2224
  ];
1743
- const schema = first
1744
- ? state.resolve(schemaAlias(first), true)
1745
- : undefined;
1746
2225
  const results = [];
1747
2226
  const completed = [];
1748
2227
  const human = [];
1749
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2228
+ const resolvedApp = parsed.path === "register set"
2229
+ ? await resolveLocalPathIfPresent(second)
2230
+ : undefined;
2231
+ if (parsed.path === "register set" && targets.length > 1) {
2232
+ const batch = (await client.swarms.fsSet({
2233
+ swarm: targets[0],
2234
+ swarms: targets,
2235
+ kind: "register",
2236
+ schema: first,
2237
+ app: resolvedApp,
2238
+ argv: parsed.template ?? ["%"],
2239
+ replace: Boolean(parsed.options.replace),
2240
+ }, { ndjson: true }));
2241
+ for (let i = 0; i < targets.length; i++) {
2242
+ const association = batch.associations[i];
2243
+ results.push({ association });
2244
+ human.push(`${targets[i]}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`);
2245
+ }
2246
+ emit({
2247
+ swarms: results.map((result, index) => ({
2248
+ configUrl: targets[index],
2249
+ ...result,
2250
+ })),
2251
+ }, human.join("\n\n"));
2252
+ return 0;
2253
+ }
1750
2254
  for (const configUrl of targets) {
1751
- const context = swarmContext();
1752
2255
  try {
1753
2256
  if (parsed.path === "register list") {
1754
- const items = await swarmRegistrations(context, configUrl);
1755
- const alias = state
1756
- .allSwarms()
1757
- .find((swarm) => swarm.cid === configUrl)?.alias;
1758
- results.push({ items });
1759
- human.push(`Swarm: ${alias ? printable(alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nAssociations: ${items.length}\n\n${table(["TYPE CID", "APP CID"], items.map((item) => [item.schemaCid, item.appCid]), "No associations registered in this Swarm.\nRegister an App: ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS")}`);
2257
+ const response = (await client.swarms.fsLs({ swarm: configUrl, kind: "register" }, { ndjson: true }));
2258
+ results.push({ items: response.items });
2259
+ human.push(`Swarm: ${response.alias ? printable(response.alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nAssociations: ${response.items.length}\n\n${table(["TYPE CID", "APP CID"], response.items.map((item) => [item.schemaCid, item.appCid]), "No associations registered in this Swarm.\nRegister an App: ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS")}`);
1760
2260
  }
1761
2261
  else if (parsed.path === "register set") {
1762
- const appCid = parseNameReference(second)
1763
- ? (await resolveReference(context, second, configUrl, (reference) => state.resolve(reference))).cid
1764
- : state.resolve(second);
1765
- const association = await setSwarmAssociation(context, configUrl, createAssociation(schema, appCid, parsed.template ?? ["%"]), Boolean(parsed.options.replace));
2262
+ const association = (await client.swarms.fsSet({
2263
+ swarm: configUrl,
2264
+ kind: "register",
2265
+ schema: first,
2266
+ app: resolvedApp,
2267
+ argv: parsed.template ?? ["%"],
2268
+ replace: Boolean(parsed.options.replace),
2269
+ }, { ndjson: true }));
1766
2270
  results.push({ association });
1767
2271
  human.push(`${configUrl}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`);
1768
2272
  }
1769
2273
  else {
1770
- const removed = await removeSwarmAssociation(context, configUrl, schema);
1771
- results.push({ removed: [removed] });
1772
- human.push(`${configUrl}: removed association for ${removed}.`);
2274
+ const response = (await client.swarms.fsRm({ swarm: configUrl, kind: "register", schema: first }, { ndjson: true }));
2275
+ results.push({ removed: [response.removed] });
2276
+ human.push(`${configUrl}: removed association for ${response.removed}.`);
1773
2277
  }
1774
2278
  completed.push(configUrl);
1775
2279
  }
@@ -1778,9 +2282,6 @@ async function performCli(argv, io, env) {
1778
2282
  ? `Cannot list associations for Swarm ${configUrl}: ${message(cause)}`
1779
2283
  : `Registry operation failed for ${configUrl}: ${message(cause)}. Completed Swarms: ${completed.length ? completed.join(", ") : "(none)"}. Multiple Swarm edits are not atomic.`, cause instanceof HostError ? cause.exitCode : 1, cause instanceof HostError ? cause.code : "REGISTRY_FAILED", "publication");
1780
2284
  }
1781
- finally {
1782
- await context.finishRead?.();
1783
- }
1784
2285
  }
1785
2286
  emit({
1786
2287
  swarms: results.map((result, index) => ({
@@ -1792,8 +2293,6 @@ async function performCli(argv, io, env) {
1792
2293
  }
1793
2294
  switch (parsed.path) {
1794
2295
  case "profile": {
1795
- const context = swarmContext();
1796
- readContext = context;
1797
2296
  const changes = {
1798
2297
  ...(typeof parsed.options.name === "string"
1799
2298
  ? { name: parsed.options.name }
@@ -1803,11 +2302,15 @@ async function performCli(argv, io, env) {
1803
2302
  : {}),
1804
2303
  };
1805
2304
  if (!Object.keys(changes).length) {
1806
- const profile = await accountProfile(context);
2305
+ const profile = (await client.swarms.identity({
2306
+ ndjson: true,
2307
+ }));
1807
2308
  emit({ profile, localPersisted: profile.updatedAt !== null }, `Name: ${printable(profile.name)}\nDescription: ${printable(profile.description)}\nPublic key: ${profile.publicKey}`);
1808
2309
  }
1809
2310
  else {
1810
- const result = await updateAccountProfile(context, changes);
2311
+ const result = (await client.swarms.governance("profile", changes, {
2312
+ ndjson: true,
2313
+ }));
1811
2314
  emit(result, [
1812
2315
  `Name: ${printable(result.profile.name)}`,
1813
2316
  `Description: ${printable(result.profile.description)}`,
@@ -1821,49 +2324,30 @@ async function performCli(argv, io, env) {
1821
2324
  }
1822
2325
  break;
1823
2326
  }
1824
- case "swarm list": {
1825
- const result = { swarms: state.allSwarms(), ...selection() };
1826
- emit({
1827
- ...result,
1828
- swarms: result.swarms.map((entry) => ({
1829
- configUrl: entry.cid,
1830
- alias: entry.alias,
1831
- local: Boolean(entry.local),
1832
- })),
1833
- }, [
1834
- ...alignedRows(result.swarms.map((entry) => [
1835
- `${entry.cid === result.effectiveCurrent ? "*" : " "} ${entry.alias ?? entry.cid}${entry.local ? " [local]" : ""}`,
1836
- entry.cid,
1837
- ])),
1838
- ...(result.source === "flag" &&
1839
- result.effectiveCurrent !== result.savedCurrent
1840
- ? [
1841
- `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)"))}.`,
1842
- ]
1843
- : []),
1844
- ].join("\n"));
1845
- break;
1846
- }
1847
2327
  case "swarm use": {
1848
- state.useSwarm(first);
1849
- const result = selection();
2328
+ const resolvedUrl = resolveSwarm(first);
2329
+ const registered = registeredSwarms.some((entry) => entry.cid === resolvedUrl);
2330
+ if (!registered) {
2331
+ throw new HostError(`Unknown Swarm "${first}". Run ipab swarm list or register it with ipab swarm set ALIAS CONFIG_URL.`);
2332
+ }
2333
+ await client.host.setConfig("swarm.default", resolvedUrl, {
2334
+ fromString: true,
2335
+ });
2336
+ const result = selection(resolvedUrl);
1850
2337
  emit(result, `Saved current swarm: ${result.savedCurrent}`);
1851
2338
  if (result.source === "flag" || result.source === "env")
1852
2339
  io.err(`The saved default is overridden by ${result.source}: ${result.effectiveCurrent}.`);
1853
2340
  break;
1854
2341
  }
1855
2342
  case "swarm remove": {
1856
- const removed = state.removeSwarm(first);
1857
- emit({
1858
- removed,
1859
- savedCurrent: state.config({ includeSecrets: false })["swarm.default"] ?? null,
1860
- }, `Removed registration ${removed}. Credentials, content and remote membership are unchanged.`);
2343
+ const result = await client.swarms.remove({ swarm: first });
2344
+ emit(result, `Removed registration ${result.removed}. Credentials, content and remote membership are unchanged.`);
1861
2345
  break;
1862
2346
  }
1863
2347
  case "swarm set": {
1864
2348
  swarmAlias(first);
1865
2349
  const cid = swarmUrl(second);
1866
- const previous = state.swarms().find((entry) => entry.alias === first);
2350
+ const previous = registeredSwarms.find((entry) => entry.alias === first);
1867
2351
  if (previous && previous.cid !== cid) {
1868
2352
  io.err(`Swarm alias ${first}: ${previous.cid} -> ${cid}`);
1869
2353
  if (!parsed.options.yes &&
@@ -1871,473 +2355,645 @@ async function performCli(argv, io, env) {
1871
2355
  !(await io.confirm(`Retarget local Swarm alias "${first}" from ${previous.cid} to ${cid}?`))))
1872
2356
  throw new HostError("Alias unchanged. Retargeting requires --yes or interactive confirmation.");
1873
2357
  }
1874
- const entry = state.setSwarm(first, cid, previous?.cid ?? null);
1875
- emit({
1876
- configUrl: entry.cid,
1877
- alias: entry.alias,
1878
- savedCurrent: state.config({ includeSecrets: false })["swarm.default"] ?? null,
1879
- }, `Set local swarm alias ${entry.alias} (${cid}).`);
2358
+ const entry = await client.swarms.set({
2359
+ alias: first,
2360
+ url: cid,
2361
+ expectedTarget: previous?.cid ?? null,
2362
+ });
2363
+ emit(entry, `Set local swarm alias ${entry.alias} (${cid}).`);
1880
2364
  break;
1881
2365
  }
1882
- case "daemon": {
1883
- if (parsed.flags.json)
1884
- syntax("--json is not supported for daemon; diagnostics are written to stderr.");
1885
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1886
- const controller = new AbortController();
1887
- const interrupt = () => {
1888
- controller.abort();
1889
- };
1890
- process.once("SIGINT", interrupt);
1891
- process.once("SIGTERM", interrupt);
1892
- try {
1893
- await swarmDaemon(swarmContext(), controller.signal, (ctx, url, report) => syncDaemonSwarm(ctx, url, undefined, report));
1894
- }
1895
- catch (cause) {
1896
- if (!controller.signal.aborted)
1897
- throw cause;
1898
- }
1899
- finally {
1900
- process.removeListener("SIGINT", interrupt);
1901
- process.removeListener("SIGTERM", interrupt);
2366
+ case "fs ls": {
2367
+ const result = await client.swarms.fsLs({
2368
+ swarm: requireSwarm(),
2369
+ path: first,
2370
+ all: Boolean(parsed.options.all),
2371
+ recursive: Boolean(parsed.options.recursive),
2372
+ refresh: explicitRefresh,
2373
+ }, { ndjson: true });
2374
+ const text = result.entries.length
2375
+ ? result.entries
2376
+ .map((entry) => `${result.recursive ? entry.path : entry.name}\t${entry.cid ?? "<dir>"}\t${entry.size !== null ? String(entry.size) : entry.kind}`)
2377
+ .join("\n")
2378
+ : "No entries.";
2379
+ emit(result, text);
2380
+ if (result.truncated || result.skippedSubtrees > 0) {
2381
+ io.err(`Listing incomplete: truncated=${String(result.truncated)}, skippedSubtrees=${String(result.skippedSubtrees)}.`);
1902
2382
  }
1903
2383
  break;
1904
2384
  }
1905
- case "swarm update":
1906
- case "search":
1907
- case "skills list":
1908
- case "skills sync":
1909
- case "swarm create":
1910
- case "swarm request":
1911
- case "swarm approve":
1912
- case "swarm pivot grant":
1913
- case "swarm export":
1914
- case "swarm exclude":
1915
- case "swarm resume":
1916
- case "swarm profile":
1917
- case "swarm members":
1918
- case "swarm status":
1919
- case "publish":
1920
- case "pin":
1921
- case "get": {
1922
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1923
- const context = swarmContext();
1924
- readContext = context;
1925
- if (parsed.path.startsWith("skills ")) {
1926
- const result = await manageSkills(context, requireSwarm(), {
1927
- sync: parsed.path === "skills sync",
1928
- names: parsed.positional,
1929
- agents: parsed.agents ?? [],
1930
- overrideExisting: Boolean(parsed.options["override-existing"]),
2385
+ case "fs stat": {
2386
+ const result = await client.swarms.fsStat({
2387
+ swarm: requireSwarm(),
2388
+ path: first,
2389
+ ...(explicitRefresh !== undefined
2390
+ ? { refresh: explicitRefresh }
2391
+ : {}),
2392
+ }, { ndjson: true });
2393
+ const lines = [
2394
+ `Path: ${result.path || "/"}`,
2395
+ `CID: ${result.cid ?? "(virtual)"}`,
2396
+ `Kind: ${result.kind}`,
2397
+ `Size: ${result.size !== null ? String(result.size) : "unavailable"}`,
2398
+ ...(result.kind === "directory" && result.isBundle !== undefined
2399
+ ? [`Bundle: ${result.isBundle ? "yes" : "no"}`]
2400
+ : []),
2401
+ ...(result.kind === "directory" && result.entryCount !== undefined
2402
+ ? [`Entries: ${result.entryCount}`]
2403
+ : []),
2404
+ `Swarm: ${result.swarm}`,
2405
+ `Snapshot: ${result.snapshotVersion === "legacy" ? "legacy (read-only virtual)" : "v7"}`,
2406
+ ];
2407
+ emit(result, lines.join("\n"));
2408
+ break;
2409
+ }
2410
+ case "fs set": {
2411
+ const result = await client.swarms.fsSet({
2412
+ swarm: requireSwarm(),
2413
+ path: first,
2414
+ cid: second,
2415
+ ...(typeof parsed.options.expect === "string"
2416
+ ? { expect: parsed.options.expect }
2417
+ : {}),
2418
+ ...(parsed.options.replace ? { replace: true } : {}),
2419
+ }, { ndjson: true });
2420
+ emit(result, result.changed
2421
+ ? `Set ${result.path} -> ${result.cid} (HEAD ${result.headCid})`
2422
+ : `Unchanged ${result.path} -> ${result.cid} (HEAD ${result.headCid})`);
2423
+ break;
2424
+ }
2425
+ case "fs rm": {
2426
+ const result = await client.swarms.fsRm({
2427
+ swarm: requireSwarm(),
2428
+ path: first,
2429
+ ...(typeof parsed.options.expect === "string"
2430
+ ? { expect: parsed.options.expect }
2431
+ : {}),
2432
+ }, { ndjson: true });
2433
+ emit(result, `Removed ${result.path} (was ${result.removedCid}, HEAD ${result.headCid})`);
2434
+ break;
2435
+ }
2436
+ case "swarm replicate": {
2437
+ const result = (await client.swarms.replicate({
2438
+ swarm: requireSwarm(),
2439
+ ...(typeof parsed.options.pivot === "string"
2440
+ ? { pivot: parsed.options.pivot }
2441
+ : {}),
2442
+ }, { ndjson: true }));
2443
+ emit(result, [
2444
+ `HEAD: ${result.headCid}`,
2445
+ ...result.results.map((entry) => `${entry.peerId}: ${entry.status}${entry.error ? ` (${entry.error})` : ""}`),
2446
+ ].join("\n"));
2447
+ break;
2448
+ }
2449
+ case "skills show": {
2450
+ const named = parseNameReference(first);
2451
+ const targetSwarm = named?.swarm
2452
+ ? resolveSwarm(named.swarm)
2453
+ : requireSwarm();
2454
+ const ref = await resolveLocalPathIfPresent(first);
2455
+ const payload = (await client.swarms.fsStat({
2456
+ swarm: targetSwarm,
2457
+ kind: "skill",
2458
+ ref,
2459
+ ...(explicitRefresh !== undefined
2460
+ ? { refresh: explicitRefresh }
2461
+ : {}),
2462
+ }, { ndjson: true }));
2463
+ const lines = [
2464
+ `Swarm: ${payload.swarm}`,
2465
+ `Schema: ${payload.schemaCid}`,
2466
+ ...(payload.contentCid ? [`Content CID: ${payload.contentCid}`] : []),
2467
+ `Skill: ${payload.identity}`,
2468
+ `Skill CID: ${payload.cid}`,
2469
+ `Path: ${payload.name}`,
2470
+ `Description: ${payload.description}`,
2471
+ ];
2472
+ emit(payload, lines.join("\n"));
2473
+ break;
2474
+ }
2475
+ case "skills set": {
2476
+ const targetSwarm = requireSwarm();
2477
+ const skill = await resolveLocalPathIfPresent(first);
2478
+ const result = (await client.swarms.fsSet({
2479
+ swarm: targetSwarm,
2480
+ kind: "skill",
2481
+ skill,
2482
+ global: Boolean(parsed.options.global),
2483
+ types: parsed.types ?? [],
2484
+ replace: Boolean(parsed.options.replace),
2485
+ }, { ndjson: true }));
2486
+ const text = result.changed
2487
+ ? [
2488
+ `Skill: ${result.identity} (${result.cid})`,
2489
+ `HEAD: ${result.headCid}`,
2490
+ ...result.targets.map((target) => {
2491
+ const status = !target.changed
2492
+ ? "unchanged"
2493
+ : target.previousCid
2494
+ ? "updated"
2495
+ : "created";
2496
+ return target.scope === "global"
2497
+ ? ` global -> ${target.name} (${status})`
2498
+ : ` type ${target.schemaCid} -> ${target.name} (${status})`;
2499
+ }),
2500
+ ].join("\n")
2501
+ : `Unchanged: ${result.identity} (${result.cid}) (HEAD ${result.headCid})`;
2502
+ emit(result, text);
2503
+ break;
2504
+ }
2505
+ case "skills remove": {
2506
+ const targetSwarm = requireSwarm();
2507
+ const globalName = typeof parsed.options.global === "string"
2508
+ ? parsed.options.global
2509
+ : undefined;
2510
+ const result = (await client.swarms.fsRm({
2511
+ swarm: targetSwarm,
2512
+ kind: "skill",
2513
+ ...(globalName !== undefined ? { globalName } : {}),
2514
+ types: parsed.types ?? [],
2515
+ }, { ndjson: true }));
2516
+ const lines = [
2517
+ `Removed ${result.removed.length} Skill association(s) (HEAD ${result.headCid}):`,
2518
+ ...result.removed.map((entry) => entry.scope === "global"
2519
+ ? ` global ${entry.name} (was ${entry.removedCid})`
2520
+ : ` type ${entry.schemaCid} ${entry.name} (was ${entry.removedCid})`),
2521
+ ];
2522
+ emit(result, lines.join("\n"));
2523
+ break;
2524
+ }
2525
+ case "skills list": {
2526
+ const targetSwarm = requireSwarm();
2527
+ const result = (await client.swarms.fsLs({
2528
+ swarm: targetSwarm,
2529
+ kind: "skills",
2530
+ names: parsed.positional,
2531
+ agents: parsed.agents ?? [],
2532
+ refresh: explicitRefresh,
2533
+ }, { ndjson: true }));
2534
+ const globalLines = [
2535
+ table(["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"], result.items.map((skill) => [
2536
+ skill.name,
2537
+ skill.cid,
2538
+ skill.identity,
2539
+ skill.status,
2540
+ ]), "No Global Skills."),
2541
+ ...result.items.flatMap((skill) => skill.problems),
2542
+ ...result.orphaned.map((skill) => `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`),
2543
+ ];
2544
+ const typeLines = [
2545
+ "Type Skills:",
2546
+ table(["TYPE CID", "SKILL NAME", "SKILL CID"], result.typeSkills.map((entry) => [
2547
+ entry.schemaCid,
2548
+ entry.identity,
2549
+ entry.cid,
2550
+ ]), "No Type Skills."),
2551
+ ];
2552
+ emit(result, [...globalLines, "", ...typeLines].join("\n"));
2553
+ if (!result.ok)
2554
+ return 1;
2555
+ break;
2556
+ }
2557
+ case "skills sync": {
2558
+ const targetSwarm = requireSwarm();
2559
+ const syncParams = {
2560
+ swarm: targetSwarm,
2561
+ names: parsed.positional,
2562
+ agents: parsed.agents ?? [],
2563
+ overrideExisting: Boolean(parsed.options["override-existing"]),
2564
+ refresh: explicitRefresh,
2565
+ };
2566
+ let result;
2567
+ if (parsed.options["dry-run"] || parsed.options.yes || !io.tty) {
2568
+ result = (await client.host.syncSkills({
2569
+ ...syncParams,
1931
2570
  dryRun: Boolean(parsed.options["dry-run"]),
1932
2571
  yes: Boolean(parsed.options.yes),
1933
- tty: io.tty,
1934
- confirm: (text) => io.confirm(text),
1935
- preview: (text) => {
1936
- io.err(text);
1937
- },
1938
- });
1939
- store = context.store;
1940
- emit(result, [
1941
- table(["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"], result.items.map((skill) => [
1942
- skill.name,
1943
- skill.cid,
1944
- skill.identity,
1945
- skill.status,
1946
- ]), "No Skills."),
1947
- ...result.items.flatMap((skill) => skill.problems),
1948
- ...result.orphaned.map((skill) => `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`),
1949
- ...result.results.map((entry) => `${entry.name} / ${entry.agent}: ${entry.status}${entry.error ? `: ${entry.error}` : ""}`),
1950
- ].join("\n"));
1951
- if (!result.ok)
1952
- return 1;
1953
- break;
1954
- }
1955
- if (parsed.path === "pin") {
1956
- io.err("Fetching, verifying and retaining content...");
1957
- const result = await pinNameSubscription(context, first, selectedSwarm);
1958
- store = context.store;
1959
- emit(result, `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`);
1960
- break;
1961
- }
1962
- if (parsed.path === "swarm members") {
1963
- const result = await swarmMembers(context, requireSwarm(), Boolean(parsed.options.refresh || parsed.options.force));
1964
- if (result.mode === "local") {
1965
- emit(result, [
1966
- "Swarm: local (Built-in single-machine Swarm)",
1967
- "Mode: local",
1968
- "Members: local user only (single-machine; no remote collaborators or HOME identity required)",
1969
- ].join("\n"));
1970
- break;
1971
- }
1972
- emit(result, [
1973
- `Directory: ${result.cache.source} (${result.cache.freshness}), observed ${result.cache.updatedAt}`,
1974
- `Daemon: ${result.local.status}, observed ${result.local.updatedAt ?? "unknown"}; control-plane verified ${result.local.verifiedAt ?? "unknown"}`,
1975
- table(["NAME", "DESCRIPTION", "ROLE", "PIVOT", "PUBLIC KEY"], result.members.map((member) => [
1976
- member.name,
1977
- member.description,
1978
- member.role,
1979
- member.pivot ? (member.localStatus ?? "candidate") : "-",
1980
- member.publicKey,
1981
- ]), "No members."),
1982
- ].join("\n"));
1983
- if (result.local.error)
1984
- io.err(`Local Pivot observations (${result.local.status}): ${printable(result.local.error)}`);
1985
- break;
1986
- }
1987
- if (parsed.path === "swarm export") {
1988
- const member = await exportRequest(context, requireSwarm(), String(parsed.options.output ?? ""));
1989
- emit({ member }, member);
1990
- break;
1991
- }
1992
- if (parsed.path === "swarm pivot grant") {
1993
- const url = requireSwarm();
1994
- if (!parsed.options.yes)
1995
- syntax("Granting Pivot HEAD receipt authority requires --yes; revoking it requires swarm exclude.");
1996
- const result = await grantPivotAuthority(context, url, first);
1997
- store = context.store;
1998
- emit(result, `Granted Pivot HEAD authority to ${result.member} on ${result.configUrl} (HEAD ${result.headId}). Revoking Pivot HEAD authority requires swarm exclude.`);
1999
- break;
2572
+ }, { ndjson: true }));
2000
2573
  }
2001
- if (["swarm exclude", "swarm resume", "swarm profile"].includes(parsed.path)) {
2002
- const url = requireSwarm();
2003
- if (parsed.path === "swarm exclude") {
2004
- if (!parsed.options.yes)
2005
- syntax("Member removal is irreversible; --yes required.");
2006
- await removeMember(context, url, first);
2574
+ else {
2575
+ const preview = (await client.host.syncSkills({
2576
+ ...syncParams,
2577
+ dryRun: true,
2578
+ yes: false,
2579
+ }, { ndjson: true }));
2580
+ if (!preview.ok) {
2581
+ result = preview;
2007
2582
  }
2008
- else if (parsed.path === "swarm resume")
2009
- await resumeRemoval(context, url);
2010
2583
  else {
2011
- const profile = await updateProfile(context, url, {
2012
- ...(typeof parsed.options.address === "string"
2013
- ? { addresses: [parsed.options.address] }
2014
- : {}),
2015
- ...(typeof parsed.options.pivot === "string"
2016
- ? {
2017
- pivot: Boolean(parseValue("swarm.pivot", parsed.options.pivot, true)),
2018
- }
2019
- : {}),
2020
- });
2021
- emit(profile, JSON.stringify(profile));
2022
- store = context.store;
2023
- break;
2584
+ const selected = preview.items.filter((skill) => !parsed.positional.length ||
2585
+ parsed.positional.includes(skill.name) ||
2586
+ parsed.positional.includes(skill.identity));
2587
+ const hasChanges = selected.some((skill) => skill.agents.some((agent) => agent.status !== "current"));
2588
+ if (!selected.length) {
2589
+ result = { ...preview, dryRun: false };
2590
+ }
2591
+ else {
2592
+ if (hasChanges &&
2593
+ !(await io.confirm(`Authorize ${preview.installer} and the changes above?`))) {
2594
+ throw new HostError("Skill sync requires --yes or interactive consent. Use --override-existing to authorize replacing existing Skills; source and link conflicts remain protected.");
2595
+ }
2596
+ result = (await client.host.syncSkills({
2597
+ ...syncParams,
2598
+ dryRun: false,
2599
+ yes: true,
2600
+ quietPreview: true,
2601
+ }, { ndjson: true }));
2602
+ }
2024
2603
  }
2025
- store = context.store;
2026
- emit({ url, completed: true }, `Organization switch complete: ${url}`);
2027
- break;
2028
2604
  }
2029
- if (parsed.path === "swarm update") {
2030
- const cid = requireSwarm();
2031
- const result = await updateSwarm(context, cid, {
2032
- ...(typeof parsed.options.name === "string"
2033
- ? { name: parsed.options.name }
2034
- : {}),
2035
- ...(typeof parsed.options.description === "string"
2036
- ? { description: parsed.options.description }
2037
- : {}),
2038
- });
2039
- emit(result, `Swarm: ${result.configUrl}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD ID: ${result.headId}\nConfig content CID: ${result.valueCid}`);
2040
- break;
2041
- }
2042
- if (parsed.path === "search") {
2043
- const registrations = state.allSwarms();
2044
- const scope = parsed.options.all
2045
- ? registrations
2046
- : [
2047
- {
2048
- cid: requireSwarm(),
2049
- alias: registrations.find((entry) => entry.cid === selectedSwarm)
2050
- ?.alias ?? null,
2051
- },
2052
- ];
2053
- const searchOptions = {};
2054
- if (typeof parsed.options.prefix === "string")
2055
- searchOptions.prefix = parsed.options.prefix;
2056
- if (typeof parsed.options.kind === "string")
2057
- searchOptions.kind = parsed.options.kind;
2058
- if (typeof parsed.options.schema === "string")
2059
- searchOptions.schemaCid = parsed.options.schema;
2060
- if (typeof parsed.options.limit === "string")
2061
- searchOptions.limit = /^\d+$/.test(parsed.options.limit)
2062
- ? Number(parsed.options.limit)
2063
- : Number.NaN;
2064
- if (typeof parsed.options.offset === "string")
2065
- searchOptions.offset = /^\d+$/.test(parsed.options.offset)
2066
- ? Number(parsed.options.offset)
2067
- : Number.NaN;
2068
- const result = Object.keys(searchOptions).length
2069
- ? await searchNames(context, first, scope, searchOptions)
2070
- : await searchNames(context, first, scope);
2071
- emit(result, formatSearchResults(result.matches));
2605
+ emit(result, [
2606
+ table(["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"], result.items.map((skill) => [
2607
+ skill.name,
2608
+ skill.cid,
2609
+ skill.identity,
2610
+ skill.status,
2611
+ ]), "No Skills."),
2612
+ ...result.items.flatMap((skill) => skill.problems),
2613
+ ...result.orphaned.map((skill) => `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`),
2614
+ ...result.results.map((entry) => `${entry.name} / ${entry.agent}: ${entry.status}${entry.error ? `: ${entry.error}` : ""}`),
2615
+ ].join("\n"));
2616
+ if (!result.ok)
2617
+ return 1;
2618
+ break;
2619
+ }
2620
+ case "pin": {
2621
+ io.err("Fetching, verifying and retaining content...");
2622
+ const result = await client.store.addPin({
2623
+ ref: first,
2624
+ swarm: selectedSwarm,
2625
+ refresh: explicitRefresh,
2626
+ }, { ndjson: true });
2627
+ emit(result, `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`);
2628
+ break;
2629
+ }
2630
+ case "swarm members": {
2631
+ const result = (await client.swarms.members({
2632
+ swarm: requireSwarm(),
2633
+ refresh: Boolean(parsed.options.refresh || parsed.options.force),
2634
+ }, { ndjson: true }));
2635
+ if (result.mode === "local") {
2636
+ emit(result, [
2637
+ "Swarm: local (Built-in single-machine Swarm)",
2638
+ "Mode: local",
2639
+ "Members: local user only (single-machine; no remote collaborators or HOME identity required)",
2640
+ ].join("\n"));
2072
2641
  break;
2073
2642
  }
2074
- if (parsed.path === "swarm status") {
2075
- const cid = requireSwarm();
2076
- const status = await inspectSwarmStatus(context, cid, Boolean(parsed.options.refresh || parsed.options.force));
2077
- store = context.store;
2078
- if (status.mode === "local") {
2079
- emit({
2080
- mode: "local",
2081
- configUrl: cid,
2082
- root: status.head.root,
2083
- valueCid: status.head.cid,
2084
- properties: {
2085
- name: status.config.name,
2086
- description: status.config.description,
2087
- },
2088
- local: status.local,
2089
- }, [
2090
- "Swarm",
2091
- " Mode: local (built-in single-machine Swarm)",
2092
- ` Name: ${printable(status.config.name)}`,
2093
- ` Description: ${printable(status.config.description)}`,
2094
- " Config URL:",
2095
- ` ${cid}`,
2096
- "",
2097
- "Content",
2098
- " HEAD (publication root):",
2099
- ` ${status.head.root}`,
2100
- " Content CID (HEAD value):",
2101
- ` ${status.head.cid}`,
2102
- ` Names: ${status.local.names} (Templates: ${status.local.templates}, Skills: ${status.local.skills}, Registrations: ${status.local.registrations})`,
2103
- ].join("\n"));
2104
- break;
2105
- }
2106
- const { head, config, networking, cache, lastWriter, state: contentState, } = status;
2107
- const fingerprint = await keyId(config.owner);
2643
+ emit(result, [
2644
+ `Directory: ${result.cache.source} (${result.cache.freshness}), observed ${result.cache.updatedAt}`,
2645
+ `Daemon: ${result.local.status}, observed ${result.local.updatedAt ?? "unknown"}; control-plane verified ${result.local.verifiedAt ?? "unknown"}`,
2646
+ table(["NAME", "DESCRIPTION", "ROLE", "PIVOT", "PUBLIC KEY"], result.members.map((member) => [
2647
+ member.name,
2648
+ member.description,
2649
+ member.role,
2650
+ member.pivot ? (member.localStatus ?? "candidate") : "-",
2651
+ member.publicKey,
2652
+ ]), "No members."),
2653
+ ].join("\n"));
2654
+ if (result.local.error)
2655
+ io.err(`Local Pivot observations (${result.local.status}): ${printable(result.local.error)}`);
2656
+ break;
2657
+ }
2658
+ case "swarm export": {
2659
+ const output = typeof parsed.options.output === "string"
2660
+ ? resolve(parsed.options.output)
2661
+ : "";
2662
+ const result = (await client.swarms.governance("export", { swarm: requireSwarm(), output }, { ndjson: true }));
2663
+ emit({ member: result.member }, result.member);
2664
+ break;
2665
+ }
2666
+ case "swarm pivot grant": {
2667
+ const url = requireSwarm();
2668
+ if (!parsed.options.yes)
2669
+ syntax("Granting Pivot HEAD receipt authority requires --yes; revoking it requires swarm exclude.");
2670
+ const result = (await client.swarms.governance("pivot-grant", { swarm: url, member: first }, { ndjson: true }));
2671
+ emit(result, `Granted Pivot HEAD authority to ${result.member} on ${result.configUrl} (HEAD ${result.headId}). Revoking Pivot HEAD authority requires swarm exclude.`);
2672
+ break;
2673
+ }
2674
+ case "swarm exclude": {
2675
+ const url = requireSwarm();
2676
+ if (!parsed.options.yes)
2677
+ syntax("Member removal is irreversible; --yes required.");
2678
+ await client.swarms.governance("exclude", { swarm: url, member: first }, { ndjson: true });
2679
+ emit({ url, completed: true }, `Organization switch complete: ${url}`);
2680
+ break;
2681
+ }
2682
+ case "swarm resume": {
2683
+ const url = requireSwarm();
2684
+ await client.swarms.governance("resume", { swarm: url }, { ndjson: true });
2685
+ emit({ url, completed: true }, `Organization switch complete: ${url}`);
2686
+ break;
2687
+ }
2688
+ case "swarm profile": {
2689
+ const url = requireSwarm();
2690
+ const profile = await client.swarms.governance("profile", {
2691
+ swarm: url,
2692
+ ...(typeof parsed.options.address === "string"
2693
+ ? { addresses: [parsed.options.address] }
2694
+ : {}),
2695
+ ...(typeof parsed.options.pivot === "string"
2696
+ ? {
2697
+ pivot: Boolean(parseValue("swarm.pivot", parsed.options.pivot, true)),
2698
+ }
2699
+ : {}),
2700
+ }, { ndjson: true });
2701
+ emit(profile, JSON.stringify(profile));
2702
+ break;
2703
+ }
2704
+ case "swarm update": {
2705
+ const cid = requireSwarm();
2706
+ const result = (await client.swarms.update({
2707
+ swarm: cid,
2708
+ ...(typeof parsed.options.name === "string"
2709
+ ? { name: parsed.options.name }
2710
+ : {}),
2711
+ ...(typeof parsed.options.description === "string"
2712
+ ? { description: parsed.options.description }
2713
+ : {}),
2714
+ }, { ndjson: true }));
2715
+ emit(result, `Swarm: ${result.configUrl}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD ID: ${result.headId}\nConfig content CID: ${result.valueCid}`);
2716
+ break;
2717
+ }
2718
+ case "search": {
2719
+ const result = (await client.swarms.search({
2720
+ ...(parsed.options.all
2721
+ ? { swarms: registeredSwarms.map((entry) => entry.cid) }
2722
+ : { swarm: requireSwarm() }),
2723
+ q: first,
2724
+ ...(typeof parsed.options.prefix === "string"
2725
+ ? { prefix: parsed.options.prefix }
2726
+ : {}),
2727
+ ...(typeof parsed.options.kind === "string"
2728
+ ? {
2729
+ kind: parsed.options.kind,
2730
+ }
2731
+ : {}),
2732
+ ...(typeof parsed.options.schema === "string"
2733
+ ? { schemaCid: parsed.options.schema }
2734
+ : {}),
2735
+ ...(typeof parsed.options.limit === "string"
2736
+ ? { limit: parsed.options.limit }
2737
+ : {}),
2738
+ ...(typeof parsed.options.offset === "string"
2739
+ ? { offset: parsed.options.offset }
2740
+ : {}),
2741
+ refresh: explicitRefresh,
2742
+ }, { ndjson: true }));
2743
+ emit(result, formatSearchResults(result.matches));
2744
+ break;
2745
+ }
2746
+ case "swarm status": {
2747
+ const { keyId } = await import("@ipab/bundle/pointer/crypto");
2748
+ const cid = requireSwarm();
2749
+ const status = (await client.swarms.status({
2750
+ swarm: cid,
2751
+ refresh: Boolean(parsed.options.refresh || parsed.options.force),
2752
+ }, { ndjson: true }));
2753
+ if (status.mode === "local") {
2108
2754
  emit({
2755
+ mode: "local",
2109
2756
  configUrl: cid,
2110
- owner: config.owner,
2111
- ownerFingerprint: fingerprint,
2112
- epoch: config.epoch,
2113
- scopeId: config.scopeId,
2114
- headId: config.headId,
2115
- cache,
2116
- state: contentState,
2117
- networking,
2118
- root: head.root,
2119
- valueCid: head.cid,
2120
- lastWriter,
2757
+ root: status.head.root,
2758
+ valueCid: status.head.cid,
2121
2759
  properties: {
2122
- name: config.name,
2123
- description: config.description,
2760
+ name: status.config.name,
2761
+ description: status.config.description,
2124
2762
  },
2763
+ local: status.local,
2125
2764
  }, [
2126
2765
  "Swarm",
2127
- ` Directory: ${cache.source} (${cache.freshness}), observed ${cache.updatedAt}`,
2128
- ` Name: ${printable(config.name)}`,
2129
- ` Description: ${config.description ? printable(config.description) : "(none)"}`,
2766
+ " Mode: local (built-in single-machine Swarm)",
2767
+ ` Name: ${printable(status.config.name)}`,
2768
+ ` Description: ${printable(status.config.description)}`,
2130
2769
  " Config URL:",
2131
2770
  ` ${cid}`,
2132
2771
  "",
2133
- "Identity",
2134
- " Owner fingerprint:",
2135
- ` ${fingerprint}`,
2136
- "",
2137
2772
  "Content",
2138
2773
  " HEAD (publication root):",
2139
- ` ${head.root}`,
2774
+ ` ${status.head.root}`,
2140
2775
  " Content CID (HEAD value):",
2141
- ` ${head.cid}`,
2142
- ...(lastWriter
2143
- ? [
2144
- ` Last HEAD writer: ${lastWriter.name ? printable(lastWriter.name) : "(profile name unavailable)"}`,
2145
- ` Public key: ${lastWriter.subject}`,
2146
- ` PeerID: ${lastWriter.peerId ?? "unknown"}`,
2147
- ` Updated: ${lastWriter.updatedAt} (service time)`,
2148
- " Last writer is not a confirmed content holder or the only copy.",
2149
- ]
2150
- : [
2151
- " Last HEAD writer/time: unknown (legacy record or service without update metadata).",
2152
- ]),
2153
- ` State: ${contentState.status}. ${contentState.error}`,
2154
- "",
2155
- "Local networking",
2156
- ` Daemon observations: ${networking.daemon.status}`,
2157
- ` Updated: ${networking.daemon.updatedAt ?? "unknown"}`,
2158
- ` Control-plane verified: ${networking.daemon.verifiedAt ?? "unknown"}`,
2159
- ...(networking.daemon.error
2160
- ? [` Observation error: ${printable(networking.daemon.error)}`]
2161
- : []),
2162
- ` Connections observed: ${networking.connections.observedAt ?? "unknown"} (${networking.connections.freshness})`,
2163
- ...(networking.connections.error
2164
- ? [
2165
- ` Connection error: ${printable(networking.connections.error)}`,
2166
- ]
2167
- : []),
2168
- table([
2169
- "PIVOT PEER ID",
2170
- "LOCAL",
2171
- "PROBE",
2172
- "PROBED AT",
2173
- "FAILURES",
2174
- "RETRY AT",
2175
- "CONNECTION",
2176
- ], networking.pivots.map((pivot) => [
2177
- pivot.peerId,
2178
- pivot.localStatus ?? "unknown",
2179
- `${pivot.probe.result} (${pivot.probe.freshness})`,
2180
- pivot.probe.at ?? "-",
2181
- pivot.failures === null ? "-" : String(pivot.failures),
2182
- pivot.retryAt ?? "-",
2183
- pivot.connection.status,
2184
- ]), "No declared Pivots."),
2185
- ...networking.pivots.flatMap((pivot) => pivot.probe.error
2186
- ? [
2187
- ` ${pivot.peerId} probe error: ${printable(pivot.probe.error)}`,
2188
- ]
2189
- : []),
2190
- ...(networking.connections.error
2191
- ? []
2192
- : [
2193
- table(["CONNECTED PEER ID", "TRANSPORT", "ADDRESS"], networking.connections.peers.map((peer) => [
2194
- peer.peerId,
2195
- peer.transport,
2196
- peer.address,
2197
- ]), "No observed peer connections."),
2198
- ]),
2199
- " Selected is configuration, not connection success. Relay connectivity does not guarantee content availability.",
2776
+ ` ${status.head.cid}`,
2777
+ ` Names: ${status.local.names} (Templates: ${status.local.templates}, Skills: ${status.local.skills} [global: ${status.local.globalSkills}, types: ${status.local.typeSkills}], Registrations: ${status.local.registrations})`,
2200
2778
  ].join("\n"));
2201
2779
  break;
2202
2780
  }
2203
- if (parsed.path === "get") {
2204
- const localCid = /^(ipab|name):/i.test(first)
2205
- ? undefined
2206
- : state.resolve(first);
2207
- const builtin = builtins.pins.find((pin) => pin.cid === localCid);
2208
- const selected = builtin
2209
- ? { cid: builtin.cid, targetCid: builtin.cid }
2210
- : await resolveReference(context, first, selectedSwarm, (reference) => state.resolve(reference), Boolean(parsed.options.raw), "local-first");
2211
- const contentStore = context.store;
2212
- const source = IpfsStore.fromClient({
2213
- block: {
2214
- get: (key, options) => {
2215
- options?.signal?.throwIfAborted();
2216
- const builtin = builtins.blocks.get(CID.parse(key).toV1().toString());
2217
- return builtin
2218
- ? Promise.resolve(builtin.slice())
2219
- : contentStore.block.get(key, options);
2220
- },
2221
- },
2222
- }, contentStore.limits);
2223
- let directory;
2224
- try {
2225
- directory = await getBundle(source, selected.cid, typeof parsed.options.output === "string"
2226
- ? parsed.options.output
2227
- : undefined);
2228
- }
2229
- finally {
2230
- await source.close();
2231
- }
2232
- try {
2233
- await context.finishRead?.();
2234
- }
2235
- finally {
2236
- readContext = undefined;
2237
- }
2238
- const closing = store;
2239
- store = undefined;
2240
- await closeStore(closing, undefined);
2241
- state.close();
2242
- state = undefined;
2243
- emit({ ...selected, directory }, directory);
2244
- break;
2245
- }
2246
- let cid;
2247
- let contentCid;
2248
- if (parsed.path === "swarm create") {
2249
- cid = await createSwarm(context, {
2250
- ...(typeof parsed.options.service === "string"
2251
- ? { service: parsed.options.service }
2252
- : {}),
2253
- ...(typeof parsed.options.resume === "string"
2254
- ? { resume: parsed.options.resume }
2255
- : {}),
2256
- properties: {
2257
- name: String(parsed.options.name ?? ""),
2258
- description: String(parsed.options.description ?? ""),
2259
- },
2260
- ...(typeof parsed.options.alias === "string"
2261
- ? { alias: parsed.options.alias }
2262
- : {}),
2263
- });
2264
- }
2265
- else if (parsed.path === "swarm request") {
2266
- const result = await requestMembership(context, state.resolveSwarm(first), {
2267
- ...(typeof parsed.options.output === "string"
2268
- ? { output: parsed.options.output }
2269
- : {}),
2270
- ...(parsed.options.pivot ? { role: "pivot" } : {}),
2271
- });
2272
- store = context.store;
2273
- io.err(`Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`);
2274
- if (result.file === undefined)
2275
- io.out(JSON.stringify(result.request, null, 2));
2276
- else {
2277
- io.err(`Request saved to: ${result.file}`);
2278
- if (parsed.flags.json)
2279
- emit({
2280
- file: result.file,
2281
- member: result.request.member,
2282
- ownerFingerprint: result.ownerFingerprint,
2283
- }, "");
2284
- }
2285
- break;
2286
- }
2287
- else if (parsed.path === "swarm approve") {
2288
- const selected = requireSwarm();
2289
- if (isLocalSwarm(selected))
2290
- throw new HostError(`The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support swarm approve.`);
2291
- if (first === "-" && !parsed.options.yes)
2292
- syntax("Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.");
2293
- const request = first === "-"
2294
- ? await verifiedRequestStream((io.requestInput ?? processIO.requestInput)())
2295
- : await verifiedRequest(first);
2296
- if (request.configUrl !== selected)
2297
- syntax(`Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`);
2298
- io.err(await membershipRequestSummary(request));
2299
- if (!parsed.options.yes &&
2300
- (!io.tty ||
2301
- !(await io.confirm(`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.`))))
2302
- throw new HostError("Approval requires explicit --yes or interactive confirmation.");
2303
- cid = await approveMembership(context, request, {
2304
- again: Boolean(parsed.options.again),
2305
- pivot: Boolean(parsed.options.pivot),
2306
- });
2307
- }
2781
+ const { head, config, networking, cache, lastWriter, state: contentState, } = status;
2782
+ const fingerprint = await keyId(config.owner);
2783
+ emit({
2784
+ configUrl: cid,
2785
+ owner: config.owner,
2786
+ ownerFingerprint: fingerprint,
2787
+ epoch: config.epoch,
2788
+ scopeId: config.scopeId,
2789
+ headId: config.headId,
2790
+ cache,
2791
+ state: contentState,
2792
+ networking,
2793
+ root: head.root,
2794
+ valueCid: head.cid,
2795
+ lastWriter,
2796
+ properties: {
2797
+ name: config.name,
2798
+ description: config.description,
2799
+ },
2800
+ }, [
2801
+ "Swarm",
2802
+ ` Directory: ${cache.source} (${cache.freshness}), observed ${cache.updatedAt}`,
2803
+ ` Name: ${printable(config.name)}`,
2804
+ ` Description: ${config.description ? printable(config.description) : "(none)"}`,
2805
+ " Config URL:",
2806
+ ` ${cid}`,
2807
+ "",
2808
+ "Identity",
2809
+ " Owner fingerprint:",
2810
+ ` ${fingerprint}`,
2811
+ "",
2812
+ "Content",
2813
+ " HEAD (publication root):",
2814
+ ` ${head.root}`,
2815
+ " Content CID (HEAD value):",
2816
+ ` ${head.cid}`,
2817
+ ...(lastWriter
2818
+ ? [
2819
+ ` Last HEAD writer: ${lastWriter.name ? printable(lastWriter.name) : "(profile name unavailable)"}`,
2820
+ ` Public key: ${lastWriter.subject}`,
2821
+ ` PeerID: ${lastWriter.peerId ?? "unknown"}`,
2822
+ ` Updated: ${lastWriter.updatedAt} (service time)`,
2823
+ " Last writer is not a confirmed content holder or the only copy.",
2824
+ ]
2825
+ : [
2826
+ " Last HEAD writer/time: unknown (legacy record or service without update metadata).",
2827
+ ]),
2828
+ ` State: ${contentState.status}. ${contentState.error}`,
2829
+ "",
2830
+ "Local networking",
2831
+ ` Daemon observations: ${networking.daemon.status}`,
2832
+ ` Updated: ${networking.daemon.updatedAt ?? "unknown"}`,
2833
+ ` Control-plane verified: ${networking.daemon.verifiedAt ?? "unknown"}`,
2834
+ ...(networking.daemon.error
2835
+ ? [` Observation error: ${printable(networking.daemon.error)}`]
2836
+ : []),
2837
+ ` Connections observed: ${networking.connections.observedAt ?? "unknown"} (${networking.connections.freshness})`,
2838
+ ...(networking.connections.error
2839
+ ? [
2840
+ ` Connection error: ${printable(networking.connections.error)}`,
2841
+ ]
2842
+ : []),
2843
+ table([
2844
+ "PIVOT PEER ID",
2845
+ "LOCAL",
2846
+ "PROBE",
2847
+ "PROBED AT",
2848
+ "FAILURES",
2849
+ "RETRY AT",
2850
+ "CONNECTION",
2851
+ "READINESS",
2852
+ ], networking.pivots.map((pivot) => [
2853
+ pivot.peerId,
2854
+ pivot.localStatus ?? "unknown",
2855
+ `${pivot.probe.result} (${pivot.probe.freshness})`,
2856
+ pivot.probe.at ?? "-",
2857
+ pivot.failures === null ? "-" : String(pivot.failures),
2858
+ pivot.retryAt ?? "-",
2859
+ pivot.connection.status,
2860
+ pivot.readiness.status,
2861
+ ]), "No declared Pivots."),
2862
+ ...networking.pivots.flatMap((pivot) => pivot.probe.error
2863
+ ? [
2864
+ ` ${pivot.peerId} probe error: ${printable(pivot.probe.error)}`,
2865
+ ]
2866
+ : []),
2867
+ ...(networking.connections.error
2868
+ ? []
2869
+ : [
2870
+ table(["CONNECTED PEER ID", "TRANSPORT", "ADDRESS"], networking.connections.peers.map((peer) => [
2871
+ peer.peerId,
2872
+ peer.transport,
2873
+ peer.address,
2874
+ ]), "No observed peer connections."),
2875
+ ]),
2876
+ " Selected is configuration, not connection success. Relay connectivity does not guarantee content availability.",
2877
+ ].join("\n"));
2878
+ break;
2879
+ }
2880
+ case "get": {
2881
+ const destination = typeof parsed.options.output === "string"
2882
+ ? resolve(parsed.options.output)
2883
+ : undefined;
2884
+ const result = (await client.store.export({
2885
+ mode: "get",
2886
+ ref: first,
2887
+ ...(destination !== undefined ? { destination } : {}),
2888
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
2889
+ raw: Boolean(parsed.options.raw),
2890
+ ...(explicitRefresh !== undefined
2891
+ ? { refresh: explicitRefresh }
2892
+ : {}),
2893
+ }, { ndjson: true }));
2894
+ const payload = { ...result };
2895
+ delete payload.destination;
2896
+ const closing = cliHandle;
2897
+ cliHandle = undefined;
2898
+ await closing.close();
2899
+ emit(payload, result.directory);
2900
+ break;
2901
+ }
2902
+ case "swarm create": {
2903
+ const created = (await client.swarms.governance("create", {
2904
+ ...(typeof parsed.options.service === "string"
2905
+ ? { service: parsed.options.service }
2906
+ : {}),
2907
+ ...(typeof parsed.options.resume === "string"
2908
+ ? { resume: parsed.options.resume }
2909
+ : {}),
2910
+ name: String(parsed.options.name ?? ""),
2911
+ description: String(parsed.options.description ?? ""),
2912
+ ...(typeof parsed.options.alias === "string"
2913
+ ? { alias: parsed.options.alias }
2914
+ : {}),
2915
+ }, { ndjson: true }));
2916
+ io.err(`Registered swarm ${created.alias ?? created.configUrl}. Saved current: ${created.savedCurrent ?? "(none)"}.`);
2917
+ io.err("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.");
2918
+ emit({ configUrl: created.configUrl }, created.configUrl);
2919
+ break;
2920
+ }
2921
+ case "swarm request": {
2922
+ const output = typeof parsed.options.output === "string"
2923
+ ? parsed.options.output
2924
+ : undefined;
2925
+ const result = (await client.swarms.governance("request", {
2926
+ swarm: first,
2927
+ ...(output !== undefined ? { output, cwd: process.cwd() } : {}),
2928
+ ...(parsed.options.pivot ? { role: "pivot" } : {}),
2929
+ }, { ndjson: true }));
2930
+ io.err(`Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`);
2931
+ if (result.file === undefined)
2932
+ io.out(JSON.stringify(result.request, null, 2));
2308
2933
  else {
2309
- const content = await publicationSource(second, store);
2310
- contentCid = content;
2311
- cid = await publish(context, content, {
2312
- ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
2313
- name: first,
2314
- ...(typeof parsed.options.expect === "string"
2315
- ? { expect: parsed.options.expect }
2316
- : {}),
2317
- snapshot: Boolean(parsed.options.snapshot),
2318
- });
2934
+ io.err(`Request saved to: ${result.file}`);
2935
+ if (parsed.flags.json)
2936
+ emit({
2937
+ file: result.file,
2938
+ member: result.request.member,
2939
+ ownerFingerprint: result.ownerFingerprint,
2940
+ }, "");
2319
2941
  }
2320
- store = context.store;
2321
- if (parsed.path === "swarm create")
2322
- io.err(`Registered swarm ${state.registeredSwarm(cid).alias ?? cid}. Saved current: ${state.config({ includeSecrets: false })["swarm.default"] ?? "(none)"}.`);
2323
- if (contentCid)
2324
- io.err(`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.`);
2325
- emit(parsed.path === "swarm create" || parsed.path === "swarm approve"
2326
- ? { configUrl: cid }
2327
- : { cid, ...(contentCid ? { contentCid } : {}) }, cid);
2328
2942
  break;
2329
2943
  }
2330
- case "store usage":
2944
+ case "swarm approve": {
2945
+ const { verifiedRequest, verifiedRequestStream, membershipRequestSummary, } = await import("./swarm.js");
2946
+ const selected = requireSwarm();
2947
+ if (isLocalSwarm(selected))
2948
+ throw new HostError(`The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support swarm approve.`);
2949
+ if (first === "-" && !parsed.options.yes)
2950
+ syntax("Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.");
2951
+ const request = first === "-"
2952
+ ? await verifiedRequestStream((io.requestInput ?? processIO.requestInput)())
2953
+ : await verifiedRequest(resolve(first));
2954
+ if (request.configUrl !== selected)
2955
+ syntax(`Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`);
2956
+ io.err(await membershipRequestSummary(request));
2957
+ if (!parsed.options.yes &&
2958
+ (!io.tty ||
2959
+ !(await io.confirm(`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.`))))
2960
+ throw new HostError("Approval requires explicit --yes or interactive confirmation.");
2961
+ const result = (await client.swarms.governance("approve", {
2962
+ request,
2963
+ again: Boolean(parsed.options.again),
2964
+ pivot: Boolean(parsed.options.pivot),
2965
+ }, { ndjson: true }));
2966
+ emit({ configUrl: result.approved }, result.approved);
2967
+ break;
2968
+ }
2969
+ case "publish": {
2970
+ const named = parseNameReference(first);
2971
+ const targetSwarm = named?.swarm
2972
+ ? resolveSwarm(named.swarm)
2973
+ : requireSwarm();
2974
+ const source = await resolveLocalPathIfPresent(second);
2975
+ const result = (await client.swarms.fsSet({
2976
+ swarm: targetSwarm,
2977
+ kind: "publish",
2978
+ name: first,
2979
+ source,
2980
+ ...(typeof parsed.options.expect === "string"
2981
+ ? { expect: parsed.options.expect }
2982
+ : {}),
2983
+ snapshot: Boolean(parsed.options.snapshot),
2984
+ }, { ndjson: true }));
2985
+ io.err(`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.`);
2986
+ emit(result, result.cid);
2987
+ break;
2988
+ }
2989
+ case "store usage": {
2990
+ const result = await client.store.usage();
2991
+ emit(result, `Cached blocks: ${storageBytes(result.cachedBytes)}\nPinned blocks (deduplicated): ${storageBytes(result.pinnedBytes)}`);
2992
+ break;
2993
+ }
2331
2994
  case "store gc": {
2332
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2333
- if (parsed.path === "store usage") {
2334
- const result = await store.usage();
2335
- emit(result, `Cached blocks: ${storageBytes(result.cachedBytes)}\nPinned blocks (deduplicated): ${storageBytes(result.pinnedBytes)}`);
2336
- }
2337
- else {
2338
- const result = await store.gc();
2339
- emit(result, `Removed ${result.removedBlocks} blocks; reclaimed ${storageBytes(result.reclaimedBytes)}.`);
2340
- }
2995
+ const result = await client.store.gc({ ndjson: true });
2996
+ emit(result, `Removed ${result.removedBlocks} blocks; reclaimed ${storageBytes(result.reclaimedBytes)}.`);
2341
2997
  break;
2342
2998
  }
2343
2999
  case "templates render":
@@ -2345,6 +3001,7 @@ async function performCli(argv, io, env) {
2345
3001
  case "bundle build":
2346
3002
  case "bundle inspect":
2347
3003
  case "bundle import": {
3004
+ const { message } = await import("./errors.js");
2348
3005
  const controller = new AbortController();
2349
3006
  let cancelled = 0;
2350
3007
  const interrupt = () => {
@@ -2358,145 +3015,97 @@ async function performCli(argv, io, env) {
2358
3015
  process.once("SIGINT", interrupt);
2359
3016
  process.once("SIGTERM", terminate);
2360
3017
  try {
2361
- let pendingStore;
2362
- const getStore = () => {
2363
- pendingStore ??= storeConfiguration(value("store.gateway")).then((configuration) => {
2364
- store = new IpfsStore(configuration);
2365
- return store;
2366
- });
2367
- return pendingStore;
2368
- };
2369
- const request = {
2370
- signal: controller.signal,
2371
- diagnostic: (text) => {
2372
- io.err(text);
2373
- },
2374
- resolveCid: async (cid, options) => {
2375
- options.signal?.throwIfAborted();
2376
- const builtin = builtins.blocks.get(cid.toV1().toString());
2377
- if (builtin)
2378
- return builtin.slice();
2379
- return (store ?? (await getStore())).block.get(cid.toString(), options);
2380
- },
2381
- };
2382
- const builtinSource = first ? state.pin(first) : undefined;
2383
- const source = builtinSource?.builtin && builtinSource.metadata?.kind === "bundle"
2384
- ? builtinSource.cid
2385
- : first;
2386
- let selectedTemplate;
3018
+ const requestOpts = { signal: controller.signal, ndjson: true };
3019
+ const outputOpt = typeof parsed.options.output === "string"
3020
+ ? resolve(parsed.options.output)
3021
+ : undefined;
3022
+ const outputDirOpt = String(value("bundle.outputDir"));
3023
+ let result;
2387
3024
  if (parsed.path === "templates render") {
2388
- const selector = first;
2389
- selectedTemplate = selector;
2390
- if (parseNameReference(selector)) {
2391
- await getStore();
2392
- const context = swarmContext();
2393
- readContext = context;
2394
- selectedTemplate = (await resolveReference(context, selector, selectedSwarm, (reference) => state.resolve(reference), false, "local-first")).cid;
2395
- store = context.store;
2396
- }
2397
- else {
2398
- let explicit = false;
2399
- try {
2400
- CID.parse(selector);
2401
- explicit = true;
2402
- }
2403
- catch {
2404
- /* Not a CID. */
2405
- }
2406
- explicit ||= selector.toLowerCase().endsWith(".car");
2407
- if (!explicit) {
2408
- try {
2409
- await lstat(selector);
2410
- explicit = true;
2411
- }
2412
- catch (cause) {
2413
- if (!nodeError(cause, "ENOENT") &&
2414
- !nodeError(cause, "ENOTDIR"))
2415
- throw cause;
2416
- }
2417
- }
2418
- if (!explicit) {
2419
- templateName(selector);
2420
- if (!selectedSwarm)
2421
- throw new HostError("Template selectors require a selected Swarm. Use --swarm or swarm use, or supply an explicit Bundle directory, CAR, exact CID or IPAB URI.");
2422
- await getStore();
2423
- const context = swarmContext();
2424
- readContext = context;
2425
- selectedTemplate = await resolveTemplateSelector(context, selector, selectedSwarm);
2426
- store = context.store;
2427
- }
2428
- }
3025
+ const template = await resolveLocalPathIfPresent(first);
3026
+ const destination = resolve(parsed.positional[2] ?? second);
3027
+ const parameters = [
3028
+ ...(parsed.parameters ?? []),
3029
+ ...(typeof parsed.options.description === "string"
3030
+ ? [`description=${parsed.options.description}`]
3031
+ : []),
3032
+ ];
3033
+ result = await client.store.export({
3034
+ mode: "render-template",
3035
+ template,
3036
+ name: second,
3037
+ destination,
3038
+ parameters,
3039
+ swarm: selectedSwarm,
3040
+ refresh: explicitRefresh,
3041
+ }, requestOpts);
2429
3042
  }
2430
- if (parsed.path === "bundle build" || parsed.path === "build")
2431
- io.err(parsed.path === "build"
2432
- ? "Assembling and validating Bundle (no compilation)..."
2433
- : "Validating and building bundle...");
2434
- if (parsed.path === "bundle import")
2435
- io.err("Validating and importing CAR into Store...");
2436
- const result = parsed.path === "templates render"
2437
- ? await initApp(second, parsed.positional[2], {
2438
- ...request,
2439
- ...(selectedTemplate ? { template: selectedTemplate } : {}),
2440
- parameters: [
2441
- ...(parsed.parameters ?? []),
2442
- ...(typeof parsed.options.description === "string"
2443
- ? [`description=${parsed.options.description}`]
2444
- : []),
2445
- ],
2446
- })
2447
- : parsed.path === "build"
2448
- ? await assembleBundle(first, {
2449
- ...request,
2450
- replace: Boolean(parsed.options.replace),
2451
- ...(typeof parsed.options.output === "string"
2452
- ? { output: parsed.options.output }
2453
- : {}),
2454
- outputDir: String(value("bundle.outputDir")),
2455
- })
2456
- : parsed.path === "bundle build"
2457
- ? await buildBundle(source, {
2458
- ...request,
2459
- schemaOnly: Boolean(parsed.options["schema-only"]),
2460
- replace: Boolean(parsed.options.replace),
2461
- ...(typeof parsed.options.output === "string"
2462
- ? { output: parsed.options.output }
2463
- : {}),
2464
- outputDir: String(value("bundle.outputDir")),
2465
- })
2466
- : parsed.path === "bundle import"
2467
- ? await importBundle(first, getStore, request)
2468
- : await inspectBundle(source, request);
2469
- const importing = "output" in result && !parsed.options["no-import"];
2470
- if (importing) {
2471
- io.err("Importing build result into Store (without pinning)...");
2472
- try {
2473
- await importBundle(result.output, getStore, request);
2474
- }
2475
- catch (cause) {
2476
- throw new HostError(`${message(cause)} CAR remains at ${JSON.stringify(result.output)}; retry with ipab bundle import ${JSON.stringify(result.output)}, or build with --no-import.`, 1, "IMPORT_FAILED", "authoring");
2477
- }
3043
+ else if (parsed.path === "build") {
3044
+ const sourcePath = first ? resolve(first) : process.cwd();
3045
+ result = (await client.store.import({
3046
+ mode: "assemble",
3047
+ path: sourcePath,
3048
+ replace: Boolean(parsed.options.replace),
3049
+ output: outputOpt,
3050
+ outputDir: outputDirOpt,
3051
+ autoImport: !parsed.options["no-import"],
3052
+ }, requestOpts));
3053
+ }
3054
+ else if (parsed.path === "bundle build") {
3055
+ const sourcePath = await resolveLocalPathIfPresent(first);
3056
+ result = (await client.store.import({
3057
+ mode: "build",
3058
+ path: sourcePath,
3059
+ schemaOnly: Boolean(parsed.options["schema-only"]),
3060
+ replace: Boolean(parsed.options.replace),
3061
+ output: outputOpt,
3062
+ outputDir: outputDirOpt,
3063
+ autoImport: !parsed.options["no-import"],
3064
+ }, requestOpts));
3065
+ }
3066
+ else if (parsed.path === "bundle import") {
3067
+ const sourcePath = resolve(first);
3068
+ result = (await client.store.import({ mode: "car", path: sourcePath }, requestOpts));
3069
+ }
3070
+ else {
3071
+ const sourceRef = await resolveLocalPathIfPresent(first);
3072
+ result = (await client.store.inspect({
3073
+ ref: sourceRef,
3074
+ swarm: selectedSwarm,
3075
+ }, requestOpts));
2478
3076
  }
2479
- const closing = store;
2480
- store = undefined;
2481
- await closeStore(closing, undefined);
2482
- state.close();
2483
- state = undefined;
2484
3077
  controller.signal.throwIfAborted();
2485
- if ("output" in result)
2486
- emit({ ...result, imported: importing }, `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)"}`);
2487
- else if (result.kind === "bundle-import")
2488
- emit(result, `Imported CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nBlocks: ${result.blocks}\nCAR: ${result.source}\nEntry validation: ${result.validation?.status ?? "not-applicable"}`);
3078
+ if ("output" in result) {
3079
+ const importing = Boolean(result.imported);
3080
+ const validation = result.validation;
3081
+ emit(result, `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)"}`);
3082
+ }
3083
+ else if (result.kind === "bundle-import") {
3084
+ const source = String(result.source);
3085
+ const validation = result.validation;
3086
+ emit(result, `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"}`);
3087
+ }
2489
3088
  else if (result.kind === "project-init") {
2490
- emit(result, `Created project: ${result.directory}${result.templateCid ? `\nTemplate CID: ${result.templateCid}` : ""}`);
2491
- if (result.files.includes("package.json") &&
2492
- (result.files.includes("ipab.yaml") ||
2493
- result.files.includes("ipab.json")))
2494
- io.err(`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.`);
2495
- else if (result.files.includes(".bundle.yaml"))
2496
- io.err(`Next: ipab bundle build ${JSON.stringify(result.directory)}`);
3089
+ const directory = String(result.directory);
3090
+ const files = Array.isArray(result.files)
3091
+ ? result.files
3092
+ : [];
3093
+ const templateCid = typeof result.templateCid === "string"
3094
+ ? result.templateCid
3095
+ : undefined;
3096
+ emit(result, `Created project: ${directory}${templateCid ? `\nTemplate CID: ${templateCid}` : ""}`);
3097
+ if (files.includes("package.json") &&
3098
+ (files.includes("ipab.yaml") || files.includes("ipab.json")))
3099
+ io.err(`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.`);
3100
+ else if (files.includes(".bundle.yaml"))
3101
+ io.err(`Next: ipab bundle build ${JSON.stringify(directory)}`);
3102
+ }
3103
+ else {
3104
+ const manifest = result.manifest;
3105
+ const type = result.type;
3106
+ const validation = result.validation;
3107
+ emit(result, `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"}`);
2497
3108
  }
2498
- else
2499
- emit(result, `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"}`);
2500
3109
  }
2501
3110
  catch (cause) {
2502
3111
  if (cancelled)
@@ -2510,23 +3119,25 @@ async function performCli(argv, io, env) {
2510
3119
  break;
2511
3120
  }
2512
3121
  case "pin list": {
2513
- const listed = state.contentPins();
2514
- const archived = state.archivedPins();
2515
- const builtins = state.pins().map(pinDetails);
2516
- emit({ items: listed, builtins, archived }, table(["REFERENCE", "CID", "STATUS", "SOURCE"], [
2517
- ...listed.map((pin) => [
3122
+ const listed = await client.store.listPins();
3123
+ emit({
3124
+ items: listed.pins,
3125
+ builtins: listed.builtins,
3126
+ archived: listed.archived,
3127
+ }, table(["REFERENCE", "CID", "STATUS", "SOURCE"], [
3128
+ ...listed.pins.map((pin) => [
2518
3129
  pin.reference,
2519
3130
  pin.cid ?? "(none)",
2520
3131
  `${pin.status}/${pin.freshness}${pin.error ? `: ${pin.error}` : ""}`,
2521
3132
  pin.swarm ? "following shared Name" : "fixed CID",
2522
3133
  ]),
2523
- ...builtins.map((pin) => [
2524
- pin.name,
2525
- pin.cid,
3134
+ ...listed.builtins.map((pin) => [
3135
+ String(pin.name),
3136
+ String(pin.cid),
2526
3137
  "read-only",
2527
3138
  "built-in",
2528
3139
  ]),
2529
- ...archived.map((pin) => [
3140
+ ...listed.archived.map((pin) => [
2530
3141
  pin.cid,
2531
3142
  pin.cid,
2532
3143
  pin.status,
@@ -2536,76 +3147,86 @@ async function performCli(argv, io, env) {
2536
3147
  break;
2537
3148
  }
2538
3149
  case "unpin": {
2539
- const canonical = pinReference(state, first, selectedSwarm);
2540
- const result = await unpin(state, canonical.reference);
2541
- emit(result, `Unpinned ${canonical.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`);
3150
+ const result = await client.store.removePin(first, {
3151
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3152
+ });
3153
+ emit(result, `Unpinned ${result.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`);
2542
3154
  break;
2543
3155
  }
2544
3156
  case "pin show": {
2545
- const builtin = first.startsWith("builtin:")
2546
- ? state.pin(first)
2547
- : undefined;
2548
- const canonical = builtin
2549
- ? undefined
2550
- : pinReference(state, first, selectedSwarm);
2551
- const pin = canonical
2552
- ? state.contentPin(canonical.reference)
2553
- : undefined;
2554
- const archived = canonical
2555
- ? state
2556
- .archivedPins()
2557
- .filter((pin) => pin.cid === canonical.reference)
2558
- : [];
2559
- if (!pin && !builtin && !archived.length)
2560
- throw new HostError(`Pin "${first}" does not exist. Run ipab pin list.`);
2561
- const result = builtin
2562
- ? pinDetails(builtin)
2563
- : {
2564
- pin: pin ?? null,
2565
- roots: pin ? state.hold(pin.owner)?.roots : [],
2566
- archived,
2567
- };
3157
+ const result = await client.store.getPin(first, {
3158
+ details: true,
3159
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3160
+ });
2568
3161
  emit(result, JSON.stringify(result, null, 2));
2569
3162
  break;
2570
3163
  }
2571
3164
  case "config get": {
2572
- const selected = (first ? items.filter((item) => item.key === first) : items).map(visibleConfig);
3165
+ const selected = first
3166
+ ? items.filter((item) => item.key === first)
3167
+ : items;
2573
3168
  emit({ items: selected }, table(["KEY", "VALUE", "SOURCE"], selected.map((item) => [item.key, String(item.value), item.source]), "No configuration values."));
2574
3169
  break;
2575
3170
  }
2576
3171
  case "config set": {
2577
3172
  const key = configKey(first);
2578
- const saved = parseValue(key, key === "pointers.apiKey"
3173
+ const rawInput = key === "pointers.apiKey"
2579
3174
  ? await (io.readSecret ?? processIO.readSecret)()
2580
- : second, true);
2581
- state.setConfig(key, saved);
2582
- const source = items.find((item) => item.key === key).source;
2583
- if (source === "env" || source === "flag")
2584
- io.err(`Warning: saved user value is masked by ${source}.`);
2585
- const display = visibleConfig({ key, value: saved, source: "user" });
3175
+ : second;
3176
+ parseValue(key, rawInput, true);
3177
+ const updated = await client.host.setConfig(key, rawInput, {
3178
+ fromString: true,
3179
+ });
3180
+ const currentSource = items.find((item) => item.key === key).source;
3181
+ const maskSource = currentSource === "env" || currentSource === "flag"
3182
+ ? currentSource
3183
+ : updated.effectiveSource === "env" ||
3184
+ updated.effectiveSource === "flag"
3185
+ ? updated.effectiveSource
3186
+ : undefined;
3187
+ if (maskSource)
3188
+ io.err(`Warning: saved user value is masked by ${maskSource}.`);
3189
+ const display = {
3190
+ key: updated.key,
3191
+ value: updated.value,
3192
+ source: updated.source,
3193
+ };
2586
3194
  emit(display, `Saved ${key} = ${printable(String(display.value))} (user).`);
2587
3195
  break;
2588
3196
  }
2589
- case "config reset":
2590
- state.resetConfig(configKey(first));
3197
+ case "config reset": {
3198
+ await client.host.resetConfig(configKey(first));
2591
3199
  emit({ reset: [first] }, `Reset user override: ${first}.`);
2592
3200
  break;
3201
+ }
2593
3202
  case "history list": {
2594
- const page = listHistory(state, filter, Number(parsed.options.limit ?? value("history.limit")), typeof parsed.options.before === "string"
2595
- ? state.resolveRunId(parsed.options.before)
2596
- : undefined);
3203
+ const page = await client.runs.list({
3204
+ ...(typeof parsed.options.app === "string"
3205
+ ? { app: parsed.options.app }
3206
+ : {}),
3207
+ ...(typeof parsed.options.status === "string"
3208
+ ? { status: parsed.options.status }
3209
+ : {}),
3210
+ ...(typeof parsed.options.since === "string"
3211
+ ? { since: parsed.options.since }
3212
+ : {}),
3213
+ ...(typeof parsed.options.until === "string"
3214
+ ? { until: parsed.options.until }
3215
+ : {}),
3216
+ limit: Number(parsed.options.limit ?? value("history.limit")),
3217
+ ...(typeof parsed.options.before === "string"
3218
+ ? { before: parsed.options.before }
3219
+ : {}),
3220
+ });
3221
+ const jsonPage = { items: page.items, nextBefore: page.nextBefore };
2597
3222
  if (parsed.flags.json) {
2598
- emit(page, "");
3223
+ emit(jsonPage, "");
2599
3224
  break;
2600
3225
  }
2601
- const names = new Map();
2602
- for (const pin of state.pins())
2603
- if (pin.status === "ready" && !names.has(pin.cid))
2604
- names.set(pin.cid, pin.name);
3226
+ const pinNames = page.pinNames ?? {};
2605
3227
  const reference = (cid) => cid === null
2606
3228
  ? "none"
2607
- : cid + (names.has(cid) ? ` (${names.get(cid)})` : "");
2608
- const shortId = state.shortRunId.bind(state);
3229
+ : cid + (pinNames[cid] ? ` (${pinNames[cid]})` : "");
2609
3230
  const rows = page.items.length
2610
3231
  ? page.items
2611
3232
  .map((record) => [
@@ -2622,167 +3243,80 @@ async function performCli(argv, io, env) {
2622
3243
  .join("\n"))
2623
3244
  .join("\n\n")
2624
3245
  : "No ended executions.";
2625
- emit(page, rows +
3246
+ emit(jsonPage, rows +
2626
3247
  (page.nextBefore
2627
- ? `\nMore matches; use --before ${shortId(page.nextBefore)} with the same filters.`
3248
+ ? `\nMore matches; use --before ${page.shortNextBefore ?? page.nextBefore} with the same filters.`
2628
3249
  : ""));
2629
3250
  break;
2630
3251
  }
2631
3252
  case "history show": {
2632
- const record = state.run(state.resolveRunId(first));
2633
- const logs = record.log
2634
- ? await logFiles(state.directory, record.id)
2635
- : undefined;
2636
- emit(logs ? { ...record, logs } : record, runDetails(record) +
3253
+ const record = await client.runs.show(first);
3254
+ const logs = record.logs;
3255
+ emit(record, runDetails(record) +
2637
3256
  (logs
2638
3257
  ? `\nLog recording: ${record.log}\nStdout log: ${printable(logs.stdout ?? "unavailable")}\nStderr log: ${printable(logs.stderr ?? "unavailable")}`
2639
3258
  : "\nLog recording: disabled"));
2640
3259
  break;
2641
3260
  }
2642
3261
  case "history remove": {
2643
- const ids = parsed.positional.length
2644
- ? [...new Set(parsed.positional.map(state.resolveRunId.bind(state)))]
2645
- : selectedIds(state, filter);
2646
- for (const id of ids)
2647
- state.run(id);
2648
- if (ids.length &&
2649
- !parsed.options.yes &&
2650
- !(await io.confirm(`Remove ${ids.length} ended records selected by ${JSON.stringify(parsed.positional.length ? { ids } : parsed.options)}? Release only their retention; no GC or disk reclamation is guaranteed.`)))
2651
- throw new HostError("History removal cancelled.");
2652
- const result = await removeHistory(state, ids);
2653
- emit(result, `Removed ${result.removed.length} records; garbage collection is not guaranteed.`);
3262
+ const removeParams = parsed.positional.length
3263
+ ? { ids: parsed.positional }
3264
+ : {
3265
+ ...(typeof parsed.options.app === "string"
3266
+ ? { app: parsed.options.app }
3267
+ : {}),
3268
+ ...(typeof parsed.options.status === "string"
3269
+ ? { status: parsed.options.status }
3270
+ : {}),
3271
+ ...(typeof parsed.options.since === "string"
3272
+ ? { since: parsed.options.since }
3273
+ : {}),
3274
+ ...(typeof parsed.options.until === "string"
3275
+ ? { until: parsed.options.until }
3276
+ : {}),
3277
+ };
3278
+ let idsToRemove;
3279
+ if (!parsed.options.yes) {
3280
+ const preview = await client.runs.remove({
3281
+ ...removeParams,
3282
+ dryRun: true,
3283
+ });
3284
+ const ids = preview.ids ?? [];
3285
+ if (ids.length &&
3286
+ !(await io.confirm(`Remove ${ids.length} ended records selected by ${JSON.stringify(parsed.positional.length ? { ids } : parsed.options)}? Release only their retention; no GC or disk reclamation is guaranteed.`)))
3287
+ throw new HostError("History removal cancelled.");
3288
+ idsToRemove = ids;
3289
+ }
3290
+ const result = await client.runs.remove(idsToRemove !== undefined ? { ids: idsToRemove } : removeParams);
3291
+ emit(result, `Removed ${(result.removed ?? []).length} records; garbage collection is not guaranteed.`);
2654
3292
  break;
2655
3293
  }
2656
3294
  case "exec":
2657
3295
  case "open": {
2658
3296
  const named = parsed.path === "open" ? parseNameReference(first) : undefined;
2659
3297
  const registrySwarm = named?.swarm
2660
- ? state.resolveSwarm(named.swarm)
3298
+ ? resolveSwarm(named.swarm)
2661
3299
  : selectedSwarm;
2662
3300
  if (parsed.path === "open" && !registrySwarm)
2663
3301
  throw new HostError("Open requires a selected Swarm. Use ipab://URL_OR_ALIAS/PATH, pass --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS. To select an App directly, use ipab exec.");
2664
3302
  if (parsed.options.log && !value("history.enabled"))
2665
3303
  throw new HostError("Execution logging requires history.enabled=true.");
2666
- await recoverInactive(state);
2667
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2668
- const context = swarmContext();
2669
- readContext = context;
2670
- const directory = parsed.path === "open"
2671
- ? await localBundleDirectory(first)
2672
- : undefined;
2673
- const target = directory
2674
- ? undefined
2675
- : (await resolveReference(context, first, selectedSwarm, (reference) => state.resolve(reference), Boolean(parsed.options.raw), "local-first")).cid;
2676
- store = context.store;
2677
- const resolveBundleReference = async (reference, signal, preferredSwarm) => {
2678
- signal.throwIfAborted();
2679
- const lookup = {
2680
- ...swarmContext(),
2681
- store: new IpfsStore(await storeConfiguration(value("store.gateway"))),
2682
- };
2683
- try {
2684
- const named = parseNameReference(reference);
2685
- const swarm = named?.swarm
2686
- ? state.resolveSwarm(named.swarm)
2687
- : preferredSwarm
2688
- ? state.resolveSwarm(preferredSwarm)
2689
- : selectedSwarm;
2690
- const resolve = (source) => resolveReference(lookup, reference, source, (input) => state.resolve(input), false, "local-first");
2691
- let resolved;
2692
- try {
2693
- resolved = await resolve(named ? swarm : undefined);
2694
- }
2695
- catch (cause) {
2696
- let failure = cause;
2697
- for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
2698
- failure = failure.cause;
2699
- if (named ||
2700
- !swarm ||
2701
- !(failure instanceof ContentError) ||
2702
- failure.code !== "missing_block")
2703
- throw cause;
2704
- signal.throwIfAborted();
2705
- resolved = await resolve(swarm);
2706
- }
2707
- signal.throwIfAborted();
2708
- return { ...resolved, ...(swarm ? { swarm } : {}) };
2709
- }
2710
- finally {
2711
- try {
2712
- await lookup.finishRead?.();
2713
- }
2714
- finally {
2715
- await lookup.store.close();
2716
- }
2717
- }
2718
- };
2719
- let appCid;
2720
- let appArgv;
2721
- if (parsed.path === "open") {
2722
- const session = directory ? `open:${randomUUID()}` : null;
2723
- const owner = await Ownership.create(state, store, `open:${randomUUID()}`, session);
2724
- try {
2725
- const root = directory
2726
- ? await snapshotBundle(directory, owner, session)
2727
- : target;
2728
- const content = await validatedBundle(root, store, owner);
2729
- const schema = content.schemaKey;
2730
- let association;
2731
- if (registrySwarm) {
2732
- const lookup = {
2733
- ...swarmContext(),
2734
- store: new IpfsStore(await storeConfiguration(value("store.gateway"))),
2735
- };
2736
- try {
2737
- association = await swarmAssociation(lookup, registrySwarm, schema, "local-first");
2738
- }
2739
- finally {
2740
- try {
2741
- await lookup.finishRead?.();
2742
- }
2743
- finally {
2744
- await lookup.store.close();
2745
- }
2746
- }
2747
- }
2748
- if (!association)
2749
- throw new HostError(`No App registered for Schema ${schema} in Swarm ${registrySwarm}. Use ipab register set ${schema} APP_CID --swarm ${registrySwarm} or ipab exec.`);
2750
- appCid = association.appCid;
2751
- if (association.argv.length !== 1 || association.argv[0] !== "%")
2752
- throw new HostError("Custom per-association argv is unsupported; adapt the App to accept only the content CID or use ipab exec APP_CID ARGS.");
2753
- appArgv = [root];
2754
- // execute owns the App/input context before this validation owner's eventual release.
2755
- const result = await execute(state, store, { origin: "open", appCid, argv: appArgv }, {
2756
- inputSchema: schema,
2757
- resolveBundleReference,
2758
- history: Boolean(value("history.enabled")),
2759
- retain: value("output.retention") === "history",
2760
- log: Boolean(parsed.options.log),
2761
- diagnostic: (text) => {
2762
- io.err(text);
2763
- },
2764
- });
2765
- appExitCode = result.exitCode;
2766
- return appExitCode;
2767
- }
2768
- finally {
2769
- await owner.release();
2770
- }
2771
- }
2772
- else {
2773
- appCid = target;
2774
- appArgv = parsed.positional.slice(1);
2775
- }
2776
- appExitCode = (await execute(state, store, { origin: "exec", appCid, argv: appArgv }, {
2777
- resolveBundleReference,
3304
+ const resolvedFirst = await resolveLocalPathIfPresent(first);
3305
+ const prepared = await client.runs.prepare({
3306
+ origin: parsed.path,
3307
+ ...(parsed.path === "open"
3308
+ ? { target: resolvedFirst }
3309
+ : { appCid: resolvedFirst, argv: parsed.positional.slice(1) }),
3310
+ swarm: selectedSwarm,
2778
3311
  history: Boolean(value("history.enabled")),
2779
3312
  retain: value("output.retention") === "history",
2780
3313
  log: Boolean(parsed.options.log),
2781
- diagnostic: (text) => {
2782
- io.err(text);
2783
- },
2784
- })).exitCode;
2785
- return appExitCode;
3314
+ raw: Boolean(parsed.options.raw),
3315
+ refresh: explicitRefresh,
3316
+ }, { ndjson: true });
3317
+ return await runPreparedApp(client, prepared, (text, prog) => {
3318
+ io.err(text, prog);
3319
+ });
2786
3320
  }
2787
3321
  default:
2788
3322
  syntax("Unknown command.");
@@ -2790,20 +3324,16 @@ async function performCli(argv, io, env) {
2790
3324
  return 0;
2791
3325
  }
2792
3326
  catch (error) {
3327
+ const { message } = await import("./errors.js");
2793
3328
  io.err(`Error: ${message(error)}`);
2794
3329
  return error instanceof HostError ? error.exitCode : 1;
2795
3330
  }
2796
3331
  finally {
2797
3332
  try {
2798
- try {
2799
- await readContext?.finishRead?.();
2800
- }
2801
- finally {
2802
- await closeStore(store, appExitCode);
2803
- }
3333
+ await cliHandle?.close();
2804
3334
  }
2805
3335
  finally {
2806
- state?.close();
3336
+ await closeStore(daemonStore, undefined);
2807
3337
  }
2808
3338
  }
2809
3339
  }
@@ -2812,6 +3342,7 @@ export async function runCli(argv, io = processIO, env = process.env) {
2812
3342
  return await performCli(argv, io, env);
2813
3343
  }
2814
3344
  catch (error) {
3345
+ const { message } = await import("./errors.js");
2815
3346
  io.err(`Error: ${message(error)}`);
2816
3347
  return error instanceof HostError ? error.exitCode : 1;
2817
3348
  }