@ipab/cli 0.1.0-rc.1 → 0.1.0-rc.10

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 (285) hide show
  1. package/README.md +226 -9
  2. package/dist/app-authoring.d.ts +15 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +144 -58
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -57
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -38
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-prebuild.d.ts +18 -0
  11. package/dist/app-prebuild.d.ts.map +1 -1
  12. package/dist/app-prebuild.js +46 -0
  13. package/dist/app-prebuild.js.map +1 -1
  14. package/dist/app-templates.d.ts +0 -1
  15. package/dist/app-templates.d.ts.map +1 -1
  16. package/dist/app-templates.js +8 -46
  17. package/dist/app-templates.js.map +1 -1
  18. package/dist/assembly.d.ts +7 -0
  19. package/dist/assembly.d.ts.map +1 -0
  20. package/dist/assembly.js +130 -0
  21. package/dist/assembly.js.map +1 -0
  22. package/dist/authoring.d.ts +4 -8
  23. package/dist/authoring.d.ts.map +1 -1
  24. package/dist/authoring.js +25 -15
  25. package/dist/authoring.js.map +1 -1
  26. package/dist/builtins/skill.ipab.car +0 -0
  27. package/dist/builtins/template.bundle-viewer.car +0 -0
  28. package/dist/builtins/template.check.car +0 -0
  29. package/dist/builtins/template.node.car +0 -0
  30. package/dist/builtins/template.web-app.car +0 -0
  31. package/dist/builtins.d.ts.map +1 -1
  32. package/dist/builtins.js +1 -23
  33. package/dist/builtins.js.map +1 -1
  34. package/dist/bundled-skills.d.ts +14 -0
  35. package/dist/bundled-skills.d.ts.map +1 -0
  36. package/dist/bundled-skills.js +34 -0
  37. package/dist/bundled-skills.js.map +1 -0
  38. package/dist/cli.d.ts +8 -2
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +1919 -256
  41. package/dist/cli.js.map +1 -1
  42. package/dist/config-secret.d.ts +3 -0
  43. package/dist/config-secret.d.ts.map +1 -0
  44. package/dist/config-secret.js +12 -0
  45. package/dist/config-secret.js.map +1 -0
  46. package/dist/config.d.ts +7 -2
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +151 -8
  49. package/dist/config.js.map +1 -1
  50. package/dist/content-provider.d.ts +32 -0
  51. package/dist/content-provider.d.ts.map +1 -0
  52. package/dist/content-provider.js +222 -0
  53. package/dist/content-provider.js.map +1 -0
  54. package/dist/context-types.d.ts +12 -0
  55. package/dist/context-types.d.ts.map +1 -0
  56. package/dist/context-types.js +2 -0
  57. package/dist/context-types.js.map +1 -0
  58. package/dist/context.d.ts +26 -1
  59. package/dist/context.d.ts.map +1 -1
  60. package/dist/context.js +54 -10
  61. package/dist/context.js.map +1 -1
  62. package/dist/daemon-ui.d.ts +93 -0
  63. package/dist/daemon-ui.d.ts.map +1 -0
  64. package/dist/daemon-ui.js +713 -0
  65. package/dist/daemon-ui.js.map +1 -0
  66. package/dist/daemon.d.ts +21 -0
  67. package/dist/daemon.d.ts.map +1 -0
  68. package/dist/daemon.js +317 -0
  69. package/dist/daemon.js.map +1 -0
  70. package/dist/doctor.d.ts +32 -0
  71. package/dist/doctor.d.ts.map +1 -0
  72. package/dist/doctor.js +684 -0
  73. package/dist/doctor.js.map +1 -0
  74. package/dist/errors.d.ts +1 -8
  75. package/dist/errors.d.ts.map +1 -1
  76. package/dist/errors.js +1 -20
  77. package/dist/errors.js.map +1 -1
  78. package/dist/get.d.ts +3 -0
  79. package/dist/get.d.ts.map +1 -0
  80. package/dist/get.js +80 -0
  81. package/dist/get.js.map +1 -0
  82. package/dist/history.d.ts.map +1 -1
  83. package/dist/history.js +6 -14
  84. package/dist/history.js.map +1 -1
  85. package/dist/host-error.d.ts +9 -0
  86. package/dist/host-error.d.ts.map +1 -0
  87. package/dist/host-error.js +21 -0
  88. package/dist/host-error.js.map +1 -0
  89. package/dist/identity.d.ts +16 -0
  90. package/dist/identity.d.ts.map +1 -0
  91. package/dist/identity.js +119 -0
  92. package/dist/identity.js.map +1 -0
  93. package/dist/ipc.d.ts +5 -2
  94. package/dist/ipc.d.ts.map +1 -1
  95. package/dist/ipc.js +124 -12
  96. package/dist/ipc.js.map +1 -1
  97. package/dist/kubo-install.d.ts +26 -0
  98. package/dist/kubo-install.d.ts.map +1 -0
  99. package/dist/kubo-install.js +724 -0
  100. package/dist/kubo-install.js.map +1 -0
  101. package/dist/kubo-peering.d.ts +11 -0
  102. package/dist/kubo-peering.d.ts.map +1 -0
  103. package/dist/kubo-peering.js +93 -0
  104. package/dist/kubo-peering.js.map +1 -0
  105. package/dist/kubo-peers.d.ts +12 -0
  106. package/dist/kubo-peers.d.ts.map +1 -0
  107. package/dist/kubo-peers.js +119 -0
  108. package/dist/kubo-peers.js.map +1 -0
  109. package/dist/kubo-release.d.ts +22 -0
  110. package/dist/kubo-release.d.ts.map +1 -0
  111. package/dist/kubo-release.js +176 -0
  112. package/dist/kubo-release.js.map +1 -0
  113. package/dist/kubo-topology.d.ts +19 -0
  114. package/dist/kubo-topology.d.ts.map +1 -0
  115. package/dist/kubo-topology.js +113 -0
  116. package/dist/kubo-topology.js.map +1 -0
  117. package/dist/kubo.d.ts +85 -0
  118. package/dist/kubo.d.ts.map +1 -0
  119. package/dist/kubo.js +755 -0
  120. package/dist/kubo.js.map +1 -0
  121. package/dist/pins.d.ts +16 -18
  122. package/dist/pins.d.ts.map +1 -1
  123. package/dist/pins.js +144 -106
  124. package/dist/pins.js.map +1 -1
  125. package/dist/pivot-rpc.d.ts +62 -0
  126. package/dist/pivot-rpc.d.ts.map +1 -0
  127. package/dist/pivot-rpc.js +407 -0
  128. package/dist/pivot-rpc.js.map +1 -0
  129. package/dist/pivot-service.d.ts +16 -0
  130. package/dist/pivot-service.d.ts.map +1 -0
  131. package/dist/pivot-service.js +50 -0
  132. package/dist/pivot-service.js.map +1 -0
  133. package/dist/publish-source.d.ts +3 -0
  134. package/dist/publish-source.d.ts.map +1 -0
  135. package/dist/publish-source.js +85 -0
  136. package/dist/publish-source.js.map +1 -0
  137. package/dist/runtime.d.ts +2 -0
  138. package/dist/runtime.d.ts.map +1 -1
  139. package/dist/runtime.js +9 -4
  140. package/dist/runtime.js.map +1 -1
  141. package/dist/search-index.d.ts +64 -0
  142. package/dist/search-index.d.ts.map +1 -0
  143. package/dist/search-index.js +409 -0
  144. package/dist/search-index.js.map +1 -0
  145. package/dist/search-service.d.ts +23 -0
  146. package/dist/search-service.d.ts.map +1 -0
  147. package/dist/search-service.js +116 -0
  148. package/dist/search-service.js.map +1 -0
  149. package/dist/skill-definition.d.ts +6 -0
  150. package/dist/skill-definition.d.ts.map +1 -0
  151. package/dist/skill-definition.js +38 -0
  152. package/dist/skill-definition.js.map +1 -0
  153. package/dist/skill-source.d.ts +9 -0
  154. package/dist/skill-source.d.ts.map +1 -0
  155. package/dist/skill-source.js +24 -0
  156. package/dist/skill-source.js.map +1 -0
  157. package/dist/skills.d.ts +104 -0
  158. package/dist/skills.d.ts.map +1 -0
  159. package/dist/skills.js +894 -0
  160. package/dist/skills.js.map +1 -0
  161. package/dist/source-bundle.d.ts +3 -8
  162. package/dist/source-bundle.d.ts.map +1 -1
  163. package/dist/source-bundle.js +17 -12
  164. package/dist/source-bundle.js.map +1 -1
  165. package/dist/space-path.d.ts +3 -0
  166. package/dist/space-path.d.ts.map +1 -0
  167. package/dist/space-path.js +17 -0
  168. package/dist/space-path.js.map +1 -0
  169. package/dist/space.d.ts +16 -4
  170. package/dist/space.d.ts.map +1 -1
  171. package/dist/space.js +170 -24
  172. package/dist/space.js.map +1 -1
  173. package/dist/state-storage-windows.d.ts +2 -0
  174. package/dist/state-storage-windows.d.ts.map +1 -0
  175. package/dist/state-storage-windows.js +114 -0
  176. package/dist/state-storage-windows.js.map +1 -0
  177. package/dist/state-storage.d.ts +5 -0
  178. package/dist/state-storage.d.ts.map +1 -0
  179. package/dist/state-storage.js +333 -0
  180. package/dist/state-storage.js.map +1 -0
  181. package/dist/state.d.ts +115 -13
  182. package/dist/state.d.ts.map +1 -1
  183. package/dist/state.js +492 -91
  184. package/dist/state.js.map +1 -1
  185. package/dist/swarm-envelope.d.ts +57 -0
  186. package/dist/swarm-envelope.d.ts.map +1 -0
  187. package/dist/swarm-envelope.js +299 -0
  188. package/dist/swarm-envelope.js.map +1 -0
  189. package/dist/swarm-files.d.ts +6 -0
  190. package/dist/swarm-files.d.ts.map +1 -0
  191. package/dist/swarm-files.js +116 -0
  192. package/dist/swarm-files.js.map +1 -0
  193. package/dist/swarm-meta.d.ts +15 -0
  194. package/dist/swarm-meta.d.ts.map +1 -0
  195. package/dist/swarm-meta.js +68 -0
  196. package/dist/swarm-meta.js.map +1 -0
  197. package/dist/swarm-observations.d.ts +40 -0
  198. package/dist/swarm-observations.d.ts.map +1 -0
  199. package/dist/swarm-observations.js +271 -0
  200. package/dist/swarm-observations.js.map +1 -0
  201. package/dist/swarm.d.ts +469 -0
  202. package/dist/swarm.d.ts.map +1 -0
  203. package/dist/swarm.js +4708 -0
  204. package/dist/swarm.js.map +1 -0
  205. package/dist/template-definition.d.ts +47 -52
  206. package/dist/template-definition.d.ts.map +1 -1
  207. package/dist/template-definition.js +36 -41
  208. package/dist/template-definition.js.map +1 -1
  209. package/dist/template-paths.d.ts +7 -0
  210. package/dist/template-paths.d.ts.map +1 -0
  211. package/dist/template-paths.js +23 -0
  212. package/dist/template-paths.js.map +1 -0
  213. package/dist/template-presentation.d.ts +20 -0
  214. package/dist/template-presentation.d.ts.map +1 -0
  215. package/dist/template-presentation.js +133 -0
  216. package/dist/template-presentation.js.map +1 -0
  217. package/dist/template-source.d.ts +4 -1
  218. package/dist/template-source.d.ts.map +1 -1
  219. package/dist/template-source.js +11 -4
  220. package/dist/template-source.js.map +1 -1
  221. package/dist/templates.d.ts +11 -0
  222. package/dist/templates.d.ts.map +1 -0
  223. package/dist/templates.js +53 -0
  224. package/dist/templates.js.map +1 -0
  225. package/dist/unixfs-tree.d.ts +67 -0
  226. package/dist/unixfs-tree.d.ts.map +1 -0
  227. package/dist/unixfs-tree.js +329 -0
  228. package/dist/unixfs-tree.js.map +1 -0
  229. package/package.json +14 -7
  230. package/src/app-authoring.ts +240 -76
  231. package/src/app-definition.ts +33 -39
  232. package/src/app-prebuild.ts +61 -0
  233. package/src/app-templates.ts +17 -73
  234. package/src/assembly.ts +185 -0
  235. package/src/authoring.ts +41 -17
  236. package/src/builtins.ts +2 -27
  237. package/src/bundled-skills.ts +60 -0
  238. package/src/cli.ts +2399 -320
  239. package/src/config-secret.ts +14 -0
  240. package/src/config.ts +196 -8
  241. package/src/content-provider.ts +299 -0
  242. package/src/context-types.ts +11 -0
  243. package/src/context.ts +98 -10
  244. package/src/daemon-ui.ts +812 -0
  245. package/src/daemon.ts +386 -0
  246. package/src/doctor.ts +1082 -0
  247. package/src/errors.ts +1 -25
  248. package/src/get.ts +90 -0
  249. package/src/history.ts +5 -15
  250. package/src/host-error.ts +26 -0
  251. package/src/identity.ts +175 -0
  252. package/src/ipc.ts +160 -11
  253. package/src/kubo-install.ts +936 -0
  254. package/src/kubo-peering.ts +126 -0
  255. package/src/kubo-peers.ts +144 -0
  256. package/src/kubo-release.ts +230 -0
  257. package/src/kubo-topology.ts +148 -0
  258. package/src/kubo.ts +1088 -0
  259. package/src/pins.ts +188 -126
  260. package/src/pivot-rpc.ts +601 -0
  261. package/src/pivot-service.ts +87 -0
  262. package/src/publish-source.ts +103 -0
  263. package/src/runtime.ts +16 -4
  264. package/src/search-index.ts +560 -0
  265. package/src/search-service.ts +152 -0
  266. package/src/skill-definition.ts +53 -0
  267. package/src/skill-source.ts +29 -0
  268. package/src/skills.ts +1236 -0
  269. package/src/source-bundle.ts +26 -13
  270. package/src/space-path.ts +30 -0
  271. package/src/space.ts +230 -42
  272. package/src/state-storage-windows.ts +134 -0
  273. package/src/state-storage.ts +378 -0
  274. package/src/state.ts +759 -107
  275. package/src/swarm-envelope.ts +461 -0
  276. package/src/swarm-files.ts +126 -0
  277. package/src/swarm-meta.ts +98 -0
  278. package/src/swarm-observations.ts +393 -0
  279. package/src/swarm.ts +7051 -0
  280. package/src/template-definition.ts +36 -41
  281. package/src/template-paths.ts +43 -0
  282. package/src/template-presentation.ts +151 -0
  283. package/src/template-source.ts +19 -5
  284. package/src/templates.ts +77 -0
  285. package/src/unixfs-tree.ts +401 -0
package/dist/cli.js CHANGED
@@ -1,38 +1,70 @@
1
1
  import { createInterface } from "node:readline/promises";
2
- import { readFile } from "node:fs/promises";
3
- import { IpfsStore } from "@ipab/ipfs-store";
2
+ import { lstat, readFile } from "node:fs/promises";
3
+ import { ContentError, IpfsStore } from "@ipab/ipfs-store";
4
+ import { ContentBundleError } from "@ipab/bundle";
4
5
  import { randomUUID } from "node:crypto";
6
+ import { CID } from "multiformats/cid";
5
7
  import stringWidth from "string-width";
6
- import { configKey, effectiveConfig, parseValue, publicUrl, stateLocation, storeConfiguration, } from "./config.js";
8
+ import { configKey, effectiveConfig, parseValue, publicUrl, stateLocation, storeConfiguration, swarmUrl, visibleConfig, } from "./config.js";
7
9
  import { HostError, message, object, syntax } from "./errors.js";
8
10
  import { filters, listHistory, selectedIds, Ownership, recoverInactive, removeHistory, } from "./history.js";
9
11
  import { execute } from "./runtime.js";
10
12
  import { validatedBundle } from "./space.js";
11
- import { exactCid, pinName, State } from "./state.js";
12
- import { buildBundle, inspectBundle, importBundle } from "./authoring.js";
13
- import { buildApp, initApp } from "./app-authoring.js";
13
+ import { createAssociation, exactCid, swarmAlias, State, } from "./state.js";
14
+ import { buildBundle, inspectBundle, importBundle, nodeError, } 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";
14
22
  import { schemaAlias } from "./app-definition.js";
15
- import { addPin, deletePin, pinDetails, renamePin } from "./pins.js";
23
+ import { unpin, pinDetails } from "./pins.js";
24
+ import { publicationSource } from "./publish-source.js";
25
+ import { templateRenderExample, templateOutputTree, templateParameterRows, } from "./template-presentation.js";
16
26
  import { logFiles } from "./logs.js";
17
27
  import { builtinContent } from "./builtins.js";
28
+ import { readSecretStream } from "./config-secret.js";
29
+ import { manageSkills, syncDaemonSwarm } from "./skills.js";
30
+ let progressLine = false;
18
31
  export const processIO = {
19
32
  out(text) {
20
33
  process.stdout.write(`${text}\n`);
21
34
  },
22
- err(text) {
23
- process.stderr.write(`${text}\n`);
35
+ err(text, progress = false) {
36
+ if (progress && process.stderr.isTTY) {
37
+ const width = (process.stderr.columns > 1 ? process.stderr.columns : 80) - 1;
38
+ process.stderr.write(`\r\x1b[2K${text.slice(0, width)}`);
39
+ progressLine = true;
40
+ }
41
+ else {
42
+ process.stderr.write(`${progressLine ? "\n" : ""}${text}\n`);
43
+ progressLine = false;
44
+ }
24
45
  },
25
46
  tty: Boolean(process.stdin.isTTY && process.stderr.isTTY),
26
47
  columns() {
27
48
  return process.stdout.columns;
28
49
  },
29
- async confirm(text) {
50
+ requestInput() {
51
+ if (process.stdin.isTTY)
52
+ syntax("Pipe Request JSON into swarm approve - --yes, or pass a Request file.");
53
+ return process.stdin;
54
+ },
55
+ async readSecret() {
56
+ if (process.stdin.isTTY)
57
+ syntax("Pipe the API key through stdin; interactive echo is not permitted.");
58
+ process.stdin.setEncoding("utf8");
59
+ return readSecretStream(process.stdin);
60
+ },
61
+ async confirm(text, signal) {
30
62
  const reader = createInterface({
31
63
  input: process.stdin,
32
64
  output: process.stderr,
33
65
  });
34
66
  try {
35
- return /^(y|yes)$/i.test((await reader.question(`${text} [y/N] `)).trim());
67
+ return /^(y|yes)$/i.test((await reader.question(`${text} [y/N] `, signal ? { signal } : {})).trim());
36
68
  }
37
69
  finally {
38
70
  reader.close();
@@ -40,23 +72,50 @@ export const processIO = {
40
72
  },
41
73
  };
42
74
  const commands = {
43
- init: "init NAME [DIR] [OPTIONS]",
44
- build: "build [DIR] [OPTIONS]",
75
+ daemon: "daemon",
76
+ "daemon ui": "daemon ui [--open]",
77
+ "skills list": "skills list [--refresh | --no-refresh]",
78
+ "skills sync": "skills sync [NAMES...] [--agent AGENT]... [--override-existing] [--dry-run] [--yes] [--refresh | --no-refresh]",
79
+ doctor: "doctor [--fix [--yes]]",
80
+ profile: "profile [--name NAME] [--description TEXT]",
81
+ "swarm create": "swarm create [--service URL] [--resume OPERATION]",
82
+ "swarm request": "swarm request URL_OR_ALIAS [--pivot] [--output FILE]",
83
+ "swarm export": "swarm export --output FILE",
84
+ "swarm approve": "swarm approve REQUEST_FILE [--pivot] [--again] --yes",
85
+ "swarm pivot grant": "swarm pivot grant MEMBER_PUBLIC_KEY --yes",
86
+ "swarm exclude": "swarm exclude MEMBER_PUBLIC_KEY --yes",
87
+ "swarm resume": "swarm resume",
88
+ "swarm profile": "swarm profile [--address MULTIADDR] [--pivot true|false]",
89
+ "swarm status": "swarm status [--refresh | --no-refresh]",
90
+ "swarm members": "swarm members [--refresh | --no-refresh]",
91
+ "swarm list": "swarm list",
92
+ "swarm set": "swarm set ALIAS CONFIG_URL [--yes]",
93
+ "swarm use": "swarm use URL_OR_ALIAS",
94
+ "swarm remove": "swarm remove URL_OR_ALIAS",
95
+ "swarm update": "swarm update [--name TEXT] [--description TEXT]",
96
+ publish: "publish NAME SOURCE [--expect OLD_CID | --snapshot]",
97
+ get: "get REF [--raw] [--refresh | --no-refresh] [-o DIRECTORY]",
98
+ search: "search QUERY [--all | --current] [--prefix PATH] [--kind all|bundle|dir|file] [--schema CID] [--limit N] [--offset N] [--refresh | --no-refresh]",
99
+ "templates render": "templates render TEMPLATE NAME [DIR] [OPTIONS]",
100
+ build: "build [SOURCE] [OPTIONS]",
45
101
  "bundle build": "bundle build SOURCE [OPTIONS]",
46
102
  "bundle inspect": "bundle inspect SOURCE",
47
103
  "bundle import": "bundle import FILE.car",
48
- exec: "exec [--log] APP [APP_ARGS...]",
49
- open: "open [--log] CONTENT",
50
- "pin add": "pin add NAME CID",
51
- "pin delete": "pin delete NAME",
52
- "pin list": "pin list [--type TYPE]",
53
- "pin show": "pin show NAME",
54
- "pin rename": "pin rename OLD_NAME NEW_NAME",
55
- "register list": "register list",
56
- "register set": "register set SCHEMA APP [--replace] [-- TEMPLATE...]",
57
- "register remove": "register remove SCHEMA",
104
+ exec: "exec [--log] [--refresh | --no-refresh] APP [APP_ARGS...]",
105
+ open: "open [--log] [--raw] [--refresh | --no-refresh] CONTENT",
106
+ pin: "pin REF [--refresh | --no-refresh]",
107
+ unpin: "unpin REF",
108
+ "pin list": "pin list",
109
+ "pin show": "pin show REF",
110
+ "register list": "register list [--swarm URL_OR_ALIAS]",
111
+ "register set": "register set SCHEMA APP [--swarm URL_OR_ALIAS]... [--replace]",
112
+ "register remove": "register remove SCHEMA [--swarm URL_OR_ALIAS]...",
113
+ "templates list": "templates list [--refresh | --no-refresh]",
114
+ "templates show": "templates show NAME [--refresh | --no-refresh]",
115
+ "templates set": "templates set NAME SOURCE [--expect OLD_TARGET_CID]",
116
+ "templates remove": "templates remove NAME --expect OLD_TARGET_CID",
58
117
  "config get": "config get [KEY]",
59
- "config set": "config set KEY VALUE",
118
+ "config set": "config set KEY VALUE\n ipab config set pointers.apiKey - < protected-key-file",
60
119
  "config reset": "config reset KEY",
61
120
  "store usage": "store usage",
62
121
  "store gc": "store gc",
@@ -65,14 +124,419 @@ const commands = {
65
124
  "history remove": "history remove RUN_ID... [--yes]\n ipab history remove FILTERS [--yes]",
66
125
  };
67
126
  const groups = {
127
+ skills: "Discover and explicitly synchronize selected Swarm Skills globally",
128
+ swarm: "Create, authorize, select and manage personal swarms",
68
129
  bundle: "Create, inspect and import content bundles",
69
- pin: "Retain content and manage short names",
130
+ pin: "Retain an exact CID or follow a shared Swarm Name",
70
131
  register: "Associate content types with Apps",
132
+ templates: "Inspect, render and manage Template Bundles",
71
133
  config: "Manage local configuration",
72
134
  store: "Query local storage and collect unreferenced blocks",
73
135
  history: "View and remove execution history",
74
136
  };
75
137
  const commandHelp = {
138
+ daemon: {
139
+ summary: "Manage all registered private Swarm nodes in the foreground",
140
+ examples: ["ipab daemon", "ipab daemon ui --open"],
141
+ notes: [
142
+ "Manages all registered Swarms independently and does not accept --swarm; ignores the saved default.",
143
+ "Maintains membership and network topology: probes pivot candidates, refreshes approved profiles and retries with cooldown. Diagnostics go to stderr.",
144
+ "Synchronizes the latest HEAD/State and automatically syncs Skills (to universal), Templates and Registry App Bundles for each activated Swarm on startup and every swarm.syncInterval seconds (default 60; IPAB_SWARM_SYNC_INTERVAL). Preserves local edits and other sources.",
145
+ "Serves a read-only loopback status WebUI on 127.0.0.1 (automatic port by default; configurable via daemon.uiPort / IPAB_DAEMON_UI_PORT). Inspect or open it with `ipab daemon ui [--open]`.",
146
+ "Swarm network operations start one background daemon on demand per state-dir; local commands, doctor and status/members inspections do not. No OS startup service is installed.",
147
+ "Ctrl-C / TERM drains foreground operations and releases the device/state-dir lock; Kubo stays running. An existing background daemon already owns this lock.",
148
+ "Role and relay candidate changes restart only the verified managed Kubo node.",
149
+ ],
150
+ },
151
+ "daemon ui": {
152
+ summary: "Show or open the running daemon's read-only loopback status WebUI",
153
+ options: [
154
+ "--open Open the 127.0.0.1 status WebUI URL in the default browser.",
155
+ ],
156
+ examples: [
157
+ "ipab daemon ui",
158
+ "ipab daemon ui --open",
159
+ "ipab --json daemon ui",
160
+ ],
161
+ notes: [
162
+ "Inspects the protected loopback endpoint for the selected state-dir without starting a daemon.",
163
+ "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
+ ],
165
+ },
166
+ "templates list": {
167
+ summary: "List templates under the selected Swarm Meta templatePath",
168
+ options: [
169
+ "--refresh / --no-refresh Refresh HEAD now / allow a valid cached snapshot.",
170
+ ],
171
+ examples: [
172
+ "ipab --swarm work templates list",
173
+ "ipab --json templates list",
174
+ ],
175
+ notes: [
176
+ "Uses only global --swarm (once, before the command), otherwise the saved default. No builtin or other Swarm fallback.",
177
+ ],
178
+ },
179
+ "templates show": {
180
+ summary: "Show one template, its exact targets and declared parameters",
181
+ arguments: [
182
+ "NAME Safe relative template Name; nested names are supported.",
183
+ ],
184
+ options: [
185
+ "--refresh / --no-refresh Refresh HEAD now / allow a valid cached snapshot.",
186
+ ],
187
+ examples: ["ipab --swarm work templates show node"],
188
+ },
189
+ "templates set": {
190
+ summary: "Publish one validated Template Bundle with exact Name conflict checks",
191
+ arguments: [
192
+ "NAME Safe relative template Name.",
193
+ "SOURCE Exact Template CID, self-contained CAR or explicit manifest directory; no URI, build or hooks.",
194
+ ],
195
+ options: [
196
+ "--expect OLD_TARGET_CID Required to replace an occupied Name; use its exact target CID, including an Artifact wrapper.",
197
+ ],
198
+ examples: [
199
+ "ipab --swarm work templates set team/node ./template.car",
200
+ "ipab templates set node TEMPLATE_CID --expect OLD_TARGET_CID",
201
+ ],
202
+ notes: [
203
+ "Publishes an ordinary Artifact and preserves publication history and content retention.",
204
+ ],
205
+ },
206
+ "templates remove": {
207
+ summary: "Remove only one template Name, without deleting content",
208
+ arguments: ["NAME Safe relative template Name."],
209
+ options: [
210
+ "--expect OLD_TARGET_CID Required exact current Name target CID.",
211
+ ],
212
+ examples: [
213
+ "ipab --swarm work templates remove team/node --expect OLD_TARGET_CID",
214
+ ],
215
+ notes: [
216
+ "Missing Names are errors. Does not unpin, GC or delete content or history.",
217
+ ],
218
+ },
219
+ "skills list": {
220
+ summary: "List typed Skills and local installation status from one Swarm",
221
+ options: [
222
+ "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
223
+ "Global --json Emit machine-readable names, exact payload CIDs and status.",
224
+ ],
225
+ examples: ["ipab --swarm work skills list", "ipab --json skills list"],
226
+ notes: [
227
+ "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.",
229
+ ],
230
+ },
231
+ "skills sync": {
232
+ summary: "Install reviewed Swarm Skills using the pinned official npx installer",
233
+ 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.",
235
+ ],
236
+ options: [
237
+ "--agent AGENT Repeatable globally supported agent ID; default is universal (~/.agents/skills).",
238
+ "--override-existing Replace non-IPAB-managed Skills and local edits at selected targets.",
239
+ "--dry-run Preview without invoking npx or changing installed Skills.",
240
+ "--yes Skip IPAB consent only; does not imply --override-existing.",
241
+ "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
242
+ ],
243
+ examples: [
244
+ "ipab --swarm work skills sync --dry-run",
245
+ "ipab skills sync ipab code-review --agent github-copilot --yes",
246
+ ],
247
+ notes: [
248
+ "Global installs only, through official skills@1.9.1 with --copy. Requires Node >=22.20.0.",
249
+ "Non-interactive execution requires --yes. Installer version, source, paths and agents are shown first.",
250
+ "No Skill hooks/scripts run. The trusted installer is not sandboxed. Telemetry and remote audits are disabled.",
251
+ "Non-IPAB installs and local edits require --override-existing. Cross-Swarm collisions and symlink/junction aliases remain protected. Removed sources are reported, not deleted.",
252
+ "Partial failures report individual results, preserve pending attribution and exit nonzero; retry the same sync.",
253
+ ],
254
+ },
255
+ profile: {
256
+ summary: "Read or update your account-wide public name and description",
257
+ examples: [
258
+ "ipab profile",
259
+ 'ipab profile --name Wei --description "Developer"',
260
+ 'ipab profile --description ""',
261
+ ],
262
+ options: [
263
+ "--name NAME Replace only your personal name.",
264
+ "--description TEXT Replace only your description; empty text clears it.",
265
+ ],
266
+ notes: [
267
+ "Independent of Swarm selection. Reading never creates an identity, persists a profile or activates a node.",
268
+ "An explicit update prepares a missing account identity without starting Kubo.",
269
+ "Updates persist locally first, then synchronize all registered memberships without changing network addresses. Partial failure exits nonzero and reports every result.",
270
+ "Retry the same profile update, or normally activate a failed membership to synchronize the saved profile.",
271
+ "First use preserves unanimous legacy values; conflicting fields require an explicit choice. New memberships adopt this same profile.",
272
+ ],
273
+ },
274
+ doctor: {
275
+ summary: "Inspect device readiness without writes; explicitly authorize safe repairs",
276
+ examples: [
277
+ "ipab doctor",
278
+ "ipab doctor --fix",
279
+ "ipab --json doctor --fix --yes",
280
+ ],
281
+ options: [
282
+ "--fix Repair missing components, cache official archives to verify existing Kubo without reinstall, and authorize healthy compatible upgrades within ^0.43.2.",
283
+ "--yes Authorize planned repairs without prompting; requires --fix.",
284
+ ],
285
+ notes: [
286
+ "Always checks local state/configuration, managed Kubo, HOME identity, local Swarm registry, compatible updates and the CLI-bundled IPAB Skill for detected Agents.",
287
+ "--fix also installs/updates the bundled IPAB Skill globally using the pinned official installer, without joining a Swarm. Custom content and Swarm-managed Skills are never overwritten.",
288
+ "Inspection never creates state, locks, credentials or caches. Official release metadata may be queried; unavailable updates are not claimed current.",
289
+ "Healthy current components are reused without download or confirmation. Fixed protected archive cache is automatic.",
290
+ "Unverified existing Kubo: --fix may download/cache its exact-version official archive for byte comparison only; never execute it to authenticate itself or overwrite a mismatch.",
291
+ "Does not create Swarm repos, start or contact any daemon, deploy services or install login startup.",
292
+ ],
293
+ },
294
+ "swarm create": {
295
+ summary: "Create a swarm using the account HOME identity",
296
+ options: [
297
+ "--service URL Must match the protected pointers.service origin.",
298
+ "--resume OPERATION Recover the same saved create/idempotency result.",
299
+ "--name TEXT Initial mutable swarm name.",
300
+ "--description TEXT Initial mutable description.",
301
+ "--alias ALIAS Optional local registry alias (not the shared name).",
302
+ ],
303
+ examples: [
304
+ "ipab config set pointers.service https://service.example",
305
+ "ipab config set pointers.apiKey -",
306
+ "ipab swarm create",
307
+ ],
308
+ notes: [
309
+ "Creation uses the protected, origin-bound API key and owner possession proof.",
310
+ "Installs checksum-verified Kubo on demand; each Swarm has its own protected repo and ports.",
311
+ "Returns the public organization configuration URL; owner needs no certificate.",
312
+ ],
313
+ },
314
+ "swarm request": {
315
+ summary: "Save and export a signed self-contained membership Request",
316
+ examples: [
317
+ "ipab swarm request work",
318
+ "ipab swarm request CONFIG_URL --output request.json",
319
+ ],
320
+ options: [
321
+ "--pivot Request Pivot Member role (HEAD write + ScopeWriteReceipt issuer); defaults to ordinary.",
322
+ "--output FILE Export to a new file instead of stdout; never overwrites.",
323
+ ],
324
+ notes: [
325
+ "Verify the printed Owner fingerprint through an independent trusted channel before manually sending the Request file to the Owner.",
326
+ "Without --output, stdout is the signed Request JSON, including in --json mode.",
327
+ "With --output, reports the file on stderr; --json returns file, member and ownerFingerprint.",
328
+ "Retries export the exact saved Request without expiry.",
329
+ "No Invite, Response file, password or Join. Next normal use fetches and decrypts the approved package.",
330
+ "Accepts a local alias or a configuration URL. Never changes local registrations, aliases or the saved default; use ipab swarm set ALIAS CONFIG_URL separately.",
331
+ ],
332
+ },
333
+ "swarm approve": {
334
+ summary: "Owner signs a certificate for an exact request",
335
+ options: [
336
+ "--yes Explicit approval; required outside a TTY.",
337
+ "--pivot Also authorize this member to sign HEAD write receipts as a Pivot.",
338
+ "--again Explicit fresh approval of an old Request; history is advisory.",
339
+ ],
340
+ examples: [
341
+ "ipab --swarm work swarm approve request.json --yes",
342
+ "ipab --swarm work swarm approve request.json --pivot --yes",
343
+ "ipab --swarm work swarm approve - --yes < request.json",
344
+ ],
345
+ notes: [
346
+ "Use '-' to read Request JSON from stdin (maximum 16 KiB); --yes is required and no confirmation prompt reads stdin.",
347
+ "Ordinary approval grants only the member's profile write access; --pivot also grants current HEAD write authority. Exact-ID certificates have no expiry; revoking Pivot HEAD authority requires swarm exclude.",
348
+ ],
349
+ },
350
+ "swarm pivot grant": {
351
+ summary: "Owner grants an approved member Pivot HEAD receipt authority",
352
+ options: ["--yes Explicit confirmation; required."],
353
+ examples: ["ipab --swarm work swarm pivot grant MEMBER_PUBLIC_KEY --yes"],
354
+ notes: [
355
+ "Re-issues the approved member's ScopeCertificate with current HEAD and profile write access and updates their approval envelope without rotating the epoch.",
356
+ "Exact-ID certificates are stateless with no expiry; revoking Pivot HEAD authority requires swarm exclude (epoch/HEAD rotation).",
357
+ ],
358
+ },
359
+ "swarm export": {
360
+ summary: "Re-export the same persisted Request",
361
+ examples: ["ipab --swarm work swarm export --output request.json"],
362
+ },
363
+ "swarm exclude": {
364
+ summary: "Owner removes a member with irreversible HEAD/key rotation",
365
+ examples: ["ipab --swarm work swarm exclude MEMBER_PUBLIC_KEY --yes"],
366
+ notes: [
367
+ "Freezes the old HEAD atomically, preserves its final committed publication, rotates the key and remaining packages, deletes the leaving profile and retires the old HEAD.",
368
+ ],
369
+ },
370
+ "swarm resume": {
371
+ summary: "Owner resumes an interrupted organization switch",
372
+ examples: ["ipab --swarm work swarm resume"],
373
+ },
374
+ "swarm profile": {
375
+ summary: "Configure your selected Swarm's address and Pivot role",
376
+ options: [
377
+ "--pivot true|false Declare or withdraw this member's Pivot backbone role.",
378
+ ],
379
+ examples: [
380
+ "ipab --swarm work swarm profile --address /ip4/192.168.1.12/tcp/4001/p2p/PEER_ID",
381
+ "ipab --swarm work swarm profile --pivot true",
382
+ ],
383
+ notes: [
384
+ "Personal name/description are managed only by ipab profile, not this network configuration command.",
385
+ "Pivot provides backbone connectivity and durable published-content Pin service through daemon. Keep it online with sufficient storage.",
386
+ ],
387
+ },
388
+ "swarm members": {
389
+ summary: "List every public member, including the Owner",
390
+ options: [
391
+ "--refresh / --no-refresh Fetch public Variables now / reuse the saved inspection, fetching if missing.",
392
+ "--local Deprecated no-op; local daemon observations are always included.",
393
+ ],
394
+ examples: [
395
+ "ipab --swarm work swarm members",
396
+ "ipab --json swarm members --refresh",
397
+ ],
398
+ notes: [
399
+ "Default: reuse the inspection cache, fetching public Variables if missing. Includes Pivot declarations and existing daemon observations; no HOME identity access, node activation or probes.",
400
+ "PIVOT: - for ordinary members; selected, cooldown, unknown, self or candidate for declared Pivots. Selected means applied configuration, not connectivity.",
401
+ ],
402
+ },
403
+ "swarm status": {
404
+ summary: "Inspect cached Swarm directory, HEAD and local networking",
405
+ options: [
406
+ "--refresh / --no-refresh Fetch public Variables now / reuse the saved inspection, fetching if missing.",
407
+ "--local Deprecated no-op; never activates a node.",
408
+ ],
409
+ examples: [
410
+ "ipab swarm status",
411
+ "ipab --swarm work swarm status",
412
+ "ipab --swarm work swarm status --refresh",
413
+ ],
414
+ notes: [
415
+ "Default: reuse the inspection cache, fetching public Variables if missing. Refresh verifies Config, Scope, members, Profiles and HEAD, not connectivity or State content.",
416
+ "Always shows daemon freshness, Pivot selection, probes/cooldown and separately timestamped daemon connection snapshots. Never contacts Kubo, initializes HOME identity, changes remote profiles or activates a node.",
417
+ "State content is explicitly unavailable in inspection; use get ipab:/// to obtain the State Bundle.",
418
+ "Local connectivity is not global availability; a relay connection does not guarantee content transfer.",
419
+ ],
420
+ },
421
+ "swarm list": {
422
+ summary: "List local swarm registrations and the effective selection",
423
+ examples: ["ipab swarm list", "ipab --json swarm list"],
424
+ notes: ["Local only; does not verify remote membership or refresh HEAD."],
425
+ },
426
+ "swarm set": {
427
+ summary: "Set a local alias for a swarm configuration URL",
428
+ options: [
429
+ "--yes Authorize retargeting an existing alias without prompting.",
430
+ ],
431
+ examples: [
432
+ "ipab swarm set work CONFIG_URL",
433
+ "ipab swarm set work OTHER_CONFIG_URL --yes",
434
+ ],
435
+ notes: [
436
+ "Local only; no network, account identity or approved membership required.",
437
+ "Setting the same mapping is idempotent. One alias per URL; a new alias for that URL replaces its old alias.",
438
+ "Retargeting an alias requires confirmation or --yes. Keeps the old URL registered without that alias; credentials, caches and the saved default URL are unchanged.",
439
+ "Not a membership grant. The first registration becomes the saved default only if none exists.",
440
+ ],
441
+ },
442
+ "swarm use": {
443
+ summary: "Save a registered swarm as the current default",
444
+ examples: ["ipab swarm use work"],
445
+ notes: ["Local only. --swarm still overrides the saved default."],
446
+ },
447
+ "swarm remove": {
448
+ summary: "Forget a local registration without revoking membership",
449
+ examples: ["ipab swarm remove work"],
450
+ notes: [
451
+ "Preserves credentials, content and remote membership. Clears a matching saved default without selecting a replacement.",
452
+ ],
453
+ },
454
+ "swarm update": {
455
+ summary: "Owner updates public organization information",
456
+ options: [
457
+ "--name TEXT Replace the shared display name; empty text clears it.",
458
+ "--description TEXT Replace the shared description; empty text clears it.",
459
+ ],
460
+ examples: [
461
+ 'ipab --swarm work swarm update --name "Team" --description "Shared workspace"',
462
+ 'ipab swarm update --description ""',
463
+ ],
464
+ notes: [
465
+ "Requires at least one field. Members can change only their own profile.",
466
+ "Content-CID CAS prevents overwriting concurrent organization changes.",
467
+ "Shared name changes do not rename local registry aliases.",
468
+ ],
469
+ },
470
+ search: {
471
+ summary: "Search formal Names in the current swarm",
472
+ arguments: [
473
+ "QUERY Case-insensitive literal name substring, 1..256 characters.",
474
+ ],
475
+ options: [
476
+ "--all Search all registered swarms; conflicts with --current and --swarm.",
477
+ "--current Explicitly select the default search scope; conflicts with --swarm.",
478
+ "--prefix PATH Restrict v7 search results to paths under PATH.",
479
+ "--kind KIND Filter v7 search results by kind: all, bundle, dir, or file.",
480
+ "--schema CID Filter v7 search results to Bundles with exact schema CID.",
481
+ "--limit N Maximum number of results per v7 swarm (1..100, default 20).",
482
+ "--offset N Zero-based result offset for v7 pagination (default 0).",
483
+ "--refresh Refresh HEAD for every swarm in the search scope.",
484
+ "--no-refresh Override swarm.forceRefresh and use valid cached headers.",
485
+ ],
486
+ examples: [
487
+ "ipab search hello",
488
+ "ipab search hello --all",
489
+ "ipab --swarm work search hello --refresh",
490
+ ],
491
+ notes: [
492
+ "Searches only --swarm or the saved current swarm by default. Use --all to search every registration.",
493
+ "Valid caches use local Names; absent/expired caches refresh. Active Name pins may synchronize content.",
494
+ "Refresh reads public configuration and HEAD; private networking is activated only for missing content.",
495
+ "No matches is success, not a reason to refresh valid caches. Any failed swarm fails the whole search.",
496
+ "Text uses local alias URIs when available; JSON references use full configuration URLs for cross-device sharing.",
497
+ ],
498
+ },
499
+ publish: {
500
+ summary: "Protect content locally and publish a shared Swarm Name",
501
+ options: [
502
+ "--expect CID Exact old Name target CID, required for iteration.",
503
+ "--snapshot Name ordinary content without an Artifact; initial only.",
504
+ ],
505
+ examples: [
506
+ "ipab --swarm work publish apps/hello app.car",
507
+ "ipab publish apps/hello APP_CID --expect OLD_APP_CID",
508
+ "ipab publish notes/readme ./README.md",
509
+ ],
510
+ notes: [
511
+ "SOURCE is an exact Bundle CID, CAR, regular file or directory. No compiler, hooks, install or App execution.",
512
+ "Directories require .bundle.yaml/type, or a package.json source snapshot. Standalone .json/.yaml/.yml/.md/.txt entries get a standard Bundle; other file types require explicit metadata.",
513
+ "App and Meta Bundles publish direct CID links; other content uses Artifact records. Occupied Names require --expect EXACT_OLD_CID (the old Artifact CID when applicable). Published payloads are local CID pins; unpin CID releases that protection, not history holders.",
514
+ "Different-name CAS contention is rebased; same-name edits conflict (exit 3).",
515
+ "Kubo pin confirmation precedes HEAD; it does not prove a remote device is online.",
516
+ ],
517
+ },
518
+ get: {
519
+ summary: "Verify and unpack Bundle content without executing it",
520
+ options: [
521
+ "--raw Select the Artifact node instead of its value.",
522
+ "--refresh Refresh the shared Name's swarm HEAD.",
523
+ "--no-refresh Override swarm.forceRefresh and use valid cached headers.",
524
+ "-o, --output DIRECTORY New or empty directory; defaults to a unique temporary directory.",
525
+ ],
526
+ examples: [
527
+ "ipab --json get ipab:///apps/hello -o hello-app",
528
+ "ipab get ipab://work/apps/hello -o hello-app",
529
+ "ipab get CONTENT_CID",
530
+ "ipab get --raw RELEASE_CID",
531
+ ],
532
+ notes: [
533
+ "Stdout contains only the absolute directory path; --json also returns content and original target CIDs.",
534
+ "Temporary exports remain after exit; copy before cleanup, not symlink. Use --output for a persistent destination.",
535
+ "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
536
+ "Copy the reference from ipab search, or percent-encode the entire configuration URL and each Name path segment separately.",
537
+ "Does not install, build, edit, or automatically retrieve associated source.",
538
+ ],
539
+ },
76
540
  "store usage": {
77
541
  summary: "Query cached and recursively pinned block bytes",
78
542
  examples: ["ipab store usage", "ipab --json store usage"],
@@ -89,37 +553,48 @@ const commandHelp = {
89
553
  "Does not unpin, clear history, delete unknown files or request Kubo daemon GC.",
90
554
  ],
91
555
  },
92
- init: {
93
- summary: "Create files from a Template Bundle (default: Node App project)",
94
- arguments: ["NAME Project name; DIR defaults to NAME (new/empty only)."],
556
+ "templates render": {
557
+ summary: "Render a template's project files into a new or empty folder",
558
+ arguments: [
559
+ "TEMPLATE Explicit Swarm selector, directory, CAR, exact CID or IPAB URI.",
560
+ "NAME Project name parameter; DIR defaults to NAME (new/empty only).",
561
+ ],
95
562
  options: [
96
- "--template TEMPLATE node (default), web-app, directory, CAR, CID or pin.",
563
+ "--description TEXT Set the declared description parameter.",
564
+ "--refresh / --no-refresh Refresh Swarm HEAD now / allow its valid cached snapshot.",
97
565
  "--param KEY=VALUE Template parameter; repeatable. Strings are literal;",
98
566
  " other parameter types use JSON.",
99
567
  ],
100
568
  examples: [
101
- "ipab init hello",
102
- "ipab init dashboard --template web-app",
103
- "ipab init hello --param description=Demo",
569
+ "ipab templates render node hello",
570
+ "ipab templates render web-app dashboard --param webAppDependency=0.1.0-rc.2",
571
+ "ipab templates render ./template.car hello --description Demo",
572
+ ],
573
+ notes: [
574
+ "Short selectors resolve through the selected Swarm's typed root configuration (legacy v2/v3/v4 use Meta Name ipab); no builtin fallback.",
575
+ "Explicit directory, CAR and available exact CID work offline without a Swarm.",
576
+ "Does not install dependencies or execute template code.",
104
577
  ],
105
- notes: ["Does not install dependencies or execute template code."],
106
578
  },
107
579
  build: {
108
- summary: "Build an App CAR from a project",
109
- arguments: ["DIR Project directory (default: current directory)."],
580
+ summary: "Assemble any Bundle using ipab.build.yaml (no compilation)",
581
+ arguments: [
582
+ "SOURCE Recipe file or Bundle directory (default: current directory).",
583
+ ],
110
584
  options: [
111
- "-o, --output FILE Destination (default: dist/app.car).",
585
+ "-o, --output FILE Destination (default: dist/bundle.car).",
112
586
  "--replace Allow replacing existing regular artifacts.",
113
- "--no-import Write CAR files without importing the App into Store.",
114
- "--with-source Include a separate source CAR (default: enabled).",
115
- "--without-source Omit source CAR; conflicts with --with-source.",
587
+ "--no-import Write the CAR without importing the Bundle into Store.",
588
+ ],
589
+ examples: [
590
+ "ipab build prepared-app",
591
+ "ipab build ipab.build.yaml --replace",
116
592
  ],
117
- examples: ["ipab build", "ipab build hello --replace --without-source"],
118
593
  notes: [
119
- "Uses local tsc and bundles Node CommonJS; ipab.yaml configures the build.",
120
- "Explicit ipab-prebuild strategy executes trusted project code.",
121
- "Source follows project .gitignore rules; review private files before sharing.",
122
- "Imports only the App, without pinning; source needs separate import/retention.",
594
+ "Recipe explicitly maps source files and exact CID imports to target paths.",
595
+ "Instance paths come from .bundle.yaml; the referenced file defines the type. Imported DAG identities are preserved.",
596
+ "Legacy App ipab.yaml is rejected; use project preparation tools separately.",
597
+ "Select explicit files; review private files before providing Bundles.",
123
598
  "Store failures preserve the CAR; retry with ipab bundle import FILE.car.",
124
599
  ],
125
600
  },
@@ -134,7 +609,7 @@ const commandHelp = {
134
609
  ],
135
610
  examples: [
136
611
  "ipab bundle build note",
137
- "ipab bundle build types\\.bundle.yaml --schema-only",
612
+ "ipab bundle build types\\.bundle-type.yaml --schema-only",
138
613
  ],
139
614
  notes: [
140
615
  "Imports into the configured Store without pinning or executing Apps.",
@@ -143,7 +618,9 @@ const commandHelp = {
143
618
  },
144
619
  "bundle inspect": {
145
620
  summary: "Inspect a Bundle or type definition",
146
- arguments: ["SOURCE Directory, definition file, CAR, CID or named pin."],
621
+ arguments: [
622
+ "SOURCE Directory, definition file, CAR, CID or packaged builtin reference.",
623
+ ],
147
624
  examples: ["ipab bundle inspect note\\dist\\bundle.car"],
148
625
  notes: ["Does not execute Apps, import content or create pins."],
149
626
  },
@@ -153,24 +630,27 @@ const commandHelp = {
153
630
  examples: ["ipab bundle import hello\\dist\\app.car"],
154
631
  notes: [
155
632
  "Repeated imports are safe; no App execution or daemon startup.",
156
- "Does not pin or retain content. Use pin add for persistent retention.",
633
+ "Does not pin or retain content. Use pin CID for persistent retention.",
157
634
  ],
158
635
  },
159
636
  exec: {
160
- summary: "Run an App by CID or named pin",
637
+ summary: "Run an App by exact CID or Swarm IPAB URI",
161
638
  arguments: [
162
639
  "APP_ARGS Everything after APP is passed verbatim, including --help.",
163
640
  ],
164
641
  options: [
165
642
  "--log Record stdout/stderr; must precede APP. Requires history enabled.",
643
+ "--refresh Refresh the shared Name's swarm HEAD; must precede APP.",
644
+ "--no-refresh Override swarm.forceRefresh; must precede APP.",
166
645
  ],
167
646
  examples: [
168
647
  "ipab exec reader",
169
- "ipab exec reader --help",
170
648
  "ipab exec --log reader",
649
+ "ipab exec ipab://work/apps/hello --help",
171
650
  ],
172
651
  notes: [
173
652
  "Apps are NOT sandboxed; run only Apps you trust.",
653
+ "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
174
654
  "History stores argv by default; do not put secrets in arguments.",
175
655
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
176
656
  "--json is not supported; App stdio is passed through.",
@@ -178,90 +658,126 @@ const commandHelp = {
178
658
  },
179
659
  open: {
180
660
  summary: "Open content with its registered App",
181
- arguments: ["CONTENT Bundle CID or named pin."],
182
- options: ["--log Record stdout/stderr; requires history enabled."],
183
- examples: ["ipab open CONTENT_CID", "ipab open --log my-note"],
661
+ arguments: [
662
+ "CONTENT Bundle CID, packaged builtin reference or Swarm IPAB URI.",
663
+ ],
664
+ options: [
665
+ "--log Record stdout/stderr; requires history enabled.",
666
+ "--raw Open the Artifact node rather than its value.",
667
+ "--refresh Refresh the shared Name's swarm HEAD.",
668
+ "--no-refresh Override swarm.forceRefresh and use valid cached headers.",
669
+ ],
670
+ examples: [
671
+ "ipab open CONTENT_CID",
672
+ "ipab open --log --refresh ipab:///documents/readme",
673
+ "ipab open ipab:///",
674
+ ],
184
675
  notes: [
185
676
  "Requires a saved registration and App support for the exact content type.",
677
+ "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.",
678
+ "Uses only the content URI's Swarm, otherwise --swarm, otherwise swarm.default. A selected Swarm is required.",
679
+ "A registered App's retrieval, compatibility or execution failure never triggers fallback.",
680
+ "Legacy User registrations are inactive and preserved in the state database's legacy_user_registrations table; review them before explicit Swarm registration.",
681
+ "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
186
682
  "Apps are NOT sandboxed; run only Apps you trust.",
187
683
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
188
684
  "--json is not supported; App stdio is passed through.",
189
685
  ],
190
686
  },
191
- "pin add": {
192
- summary: "Verify, retain and name a Bundle",
687
+ pin: {
688
+ summary: "Retain an immutable CID or follow a shared Swarm Name",
193
689
  arguments: [
194
- "NAME Unused short name.",
195
- "CID Exact Bundle CID, not another pin name or a standalone type block.",
690
+ "REF Exact Bundle CID or ipab://SWARM/NAME; no local content aliases.",
691
+ ],
692
+ options: [
693
+ "--refresh / --no-refresh Refresh shared HEAD now / allow its valid cached snapshot.",
694
+ ],
695
+ examples: [
696
+ "ipab pin APP_CID",
697
+ "ipab pin ipab://work/apps/reader",
698
+ "ipab pin list",
196
699
  ],
197
- examples: ["ipab pin add reader APP_CID"],
198
700
  notes: [
199
701
  "Validates a complete Bundle and retains its full DAG in the configured Store.",
200
- "Does not execute or trust Apps, install dependencies or start a daemon.",
702
+ "A CID stays fixed. A shared Name saves its canonical configuration URL and exact Name, refreshing on related Swarm HEAD reads/sync, not continuously.",
703
+ "New content is verified and retained before the previous subscription version is released. Failures keep the last good version marked stale; deleted Names keep it marked missing.",
704
+ "Does not execute Apps or install dependencies. Shared Names connect to their Swarm content source only as needed.",
201
705
  "The builtin namespace is read-only.",
202
706
  ],
203
707
  },
204
- "pin delete": {
205
- summary: "Remove a user pin and release its retention",
206
- examples: ["ipab pin delete reader"],
708
+ unpin: {
709
+ summary: "Release a CID pin or stop following a shared Name",
710
+ examples: ["ipab unpin APP_CID", "ipab unpin ipab://work/apps/reader"],
207
711
  notes: [
208
712
  "Releases only this pin's ownership on its original backend; no block deletion or GC.",
209
- "Does not change registrations or history. Built-in pins are read-only.",
713
+ "Never re-resolves a shared Name to release content. Uses only saved actual roots. Missing pins are success.",
714
+ "Exact CID also releases archived legacy named-pin holders for that CID. Does not change shared Names, registrations or history. Built-ins are read-only.",
715
+ "Publication/history owners are independent; --snapshot payloads remain recursively retained by publication history after ordinary unpin.",
210
716
  ],
211
717
  },
212
718
  "pin list": {
213
- summary: "List user and built-in pins",
214
- options: [
215
- "--type TYPE Exact type CID or the name of a Bundle pin of that type.",
216
- ],
217
- examples: ["ipab pin list", "ipab pin list --type reader"],
719
+ summary: "List local retention, following Names and packaged built-ins",
720
+ examples: ["ipab pin list"],
218
721
  notes: [
219
- "Unfinished operations and legacy non-Bundle pins are reported separately.",
220
- "Legacy retention is preserved; use pin delete to explicitly release it.",
722
+ "Includes pending/stale/missing records and inactive archived local pin names.",
723
+ "Legacy retention is preserved; use unpin EXACT_CID to explicitly release its archived holders.",
221
724
  "Reads local registrations and packaged built-ins, not live node status.",
222
725
  ],
223
726
  },
224
727
  "pin show": {
225
- summary: "Show a pin's CID and type metadata",
226
- examples: ["ipab pin show reader", "ipab pin show builtin:template.node"],
728
+ summary: "Show saved retention and following status",
729
+ examples: ["ipab pin show APP_CID"],
227
730
  notes: [
228
731
  "Reads local metadata; built-in pins do not claim user Store retention.",
229
732
  ],
230
733
  },
231
- "pin rename": {
232
- summary: "Rename a user pin without changing its content",
233
- examples: ["ipab pin rename reader my-reader"],
734
+ "register list": {
735
+ summary: "List content-type associations in the current or selected Swarm",
736
+ options: [
737
+ "--swarm URL_OR_ALIAS Read only this Swarm registry; specify at most once.",
738
+ ],
739
+ examples: ["ipab register list", "ipab register list --swarm work"],
234
740
  notes: [
235
- "NEW_NAME must be unused. Built-in pins are read-only.",
236
- "CID, ownership, registrations and history are unchanged.",
741
+ "Without explicit --swarm, reads the saved default Swarm. Select one with --swarm or ipab swarm use.",
742
+ "Legacy User registrations are inactive and preserved in legacy_user_registrations; no automatic upload or deletion.",
237
743
  ],
238
744
  },
239
- "register list": {
240
- summary: "List saved content-type associations",
241
- examples: ["ipab register list"],
242
- },
243
745
  "register set": {
244
746
  summary: "Associate a content type with an App",
245
747
  arguments: [
246
748
  "SCHEMA Exact type CID or builtin:node-app.v1.",
247
- "APP App CID or named pin; the exact CID is saved.",
248
- "TEMPLATE App argv after --; must contain a whole argument % (default: %).",
749
+ "APP App CID or Swarm IPAB URI; the exact CID is saved.",
750
+ ],
751
+ options: [
752
+ "--replace Allow changing an existing association.",
753
+ "--swarm URL_OR_ALIAS Write this Swarm registry; repeat for multiple Swarms.",
249
754
  ],
250
- options: ["--replace Allow changing an existing association."],
251
755
  examples: [
252
- "ipab register set SCHEMA_CID reader",
253
- "ipab register set SCHEMA_CID reader '--' '--cid' '%'",
756
+ "ipab register set SCHEMA_CID APP_CID",
757
+ "ipab register set SCHEMA_CID ipab:///apps/reader --swarm work --swarm team",
254
758
  ],
255
759
  notes: [
256
- "Replaces only the whole % argument with the content CID; no shell expansion.",
760
+ "Writes the Name META.registryPath/TYPE_CID directly to the App CID. Open passes only the content CID.",
761
+ "Custom per-association argv is unsupported; adapt the App or use ipab exec APP_CID ARGS.",
257
762
  "Does not verify App type support; open checks it before execution.",
763
+ "Without explicit --swarm, writes the saved default Swarm. Swarm writes require HEAD write access.",
764
+ "Multiple Swarms commit sequentially, not atomically; failures report completed targets.",
258
765
  ],
259
766
  },
260
767
  "register remove": {
261
768
  summary: "Remove a saved content-type association",
262
769
  arguments: ["SCHEMA Exact type CID or builtin:node-app.v1."],
263
- examples: ["ipab register remove SCHEMA_CID"],
264
- notes: ["Does not remove Apps, pins or content."],
770
+ options: [
771
+ "--swarm URL_OR_ALIAS Remove from this Swarm registry; repeat for multiple Swarms.",
772
+ ],
773
+ examples: [
774
+ "ipab register remove SCHEMA_CID",
775
+ "ipab register remove SCHEMA_CID --swarm work",
776
+ ],
777
+ notes: [
778
+ "Without explicit --swarm, removes from the saved default Swarm. Multiple Swarm edits are not atomic.",
779
+ "Does not remove Apps, pins or content.",
780
+ ],
265
781
  },
266
782
  "config get": {
267
783
  summary: "Show effective configuration",
@@ -271,11 +787,15 @@ const commandHelp = {
271
787
  "config set": {
272
788
  summary: "Save a local configuration value",
273
789
  examples: [
790
+ "ipab config set pointers.apiKey -",
274
791
  "ipab config set store.gateway http://127.0.0.1:8080",
275
792
  "ipab config set history.enabled false",
276
793
  ],
277
794
  notes: [
278
795
  "store.gateway is a read-only HTTP gateway; blocks, pins and GC remain local.",
796
+ "pointers.service is a canonical HTTPS origin (HTTP loopback allowed).",
797
+ "pointers.apiKey is accepted only through stdin using VALUE '-'; queries and confirmations redact it.",
798
+ "SQLite state is account-only even without a key. Reading or saving a nonempty key rechecks Unix modes or Windows ACLs.",
279
799
  ],
280
800
  },
281
801
  "config reset": {
@@ -285,7 +805,7 @@ const commandHelp = {
285
805
  "history list": {
286
806
  summary: "List execution history",
287
807
  options: [
288
- "--app APP Filter by App CID or named pin.",
808
+ "--app APP Filter by exact App CID.",
289
809
  "--status STATUS succeeded, failed or cancelled.",
290
810
  "--since TIME Include runs ended at or after TIME.",
291
811
  "--until TIME Include runs ended before TIME.",
@@ -308,7 +828,7 @@ const commandHelp = {
308
828
  "history remove": {
309
829
  summary: "Remove execution records and their logs",
310
830
  options: [
311
- "--app APP Filter by App CID or named pin.",
831
+ "--app APP Filter by exact App CID.",
312
832
  "--status STATUS succeeded, failed or cancelled.",
313
833
  "--since TIME Include runs ended at or after TIME.",
314
834
  "--until TIME Include runs ended before TIME.",
@@ -327,7 +847,8 @@ const commandHelp = {
327
847
  };
328
848
  export function help(path = "") {
329
849
  const globalOptions = `Global options (before COMMAND):
330
- --state-dir PATH Set the local state directory
850
+ --swarm URL|ALIAS Select shared swarm (otherwise swarm.default; URI swarm takes precedence)
851
+ --state-dir PATH Set a dedicated, account-private local state directory
331
852
  --store-gateway URL Use a read-only upstream HTTP gateway
332
853
  --json Output management/development metadata, not App stdio`;
333
854
  const footer = "Full reference: https://github.com/silvermoon-work/ipab/blob/main/docs/reference.md";
@@ -341,12 +862,20 @@ Run Apps:
341
862
  open ${commandHelp.open.summary}
342
863
 
343
864
  Create:
344
- init ${commandHelp.init.summary}
865
+ templates ${groups.templates}
345
866
  build ${commandHelp.build.summary}
346
867
  bundle ${groups.bundle}
347
868
 
348
869
  Manage:
870
+ doctor ${commandHelp.doctor.summary}
871
+ profile ${commandHelp.profile.summary}
872
+ swarm ${groups.swarm}
873
+ skills ${groups.skills}
874
+ search Search formal Names in the current swarm
875
+ publish ${commandHelp.publish.summary}
876
+ get ${commandHelp.get.summary}
349
877
  pin ${groups.pin}
878
+ unpin ${commandHelp.unpin.summary}
350
879
  register ${groups.register}
351
880
  config ${groups.config}
352
881
  store ${groups.store}
@@ -366,9 +895,34 @@ ${footer}`;
366
895
  return [
367
896
  `${topic.summary}.\n\nUsage: ipab [GLOBAL_OPTIONS] ${usage}`,
368
897
  ...(topic.arguments ? [section("Arguments", topic.arguments)] : []),
369
- ...(topic.options ? [section("Options", topic.options)] : []),
898
+ ...(topic.options
899
+ ? [
900
+ section("Options", topic.options.map((line) => line.startsWith("--refresh")
901
+ ? `${line} Legacy aliases: --force/--no-force.`
902
+ : line)),
903
+ ]
904
+ : []),
370
905
  section("Examples", topic.examples),
371
- ...(topic.notes ? [section("Notes", topic.notes)] : []),
906
+ ...([
907
+ "swarm status",
908
+ "swarm members",
909
+ "swarm update",
910
+ "swarm resume",
911
+ "swarm profile",
912
+ "swarm export",
913
+ "swarm approve",
914
+ "swarm pivot grant",
915
+ "swarm exclude",
916
+ ].includes(path)
917
+ ? [
918
+ section("Notes", [
919
+ ...(topic.notes ?? []),
920
+ "Select only with global --swarm URL_OR_ALIAS (before the command), or the saved swarm.default. Neither means an error.",
921
+ ]),
922
+ ]
923
+ : topic.notes
924
+ ? [section("Notes", topic.notes)]
925
+ : []),
372
926
  `\n\n-h, --help shows this help. Global options: see 'ipab --help'.\n${footer}`,
373
927
  ].join("");
374
928
  }
@@ -393,6 +947,20 @@ function printable(text) {
393
947
  : char)
394
948
  .join("");
395
949
  }
950
+ export function formatSearchResults(matches) {
951
+ return matches.length
952
+ ? alignedRows(matches.map((match) => [
953
+ match.alias ?? match.swarm,
954
+ match.name,
955
+ match.targetCid,
956
+ ]))
957
+ .map((row, index) => {
958
+ const match = matches[index];
959
+ return `${row}\n ipab get ${formatNameReference(match.alias ?? match.swarm, match.name)}`;
960
+ })
961
+ .join("\n")
962
+ : "No matching Names.";
963
+ }
396
964
  function runTime(value, field) {
397
965
  const date = new Date(value);
398
966
  if (!Number.isFinite(date.getTime()))
@@ -432,18 +1000,17 @@ function storageBytes(bytes) {
432
1000
  ? `${exact} bytes`
433
1001
  : `${scaled.toLocaleString("en-US", { maximumFractionDigits: 2 })} ${units[unit]} (${exact} bytes)`;
434
1002
  }
435
- function table(headers, rows, empty) {
436
- if (!rows.length)
437
- return empty;
1003
+ function alignedRows(rows) {
438
1004
  const cells = rows.map((row) => row.map(printable));
439
- const widths = headers.map((header, column) => cells.reduce((width, row) => Math.max(width, stringWidth(row[column])), stringWidth(header)));
440
- return [headers, ...cells]
441
- .map((row) => row
442
- .map((cell, column) => column === headers.length - 1
1005
+ const widths = (cells[0] ?? []).map((_, column) => cells.reduce((width, row) => Math.max(width, stringWidth(row[column])), 0));
1006
+ return cells.map((row) => row
1007
+ .map((cell, column) => column === widths.length - 1
443
1008
  ? cell
444
1009
  : cell.padEnd(cell.length + widths[column] - stringWidth(cell)))
445
- .join(" "))
446
- .join("\n");
1010
+ .join(" "));
1011
+ }
1012
+ function table(headers, rows, empty) {
1013
+ return rows.length ? alignedRows([headers, ...rows]).join("\n") : empty;
447
1014
  }
448
1015
  function runDetails(record) {
449
1016
  const fields = [
@@ -474,6 +1041,12 @@ function runDetails(record) {
474
1041
  fields.push(["Retention owner", record.retention.owner]);
475
1042
  return fields.map(([key, value]) => `${key}: ${printable(value)}`).join("\n");
476
1043
  }
1044
+ function validateRefreshOptions(options) {
1045
+ const positive = ["refresh", "force"].find((key) => options[key]);
1046
+ const negative = ["no-refresh", "no-force"].find((key) => options[key]);
1047
+ if (positive && negative)
1048
+ syntax(`--${positive} and --${negative} are mutually exclusive.`);
1049
+ }
477
1050
  async function closeStore(store, appExitCode) {
478
1051
  try {
479
1052
  await store?.close();
@@ -485,6 +1058,7 @@ async function closeStore(store, appExitCode) {
485
1058
  export function parse(argv) {
486
1059
  const tokens = [...argv];
487
1060
  const flags = { json: false };
1061
+ const swarms = [];
488
1062
  while (tokens[0]?.startsWith("-")) {
489
1063
  const flag = tokens.shift();
490
1064
  if (flag === "-h" || flag === "--help")
@@ -512,12 +1086,18 @@ export function parse(argv) {
512
1086
  flags.json = true;
513
1087
  else if (flag === "--store-rpc")
514
1088
  syntax("Store RPC is no longer supported. Use --store-gateway with an HTTP gateway URL; existing Kubo pins are not migrated.");
515
- else if (flag === "--state-dir" || flag === "--store-gateway") {
1089
+ else if (flag === "--state-dir" ||
1090
+ flag === "--store-gateway" ||
1091
+ flag === "--swarm") {
516
1092
  const value = tokens.shift();
517
1093
  if (!value || value.startsWith("-"))
518
1094
  syntax(`${flag} needs a value.`);
519
1095
  if (flag === "--state-dir")
520
1096
  flags.stateDir = value;
1097
+ else if (flag === "--swarm") {
1098
+ flags.swarm = value;
1099
+ swarms.push(value);
1100
+ }
521
1101
  else {
522
1102
  flags.storeGateway = publicUrl(value);
523
1103
  }
@@ -526,6 +1106,12 @@ export function parse(argv) {
526
1106
  syntax(`Unknown global option "${flag}".`);
527
1107
  }
528
1108
  const group = tokens.shift() ?? "";
1109
+ if (group === "init")
1110
+ syntax("Root init was removed. Use ipab templates render TEMPLATE NAME [DIR]; TEMPLATE is the first positional argument, not --template.");
1111
+ if (group === "templates" && swarms.length > 1)
1112
+ syntax("Templates accepts only one global --swarm, before the command.");
1113
+ if (group === "daemon" && swarms.length)
1114
+ syntax("daemon manages all registered Swarms and does not accept --swarm.");
529
1115
  const result = {
530
1116
  flags,
531
1117
  path: group,
@@ -533,16 +1119,20 @@ export function parse(argv) {
533
1119
  options: {},
534
1120
  help: !group,
535
1121
  version: false,
1122
+ ...(group === "register" ? { registrySwarms: swarms } : {}),
536
1123
  };
537
1124
  if (!group)
538
1125
  return result;
539
1126
  if (group === "exec") {
540
1127
  if (flags.json)
541
1128
  syntax("--json is not supported for exec/open.");
542
- if (tokens[0] === "--log") {
543
- result.options.log = true;
544
- tokens.shift();
1129
+ while (["--log", "--force", "--no-force", "--refresh", "--no-refresh"].includes(tokens[0] ?? "")) {
1130
+ const option = tokens.shift().slice(2);
1131
+ if (Object.hasOwn(result.options, option))
1132
+ syntax(`Duplicate option --${option}.`);
1133
+ result.options[option] = true;
545
1134
  }
1135
+ validateRefreshOptions(result.options);
546
1136
  if (tokens[0] === "-h" || tokens[0] === "--help") {
547
1137
  result.help = true;
548
1138
  return result;
@@ -552,19 +1142,61 @@ export function parse(argv) {
552
1142
  result.positional = tokens;
553
1143
  return result;
554
1144
  }
555
- if (!["open", "init", "build"].includes(group)) {
556
- if (!["bundle", "pin", "register", "config", "history", "store"].includes(group))
557
- syntax(`Unknown command "${group}".`);
558
- if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
1145
+ if (![
1146
+ "open",
1147
+ "build",
1148
+ "publish",
1149
+ "get",
1150
+ "search",
1151
+ "doctor",
1152
+ "daemon",
1153
+ "profile",
1154
+ "unpin",
1155
+ ].includes(group)) {
1156
+ if (![
1157
+ "bundle",
1158
+ "pin",
1159
+ "register",
1160
+ "templates",
1161
+ "config",
1162
+ "history",
1163
+ "store",
1164
+ "swarm",
1165
+ "skills",
1166
+ ].includes(group))
1167
+ syntax(`Unknown command "${group}".${group === "setup" ? " Run ipab doctor to inspect, or ipab doctor --fix to prepare this device." : " Run ipab --help."}`);
1168
+ if (group === "pin" && !["list", "show"].includes(tokens[0] ?? "")) {
1169
+ if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
1170
+ result.help = true;
1171
+ return result;
1172
+ }
1173
+ }
1174
+ else if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
559
1175
  result.help = true;
560
1176
  return result;
561
1177
  }
562
- result.path = `${group} ${tokens.shift()}`;
1178
+ else
1179
+ result.path = `${group} ${tokens.shift()}`;
1180
+ if (result.path === "swarm pivot") {
1181
+ if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
1182
+ result.help = true;
1183
+ return result;
1184
+ }
1185
+ result.path = `swarm pivot ${tokens.shift()}`;
1186
+ }
563
1187
  }
564
1188
  else if (group === "open" && flags.json)
565
1189
  syntax("--json is not supported for exec/open.");
1190
+ else if (group === "daemon" && tokens[0] === "ui") {
1191
+ tokens.shift();
1192
+ result.path = "daemon ui";
1193
+ }
1194
+ if (result.path === "swarm add")
1195
+ syntax("swarm add was removed. Use ipab swarm set ALIAS CONFIG_URL for local naming, then ipab swarm request ALIAS to request membership.");
566
1196
  if (!commands[result.path])
567
1197
  syntax(`Unknown command "${result.path}".`);
1198
+ if (group === "skills" && swarms.length > 1)
1199
+ syntax("Skills operations select exactly one Swarm; repeated --swarm is not supported.");
568
1200
  const separator = result.path === "register set" ? tokens.indexOf("--") : -1;
569
1201
  if (separator >= 0)
570
1202
  result.template = tokens.splice(separator + 1);
@@ -574,70 +1206,208 @@ export function parse(argv) {
574
1206
  result.help = true;
575
1207
  return result;
576
1208
  }
577
- const booleans = result.path === "bundle build"
578
- ? ["replace", "schema-only", "no-import"]
579
- : result.path === "build"
580
- ? ["replace", "no-import", "with-source", "without-source"]
581
- : result.path === "register set"
582
- ? ["replace"]
583
- : result.path === "history remove"
584
- ? ["yes"]
585
- : result.path === "open"
586
- ? ["log"]
587
- : [];
588
- const values = result.path === "init"
589
- ? ["template"]
590
- : result.path === "bundle build" || result.path === "build"
1209
+ if (result.path === "config set" &&
1210
+ tokens.includes("pointers.apiKey") &&
1211
+ !(tokens.length === 2 && tokens[1] === "-"))
1212
+ syntax("API key must be provided through '-' and piped stdin; never pass it in command arguments.");
1213
+ const booleans = result.path.startsWith("skills ")
1214
+ ? result.path === "skills sync"
1215
+ ? ["dry-run", "yes", "override-existing", "force", "no-force"]
1216
+ : ["force", "no-force"]
1217
+ : result.path === "doctor"
1218
+ ? ["fix", "yes"]
1219
+ : result.path === "bundle build"
1220
+ ? ["replace", "schema-only", "no-import"]
1221
+ : result.path === "build"
1222
+ ? ["replace", "no-import"]
1223
+ : result.path === "publish"
1224
+ ? ["snapshot"]
1225
+ : [
1226
+ "get",
1227
+ "templates render",
1228
+ "templates list",
1229
+ "templates show",
1230
+ ].includes(result.path)
1231
+ ? result.path === "templates render"
1232
+ ? ["force", "no-force"]
1233
+ : result.path === "get"
1234
+ ? ["raw", "force", "no-force"]
1235
+ : ["force", "no-force"]
1236
+ : result.path === "search"
1237
+ ? ["all", "current", "force", "no-force"]
1238
+ : result.path === "swarm request"
1239
+ ? ["pivot"]
1240
+ : result.path === "swarm approve"
1241
+ ? ["yes", "again", "pivot"]
1242
+ : ["swarm status", "swarm members"].includes(result.path)
1243
+ ? ["local", "force", "no-force"]
1244
+ : [
1245
+ "swarm exclude",
1246
+ "swarm set",
1247
+ "swarm pivot grant",
1248
+ ].includes(result.path)
1249
+ ? ["yes"]
1250
+ : result.path === "register set"
1251
+ ? ["replace"]
1252
+ : result.path === "history remove"
1253
+ ? ["yes"]
1254
+ : result.path === "open"
1255
+ ? ["log", "raw", "force", "no-force"]
1256
+ : result.path === "pin"
1257
+ ? ["force", "no-force"]
1258
+ : result.path === "daemon ui"
1259
+ ? ["open"]
1260
+ : [];
1261
+ if (booleans.includes("force"))
1262
+ booleans.push("refresh", "no-refresh");
1263
+ const values = result.path === "swarm create"
1264
+ ? ["service", "resume", "name", "description", "alias"]
1265
+ : result.path === "swarm request"
591
1266
  ? ["output"]
592
- : result.path === "history list"
593
- ? ["app", "status", "since", "until", "limit", "before"]
594
- : result.path === "history remove"
595
- ? ["app", "status", "since", "until"]
596
- : result.path === "pin list"
597
- ? ["type"]
598
- : [];
1267
+ : result.path === "swarm export"
1268
+ ? ["output"]
1269
+ : result.path === "swarm profile"
1270
+ ? ["address", "pivot"]
1271
+ : result.path === "swarm update" || result.path === "profile"
1272
+ ? ["name", "description"]
1273
+ : result.path === "swarm approve"
1274
+ ? []
1275
+ : ["publish", "templates set", "templates remove"].includes(result.path)
1276
+ ? ["expect"]
1277
+ : result.path === "get"
1278
+ ? ["output"]
1279
+ : result.path === "search"
1280
+ ? ["prefix", "kind", "schema", "limit", "offset"]
1281
+ : result.path === "templates render"
1282
+ ? ["description"]
1283
+ : result.path === "bundle build" ||
1284
+ result.path === "build"
1285
+ ? ["output"]
1286
+ : result.path === "history list"
1287
+ ? [
1288
+ "app",
1289
+ "status",
1290
+ "since",
1291
+ "until",
1292
+ "limit",
1293
+ "before",
1294
+ ]
1295
+ : result.path === "history remove"
1296
+ ? ["app", "status", "since", "until"]
1297
+ : [];
599
1298
  while (tokens.length) {
600
1299
  const value = tokens.shift();
601
- if (value.startsWith("--") || value === "-o") {
1300
+ if (result.path === "swarm exclude" &&
1301
+ /^--[A-Za-z0-9_-]{41}$/.test(value)) {
1302
+ result.positional.push(value);
1303
+ }
1304
+ else if (value.startsWith("--") || value === "-o") {
602
1305
  const option = value === "-o" ? "output" : value.slice(2);
603
- if (result.path === "init" && option === "param") {
1306
+ if (result.path.startsWith("daemon") && option === "swarm")
1307
+ syntax("daemon manages all registered Swarms and does not accept --swarm.");
1308
+ if (result.path === "skills sync" && option === "agent") {
1309
+ const input = tokens.shift();
1310
+ if (!input || input.startsWith("-"))
1311
+ syntax("--agent needs a value.");
1312
+ (result.agents ??= []).push(input);
1313
+ continue;
1314
+ }
1315
+ if (result.path.startsWith("register ") && option === "swarm") {
1316
+ const input = tokens.shift();
1317
+ if (!input || input.startsWith("-"))
1318
+ syntax("--swarm needs a value.");
1319
+ result.registrySwarms.push(input);
1320
+ flags.swarm = input;
1321
+ continue;
1322
+ }
1323
+ if (result.path === "templates render" && option === "template")
1324
+ syntax("--template was removed. Use ipab templates render TEMPLATE NAME [DIR], with TEMPLATE first.");
1325
+ if (result.path === "templates render" && option === "param") {
604
1326
  const input = tokens.shift();
605
1327
  if (!input || input.startsWith("--") || input.indexOf("=") < 1)
606
1328
  syntax("--param requires KEY=VALUE.");
607
1329
  (result.parameters ??= []).push(input);
608
1330
  continue;
609
1331
  }
1332
+ if (result.path === "swarm request" && option === "alias")
1333
+ syntax("swarm request --alias was removed. First run ipab swarm set ALIAS CONFIG_URL, then ipab swarm request ALIAS.");
610
1334
  if (Object.hasOwn(result.options, option))
611
1335
  syntax(`Duplicate option ${value}.`);
612
1336
  if (booleans.includes(option))
613
1337
  result.options[option] = true;
614
1338
  else if (values.includes(option)) {
615
1339
  const input = tokens.shift();
616
- if (!input || input.startsWith("--"))
1340
+ if (input === undefined ||
1341
+ (input.startsWith("--") &&
1342
+ !(option === "resume" && /^[A-Za-z0-9_-]{43}$/.test(input))) ||
1343
+ (input === "" &&
1344
+ !["swarm update", "profile", "templates render"].includes(result.path)))
617
1345
  syntax(`${value} needs a value.`);
618
1346
  result.options[option] = input;
619
1347
  }
1348
+ else if (option === "name" &&
1349
+ ["swarm profile", "swarm request"].includes(result.path))
1350
+ syntax(`Personal names are account-wide. Use ipab profile --name NAME instead.${result.path === "swarm profile" ? " For network configuration, use ipab --swarm URL_OR_ALIAS swarm profile --address MULTIADDR." : ""}`);
620
1351
  else
621
1352
  syntax(`Unknown option "${value}".`);
622
1353
  }
623
1354
  else
624
1355
  result.positional.push(value);
625
1356
  }
1357
+ validateRefreshOptions(result.options);
1358
+ if (result.path === "search" &&
1359
+ result.options.current &&
1360
+ flags.swarm !== undefined)
1361
+ syntax("--current and --swarm are mutually exclusive.");
1362
+ if (result.path === "search" &&
1363
+ result.options.all &&
1364
+ (result.options.current || flags.swarm !== undefined))
1365
+ syntax("--all is mutually exclusive with --current and --swarm.");
1366
+ if (result.path === "register list" &&
1367
+ (result.registrySwarms?.length ?? 0) > 1)
1368
+ syntax("register list accepts --swarm at most once. Select one Swarm or omit it to use the current Swarm.");
626
1369
  const counts = {
627
- init: [1, 2],
1370
+ daemon: [0, 0],
1371
+ "daemon ui": [0, 0],
1372
+ doctor: [0, 0],
1373
+ "skills list": [0, 0],
1374
+ "skills sync": [0, Number.MAX_SAFE_INTEGER],
1375
+ profile: [0, 0],
1376
+ "swarm create": [0, 0],
1377
+ "swarm request": [1, 1],
1378
+ "swarm approve": [1, 1],
1379
+ "swarm pivot grant": [1, 1],
1380
+ "swarm export": [0, 0],
1381
+ "swarm exclude": [1, 1],
1382
+ "swarm resume": [0, 0],
1383
+ "swarm profile": [0, 0],
1384
+ "swarm status": [0, 0],
1385
+ "swarm members": [0, 0],
1386
+ "swarm list": [0, 0],
1387
+ "swarm set": [2, 2],
1388
+ "swarm use": [1, 1],
1389
+ "swarm remove": [1, 1],
1390
+ "swarm update": [0, 0],
1391
+ publish: [2, 2],
1392
+ get: [1, 1],
1393
+ search: [1, 1],
1394
+ "templates render": [2, 3],
628
1395
  build: [0, 1],
629
1396
  "bundle build": [1, 1],
630
1397
  "bundle inspect": [1, 1],
631
1398
  "bundle import": [1, 1],
632
1399
  open: [1, 1],
633
- "pin add": [2, 2],
634
- "pin delete": [1, 1],
1400
+ pin: [1, 1],
1401
+ unpin: [1, 1],
635
1402
  "pin list": [0, 0],
636
1403
  "pin show": [1, 1],
637
- "pin rename": [2, 2],
638
1404
  "register list": [0, 0],
639
1405
  "register set": [2, 2],
640
1406
  "register remove": [1, 1],
1407
+ "templates list": [0, 0],
1408
+ "templates show": [1, 1],
1409
+ "templates set": [2, 2],
1410
+ "templates remove": [1, 1],
641
1411
  "config get": [0, 1],
642
1412
  "config set": [2, 2],
643
1413
  "config reset": [1, 1],
@@ -650,11 +1420,22 @@ export function parse(argv) {
650
1420
  if (result.options["with-source"] && result.options["without-source"])
651
1421
  syntax("--with-source and --without-source are mutually exclusive.");
652
1422
  const [minimum, maximum] = counts[result.path];
1423
+ if (result.path === "profile" && flags.swarm !== undefined)
1424
+ syntax("Personal profile is account-wide; do not pass --swarm.");
1425
+ if (result.positional.length &&
1426
+ [
1427
+ "swarm status",
1428
+ "swarm update",
1429
+ "swarm resume",
1430
+ "swarm profile",
1431
+ "swarm export",
1432
+ "swarm members",
1433
+ ].includes(result.path))
1434
+ syntax(`Swarm target positionals are no longer supported. Use ipab --swarm URL_OR_ALIAS ${result.path} instead.`);
653
1435
  if (result.positional.length < minimum || result.positional.length > maximum)
654
1436
  syntax(`Invalid arguments.\n${help(result.path)}`);
655
- if (result.template &&
656
- (!result.template.length || !result.template.includes("%")))
657
- syntax('Argument template must contain a whole "%" token.');
1437
+ if (result.template)
1438
+ syntax('Custom per-association argv is unsupported. Remove "-- TEMPLATE..."; open passes only the content CID. Adapt the App or use ipab exec APP_CID ARGS.');
658
1439
  if (result.path === "history remove") {
659
1440
  const selected = values.some((value) => Object.hasOwn(result.options, value));
660
1441
  if ((!selected && !result.positional.length) ||
@@ -662,30 +1443,56 @@ export function parse(argv) {
662
1443
  syntax("history remove requires explicit IDs OR filters, not both.");
663
1444
  }
664
1445
  // Validate syntactic values before state access, let alone a backend connection.
665
- if (result.path.startsWith("pin ") && result.path !== "pin list") {
666
- pinName(result.positional[0], result.path === "pin show");
667
- if (result.path === "pin add")
668
- exactCid(result.positional[1]);
669
- if (result.path === "pin rename")
670
- pinName(result.positional[1]);
1446
+ if (["pin", "unpin", "pin show"].includes(result.path)) {
1447
+ const reference = result.positional[0];
1448
+ if (reference.startsWith("builtin:") && result.path !== "pin show")
1449
+ syntax("Packaged builtin references are read-only; they cannot be pinned or unpinned.");
1450
+ if (!(result.path === "pin show" && reference.startsWith("builtin:")) &&
1451
+ !parseNameReference(reference))
1452
+ exactCid(reference);
1453
+ }
1454
+ if (result.path === "publish") {
1455
+ formalName(result.positional[0]);
1456
+ if (typeof result.options.expect === "string")
1457
+ exactCid(result.options.expect);
1458
+ if (result.options.expect && result.options.snapshot)
1459
+ syntax("--snapshot is initial-only and cannot be combined with --expect.");
1460
+ }
1461
+ if (result.path.startsWith("templates ") &&
1462
+ result.path !== "templates render") {
1463
+ if (result.positional[0] !== undefined)
1464
+ templateName(result.positional[0]);
1465
+ if (typeof result.options.expect === "string")
1466
+ exactCid(result.options.expect);
1467
+ if (result.path === "templates remove" && !result.options.expect)
1468
+ syntax("templates remove requires --expect OLD_TARGET_CID.");
671
1469
  }
672
1470
  if (result.path.startsWith("config ") && result.positional[0]) {
673
1471
  if (!(result.path === "config get" && result.positional[0] === "state-dir") &&
674
1472
  !(result.path === "config reset" && result.positional[0] === "store.rpc"))
675
1473
  configKey(result.positional[0]);
676
- if (result.path === "config set")
677
- parseValue(configKey(result.positional[0]), result.positional[1], true);
1474
+ if (result.path === "config set") {
1475
+ if (result.positional[0] === "pointers.apiKey") {
1476
+ if (result.positional[1] !== "-")
1477
+ syntax("Set pointers.apiKey using '-' and piped stdin; never put the key in command-line arguments.");
1478
+ }
1479
+ else
1480
+ parseValue(configKey(result.positional[0]), result.positional[1], true);
1481
+ }
678
1482
  }
679
1483
  if (typeof result.options.limit === "string")
680
1484
  parseValue("history.limit", result.options.limit, true);
681
1485
  if (result.options.output === "-")
682
1486
  syntax("CAR output requires a file path; binary stdout is not supported.");
1487
+ if (result.path === "doctor" && result.options.yes && !result.options.fix)
1488
+ syntax("doctor --yes requires --fix.");
683
1489
  return result;
684
1490
  }
685
1491
  async function performCli(argv, io, env) {
686
1492
  let state;
687
1493
  let store;
688
1494
  let appExitCode;
1495
+ let readContext;
689
1496
  try {
690
1497
  const parsed = parse(argv);
691
1498
  if (parsed.help) {
@@ -701,8 +1508,52 @@ async function performCli(argv, io, env) {
701
1508
  }
702
1509
  if (parsed.path === "history remove" && !parsed.options.yes && !io.tty)
703
1510
  syntax("Non-interactive history remove requires --yes.");
1511
+ if (parsed.path === "doctor") {
1512
+ const controller = new AbortController();
1513
+ const interrupt = () => {
1514
+ controller.abort(new HostError("Doctor interrupted.", 130, "ABORTED"));
1515
+ };
1516
+ const terminate = () => {
1517
+ controller.abort(new HostError("Doctor terminated.", 143, "ABORTED"));
1518
+ };
1519
+ process.once("SIGINT", interrupt);
1520
+ process.once("SIGTERM", terminate);
1521
+ try {
1522
+ const result = await doctorDevice(stateLocation(parsed.flags, env).path, env, {
1523
+ diagnostic: (text, progress) => {
1524
+ io.err(text, progress);
1525
+ },
1526
+ signal: controller.signal,
1527
+ fix: Boolean(parsed.options.fix),
1528
+ yes: Boolean(parsed.options.yes),
1529
+ tty: io.tty,
1530
+ confirm: (text, signal) => io.confirm(text, signal),
1531
+ });
1532
+ io.out(parsed.flags.json ? JSON.stringify(result) : doctorText(result));
1533
+ return result.ready ? 0 : 1;
1534
+ }
1535
+ finally {
1536
+ process.removeListener("SIGINT", interrupt);
1537
+ process.removeListener("SIGTERM", terminate);
1538
+ }
1539
+ }
1540
+ if (parsed.path === "daemon ui") {
1541
+ const stateDir = stateLocation(parsed.flags, env).path;
1542
+ const endpoint = await daemonEndpoint(stateDir);
1543
+ if (!endpoint)
1544
+ throw new HostError("IPAB daemon is not running for this state directory. Start it with `ipab daemon` or run a Swarm network command.");
1545
+ const opened = Boolean(parsed.options.open);
1546
+ if (opened)
1547
+ openLoopbackUrl(endpoint.url);
1548
+ io.out(parsed.flags.json
1549
+ ? JSON.stringify({ ...endpoint, opened })
1550
+ : opened
1551
+ ? `Opened daemon status UI: ${endpoint.url}`
1552
+ : endpoint.url);
1553
+ return 0;
1554
+ }
704
1555
  const builtins = await builtinContent();
705
- state = new State(stateLocation(parsed.flags, env).path, builtins.pins);
1556
+ state = new State(stateLocation(parsed.flags, env).path, builtins.pins, env);
706
1557
  if (parsed.path === "config reset" &&
707
1558
  parsed.positional[0] === "store.rpc") {
708
1559
  state.resetConfig("store.rpc");
@@ -711,16 +1562,733 @@ async function performCli(argv, io, env) {
711
1562
  : "Removed legacy store.rpc configuration. Existing Kubo pins and content are unchanged.");
712
1563
  return 0;
713
1564
  }
714
- const items = effectiveConfig(state.config(), parsed.flags, env);
1565
+ const items = effectiveConfig(state.config({
1566
+ includeSecrets: ![
1567
+ "swarm members",
1568
+ "profile",
1569
+ "swarm status",
1570
+ "swarm set",
1571
+ ].includes(parsed.path),
1572
+ }), parsed.flags, env, (reference) => state.resolveSwarm(reference));
715
1573
  const value = (key) => items.find((item) => item.key === key).value;
716
1574
  const emit = (result, human) => {
717
1575
  io.out(parsed.flags.json ? JSON.stringify(result) : human);
718
1576
  };
719
1577
  const [first, second] = parsed.positional;
1578
+ const selectedSwarm = value("swarm.default") === null
1579
+ ? undefined
1580
+ : String(value("swarm.default"));
1581
+ const requireSwarm = () => {
1582
+ if (!selectedSwarm)
1583
+ syntax("Select a Swarm with ipab --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.");
1584
+ return selectedSwarm;
1585
+ };
1586
+ const swarmContext = () => ({
1587
+ get store() {
1588
+ return store;
1589
+ },
1590
+ set store(next) {
1591
+ store = next;
1592
+ },
1593
+ state: state,
1594
+ env,
1595
+ stateDir: stateLocation(parsed.flags, env).path,
1596
+ cacheTtl: Number(value("swarm.cacheTtl")),
1597
+ syncInterval: Number(value("swarm.syncInterval")),
1598
+ listen: value("swarm.listen") === "loopback" ? "loopback" : "lan",
1599
+ ...(items.find((item) => item.key === "swarm.pivot").source === "default"
1600
+ ? {}
1601
+ : { pivot: Boolean(value("swarm.pivot")) }),
1602
+ ...(parsed.path === "daemon"
1603
+ ? {
1604
+ daemonReady: (status, onListen) => serveDaemon(stateLocation(parsed.flags, env).path, {
1605
+ port: Number(value("daemon.uiPort")),
1606
+ ...(status ? { status } : {}),
1607
+ ...(onListen ? { onListen } : {}),
1608
+ }),
1609
+ }
1610
+ : {
1611
+ ensureDaemon: () => ensureDaemon(stateLocation(parsed.flags, env).path, env, (text) => {
1612
+ io.err(text);
1613
+ }),
1614
+ }),
1615
+ forceRefresh: parsed.options.refresh || parsed.options.force
1616
+ ? true
1617
+ : parsed.options["no-refresh"] || parsed.options["no-force"]
1618
+ ? false
1619
+ : Boolean(value("swarm.forceRefresh")),
1620
+ diagnostic: (text) => {
1621
+ io.err(text);
1622
+ },
1623
+ ...(typeof value("pointers.service") === "string"
1624
+ ? { pointerService: String(value("pointers.service")) }
1625
+ : {}),
1626
+ ...(typeof value("pointers.apiKey") === "string"
1627
+ ? { pointerApiKey: String(value("pointers.apiKey")) }
1628
+ : {}),
1629
+ });
720
1630
  const filter = parsed.path.startsWith("history ")
721
1631
  ? filters(state, parsed.options)
722
1632
  : {};
1633
+ const selection = () => {
1634
+ const saved = state.config({ includeSecrets: false });
1635
+ const current = effectiveConfig(saved, parsed.flags, env, (reference) => state.resolveSwarm(reference)).find((item) => item.key === "swarm.default");
1636
+ return {
1637
+ savedCurrent: saved["swarm.default"] ?? null,
1638
+ effectiveCurrent: current.value,
1639
+ source: current.source,
1640
+ };
1641
+ };
1642
+ if (parsed.path === "open" || parsed.path.startsWith("register ")) {
1643
+ if (state.legacyRegistrationCount)
1644
+ 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.`);
1645
+ }
1646
+ if (state.legacyPinCount)
1647
+ 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.`);
1648
+ if (parsed.path.startsWith("templates ") &&
1649
+ parsed.path !== "templates render") {
1650
+ const configUrl = requireSwarm();
1651
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1652
+ const context = swarmContext();
1653
+ const expected = typeof parsed.options.expect === "string"
1654
+ ? parsed.options.expect
1655
+ : undefined;
1656
+ try {
1657
+ if (parsed.path === "templates list") {
1658
+ const items = await swarmTemplates(context, configUrl);
1659
+ const alias = state
1660
+ .swarms()
1661
+ .find((swarm) => swarm.cid === configUrl)?.alias;
1662
+ 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) => [
1663
+ item.selector,
1664
+ item.title,
1665
+ item.targetCid,
1666
+ item.templateCid,
1667
+ ]), "No templates registered in this Swarm.\nAdd a template: ipab templates set NAME SOURCE")}`);
1668
+ }
1669
+ else if (parsed.path === "templates show") {
1670
+ const item = (await swarmTemplates(context, configUrl, first))[0];
1671
+ if (parsed.flags.json)
1672
+ io.out(JSON.stringify(item));
1673
+ else {
1674
+ const alias = state
1675
+ .swarms()
1676
+ .find((swarm) => swarm.cid === configUrl)?.alias;
1677
+ const swarm = alias ?? configUrl;
1678
+ const reference = formatNameReference(swarm, item.name);
1679
+ const tree = await templateOutputTree(context.store, item.templateCid);
1680
+ const shell = process.platform === "win32" ? "powershell" : "posix";
1681
+ io.out([
1682
+ `${printable(item.selector)} — ${printable(item.title)}`,
1683
+ printable(item.description) || "(No description.)",
1684
+ "",
1685
+ "Location",
1686
+ ` Swarm: ${printable(swarm)}`,
1687
+ ` Name: ${printable(item.name)}`,
1688
+ "",
1689
+ `Create a project (${shell === "powershell" ? "PowerShell" : "POSIX shell"})`,
1690
+ ` ${templateRenderExample(reference, swarm, item.definition, shell)}`,
1691
+ " Replace example parameter values as needed. No code is run by show.",
1692
+ "",
1693
+ "Parameters",
1694
+ table(["NAME", "TYPE", "REQUIRED", "DEFAULT", "INPUT"], templateParameterRows(item.definition), "No parameters declared."),
1695
+ "Required means an input is needed when no default is declared.",
1696
+ "",
1697
+ "Output files (from project/)",
1698
+ " my-project/",
1699
+ ...tree.entries.map((entry) => `${" ".repeat(entry.path.split("/").length + 1)}${printable(entry.path.split("/").at(-1))}${entry.kind === "directory" ? "/" : ""}`),
1700
+ ...(tree.truncated
1701
+ ? [
1702
+ ` ... truncated: ${tree.truncated}; more files may exist.`,
1703
+ ]
1704
+ : tree.entries.length
1705
+ ? []
1706
+ : [" (no output files)"]),
1707
+ "",
1708
+ "Versions",
1709
+ ` Template CID: ${item.templateCid}`,
1710
+ ` Reference: ${reference}`,
1711
+ ...(item.targetCid !== item.templateCid
1712
+ ? [` Target CID (--expect): ${item.targetCid}`]
1713
+ : []),
1714
+ ].join("\n"));
1715
+ }
1716
+ }
1717
+ else if (parsed.path === "templates set") {
1718
+ const item = await setSwarmTemplate(context, configUrl, first, second, expected);
1719
+ emit(item, `${item.reference} → ${item.targetCid} (Template ${item.templateCid})`);
1720
+ }
1721
+ else {
1722
+ const item = await removeSwarmTemplate(context, configUrl, first, expected);
1723
+ emit({ removed: item }, `Removed ${item.reference}; content and history are retained.`);
1724
+ }
1725
+ }
1726
+ finally {
1727
+ await context.finishRead?.();
1728
+ }
1729
+ return 0;
1730
+ }
1731
+ if (parsed.path.startsWith("register ")) {
1732
+ const references = parsed.registrySwarms?.length
1733
+ ? parsed.registrySwarms
1734
+ : selectedSwarm
1735
+ ? [selectedSwarm]
1736
+ : [];
1737
+ if (!references.length)
1738
+ throw new HostError("Register requires a selected Swarm. Pass --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.");
1739
+ const targets = [
1740
+ ...new Set(references.map((reference) => state.resolveSwarm(reference))),
1741
+ ];
1742
+ const schema = first
1743
+ ? state.resolve(schemaAlias(first), true)
1744
+ : undefined;
1745
+ const results = [];
1746
+ const completed = [];
1747
+ const human = [];
1748
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1749
+ for (const configUrl of targets) {
1750
+ const context = swarmContext();
1751
+ try {
1752
+ if (parsed.path === "register list") {
1753
+ const items = await swarmRegistrations(context, configUrl);
1754
+ const alias = state
1755
+ .swarms()
1756
+ .find((swarm) => swarm.cid === configUrl)?.alias;
1757
+ results.push({ items });
1758
+ 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")}`);
1759
+ }
1760
+ else if (parsed.path === "register set") {
1761
+ const appCid = parseNameReference(second)
1762
+ ? (await resolveReference(context, second, configUrl, (reference) => state.resolve(reference))).cid
1763
+ : state.resolve(second);
1764
+ const association = await setSwarmAssociation(context, configUrl, createAssociation(schema, appCid, parsed.template ?? ["%"]), Boolean(parsed.options.replace));
1765
+ results.push({ association });
1766
+ human.push(`${configUrl}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`);
1767
+ }
1768
+ else {
1769
+ const removed = await removeSwarmAssociation(context, configUrl, schema);
1770
+ results.push({ removed: [removed] });
1771
+ human.push(`${configUrl}: removed association for ${removed}.`);
1772
+ }
1773
+ completed.push(configUrl);
1774
+ }
1775
+ catch (cause) {
1776
+ throw new HostError(parsed.path === "register list"
1777
+ ? `Cannot list associations for Swarm ${configUrl}: ${message(cause)}`
1778
+ : `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");
1779
+ }
1780
+ finally {
1781
+ await context.finishRead?.();
1782
+ }
1783
+ }
1784
+ emit({
1785
+ swarms: results.map((result, index) => ({
1786
+ configUrl: targets[index],
1787
+ ...result,
1788
+ })),
1789
+ }, human.join("\n\n"));
1790
+ return 0;
1791
+ }
723
1792
  switch (parsed.path) {
1793
+ case "profile": {
1794
+ const context = swarmContext();
1795
+ readContext = context;
1796
+ const changes = {
1797
+ ...(typeof parsed.options.name === "string"
1798
+ ? { name: parsed.options.name }
1799
+ : {}),
1800
+ ...(typeof parsed.options.description === "string"
1801
+ ? { description: parsed.options.description }
1802
+ : {}),
1803
+ };
1804
+ if (!Object.keys(changes).length) {
1805
+ const profile = await accountProfile(context);
1806
+ emit({ profile, localPersisted: profile.updatedAt !== null }, `Name: ${printable(profile.name)}\nDescription: ${printable(profile.description)}\nPublic key: ${profile.publicKey}`);
1807
+ }
1808
+ else {
1809
+ const result = await updateAccountProfile(context, changes);
1810
+ emit(result, [
1811
+ `Name: ${printable(result.profile.name)}`,
1812
+ `Description: ${printable(result.profile.description)}`,
1813
+ "Personal profile saved locally.",
1814
+ ...result.swarms.map((entry) => `${entry.configUrl}: ${entry.synchronized ? "synchronized" : `FAILED: ${entry.error}`}`),
1815
+ ].join("\n"));
1816
+ if (result.swarms.some((entry) => !entry.synchronized)) {
1817
+ io.err("Profile saved locally, but some Swarms failed. Retry the profile update or normally activate each failed membership to synchronize it.");
1818
+ return 1;
1819
+ }
1820
+ }
1821
+ break;
1822
+ }
1823
+ case "swarm list": {
1824
+ const result = { swarms: state.swarms(), ...selection() };
1825
+ emit({
1826
+ ...result,
1827
+ swarms: result.swarms.map((entry) => ({
1828
+ configUrl: entry.cid,
1829
+ alias: entry.alias,
1830
+ })),
1831
+ }, [
1832
+ ...alignedRows(result.swarms.map((entry) => [
1833
+ `${entry.cid === result.effectiveCurrent ? "*" : " "} ${entry.alias ?? entry.cid}`,
1834
+ entry.cid,
1835
+ ])),
1836
+ ...(result.swarms.length ? [] : ["No registered Swarms."]),
1837
+ ...(result.effectiveCurrent === null
1838
+ ? ["Use ipab swarm use <alias> to select a default Swarm."]
1839
+ : []),
1840
+ ...(result.effectiveCurrent !== result.savedCurrent
1841
+ ? [
1842
+ `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)"))}.`,
1843
+ ]
1844
+ : []),
1845
+ ].join("\n"));
1846
+ break;
1847
+ }
1848
+ case "swarm use": {
1849
+ state.useSwarm(first);
1850
+ const result = selection();
1851
+ emit(result, `Saved current swarm: ${result.savedCurrent}`);
1852
+ if (result.source === "flag" || result.source === "env")
1853
+ io.err(`The saved default is overridden by ${result.source}: ${result.effectiveCurrent}.`);
1854
+ break;
1855
+ }
1856
+ case "swarm remove": {
1857
+ const removed = state.removeSwarm(first);
1858
+ emit({
1859
+ removed,
1860
+ savedCurrent: state.config({ includeSecrets: false })["swarm.default"] ?? null,
1861
+ }, `Removed registration ${removed}. Credentials, content and remote membership are unchanged.`);
1862
+ break;
1863
+ }
1864
+ case "swarm set": {
1865
+ swarmAlias(first);
1866
+ const cid = swarmUrl(second);
1867
+ const previous = state.swarms().find((entry) => entry.alias === first);
1868
+ if (previous && previous.cid !== cid) {
1869
+ io.err(`Swarm alias ${first}: ${previous.cid} -> ${cid}`);
1870
+ if (!parsed.options.yes &&
1871
+ (!io.tty ||
1872
+ !(await io.confirm(`Retarget local Swarm alias "${first}" from ${previous.cid} to ${cid}?`))))
1873
+ throw new HostError("Alias unchanged. Retargeting requires --yes or interactive confirmation.");
1874
+ }
1875
+ const entry = state.setSwarm(first, cid, previous?.cid ?? null);
1876
+ emit({
1877
+ configUrl: entry.cid,
1878
+ alias: entry.alias,
1879
+ savedCurrent: state.config({ includeSecrets: false })["swarm.default"] ?? null,
1880
+ }, `Set local swarm alias ${entry.alias} (${cid}).`);
1881
+ break;
1882
+ }
1883
+ case "daemon": {
1884
+ if (parsed.flags.json)
1885
+ syntax("--json is not supported for daemon; diagnostics are written to stderr.");
1886
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1887
+ const controller = new AbortController();
1888
+ const interrupt = () => {
1889
+ controller.abort();
1890
+ };
1891
+ process.once("SIGINT", interrupt);
1892
+ process.once("SIGTERM", interrupt);
1893
+ try {
1894
+ await swarmDaemon(swarmContext(), controller.signal, (ctx, url, report) => syncDaemonSwarm(ctx, url, undefined, report));
1895
+ }
1896
+ catch (cause) {
1897
+ if (!controller.signal.aborted)
1898
+ throw cause;
1899
+ }
1900
+ finally {
1901
+ process.removeListener("SIGINT", interrupt);
1902
+ process.removeListener("SIGTERM", interrupt);
1903
+ }
1904
+ break;
1905
+ }
1906
+ case "swarm update":
1907
+ case "search":
1908
+ case "skills list":
1909
+ case "skills sync":
1910
+ case "swarm create":
1911
+ case "swarm request":
1912
+ case "swarm approve":
1913
+ case "swarm pivot grant":
1914
+ case "swarm export":
1915
+ case "swarm exclude":
1916
+ case "swarm resume":
1917
+ case "swarm profile":
1918
+ case "swarm members":
1919
+ case "swarm status":
1920
+ case "publish":
1921
+ case "pin":
1922
+ case "get": {
1923
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1924
+ const context = swarmContext();
1925
+ readContext = context;
1926
+ if (parsed.path.startsWith("skills ")) {
1927
+ const result = await manageSkills(context, requireSwarm(), {
1928
+ sync: parsed.path === "skills sync",
1929
+ names: parsed.positional,
1930
+ agents: parsed.agents ?? [],
1931
+ overrideExisting: Boolean(parsed.options["override-existing"]),
1932
+ dryRun: Boolean(parsed.options["dry-run"]),
1933
+ yes: Boolean(parsed.options.yes),
1934
+ tty: io.tty,
1935
+ confirm: (text) => io.confirm(text),
1936
+ preview: (text) => {
1937
+ io.err(text);
1938
+ },
1939
+ });
1940
+ store = context.store;
1941
+ emit(result, [
1942
+ table(["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"], result.items.map((skill) => [
1943
+ skill.name,
1944
+ skill.cid,
1945
+ skill.identity,
1946
+ skill.status,
1947
+ ]), "No Skills."),
1948
+ ...result.items.flatMap((skill) => skill.problems),
1949
+ ...result.orphaned.map((skill) => `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`),
1950
+ ...result.results.map((entry) => `${entry.name} / ${entry.agent}: ${entry.status}${entry.error ? `: ${entry.error}` : ""}`),
1951
+ ].join("\n"));
1952
+ if (!result.ok)
1953
+ return 1;
1954
+ break;
1955
+ }
1956
+ if (parsed.path === "pin") {
1957
+ io.err("Fetching, verifying and retaining content...");
1958
+ const result = await pinNameSubscription(context, first, selectedSwarm);
1959
+ store = context.store;
1960
+ emit(result, `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`);
1961
+ break;
1962
+ }
1963
+ if (parsed.path === "swarm members") {
1964
+ const result = await swarmMembers(context, requireSwarm(), Boolean(parsed.options.refresh || parsed.options.force));
1965
+ emit(result, [
1966
+ `Directory: ${result.cache.source} (${result.cache.freshness}), observed ${result.cache.updatedAt}`,
1967
+ `Daemon: ${result.local.status}, observed ${result.local.updatedAt ?? "unknown"}; control-plane verified ${result.local.verifiedAt ?? "unknown"}`,
1968
+ table(["NAME", "DESCRIPTION", "ROLE", "PIVOT", "PUBLIC KEY"], result.members.map((member) => [
1969
+ member.name,
1970
+ member.description,
1971
+ member.role,
1972
+ member.pivot ? (member.localStatus ?? "candidate") : "-",
1973
+ member.publicKey,
1974
+ ]), "No members."),
1975
+ ].join("\n"));
1976
+ if (result.local.error)
1977
+ io.err(`Local Pivot observations (${result.local.status}): ${printable(result.local.error)}`);
1978
+ break;
1979
+ }
1980
+ if (parsed.path === "swarm export") {
1981
+ const member = await exportRequest(context, requireSwarm(), String(parsed.options.output ?? ""));
1982
+ emit({ member }, member);
1983
+ break;
1984
+ }
1985
+ if (parsed.path === "swarm pivot grant") {
1986
+ const url = requireSwarm();
1987
+ if (!parsed.options.yes)
1988
+ syntax("Granting Pivot HEAD receipt authority requires --yes; revoking it requires swarm exclude.");
1989
+ const result = await grantPivotAuthority(context, url, first);
1990
+ store = context.store;
1991
+ emit(result, `Granted Pivot HEAD authority to ${result.member} on ${result.configUrl} (HEAD ${result.headId}). Revoking Pivot HEAD authority requires swarm exclude.`);
1992
+ break;
1993
+ }
1994
+ if (["swarm exclude", "swarm resume", "swarm profile"].includes(parsed.path)) {
1995
+ const url = requireSwarm();
1996
+ if (parsed.path === "swarm exclude") {
1997
+ if (!parsed.options.yes)
1998
+ syntax("Member removal is irreversible; --yes required.");
1999
+ await removeMember(context, url, first);
2000
+ }
2001
+ else if (parsed.path === "swarm resume")
2002
+ await resumeRemoval(context, url);
2003
+ else {
2004
+ const profile = await updateProfile(context, url, {
2005
+ ...(typeof parsed.options.address === "string"
2006
+ ? { addresses: [parsed.options.address] }
2007
+ : {}),
2008
+ ...(typeof parsed.options.pivot === "string"
2009
+ ? {
2010
+ pivot: Boolean(parseValue("swarm.pivot", parsed.options.pivot, true)),
2011
+ }
2012
+ : {}),
2013
+ });
2014
+ emit(profile, JSON.stringify(profile));
2015
+ store = context.store;
2016
+ break;
2017
+ }
2018
+ store = context.store;
2019
+ emit({ url, completed: true }, `Organization switch complete: ${url}`);
2020
+ break;
2021
+ }
2022
+ if (parsed.path === "swarm update") {
2023
+ const cid = requireSwarm();
2024
+ const result = await updateSwarm(context, cid, {
2025
+ ...(typeof parsed.options.name === "string"
2026
+ ? { name: parsed.options.name }
2027
+ : {}),
2028
+ ...(typeof parsed.options.description === "string"
2029
+ ? { description: parsed.options.description }
2030
+ : {}),
2031
+ });
2032
+ emit(result, `Swarm: ${result.configUrl}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD ID: ${result.headId}\nConfig content CID: ${result.valueCid}`);
2033
+ break;
2034
+ }
2035
+ if (parsed.path === "search") {
2036
+ const registrations = state.swarms();
2037
+ const scope = parsed.options.all
2038
+ ? registrations
2039
+ : [
2040
+ {
2041
+ cid: requireSwarm(),
2042
+ alias: registrations.find((entry) => entry.cid === selectedSwarm)
2043
+ ?.alias ?? null,
2044
+ },
2045
+ ];
2046
+ const searchOptions = {};
2047
+ if (typeof parsed.options.prefix === "string")
2048
+ searchOptions.prefix = parsed.options.prefix;
2049
+ if (typeof parsed.options.kind === "string")
2050
+ searchOptions.kind = parsed.options.kind;
2051
+ if (typeof parsed.options.schema === "string")
2052
+ searchOptions.schemaCid = parsed.options.schema;
2053
+ if (typeof parsed.options.limit === "string")
2054
+ searchOptions.limit = /^\d+$/.test(parsed.options.limit)
2055
+ ? Number(parsed.options.limit)
2056
+ : Number.NaN;
2057
+ if (typeof parsed.options.offset === "string")
2058
+ searchOptions.offset = /^\d+$/.test(parsed.options.offset)
2059
+ ? Number(parsed.options.offset)
2060
+ : Number.NaN;
2061
+ const result = Object.keys(searchOptions).length
2062
+ ? await searchNames(context, first, scope, searchOptions)
2063
+ : await searchNames(context, first, scope);
2064
+ emit(result, formatSearchResults(result.matches));
2065
+ break;
2066
+ }
2067
+ if (parsed.path === "swarm status") {
2068
+ const cid = requireSwarm();
2069
+ const { head, config, networking, cache, lastWriter, state: contentState, } = await inspectSwarmStatus(context, cid, Boolean(parsed.options.refresh || parsed.options.force));
2070
+ const fingerprint = await keyId(config.owner);
2071
+ store = context.store;
2072
+ emit({
2073
+ configUrl: cid,
2074
+ owner: config.owner,
2075
+ ownerFingerprint: fingerprint,
2076
+ epoch: config.epoch,
2077
+ scopeId: config.scopeId,
2078
+ headId: config.headId,
2079
+ cache,
2080
+ state: contentState,
2081
+ networking,
2082
+ root: head.root,
2083
+ valueCid: head.cid,
2084
+ lastWriter,
2085
+ properties: {
2086
+ name: config.name,
2087
+ description: config.description,
2088
+ },
2089
+ }, [
2090
+ "Swarm",
2091
+ ` Directory: ${cache.source} (${cache.freshness}), observed ${cache.updatedAt}`,
2092
+ ` Name: ${printable(config.name)}`,
2093
+ ` Description: ${config.description ? printable(config.description) : "(none)"}`,
2094
+ " Config URL:",
2095
+ ` ${cid}`,
2096
+ "",
2097
+ "Identity",
2098
+ " Owner fingerprint:",
2099
+ ` ${fingerprint}`,
2100
+ "",
2101
+ "Content",
2102
+ " HEAD (publication root):",
2103
+ ` ${head.root}`,
2104
+ " Content CID (HEAD value):",
2105
+ ` ${head.cid}`,
2106
+ ...(lastWriter
2107
+ ? [
2108
+ ` Last HEAD writer: ${lastWriter.name ? printable(lastWriter.name) : "(profile name unavailable)"}`,
2109
+ ` Public key: ${lastWriter.subject}`,
2110
+ ` PeerID: ${lastWriter.peerId ?? "unknown"}`,
2111
+ ` Updated: ${lastWriter.updatedAt} (service time)`,
2112
+ " Last writer is not a confirmed content holder or the only copy.",
2113
+ ]
2114
+ : [
2115
+ " Last HEAD writer/time: unknown (legacy record or service without update metadata).",
2116
+ ]),
2117
+ ` State: ${contentState.status}. ${contentState.error}`,
2118
+ "",
2119
+ "Local networking",
2120
+ ` Daemon observations: ${networking.daemon.status}`,
2121
+ ` Updated: ${networking.daemon.updatedAt ?? "unknown"}`,
2122
+ ` Control-plane verified: ${networking.daemon.verifiedAt ?? "unknown"}`,
2123
+ ...(networking.daemon.error
2124
+ ? [` Observation error: ${printable(networking.daemon.error)}`]
2125
+ : []),
2126
+ ` Connections observed: ${networking.connections.observedAt ?? "unknown"} (${networking.connections.freshness})`,
2127
+ ...(networking.connections.error
2128
+ ? [
2129
+ ` Connection error: ${printable(networking.connections.error)}`,
2130
+ ]
2131
+ : []),
2132
+ table([
2133
+ "PIVOT PEER ID",
2134
+ "LOCAL",
2135
+ "PROBE",
2136
+ "PROBED AT",
2137
+ "FAILURES",
2138
+ "RETRY AT",
2139
+ "CONNECTION",
2140
+ ], networking.pivots.map((pivot) => [
2141
+ pivot.peerId,
2142
+ pivot.localStatus ?? "unknown",
2143
+ `${pivot.probe.result} (${pivot.probe.freshness})`,
2144
+ pivot.probe.at ?? "-",
2145
+ pivot.failures === null ? "-" : String(pivot.failures),
2146
+ pivot.retryAt ?? "-",
2147
+ pivot.connection.status,
2148
+ ]), "No declared Pivots."),
2149
+ ...networking.pivots.flatMap((pivot) => pivot.probe.error
2150
+ ? [
2151
+ ` ${pivot.peerId} probe error: ${printable(pivot.probe.error)}`,
2152
+ ]
2153
+ : []),
2154
+ ...(networking.connections.error
2155
+ ? []
2156
+ : [
2157
+ table(["CONNECTED PEER ID", "TRANSPORT", "ADDRESS"], networking.connections.peers.map((peer) => [
2158
+ peer.peerId,
2159
+ peer.transport,
2160
+ peer.address,
2161
+ ]), "No observed peer connections."),
2162
+ ]),
2163
+ " Selected is configuration, not connection success. Relay connectivity does not guarantee content availability.",
2164
+ ].join("\n"));
2165
+ break;
2166
+ }
2167
+ if (parsed.path === "get") {
2168
+ const localCid = /^(ipab|name):/i.test(first)
2169
+ ? undefined
2170
+ : state.resolve(first);
2171
+ const builtin = builtins.pins.find((pin) => pin.cid === localCid);
2172
+ const selected = builtin
2173
+ ? { cid: builtin.cid, targetCid: builtin.cid }
2174
+ : await resolveReference(context, first, selectedSwarm, (reference) => state.resolve(reference), Boolean(parsed.options.raw), "local-first");
2175
+ const contentStore = context.store;
2176
+ const source = IpfsStore.fromClient({
2177
+ block: {
2178
+ get: (key, options) => {
2179
+ options?.signal?.throwIfAborted();
2180
+ const builtin = builtins.blocks.get(CID.parse(key).toV1().toString());
2181
+ return builtin
2182
+ ? Promise.resolve(builtin.slice())
2183
+ : contentStore.block.get(key, options);
2184
+ },
2185
+ },
2186
+ }, contentStore.limits);
2187
+ let directory;
2188
+ try {
2189
+ directory = await getBundle(source, selected.cid, typeof parsed.options.output === "string"
2190
+ ? parsed.options.output
2191
+ : undefined);
2192
+ }
2193
+ finally {
2194
+ await source.close();
2195
+ }
2196
+ try {
2197
+ await context.finishRead?.();
2198
+ }
2199
+ finally {
2200
+ readContext = undefined;
2201
+ }
2202
+ const closing = store;
2203
+ store = undefined;
2204
+ await closeStore(closing, undefined);
2205
+ state.close();
2206
+ state = undefined;
2207
+ emit({ ...selected, directory }, directory);
2208
+ break;
2209
+ }
2210
+ let cid;
2211
+ let contentCid;
2212
+ if (parsed.path === "swarm create") {
2213
+ cid = await createSwarm(context, {
2214
+ ...(typeof parsed.options.service === "string"
2215
+ ? { service: parsed.options.service }
2216
+ : {}),
2217
+ ...(typeof parsed.options.resume === "string"
2218
+ ? { resume: parsed.options.resume }
2219
+ : {}),
2220
+ properties: {
2221
+ name: String(parsed.options.name ?? ""),
2222
+ description: String(parsed.options.description ?? ""),
2223
+ },
2224
+ ...(typeof parsed.options.alias === "string"
2225
+ ? { alias: parsed.options.alias }
2226
+ : {}),
2227
+ });
2228
+ }
2229
+ else if (parsed.path === "swarm request") {
2230
+ const result = await requestMembership(context, state.resolveSwarm(first), {
2231
+ ...(typeof parsed.options.output === "string"
2232
+ ? { output: parsed.options.output }
2233
+ : {}),
2234
+ ...(parsed.options.pivot ? { role: "pivot" } : {}),
2235
+ });
2236
+ store = context.store;
2237
+ io.err(`Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`);
2238
+ if (result.file === undefined)
2239
+ io.out(JSON.stringify(result.request, null, 2));
2240
+ else {
2241
+ io.err(`Request saved to: ${result.file}`);
2242
+ if (parsed.flags.json)
2243
+ emit({
2244
+ file: result.file,
2245
+ member: result.request.member,
2246
+ ownerFingerprint: result.ownerFingerprint,
2247
+ }, "");
2248
+ }
2249
+ break;
2250
+ }
2251
+ else if (parsed.path === "swarm approve") {
2252
+ const selected = requireSwarm();
2253
+ if (first === "-" && !parsed.options.yes)
2254
+ syntax("Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.");
2255
+ const request = first === "-"
2256
+ ? await verifiedRequestStream((io.requestInput ?? processIO.requestInput)())
2257
+ : await verifiedRequest(first);
2258
+ if (request.configUrl !== selected)
2259
+ syntax(`Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`);
2260
+ io.err(await membershipRequestSummary(request));
2261
+ if (!parsed.options.yes &&
2262
+ (!io.tty ||
2263
+ !(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.`))))
2264
+ throw new HostError("Approval requires explicit --yes or interactive confirmation.");
2265
+ cid = await approveMembership(context, request, {
2266
+ again: Boolean(parsed.options.again),
2267
+ pivot: Boolean(parsed.options.pivot),
2268
+ });
2269
+ }
2270
+ else {
2271
+ const content = await publicationSource(second, store);
2272
+ contentCid = content;
2273
+ cid = await publish(context, content, {
2274
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
2275
+ name: first,
2276
+ ...(typeof parsed.options.expect === "string"
2277
+ ? { expect: parsed.options.expect }
2278
+ : {}),
2279
+ snapshot: Boolean(parsed.options.snapshot),
2280
+ });
2281
+ }
2282
+ store = context.store;
2283
+ if (parsed.path === "swarm create")
2284
+ io.err(`Registered swarm ${state.registeredSwarm(cid).alias ?? cid}. Saved current: ${state.config({ includeSecrets: false })["swarm.default"] ?? "(none)"}.`);
2285
+ if (contentCid)
2286
+ 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.`);
2287
+ emit(parsed.path === "swarm create" || parsed.path === "swarm approve"
2288
+ ? { configUrl: cid }
2289
+ : { cid, ...(contentCid ? { contentCid } : {}) }, cid);
2290
+ break;
2291
+ }
724
2292
  case "store usage":
725
2293
  case "store gc": {
726
2294
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
@@ -734,7 +2302,7 @@ async function performCli(argv, io, env) {
734
2302
  }
735
2303
  break;
736
2304
  }
737
- case "init":
2305
+ case "templates render":
738
2306
  case "build":
739
2307
  case "bundle build":
740
2308
  case "bundle inspect":
@@ -770,44 +2338,78 @@ async function performCli(argv, io, env) {
770
2338
  const builtin = builtins.blocks.get(cid.toV1().toString());
771
2339
  if (builtin)
772
2340
  return builtin.slice();
773
- return (await getStore()).block.get(cid.toString(), options);
2341
+ return (store ?? (await getStore())).block.get(cid.toString(), options);
774
2342
  },
775
2343
  };
776
2344
  const builtinSource = first ? state.pin(first) : undefined;
777
2345
  const source = builtinSource?.builtin && builtinSource.metadata?.kind === "bundle"
778
2346
  ? builtinSource.cid
779
2347
  : first;
2348
+ let selectedTemplate;
2349
+ if (parsed.path === "templates render") {
2350
+ const selector = first;
2351
+ selectedTemplate = selector;
2352
+ if (parseNameReference(selector)) {
2353
+ await getStore();
2354
+ const context = swarmContext();
2355
+ readContext = context;
2356
+ selectedTemplate = (await resolveReference(context, selector, selectedSwarm, (reference) => state.resolve(reference), false, "local-first")).cid;
2357
+ store = context.store;
2358
+ }
2359
+ else {
2360
+ let explicit = false;
2361
+ try {
2362
+ CID.parse(selector);
2363
+ explicit = true;
2364
+ }
2365
+ catch {
2366
+ /* Not a CID. */
2367
+ }
2368
+ explicit ||= selector.toLowerCase().endsWith(".car");
2369
+ if (!explicit) {
2370
+ try {
2371
+ await lstat(selector);
2372
+ explicit = true;
2373
+ }
2374
+ catch (cause) {
2375
+ if (!nodeError(cause, "ENOENT") &&
2376
+ !nodeError(cause, "ENOTDIR"))
2377
+ throw cause;
2378
+ }
2379
+ }
2380
+ if (!explicit) {
2381
+ templateName(selector);
2382
+ if (!selectedSwarm)
2383
+ 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.");
2384
+ await getStore();
2385
+ const context = swarmContext();
2386
+ readContext = context;
2387
+ selectedTemplate = await resolveTemplateSelector(context, selector, selectedSwarm);
2388
+ store = context.store;
2389
+ }
2390
+ }
2391
+ }
780
2392
  if (parsed.path === "bundle build" || parsed.path === "build")
781
2393
  io.err(parsed.path === "build"
782
- ? "Typechecking, bundling and building App..."
2394
+ ? "Assembling and validating Bundle (no compilation)..."
783
2395
  : "Validating and building bundle...");
784
2396
  if (parsed.path === "bundle import")
785
2397
  io.err("Validating and importing CAR into Store...");
786
- const result = parsed.path === "init"
787
- ? await initApp(first, second, {
2398
+ const result = parsed.path === "templates render"
2399
+ ? await initApp(second, parsed.positional[2], {
788
2400
  ...request,
789
- ...(typeof parsed.options.template === "string"
790
- ? {
791
- template: state.pin(parsed.options.template)?.builtin
792
- ? parsed.options.template
793
- : state.pin(parsed.options.template)
794
- ? state.resolve(parsed.options.template)
795
- : parsed.options.template,
796
- }
797
- : {}),
798
- ...(parsed.parameters
799
- ? { parameters: parsed.parameters }
800
- : {}),
2401
+ ...(selectedTemplate ? { template: selectedTemplate } : {}),
2402
+ parameters: [
2403
+ ...(parsed.parameters ?? []),
2404
+ ...(typeof parsed.options.description === "string"
2405
+ ? [`description=${parsed.options.description}`]
2406
+ : []),
2407
+ ],
801
2408
  })
802
2409
  : parsed.path === "build"
803
- ? await buildApp(first, {
2410
+ ? await assembleBundle(first, {
804
2411
  ...request,
805
2412
  replace: Boolean(parsed.options.replace),
806
- ...(parsed.options["with-source"]
807
- ? { includeSource: true }
808
- : parsed.options["without-source"]
809
- ? { includeSource: false }
810
- : {}),
811
2413
  ...(typeof parsed.options.output === "string"
812
2414
  ? { output: parsed.options.output }
813
2415
  : {}),
@@ -843,7 +2445,7 @@ async function performCli(argv, io, env) {
843
2445
  state = undefined;
844
2446
  controller.signal.throwIfAborted();
845
2447
  if ("output" in result)
846
- emit({ ...result, imported: importing }, `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${result.validation !== undefined ? `\nEntry validation: ${result.validation?.status ?? "not-applicable"}` : ""}${"source" in result ? `\nSource CID: ${result.source.cid}\nSource CAR: ${result.source.output} (not imported or pinned)` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`);
2448
+ 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)"}`);
847
2449
  else if (result.kind === "bundle-import")
848
2450
  emit(result, `Imported CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nBlocks: ${result.blocks}\nCAR: ${result.source}\nEntry validation: ${result.validation?.status ?? "not-applicable"}`);
849
2451
  else if (result.kind === "project-init") {
@@ -851,12 +2453,12 @@ async function performCli(argv, io, env) {
851
2453
  if (result.files.includes("package.json") &&
852
2454
  (result.files.includes("ipab.yaml") ||
853
2455
  result.files.includes("ipab.json")))
854
- io.err(`Next: install declared dependencies in ${JSON.stringify(result.directory)}; then ipab build ${JSON.stringify(result.directory)} (requires locally linked ipab).`);
2456
+ 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.`);
855
2457
  else if (result.files.includes(".bundle.yaml"))
856
2458
  io.err(`Next: ipab bundle build ${JSON.stringify(result.directory)}`);
857
2459
  }
858
2460
  else
859
- emit(result, `Kind: ${result.kind}\nName: ${printable(result.name)}\nSchema CID: ${result.schemaCid}\nEntry: ${result.entry.path} (${result.entry.contentType})\nDefinition validation: passed\nStorage verification: ${result.validation.storage}\nEntry validation: ${result.validation.entry?.status ?? "not-applicable"}`);
2461
+ 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"}`);
860
2462
  }
861
2463
  catch (cause) {
862
2464
  if (cancelled)
@@ -870,96 +2472,80 @@ async function performCli(argv, io, env) {
870
2472
  break;
871
2473
  }
872
2474
  case "pin list": {
873
- const type = typeof parsed.options.type === "string"
874
- ? state.resolve(parsed.options.type, true)
875
- : undefined;
876
- const pins = state.pins();
877
- const listed = pins
878
- .filter((pin) => pin.status === "ready" && pin.metadata?.kind === "bundle")
879
- .map(pinDetails)
880
- .filter((pin) => type === undefined || pin.schemaCid === type);
881
- const invalid = pins
882
- .filter((pin) => pin.status === "ready" && pin.metadata?.kind !== "bundle")
883
- .map(({ name, cid, metadata }) => ({
884
- name,
885
- cid,
886
- kind: metadata?.kind,
887
- reason: "Not a Bundle pin; retention is preserved. Use pin delete to release it.",
888
- }));
889
- const pending = pins
890
- .filter((pin) => pin.status !== "ready")
891
- .map(({ name, cid, status }) => ({ name, cid, status }));
892
- if (pending.length)
893
- io.err(`Unfinished pin operations (not usable pins): ${JSON.stringify(pending)}. Retry pin add/delete.`);
894
- if (invalid.length)
895
- io.err(`Legacy non-Bundle pins (not usable pins): ${JSON.stringify(invalid)}. Retention is unchanged; delete explicitly and wrap content in a Bundle before pinning again.`);
896
- emit({ items: listed, pending, invalid }, table(["NAME", "CID", "KIND", "BUNDLE TYPE", "SOURCE"], listed.map((pin) => [
897
- pin.name,
898
- pin.cid,
899
- pin.kind,
900
- pin.typeName,
901
- pin.builtin ? "built-in (read-only)" : "user",
902
- ]), "No named pins."));
903
- break;
904
- }
905
- case "pin add": {
906
- io.err("Fetching, verifying and retaining content in Store...");
907
- const result = await addPin(state, first, second, await storeConfiguration(value("store.gateway")));
908
- emit(result, `${result.name} → ${result.cid}\nBundle type: ${printable(result.typeName)}`);
2475
+ const listed = state.contentPins();
2476
+ const archived = state.archivedPins();
2477
+ const builtins = state.pins().map(pinDetails);
2478
+ emit({ items: listed, builtins, archived }, table(["REFERENCE", "CID", "STATUS", "SOURCE"], [
2479
+ ...listed.map((pin) => [
2480
+ pin.reference,
2481
+ pin.cid ?? "(none)",
2482
+ `${pin.status}/${pin.freshness}${pin.error ? `: ${pin.error}` : ""}`,
2483
+ pin.swarm ? "following shared Name" : "fixed CID",
2484
+ ]),
2485
+ ...builtins.map((pin) => [
2486
+ pin.name,
2487
+ pin.cid,
2488
+ "read-only",
2489
+ "built-in",
2490
+ ]),
2491
+ ...archived.map((pin) => [
2492
+ pin.cid,
2493
+ pin.cid,
2494
+ pin.status,
2495
+ `inactive archive (${pin.name}); unpin exact CID`,
2496
+ ]),
2497
+ ], "No pins."));
909
2498
  break;
910
2499
  }
911
- case "pin delete": {
912
- const result = await deletePin(state, first);
913
- emit(result, `Deleted ${first}; released only its retention responsibility. No blocks deleted or GC requested.`);
2500
+ case "unpin": {
2501
+ const canonical = pinReference(state, first, selectedSwarm);
2502
+ const result = await unpin(state, canonical.reference);
2503
+ emit(result, `Unpinned ${canonical.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`);
914
2504
  break;
915
2505
  }
916
2506
  case "pin show": {
917
- const pin = state.pin(first);
918
- if (!pin)
2507
+ const builtin = first.startsWith("builtin:")
2508
+ ? state.pin(first)
2509
+ : undefined;
2510
+ const canonical = builtin
2511
+ ? undefined
2512
+ : pinReference(state, first, selectedSwarm);
2513
+ const pin = canonical
2514
+ ? state.contentPin(canonical.reference)
2515
+ : undefined;
2516
+ const archived = canonical
2517
+ ? state
2518
+ .archivedPins()
2519
+ .filter((pin) => pin.cid === canonical.reference)
2520
+ : [];
2521
+ if (!pin && !builtin && !archived.length)
919
2522
  throw new HostError(`Pin "${first}" does not exist. Run ipab pin list.`);
920
- const result = pinDetails(pin);
921
- emit(result, `Name: ${printable(result.name)}\nCID: ${result.cid}\nBundle type: ${printable(result.typeName)}\nSchema CID: ${result.schemaCid}\nSource: ${result.builtin ? "built-in (read-only; content bundled with IPAB)" : "local registration (not live node verification)"}`);
922
- break;
923
- }
924
- case "pin rename": {
925
- const result = renamePin(state, first, second);
926
- emit(result, `${first} → ${result.name} (${result.cid})`);
927
- break;
928
- }
929
- case "register list": {
930
- const associations = state.registrations();
931
- emit({ items: associations }, table(["SCHEMA CID", "APP CID", "ARGV"], associations.map((association) => [
932
- association.schemaCid,
933
- association.appCid,
934
- JSON.stringify(association.argv),
935
- ]), "No associations."));
936
- break;
937
- }
938
- case "register set": {
939
- const association = state.setAssociation(schemaAlias(first), second, parsed.template ?? ["%"], Boolean(parsed.options.replace));
940
- emit(association, `${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`);
941
- break;
942
- }
943
- case "register remove": {
944
- const removed = state.removeAssociation(schemaAlias(first));
945
- emit({ removed: [removed] }, `Removed association for ${removed}.`);
2523
+ const result = builtin
2524
+ ? pinDetails(builtin)
2525
+ : {
2526
+ pin: pin ?? null,
2527
+ roots: pin ? state.hold(pin.owner)?.roots : [],
2528
+ archived,
2529
+ };
2530
+ emit(result, JSON.stringify(result, null, 2));
946
2531
  break;
947
2532
  }
948
2533
  case "config get": {
949
- const selected = first
950
- ? items.filter((item) => item.key === first)
951
- : items;
2534
+ const selected = (first ? items.filter((item) => item.key === first) : items).map(visibleConfig);
952
2535
  emit({ items: selected }, table(["KEY", "VALUE", "SOURCE"], selected.map((item) => [item.key, String(item.value), item.source]), "No configuration values."));
953
2536
  break;
954
2537
  }
955
2538
  case "config set": {
956
2539
  const key = configKey(first);
957
- const saved = parseValue(key, second, true);
2540
+ const saved = parseValue(key, key === "pointers.apiKey"
2541
+ ? await (io.readSecret ?? processIO.readSecret)()
2542
+ : second, true);
958
2543
  state.setConfig(key, saved);
959
2544
  const source = items.find((item) => item.key === key).source;
960
2545
  if (source === "env" || source === "flag")
961
2546
  io.err(`Warning: saved user value is masked by ${source}.`);
962
- emit({ key, value: saved, source: "user" }, `Saved ${key} = ${printable(String(saved))} (user).`);
2547
+ const display = visibleConfig({ key, value: saved, source: "user" });
2548
+ emit(display, `Saved ${key} = ${printable(String(display.value))} (user).`);
963
2549
  break;
964
2550
  }
965
2551
  case "config reset":
@@ -1031,11 +2617,62 @@ async function performCli(argv, io, env) {
1031
2617
  }
1032
2618
  case "exec":
1033
2619
  case "open": {
2620
+ const named = parsed.path === "open" ? parseNameReference(first) : undefined;
2621
+ const registrySwarm = named?.swarm
2622
+ ? state.resolveSwarm(named.swarm)
2623
+ : selectedSwarm;
2624
+ if (parsed.path === "open" && !registrySwarm)
2625
+ 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.");
1034
2626
  if (parsed.options.log && !value("history.enabled"))
1035
2627
  throw new HostError("Execution logging requires history.enabled=true.");
1036
- const target = state.resolve(first);
1037
2628
  await recoverInactive(state);
1038
2629
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2630
+ const context = swarmContext();
2631
+ readContext = context;
2632
+ const target = (await resolveReference(context, first, selectedSwarm, (reference) => state.resolve(reference), Boolean(parsed.options.raw), "local-first")).cid;
2633
+ store = context.store;
2634
+ const resolveBundleReference = async (reference, signal, preferredSwarm) => {
2635
+ signal.throwIfAborted();
2636
+ const lookup = {
2637
+ ...swarmContext(),
2638
+ store: new IpfsStore(await storeConfiguration(value("store.gateway"))),
2639
+ };
2640
+ try {
2641
+ const named = parseNameReference(reference);
2642
+ const swarm = named?.swarm
2643
+ ? state.resolveSwarm(named.swarm)
2644
+ : preferredSwarm
2645
+ ? state.resolveSwarm(preferredSwarm)
2646
+ : selectedSwarm;
2647
+ const resolve = (source) => resolveReference(lookup, reference, source, (input) => state.resolve(input), false, "local-first");
2648
+ let resolved;
2649
+ try {
2650
+ resolved = await resolve(named ? swarm : undefined);
2651
+ }
2652
+ catch (cause) {
2653
+ let failure = cause;
2654
+ for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
2655
+ failure = failure.cause;
2656
+ if (named ||
2657
+ !swarm ||
2658
+ !(failure instanceof ContentError) ||
2659
+ failure.code !== "missing_block")
2660
+ throw cause;
2661
+ signal.throwIfAborted();
2662
+ resolved = await resolve(swarm);
2663
+ }
2664
+ signal.throwIfAborted();
2665
+ return { ...resolved, ...(swarm ? { swarm } : {}) };
2666
+ }
2667
+ finally {
2668
+ try {
2669
+ await lookup.finishRead?.();
2670
+ }
2671
+ finally {
2672
+ await lookup.store.close();
2673
+ }
2674
+ }
2675
+ };
1039
2676
  let appCid;
1040
2677
  let appArgv;
1041
2678
  if (parsed.path === "open") {
@@ -1044,14 +2681,34 @@ async function performCli(argv, io, env) {
1044
2681
  try {
1045
2682
  const content = await validatedBundle(root, store, owner);
1046
2683
  const schema = content.schemaKey;
1047
- const association = state.association(schema);
2684
+ let association;
2685
+ if (registrySwarm) {
2686
+ const lookup = {
2687
+ ...swarmContext(),
2688
+ store: new IpfsStore(await storeConfiguration(value("store.gateway"))),
2689
+ };
2690
+ try {
2691
+ association = await swarmAssociation(lookup, registrySwarm, schema, "local-first");
2692
+ }
2693
+ finally {
2694
+ try {
2695
+ await lookup.finishRead?.();
2696
+ }
2697
+ finally {
2698
+ await lookup.store.close();
2699
+ }
2700
+ }
2701
+ }
1048
2702
  if (!association)
1049
- throw new HostError(`No App registered for Schema ${schema}. Use ipab register set or ipab exec.`);
2703
+ throw new HostError(`No App registered for Schema ${schema} in Swarm ${registrySwarm}. Use ipab register set ${schema} APP_CID --swarm ${registrySwarm} or ipab exec.`);
1050
2704
  appCid = association.appCid;
1051
- appArgv = association.argv.map((argument) => argument === "%" ? root : argument);
2705
+ if (association.argv.length !== 1 || association.argv[0] !== "%")
2706
+ 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.");
2707
+ appArgv = [root];
1052
2708
  // execute owns the App/input context before this validation owner's eventual release.
1053
2709
  const result = await execute(state, store, { origin: "open", appCid, argv: appArgv }, {
1054
2710
  inputSchema: schema,
2711
+ resolveBundleReference,
1055
2712
  history: Boolean(value("history.enabled")),
1056
2713
  retain: value("output.retention") === "history",
1057
2714
  log: Boolean(parsed.options.log),
@@ -1071,6 +2728,7 @@ async function performCli(argv, io, env) {
1071
2728
  appArgv = parsed.positional.slice(1);
1072
2729
  }
1073
2730
  appExitCode = (await execute(state, store, { origin: "exec", appCid, argv: appArgv }, {
2731
+ resolveBundleReference,
1074
2732
  history: Boolean(value("history.enabled")),
1075
2733
  retain: value("output.retention") === "history",
1076
2734
  log: Boolean(parsed.options.log),
@@ -1091,7 +2749,12 @@ async function performCli(argv, io, env) {
1091
2749
  }
1092
2750
  finally {
1093
2751
  try {
1094
- await closeStore(store, appExitCode);
2752
+ try {
2753
+ await readContext?.finishRead?.();
2754
+ }
2755
+ finally {
2756
+ await closeStore(store, appExitCode);
2757
+ }
1095
2758
  }
1096
2759
  finally {
1097
2760
  state?.close();