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

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 +234 -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 +7 -8
  23. package/dist/authoring.d.ts.map +1 -1
  24. package/dist/authoring.js +59 -16
  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 +1967 -258
  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 +11 -2
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +166 -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 +688 -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 +135 -13
  182. package/dist/state.d.ts.map +1 -1
  183. package/dist/state.js +577 -92
  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 +537 -0
  202. package/dist/swarm.d.ts.map +1 -0
  203. package/dist/swarm.js +4991 -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 +99 -18
  236. package/src/builtins.ts +2 -27
  237. package/src/bundled-skills.ts +60 -0
  238. package/src/cli.ts +2461 -323
  239. package/src/config-secret.ts +14 -0
  240. package/src/config.ts +214 -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 +1092 -0
  247. package/src/errors.ts +1 -25
  248. package/src/get.ts +91 -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 +875 -108
  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 +7392 -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/src/cli.ts CHANGED
@@ -1,16 +1,21 @@
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";
5
- import type { CID } from "multiformats/cid";
6
+ import { CID } from "multiformats/cid";
6
7
  import stringWidth from "string-width";
7
8
  import {
9
+ LOCAL_SWARM_ALIAS,
8
10
  configKey,
9
11
  effectiveConfig,
12
+ isLocalSwarm,
10
13
  parseValue,
11
14
  publicUrl,
12
15
  stateLocation,
13
16
  storeConfiguration,
17
+ swarmUrl,
18
+ visibleConfig,
14
19
  type GlobalOptions,
15
20
  } from "./config.js";
16
21
  import { HostError, message, object, syntax } from "./errors.js";
@@ -24,40 +29,137 @@ import {
24
29
  } from "./history.js";
25
30
  import { execute } from "./runtime.js";
26
31
  import { validatedBundle } from "./space.js";
27
- import { exactCid, pinName, State, type RunRecord } from "./state.js";
28
- import { buildBundle, inspectBundle, importBundle } from "./authoring.js";
29
- import { buildApp, initApp } from "./app-authoring.js";
32
+ import {
33
+ createAssociation,
34
+ exactCid,
35
+ swarmAlias,
36
+ State,
37
+ type Association,
38
+ type RunRecord,
39
+ } from "./state.js";
40
+ import {
41
+ buildBundle,
42
+ inspectBundle,
43
+ importBundle,
44
+ localBundleDirectory,
45
+ nodeError,
46
+ snapshotBundle,
47
+ } from "./authoring.js";
48
+ import { initApp } from "./app-authoring.js";
49
+ import { assembleBundle } from "./assembly.js";
50
+ import { getBundle } from "./get.js";
51
+ import { doctorDevice, doctorText } from "./doctor.js";
52
+ import {
53
+ daemonEndpoint,
54
+ ensureDaemon,
55
+ openLoopbackUrl,
56
+ serveDaemon,
57
+ } from "./daemon.js";
58
+ import { keyId } from "@ipab/bundle/pointer/crypto";
59
+ import {
60
+ createSwarm,
61
+ swarmDaemon,
62
+ requestMembership,
63
+ approveMembership,
64
+ grantPivotAuthority,
65
+ exportRequest,
66
+ removeMember,
67
+ resumeRemoval,
68
+ updateProfile,
69
+ accountProfile,
70
+ updateAccountProfile,
71
+ swarmMembers,
72
+ inspectSwarmStatus,
73
+ verifiedRequest,
74
+ verifiedRequestStream,
75
+ membershipRequestSummary,
76
+ updateSwarm,
77
+ searchNames,
78
+ formatNameReference,
79
+ resolveReference,
80
+ parseNameReference,
81
+ formalName,
82
+ publish,
83
+ pinNameSubscription,
84
+ pinReference,
85
+ swarmRegistrations,
86
+ swarmAssociation,
87
+ setSwarmAssociation,
88
+ removeSwarmAssociation,
89
+ resolveTemplateSelector,
90
+ templateName,
91
+ swarmTemplates,
92
+ setSwarmTemplate,
93
+ removeSwarmTemplate,
94
+ type SwarmContext,
95
+ } from "./swarm.js";
30
96
  import { schemaAlias } from "./app-definition.js";
31
- import { addPin, deletePin, pinDetails, renamePin } from "./pins.js";
97
+ import { unpin, pinDetails } from "./pins.js";
98
+ import { publicationSource } from "./publish-source.js";
99
+ import {
100
+ templateRenderExample,
101
+ templateOutputTree,
102
+ templateParameterRows,
103
+ } from "./template-presentation.js";
32
104
  import { logFiles } from "./logs.js";
33
105
  import { builtinContent } from "./builtins.js";
106
+ import { readSecretStream } from "./config-secret.js";
107
+ import { manageSkills, syncDaemonSwarm } from "./skills.js";
34
108
 
35
109
  export interface IO {
36
110
  out(text: string): void;
37
- err(text: string): void;
111
+ err(text: string, progress?: boolean): void;
38
112
  tty: boolean;
39
113
  columns?(): number | undefined;
40
- confirm(text: string): Promise<boolean>;
114
+ confirm(text: string, signal?: AbortSignal): Promise<boolean>;
115
+ readSecret?(): Promise<string>;
116
+ requestInput?(): AsyncIterable<string | Uint8Array>;
41
117
  }
118
+ let progressLine = false;
42
119
  export const processIO: IO = {
43
120
  out(text) {
44
121
  process.stdout.write(`${text}\n`);
45
122
  },
46
- err(text) {
47
- process.stderr.write(`${text}\n`);
123
+ err(text, progress = false) {
124
+ if (progress && process.stderr.isTTY) {
125
+ const width =
126
+ (process.stderr.columns > 1 ? process.stderr.columns : 80) - 1;
127
+ process.stderr.write(`\r\x1b[2K${text.slice(0, width)}`);
128
+ progressLine = true;
129
+ } else {
130
+ process.stderr.write(`${progressLine ? "\n" : ""}${text}\n`);
131
+ progressLine = false;
132
+ }
48
133
  },
49
134
  tty: Boolean(process.stdin.isTTY && process.stderr.isTTY),
50
135
  columns() {
51
136
  return process.stdout.columns;
52
137
  },
53
- async confirm(text) {
138
+ requestInput() {
139
+ if (process.stdin.isTTY)
140
+ syntax(
141
+ "Pipe Request JSON into swarm approve - --yes, or pass a Request file.",
142
+ );
143
+ return process.stdin;
144
+ },
145
+ async readSecret() {
146
+ if (process.stdin.isTTY)
147
+ syntax(
148
+ "Pipe the API key through stdin; interactive echo is not permitted.",
149
+ );
150
+ process.stdin.setEncoding("utf8");
151
+ return readSecretStream(process.stdin as AsyncIterable<string>);
152
+ },
153
+ async confirm(text, signal) {
54
154
  const reader = createInterface({
55
155
  input: process.stdin,
56
156
  output: process.stderr,
57
157
  });
58
158
  try {
59
159
  return /^(y|yes)$/i.test(
60
- (await reader.question(`${text} [y/N] `)).trim(),
160
+ (
161
+ await reader.question(`${text} [y/N] `, signal ? { signal } : {})
162
+ ).trim(),
61
163
  );
62
164
  } finally {
63
165
  reader.close();
@@ -65,23 +167,54 @@ export const processIO: IO = {
65
167
  },
66
168
  };
67
169
  const commands: Record<string, string> = {
68
- init: "init NAME [DIR] [OPTIONS]",
69
- build: "build [DIR] [OPTIONS]",
170
+ daemon: "daemon",
171
+ "daemon ui": "daemon ui [--open]",
172
+ "skills list": "skills list [--refresh | --no-refresh]",
173
+ "skills sync":
174
+ "skills sync [NAMES...] [--agent AGENT]... [--override-existing] [--dry-run] [--yes] [--refresh | --no-refresh]",
175
+ doctor: "doctor [--fix [--yes]]",
176
+ profile: "profile [--name NAME] [--description TEXT]",
177
+ "swarm create": "swarm create [--service URL] [--resume OPERATION]",
178
+ "swarm request": "swarm request URL_OR_ALIAS [--pivot] [--output FILE]",
179
+ "swarm export": "swarm export --output FILE",
180
+ "swarm approve": "swarm approve REQUEST_FILE [--pivot] [--again] --yes",
181
+ "swarm pivot grant": "swarm pivot grant MEMBER_PUBLIC_KEY --yes",
182
+ "swarm exclude": "swarm exclude MEMBER_PUBLIC_KEY --yes",
183
+ "swarm resume": "swarm resume",
184
+ "swarm profile": "swarm profile [--address MULTIADDR] [--pivot true|false]",
185
+ "swarm status": "swarm status [--refresh | --no-refresh]",
186
+ "swarm members": "swarm members [--refresh | --no-refresh]",
187
+ "swarm list": "swarm list",
188
+ "swarm set": "swarm set ALIAS CONFIG_URL [--yes]",
189
+ "swarm use": "swarm use URL_OR_ALIAS",
190
+ "swarm remove": "swarm remove URL_OR_ALIAS",
191
+ "swarm update": "swarm update [--name TEXT] [--description TEXT]",
192
+ publish: "publish NAME SOURCE [--expect OLD_CID | --snapshot]",
193
+ get: "get REF [--raw] [--refresh | --no-refresh] [-o DIRECTORY]",
194
+ search:
195
+ "search QUERY [--all | --current] [--prefix PATH] [--kind all|bundle|dir|file] [--schema CID] [--limit N] [--offset N] [--refresh | --no-refresh]",
196
+ "templates render": "templates render TEMPLATE NAME [DIR] [OPTIONS]",
197
+ build: "build [SOURCE] [OPTIONS]",
70
198
  "bundle build": "bundle build SOURCE [OPTIONS]",
71
199
  "bundle inspect": "bundle inspect SOURCE",
72
200
  "bundle import": "bundle import FILE.car",
73
- exec: "exec [--log] APP [APP_ARGS...]",
74
- open: "open [--log] CONTENT",
75
- "pin add": "pin add NAME CID",
76
- "pin delete": "pin delete NAME",
77
- "pin list": "pin list [--type TYPE]",
78
- "pin show": "pin show NAME",
79
- "pin rename": "pin rename OLD_NAME NEW_NAME",
80
- "register list": "register list",
81
- "register set": "register set SCHEMA APP [--replace] [-- TEMPLATE...]",
82
- "register remove": "register remove SCHEMA",
201
+ exec: "exec [--log] [--refresh | --no-refresh] APP [APP_ARGS...]",
202
+ open: "open [--log] [--raw] [--refresh | --no-refresh] CONTENT",
203
+ pin: "pin REF [--refresh | --no-refresh]",
204
+ unpin: "unpin REF",
205
+ "pin list": "pin list",
206
+ "pin show": "pin show REF",
207
+ "register list": "register list [--swarm URL_OR_ALIAS]",
208
+ "register set":
209
+ "register set SCHEMA APP [--swarm URL_OR_ALIAS]... [--replace]",
210
+ "register remove": "register remove SCHEMA [--swarm URL_OR_ALIAS]...",
211
+ "templates list": "templates list [--refresh | --no-refresh]",
212
+ "templates show": "templates show NAME [--refresh | --no-refresh]",
213
+ "templates set": "templates set NAME SOURCE [--expect OLD_TARGET_CID]",
214
+ "templates remove": "templates remove NAME --expect OLD_TARGET_CID",
83
215
  "config get": "config get [KEY]",
84
- "config set": "config set KEY VALUE",
216
+ "config set":
217
+ "config set KEY VALUE\n ipab config set pointers.apiKey - < protected-key-file",
85
218
  "config reset": "config reset KEY",
86
219
  "store usage": "store usage",
87
220
  "store gc": "store gc",
@@ -91,9 +224,12 @@ const commands: Record<string, string> = {
91
224
  "history remove RUN_ID... [--yes]\n ipab history remove FILTERS [--yes]",
92
225
  };
93
226
  const groups: Record<string, string> = {
227
+ skills: "Discover and explicitly synchronize selected Swarm Skills globally",
228
+ swarm: "Create, authorize, select and manage personal swarms",
94
229
  bundle: "Create, inspect and import content bundles",
95
- pin: "Retain content and manage short names",
230
+ pin: "Retain an exact CID or follow a shared Swarm Name",
96
231
  register: "Associate content types with Apps",
232
+ templates: "Inspect, render and manage Template Bundles",
97
233
  config: "Manage local configuration",
98
234
  store: "Query local storage and collect unreferenced blocks",
99
235
  history: "View and remove execution history",
@@ -108,6 +244,412 @@ const commandHelp: Record<
108
244
  notes?: string[];
109
245
  }
110
246
  > = {
247
+ daemon: {
248
+ summary: "Manage all registered private Swarm nodes in the foreground",
249
+ examples: ["ipab daemon", "ipab daemon ui --open"],
250
+ notes: [
251
+ "Manages all registered Swarms independently and does not accept --swarm; ignores the saved default.",
252
+ "Maintains membership and network topology: probes pivot candidates, refreshes approved profiles and retries with cooldown. Diagnostics go to stderr.",
253
+ "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.",
254
+ "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]`.",
255
+ "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.",
256
+ "Ctrl-C / TERM drains foreground operations and releases the device/state-dir lock; Kubo stays running. An existing background daemon already owns this lock.",
257
+ "Role and relay candidate changes restart only the verified managed Kubo node.",
258
+ ],
259
+ },
260
+ "daemon ui": {
261
+ summary:
262
+ "Show or open the running daemon's read-only loopback status WebUI",
263
+ options: [
264
+ "--open Open the 127.0.0.1 status WebUI URL in the default browser.",
265
+ ],
266
+ examples: [
267
+ "ipab daemon ui",
268
+ "ipab daemon ui --open",
269
+ "ipab --json daemon ui",
270
+ ],
271
+ notes: [
272
+ "Inspects the protected loopback endpoint for the selected state-dir without starting a daemon.",
273
+ "The WebUI binds strictly to 127.0.0.1, validates Host/Origin headers against DNS rebinding, and never exposes private keys, swarm.key or Kubo Bearer tokens.",
274
+ ],
275
+ },
276
+ "templates list": {
277
+ summary: "List templates under the selected Swarm Meta templatePath",
278
+ options: [
279
+ "--refresh / --no-refresh Refresh HEAD now / allow a valid cached snapshot.",
280
+ ],
281
+ examples: [
282
+ "ipab --swarm work templates list",
283
+ "ipab --json templates list",
284
+ ],
285
+ notes: [
286
+ "Uses only global --swarm (once, before the command), otherwise the saved default. No builtin or other Swarm fallback.",
287
+ ],
288
+ },
289
+ "templates show": {
290
+ summary: "Show one template, its exact targets and declared parameters",
291
+ arguments: [
292
+ "NAME Safe relative template Name; nested names are supported.",
293
+ ],
294
+ options: [
295
+ "--refresh / --no-refresh Refresh HEAD now / allow a valid cached snapshot.",
296
+ ],
297
+ examples: ["ipab --swarm work templates show node"],
298
+ },
299
+ "templates set": {
300
+ summary:
301
+ "Publish one validated Template Bundle with exact Name conflict checks",
302
+ arguments: [
303
+ "NAME Safe relative template Name.",
304
+ "SOURCE Exact Template CID, self-contained CAR or explicit manifest directory; no URI, build or hooks.",
305
+ ],
306
+ options: [
307
+ "--expect OLD_TARGET_CID Required to replace an occupied Name; use its exact target CID, including an Artifact wrapper.",
308
+ ],
309
+ examples: [
310
+ "ipab --swarm work templates set team/node ./template.car",
311
+ "ipab templates set node TEMPLATE_CID --expect OLD_TARGET_CID",
312
+ ],
313
+ notes: [
314
+ "Publishes an ordinary Artifact and preserves publication history and content retention.",
315
+ ],
316
+ },
317
+ "templates remove": {
318
+ summary: "Remove only one template Name, without deleting content",
319
+ arguments: ["NAME Safe relative template Name."],
320
+ options: [
321
+ "--expect OLD_TARGET_CID Required exact current Name target CID.",
322
+ ],
323
+ examples: [
324
+ "ipab --swarm work templates remove team/node --expect OLD_TARGET_CID",
325
+ ],
326
+ notes: [
327
+ "Missing Names are errors. Does not unpin, GC or delete content or history.",
328
+ ],
329
+ },
330
+ "skills list": {
331
+ summary: "List typed Skills and local installation status from one Swarm",
332
+ options: [
333
+ "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
334
+ "Global --json Emit machine-readable names, exact payload CIDs and status.",
335
+ ],
336
+ examples: ["ipab --swarm work skills list", "ipab --json skills list"],
337
+ notes: [
338
+ "Select one Swarm with global --swarm or swarm use; there is no --all.",
339
+ "Requires skillPath in the exact root State Bundle or legacy Meta type. Older v5 roots require a new seeded Swarm; only legacy v2/v3/v4 Meta can be explicitly replaced with --expect. No silent upgrades.",
340
+ ],
341
+ },
342
+ "skills sync": {
343
+ summary:
344
+ "Install reviewed Swarm Skills using the pinned official npx installer",
345
+ arguments: [
346
+ "NAMES Install identities, e.g. ipab code-review, or full shared Names such as ipab/skills/ipab. Resolved from one verified snapshot; omit for all Skills.",
347
+ ],
348
+ options: [
349
+ "--agent AGENT Repeatable globally supported agent ID; default is universal (~/.agents/skills).",
350
+ "--override-existing Replace non-IPAB-managed Skills and local edits at selected targets.",
351
+ "--dry-run Preview without invoking npx or changing installed Skills.",
352
+ "--yes Skip IPAB consent only; does not imply --override-existing.",
353
+ "--refresh / --no-refresh Refresh HEAD now / reuse a valid verified snapshot.",
354
+ ],
355
+ examples: [
356
+ "ipab --swarm work skills sync --dry-run",
357
+ "ipab skills sync ipab code-review --agent github-copilot --yes",
358
+ ],
359
+ notes: [
360
+ "Global installs only, through official skills@1.9.1 with --copy. Requires Node >=22.20.0.",
361
+ "Non-interactive execution requires --yes. Installer version, source, paths and agents are shown first.",
362
+ "No Skill hooks/scripts run. The trusted installer is not sandboxed. Telemetry and remote audits are disabled.",
363
+ "Non-IPAB installs and local edits require --override-existing. Cross-Swarm collisions and symlink/junction aliases remain protected. Removed sources are reported, not deleted.",
364
+ "Partial failures report individual results, preserve pending attribution and exit nonzero; retry the same sync.",
365
+ ],
366
+ },
367
+ profile: {
368
+ summary: "Read or update your account-wide public name and description",
369
+ examples: [
370
+ "ipab profile",
371
+ 'ipab profile --name Wei --description "Developer"',
372
+ 'ipab profile --description ""',
373
+ ],
374
+ options: [
375
+ "--name NAME Replace only your personal name.",
376
+ "--description TEXT Replace only your description; empty text clears it.",
377
+ ],
378
+ notes: [
379
+ "Independent of Swarm selection. Reading never creates an identity, persists a profile or activates a node.",
380
+ "An explicit update prepares a missing account identity without starting Kubo.",
381
+ "Updates persist locally first, then synchronize all registered memberships without changing network addresses. Partial failure exits nonzero and reports every result.",
382
+ "Retry the same profile update, or normally activate a failed membership to synchronize the saved profile.",
383
+ "First use preserves unanimous legacy values; conflicting fields require an explicit choice. New memberships adopt this same profile.",
384
+ ],
385
+ },
386
+ doctor: {
387
+ summary:
388
+ "Inspect device readiness without writes; explicitly authorize safe repairs",
389
+ examples: [
390
+ "ipab doctor",
391
+ "ipab doctor --fix",
392
+ "ipab --json doctor --fix --yes",
393
+ ],
394
+ options: [
395
+ "--fix Repair missing components, cache official archives to verify existing Kubo without reinstall, and authorize healthy compatible upgrades within ^0.43.2.",
396
+ "--yes Authorize planned repairs without prompting; requires --fix.",
397
+ ],
398
+ notes: [
399
+ "Always checks local state/configuration, managed Kubo, HOME identity, local Swarm registry, compatible updates and the CLI-bundled IPAB Skill for detected Agents.",
400
+ "--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.",
401
+ "Inspection never creates state, locks, credentials or caches. Official release metadata may be queried; unavailable updates are not claimed current.",
402
+ "Healthy current components are reused without download or confirmation. Fixed protected archive cache is automatic.",
403
+ "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.",
404
+ "Does not create Swarm repos, start or contact any daemon, deploy services or install login startup.",
405
+ ],
406
+ },
407
+ "swarm create": {
408
+ summary: "Create a swarm using the account HOME identity",
409
+ options: [
410
+ "--service URL Must match the protected pointers.service origin.",
411
+ "--resume OPERATION Recover the same saved create/idempotency result.",
412
+ "--name TEXT Initial mutable swarm name.",
413
+ "--description TEXT Initial mutable description.",
414
+ "--alias ALIAS Optional local registry alias (not the shared name).",
415
+ ],
416
+ examples: [
417
+ "ipab config set pointers.service https://service.example",
418
+ "ipab config set pointers.apiKey -",
419
+ "ipab swarm create",
420
+ ],
421
+ notes: [
422
+ "Creation uses the protected, origin-bound API key and owner possession proof.",
423
+ "Installs checksum-verified Kubo on demand; each Swarm has its own protected repo and ports.",
424
+ "Returns the public organization configuration URL; owner needs no certificate.",
425
+ ],
426
+ },
427
+ "swarm request": {
428
+ summary: "Save and export a signed self-contained membership Request",
429
+ examples: [
430
+ "ipab swarm request work",
431
+ "ipab swarm request CONFIG_URL --output request.json",
432
+ ],
433
+ options: [
434
+ "--pivot Request Pivot Member role (HEAD write + ScopeWriteReceipt issuer); defaults to ordinary.",
435
+ "--output FILE Export to a new file instead of stdout; never overwrites.",
436
+ ],
437
+ notes: [
438
+ "Verify the printed Owner fingerprint through an independent trusted channel before manually sending the Request file to the Owner.",
439
+ "Without --output, stdout is the signed Request JSON, including in --json mode.",
440
+ "With --output, reports the file on stderr; --json returns file, member and ownerFingerprint.",
441
+ "Retries export the exact saved Request without expiry.",
442
+ "No Invite, Response file, password or Join. Next normal use fetches and decrypts the approved package.",
443
+ "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.",
444
+ ],
445
+ },
446
+ "swarm approve": {
447
+ summary: "Owner signs a certificate for an exact request",
448
+ options: [
449
+ "--yes Explicit approval; required outside a TTY.",
450
+ "--pivot Also authorize this member to sign HEAD write receipts as a Pivot.",
451
+ "--again Explicit fresh approval of an old Request; history is advisory.",
452
+ ],
453
+ examples: [
454
+ "ipab --swarm work swarm approve request.json --yes",
455
+ "ipab --swarm work swarm approve request.json --pivot --yes",
456
+ "ipab --swarm work swarm approve - --yes < request.json",
457
+ ],
458
+ notes: [
459
+ "Use '-' to read Request JSON from stdin (maximum 16 KiB); --yes is required and no confirmation prompt reads stdin.",
460
+ "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.",
461
+ ],
462
+ },
463
+ "swarm pivot grant": {
464
+ summary: "Owner grants an approved member Pivot HEAD receipt authority",
465
+ options: ["--yes Explicit confirmation; required."],
466
+ examples: ["ipab --swarm work swarm pivot grant MEMBER_PUBLIC_KEY --yes"],
467
+ notes: [
468
+ "Re-issues the approved member's ScopeCertificate with current HEAD and profile write access and updates their approval envelope without rotating the epoch.",
469
+ "Exact-ID certificates are stateless with no expiry; revoking Pivot HEAD authority requires swarm exclude (epoch/HEAD rotation).",
470
+ ],
471
+ },
472
+ "swarm export": {
473
+ summary: "Re-export the same persisted Request",
474
+ examples: ["ipab --swarm work swarm export --output request.json"],
475
+ },
476
+ "swarm exclude": {
477
+ summary: "Owner removes a member with irreversible HEAD/key rotation",
478
+ examples: ["ipab --swarm work swarm exclude MEMBER_PUBLIC_KEY --yes"],
479
+ notes: [
480
+ "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.",
481
+ ],
482
+ },
483
+ "swarm resume": {
484
+ summary: "Owner resumes an interrupted organization switch",
485
+ examples: ["ipab --swarm work swarm resume"],
486
+ },
487
+ "swarm profile": {
488
+ summary: "Configure your selected Swarm's address and Pivot role",
489
+ options: [
490
+ "--pivot true|false Declare or withdraw this member's Pivot backbone role.",
491
+ ],
492
+ examples: [
493
+ "ipab --swarm work swarm profile --address /ip4/192.168.1.12/tcp/4001/p2p/PEER_ID",
494
+ "ipab --swarm work swarm profile --pivot true",
495
+ ],
496
+ notes: [
497
+ "Personal name/description are managed only by ipab profile, not this network configuration command.",
498
+ "Pivot provides backbone connectivity and durable published-content Pin service through daemon. Keep it online with sufficient storage.",
499
+ ],
500
+ },
501
+ "swarm members": {
502
+ summary: "List every public member, including the Owner",
503
+ options: [
504
+ "--refresh / --no-refresh Fetch public Variables now / reuse the saved inspection, fetching if missing.",
505
+ "--local Deprecated no-op; local daemon observations are always included.",
506
+ ],
507
+ examples: [
508
+ "ipab --swarm work swarm members",
509
+ "ipab --json swarm members --refresh",
510
+ ],
511
+ notes: [
512
+ "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.",
513
+ "PIVOT: - for ordinary members; selected, cooldown, unknown, self or candidate for declared Pivots. Selected means applied configuration, not connectivity.",
514
+ ],
515
+ },
516
+ "swarm status": {
517
+ summary: "Inspect cached Swarm directory, HEAD and local networking",
518
+ options: [
519
+ "--refresh / --no-refresh Fetch public Variables now / reuse the saved inspection, fetching if missing.",
520
+ "--local Deprecated no-op; never activates a node.",
521
+ ],
522
+ examples: [
523
+ "ipab swarm status",
524
+ "ipab --swarm work swarm status",
525
+ "ipab --swarm work swarm status --refresh",
526
+ ],
527
+ notes: [
528
+ "Default: reuse the inspection cache, fetching public Variables if missing. Refresh verifies Config, Scope, members, Profiles and HEAD, not connectivity or State content.",
529
+ "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.",
530
+ "State content is explicitly unavailable in inspection; use get ipab:/// to obtain the State Bundle.",
531
+ "Local connectivity is not global availability; a relay connection does not guarantee content transfer.",
532
+ ],
533
+ },
534
+ "swarm list": {
535
+ summary: "List local swarm registrations and the effective selection",
536
+ examples: ["ipab swarm list", "ipab --json swarm list"],
537
+ notes: ["Local only; does not verify remote membership or refresh HEAD."],
538
+ },
539
+ "swarm set": {
540
+ summary: "Set a local alias for a swarm configuration URL",
541
+ options: [
542
+ "--yes Authorize retargeting an existing alias without prompting.",
543
+ ],
544
+ examples: [
545
+ "ipab swarm set work CONFIG_URL",
546
+ "ipab swarm set work OTHER_CONFIG_URL --yes",
547
+ ],
548
+ notes: [
549
+ "Local only; no network, account identity or approved membership required.",
550
+ "Setting the same mapping is idempotent. One alias per URL; a new alias for that URL replaces its old alias.",
551
+ "Retargeting an alias requires confirmation or --yes. Keeps the old URL registered without that alias; credentials, caches and the saved default URL are unchanged.",
552
+ "Not a membership grant. The first registration becomes the saved default only if none exists.",
553
+ ],
554
+ },
555
+ "swarm use": {
556
+ summary: "Save a registered swarm as the current default",
557
+ examples: ["ipab swarm use work"],
558
+ notes: ["Local only. --swarm still overrides the saved default."],
559
+ },
560
+ "swarm remove": {
561
+ summary: "Forget a local registration without revoking membership",
562
+ examples: ["ipab swarm remove work"],
563
+ notes: [
564
+ "Preserves credentials, content and remote membership. Clears a matching saved default without selecting a replacement.",
565
+ ],
566
+ },
567
+ "swarm update": {
568
+ summary: "Owner updates public organization information",
569
+ options: [
570
+ "--name TEXT Replace the shared display name; empty text clears it.",
571
+ "--description TEXT Replace the shared description; empty text clears it.",
572
+ ],
573
+ examples: [
574
+ 'ipab --swarm work swarm update --name "Team" --description "Shared workspace"',
575
+ 'ipab swarm update --description ""',
576
+ ],
577
+ notes: [
578
+ "Requires at least one field. Members can change only their own profile.",
579
+ "Content-CID CAS prevents overwriting concurrent organization changes.",
580
+ "Shared name changes do not rename local registry aliases.",
581
+ ],
582
+ },
583
+ search: {
584
+ summary: "Search formal Names in the current swarm",
585
+ arguments: [
586
+ "QUERY Case-insensitive literal name substring, 1..256 characters.",
587
+ ],
588
+ options: [
589
+ "--all Search all registered swarms; conflicts with --current and --swarm.",
590
+ "--current Explicitly select the default search scope; conflicts with --swarm.",
591
+ "--prefix PATH Restrict v7 search results to paths under PATH.",
592
+ "--kind KIND Filter v7 search results by kind: all, bundle, dir, or file.",
593
+ "--schema CID Filter v7 search results to Bundles with exact schema CID.",
594
+ "--limit N Maximum number of results per v7 swarm (1..100, default 20).",
595
+ "--offset N Zero-based result offset for v7 pagination (default 0).",
596
+ "--refresh Refresh HEAD for every swarm in the search scope.",
597
+ "--no-refresh Override swarm.forceRefresh and use valid cached headers.",
598
+ ],
599
+ examples: [
600
+ "ipab search hello",
601
+ "ipab search hello --all",
602
+ "ipab --swarm work search hello --refresh",
603
+ ],
604
+ notes: [
605
+ "Searches only --swarm or the saved current swarm by default. Use --all to search every registration.",
606
+ "Valid caches use local Names; absent/expired caches refresh. Active Name pins may synchronize content.",
607
+ "Refresh reads public configuration and HEAD; private networking is activated only for missing content.",
608
+ "No matches is success, not a reason to refresh valid caches. Any failed swarm fails the whole search.",
609
+ "Text uses local alias URIs when available; JSON references use full configuration URLs for cross-device sharing.",
610
+ ],
611
+ },
612
+ publish: {
613
+ summary: "Protect content locally and publish a shared Swarm Name",
614
+ options: [
615
+ "--expect CID Exact old Name target CID, required for iteration.",
616
+ "--snapshot Name ordinary content without an Artifact; initial only.",
617
+ ],
618
+ examples: [
619
+ "ipab --swarm work publish apps/hello app.car",
620
+ "ipab publish apps/hello APP_CID --expect OLD_APP_CID",
621
+ "ipab publish notes/readme ./README.md",
622
+ ],
623
+ notes: [
624
+ "SOURCE is an exact Bundle CID, CAR, regular file or directory. No compiler, hooks, install or App execution.",
625
+ "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.",
626
+ "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.",
627
+ "Different-name CAS contention is rebased; same-name edits conflict (exit 3).",
628
+ "Kubo pin confirmation precedes HEAD; it does not prove a remote device is online.",
629
+ ],
630
+ },
631
+ get: {
632
+ summary: "Verify and unpack Bundle content without executing it",
633
+ options: [
634
+ "--raw Select the Artifact node instead of its value.",
635
+ "--refresh Refresh the shared Name's swarm HEAD.",
636
+ "--no-refresh Override swarm.forceRefresh and use valid cached headers.",
637
+ "-o, --output DIRECTORY New or empty directory; defaults to a unique temporary directory.",
638
+ ],
639
+ examples: [
640
+ "ipab --json get ipab:///apps/hello -o hello-app",
641
+ "ipab get ipab://work/apps/hello -o hello-app",
642
+ "ipab get CONTENT_CID",
643
+ "ipab get --raw RELEASE_CID",
644
+ ],
645
+ notes: [
646
+ "Stdout contains only the absolute directory path; --json also returns content and original target CIDs.",
647
+ "Temporary exports remain after exit; copy before cleanup, not symlink. Use --output for a persistent destination.",
648
+ "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
649
+ "Copy the reference from ipab search, or percent-encode the entire configuration URL and each Name path segment separately.",
650
+ "Does not install, build, edit, or automatically retrieve associated source.",
651
+ ],
652
+ },
111
653
  "store usage": {
112
654
  summary: "Query cached and recursively pinned block bytes",
113
655
  examples: ["ipab store usage", "ipab --json store usage"],
@@ -124,37 +666,48 @@ const commandHelp: Record<
124
666
  "Does not unpin, clear history, delete unknown files or request Kubo daemon GC.",
125
667
  ],
126
668
  },
127
- init: {
128
- summary: "Create files from a Template Bundle (default: Node App project)",
129
- arguments: ["NAME Project name; DIR defaults to NAME (new/empty only)."],
669
+ "templates render": {
670
+ summary: "Render a template's project files into a new or empty folder",
671
+ arguments: [
672
+ "TEMPLATE Explicit Swarm selector, directory, CAR, exact CID or IPAB URI.",
673
+ "NAME Project name parameter; DIR defaults to NAME (new/empty only).",
674
+ ],
130
675
  options: [
131
- "--template TEMPLATE node (default), web-app, directory, CAR, CID or pin.",
676
+ "--description TEXT Set the declared description parameter.",
677
+ "--refresh / --no-refresh Refresh Swarm HEAD now / allow its valid cached snapshot.",
132
678
  "--param KEY=VALUE Template parameter; repeatable. Strings are literal;",
133
679
  " other parameter types use JSON.",
134
680
  ],
135
681
  examples: [
136
- "ipab init hello",
137
- "ipab init dashboard --template web-app",
138
- "ipab init hello --param description=Demo",
682
+ "ipab templates render node hello",
683
+ "ipab templates render web-app dashboard --param webAppDependency=0.1.0-rc.2",
684
+ "ipab templates render ./template.car hello --description Demo",
685
+ ],
686
+ notes: [
687
+ "Short selectors resolve through the selected Swarm's typed root configuration (legacy v2/v3/v4 use Meta Name ipab); no builtin fallback.",
688
+ "Explicit directory, CAR and available exact CID work offline without a Swarm.",
689
+ "Does not install dependencies or execute template code.",
139
690
  ],
140
- notes: ["Does not install dependencies or execute template code."],
141
691
  },
142
692
  build: {
143
- summary: "Build an App CAR from a project",
144
- arguments: ["DIR Project directory (default: current directory)."],
693
+ summary: "Assemble any Bundle using ipab.build.yaml (no compilation)",
694
+ arguments: [
695
+ "SOURCE Recipe file or Bundle directory (default: current directory).",
696
+ ],
145
697
  options: [
146
- "-o, --output FILE Destination (default: dist/app.car).",
698
+ "-o, --output FILE Destination (default: dist/bundle.car).",
147
699
  "--replace Allow replacing existing regular artifacts.",
148
- "--no-import Write CAR files without importing the App into Store.",
149
- "--with-source Include a separate source CAR (default: enabled).",
150
- "--without-source Omit source CAR; conflicts with --with-source.",
700
+ "--no-import Write the CAR without importing the Bundle into Store.",
701
+ ],
702
+ examples: [
703
+ "ipab build prepared-app",
704
+ "ipab build ipab.build.yaml --replace",
151
705
  ],
152
- examples: ["ipab build", "ipab build hello --replace --without-source"],
153
706
  notes: [
154
- "Uses local tsc and bundles Node CommonJS; ipab.yaml configures the build.",
155
- "Explicit ipab-prebuild strategy executes trusted project code.",
156
- "Source follows project .gitignore rules; review private files before sharing.",
157
- "Imports only the App, without pinning; source needs separate import/retention.",
707
+ "Recipe explicitly maps source files and exact CID imports to target paths.",
708
+ "Instance paths come from .bundle.yaml; the referenced file defines the type. Imported DAG identities are preserved.",
709
+ "Legacy App ipab.yaml is rejected; use project preparation tools separately.",
710
+ "Select explicit files; review private files before providing Bundles.",
158
711
  "Store failures preserve the CAR; retry with ipab bundle import FILE.car.",
159
712
  ],
160
713
  },
@@ -169,7 +722,7 @@ const commandHelp: Record<
169
722
  ],
170
723
  examples: [
171
724
  "ipab bundle build note",
172
- "ipab bundle build types\\.bundle.yaml --schema-only",
725
+ "ipab bundle build types\\.bundle-type.yaml --schema-only",
173
726
  ],
174
727
  notes: [
175
728
  "Imports into the configured Store without pinning or executing Apps.",
@@ -178,7 +731,9 @@ const commandHelp: Record<
178
731
  },
179
732
  "bundle inspect": {
180
733
  summary: "Inspect a Bundle or type definition",
181
- arguments: ["SOURCE Directory, definition file, CAR, CID or named pin."],
734
+ arguments: [
735
+ "SOURCE Directory, definition file, CAR, CID or packaged builtin reference.",
736
+ ],
182
737
  examples: ["ipab bundle inspect note\\dist\\bundle.car"],
183
738
  notes: ["Does not execute Apps, import content or create pins."],
184
739
  },
@@ -188,24 +743,27 @@ const commandHelp: Record<
188
743
  examples: ["ipab bundle import hello\\dist\\app.car"],
189
744
  notes: [
190
745
  "Repeated imports are safe; no App execution or daemon startup.",
191
- "Does not pin or retain content. Use pin add for persistent retention.",
746
+ "Does not pin or retain content. Use pin CID for persistent retention.",
192
747
  ],
193
748
  },
194
749
  exec: {
195
- summary: "Run an App by CID or named pin",
750
+ summary: "Run an App by exact CID or Swarm IPAB URI",
196
751
  arguments: [
197
752
  "APP_ARGS Everything after APP is passed verbatim, including --help.",
198
753
  ],
199
754
  options: [
200
755
  "--log Record stdout/stderr; must precede APP. Requires history enabled.",
756
+ "--refresh Refresh the shared Name's swarm HEAD; must precede APP.",
757
+ "--no-refresh Override swarm.forceRefresh; must precede APP.",
201
758
  ],
202
759
  examples: [
203
760
  "ipab exec reader",
204
- "ipab exec reader --help",
205
761
  "ipab exec --log reader",
762
+ "ipab exec ipab://work/apps/hello --help",
206
763
  ],
207
764
  notes: [
208
765
  "Apps are NOT sandboxed; run only Apps you trust.",
766
+ "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
209
767
  "History stores argv by default; do not put secrets in arguments.",
210
768
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
211
769
  "--json is not supported; App stdio is passed through.",
@@ -213,90 +771,127 @@ const commandHelp: Record<
213
771
  },
214
772
  open: {
215
773
  summary: "Open content with its registered App",
216
- arguments: ["CONTENT Bundle CID or named pin."],
217
- options: ["--log Record stdout/stderr; requires history enabled."],
218
- examples: ["ipab open CONTENT_CID", "ipab open --log my-note"],
774
+ arguments: [
775
+ "CONTENT Local Bundle directory, Bundle CID, packaged builtin reference or Swarm IPAB URI.",
776
+ ],
777
+ options: [
778
+ "--log Record stdout/stderr; requires history enabled.",
779
+ "--raw Open the Artifact node rather than its value.",
780
+ "--refresh Refresh the shared Name's swarm HEAD.",
781
+ "--no-refresh Override swarm.forceRefresh and use valid cached headers.",
782
+ ],
783
+ examples: [
784
+ "ipab open .",
785
+ "ipab open --log --refresh ipab:///documents/readme",
786
+ "ipab open ipab:///",
787
+ ],
219
788
  notes: [
220
789
  "Requires a saved registration and App support for the exact content type.",
790
+ "Local directories must contain valid Bundle metadata; quote paths with spaces. Snapshots honor .bundle-ignore without compiling, publishing, pinning, writing CAR files or updating the source.",
791
+ "An empty URI Name (ipab:/// or ipab://ALIAS/) resolves to that Swarm's verified root State CID, not its publication CID. The root binding cannot be overwritten.",
792
+ "Uses only the content URI's Swarm, otherwise --swarm, otherwise swarm.default. A selected Swarm is required.",
793
+ "A registered App's retrieval, compatibility or execution failure never triggers fallback.",
794
+ "Legacy User registrations are inactive and preserved in the state database's legacy_user_registrations table; review them before explicit Swarm registration.",
795
+ "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
221
796
  "Apps are NOT sandboxed; run only Apps you trust.",
222
797
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
223
798
  "--json is not supported; App stdio is passed through.",
224
799
  ],
225
800
  },
226
- "pin add": {
227
- summary: "Verify, retain and name a Bundle",
801
+ pin: {
802
+ summary: "Retain an immutable CID or follow a shared Swarm Name",
228
803
  arguments: [
229
- "NAME Unused short name.",
230
- "CID Exact Bundle CID, not another pin name or a standalone type block.",
804
+ "REF Exact Bundle CID or ipab://SWARM/NAME; no local content aliases.",
805
+ ],
806
+ options: [
807
+ "--refresh / --no-refresh Refresh shared HEAD now / allow its valid cached snapshot.",
808
+ ],
809
+ examples: [
810
+ "ipab pin APP_CID",
811
+ "ipab pin ipab://work/apps/reader",
812
+ "ipab pin list",
231
813
  ],
232
- examples: ["ipab pin add reader APP_CID"],
233
814
  notes: [
234
815
  "Validates a complete Bundle and retains its full DAG in the configured Store.",
235
- "Does not execute or trust Apps, install dependencies or start a daemon.",
816
+ "A CID stays fixed. A shared Name saves its canonical configuration URL and exact Name, refreshing on related Swarm HEAD reads/sync, not continuously.",
817
+ "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.",
818
+ "Does not execute Apps or install dependencies. Shared Names connect to their Swarm content source only as needed.",
236
819
  "The builtin namespace is read-only.",
237
820
  ],
238
821
  },
239
- "pin delete": {
240
- summary: "Remove a user pin and release its retention",
241
- examples: ["ipab pin delete reader"],
822
+ unpin: {
823
+ summary: "Release a CID pin or stop following a shared Name",
824
+ examples: ["ipab unpin APP_CID", "ipab unpin ipab://work/apps/reader"],
242
825
  notes: [
243
826
  "Releases only this pin's ownership on its original backend; no block deletion or GC.",
244
- "Does not change registrations or history. Built-in pins are read-only.",
827
+ "Never re-resolves a shared Name to release content. Uses only saved actual roots. Missing pins are success.",
828
+ "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.",
829
+ "Publication/history owners are independent; --snapshot payloads remain recursively retained by publication history after ordinary unpin.",
245
830
  ],
246
831
  },
247
832
  "pin list": {
248
- summary: "List user and built-in pins",
249
- options: [
250
- "--type TYPE Exact type CID or the name of a Bundle pin of that type.",
251
- ],
252
- examples: ["ipab pin list", "ipab pin list --type reader"],
833
+ summary: "List local retention, following Names and packaged built-ins",
834
+ examples: ["ipab pin list"],
253
835
  notes: [
254
- "Unfinished operations and legacy non-Bundle pins are reported separately.",
255
- "Legacy retention is preserved; use pin delete to explicitly release it.",
836
+ "Includes pending/stale/missing records and inactive archived local pin names.",
837
+ "Legacy retention is preserved; use unpin EXACT_CID to explicitly release its archived holders.",
256
838
  "Reads local registrations and packaged built-ins, not live node status.",
257
839
  ],
258
840
  },
259
841
  "pin show": {
260
- summary: "Show a pin's CID and type metadata",
261
- examples: ["ipab pin show reader", "ipab pin show builtin:template.node"],
842
+ summary: "Show saved retention and following status",
843
+ examples: ["ipab pin show APP_CID"],
262
844
  notes: [
263
845
  "Reads local metadata; built-in pins do not claim user Store retention.",
264
846
  ],
265
847
  },
266
- "pin rename": {
267
- summary: "Rename a user pin without changing its content",
268
- examples: ["ipab pin rename reader my-reader"],
848
+ "register list": {
849
+ summary: "List content-type associations in the current or selected Swarm",
850
+ options: [
851
+ "--swarm URL_OR_ALIAS Read only this Swarm registry; specify at most once.",
852
+ ],
853
+ examples: ["ipab register list", "ipab register list --swarm work"],
269
854
  notes: [
270
- "NEW_NAME must be unused. Built-in pins are read-only.",
271
- "CID, ownership, registrations and history are unchanged.",
855
+ "Without explicit --swarm, reads the saved default Swarm. Select one with --swarm or ipab swarm use.",
856
+ "Legacy User registrations are inactive and preserved in legacy_user_registrations; no automatic upload or deletion.",
272
857
  ],
273
858
  },
274
- "register list": {
275
- summary: "List saved content-type associations",
276
- examples: ["ipab register list"],
277
- },
278
859
  "register set": {
279
860
  summary: "Associate a content type with an App",
280
861
  arguments: [
281
862
  "SCHEMA Exact type CID or builtin:node-app.v1.",
282
- "APP App CID or named pin; the exact CID is saved.",
283
- "TEMPLATE App argv after --; must contain a whole argument % (default: %).",
863
+ "APP App CID or Swarm IPAB URI; the exact CID is saved.",
864
+ ],
865
+ options: [
866
+ "--replace Allow changing an existing association.",
867
+ "--swarm URL_OR_ALIAS Write this Swarm registry; repeat for multiple Swarms.",
284
868
  ],
285
- options: ["--replace Allow changing an existing association."],
286
869
  examples: [
287
- "ipab register set SCHEMA_CID reader",
288
- "ipab register set SCHEMA_CID reader '--' '--cid' '%'",
870
+ "ipab register set SCHEMA_CID APP_CID",
871
+ "ipab register set SCHEMA_CID ipab:///apps/reader --swarm work --swarm team",
289
872
  ],
290
873
  notes: [
291
- "Replaces only the whole % argument with the content CID; no shell expansion.",
874
+ "Writes the Name META.registryPath/TYPE_CID directly to the App CID. Open passes only the content CID.",
875
+ "Custom per-association argv is unsupported; adapt the App or use ipab exec APP_CID ARGS.",
292
876
  "Does not verify App type support; open checks it before execution.",
877
+ "Without explicit --swarm, writes the saved default Swarm. Swarm writes require HEAD write access.",
878
+ "Multiple Swarms commit sequentially, not atomically; failures report completed targets.",
293
879
  ],
294
880
  },
295
881
  "register remove": {
296
882
  summary: "Remove a saved content-type association",
297
883
  arguments: ["SCHEMA Exact type CID or builtin:node-app.v1."],
298
- examples: ["ipab register remove SCHEMA_CID"],
299
- notes: ["Does not remove Apps, pins or content."],
884
+ options: [
885
+ "--swarm URL_OR_ALIAS Remove from this Swarm registry; repeat for multiple Swarms.",
886
+ ],
887
+ examples: [
888
+ "ipab register remove SCHEMA_CID",
889
+ "ipab register remove SCHEMA_CID --swarm work",
890
+ ],
891
+ notes: [
892
+ "Without explicit --swarm, removes from the saved default Swarm. Multiple Swarm edits are not atomic.",
893
+ "Does not remove Apps, pins or content.",
894
+ ],
300
895
  },
301
896
  "config get": {
302
897
  summary: "Show effective configuration",
@@ -306,11 +901,15 @@ const commandHelp: Record<
306
901
  "config set": {
307
902
  summary: "Save a local configuration value",
308
903
  examples: [
904
+ "ipab config set pointers.apiKey -",
309
905
  "ipab config set store.gateway http://127.0.0.1:8080",
310
906
  "ipab config set history.enabled false",
311
907
  ],
312
908
  notes: [
313
909
  "store.gateway is a read-only HTTP gateway; blocks, pins and GC remain local.",
910
+ "pointers.service is a canonical HTTPS origin (HTTP loopback allowed).",
911
+ "pointers.apiKey is accepted only through stdin using VALUE '-'; queries and confirmations redact it.",
912
+ "SQLite state is account-only even without a key. Reading or saving a nonempty key rechecks Unix modes or Windows ACLs.",
314
913
  ],
315
914
  },
316
915
  "config reset": {
@@ -320,7 +919,7 @@ const commandHelp: Record<
320
919
  "history list": {
321
920
  summary: "List execution history",
322
921
  options: [
323
- "--app APP Filter by App CID or named pin.",
922
+ "--app APP Filter by exact App CID.",
324
923
  "--status STATUS succeeded, failed or cancelled.",
325
924
  "--since TIME Include runs ended at or after TIME.",
326
925
  "--until TIME Include runs ended before TIME.",
@@ -343,7 +942,7 @@ const commandHelp: Record<
343
942
  "history remove": {
344
943
  summary: "Remove execution records and their logs",
345
944
  options: [
346
- "--app APP Filter by App CID or named pin.",
945
+ "--app APP Filter by exact App CID.",
347
946
  "--status STATUS succeeded, failed or cancelled.",
348
947
  "--since TIME Include runs ended at or after TIME.",
349
948
  "--until TIME Include runs ended before TIME.",
@@ -363,7 +962,8 @@ const commandHelp: Record<
363
962
 
364
963
  export function help(path = ""): string {
365
964
  const globalOptions = `Global options (before COMMAND):
366
- --state-dir PATH Set the local state directory
965
+ --swarm URL|ALIAS Select Swarm (defaults to built-in local Swarm or saved swarm.default; URI swarm takes precedence)
966
+ --state-dir PATH Set a dedicated, account-private local state directory
367
967
  --store-gateway URL Use a read-only upstream HTTP gateway
368
968
  --json Output management/development metadata, not App stdio`;
369
969
  const footer =
@@ -378,12 +978,20 @@ Run Apps:
378
978
  open ${commandHelp.open!.summary}
379
979
 
380
980
  Create:
381
- init ${commandHelp.init!.summary}
981
+ templates ${groups.templates}
382
982
  build ${commandHelp.build!.summary}
383
983
  bundle ${groups.bundle}
384
984
 
385
985
  Manage:
986
+ doctor ${commandHelp.doctor!.summary}
987
+ profile ${commandHelp.profile!.summary}
988
+ swarm ${groups.swarm}
989
+ skills ${groups.skills}
990
+ search Search formal Names in the current swarm
991
+ publish ${commandHelp.publish!.summary}
992
+ get ${commandHelp.get!.summary}
386
993
  pin ${groups.pin}
994
+ unpin ${commandHelp.unpin!.summary}
387
995
  register ${groups.register}
388
996
  config ${groups.config}
389
997
  store ${groups.store}
@@ -404,9 +1012,39 @@ ${footer}`;
404
1012
  return [
405
1013
  `${topic.summary}.\n\nUsage: ipab [GLOBAL_OPTIONS] ${usage}`,
406
1014
  ...(topic.arguments ? [section("Arguments", topic.arguments)] : []),
407
- ...(topic.options ? [section("Options", topic.options)] : []),
1015
+ ...(topic.options
1016
+ ? [
1017
+ section(
1018
+ "Options",
1019
+ topic.options.map((line) =>
1020
+ line.startsWith("--refresh")
1021
+ ? `${line} Legacy aliases: --force/--no-force.`
1022
+ : line,
1023
+ ),
1024
+ ),
1025
+ ]
1026
+ : []),
408
1027
  section("Examples", topic.examples),
409
- ...(topic.notes ? [section("Notes", topic.notes)] : []),
1028
+ ...([
1029
+ "swarm status",
1030
+ "swarm members",
1031
+ "swarm update",
1032
+ "swarm resume",
1033
+ "swarm profile",
1034
+ "swarm export",
1035
+ "swarm approve",
1036
+ "swarm pivot grant",
1037
+ "swarm exclude",
1038
+ ].includes(path)
1039
+ ? [
1040
+ section("Notes", [
1041
+ ...(topic.notes ?? []),
1042
+ "Select only with global --swarm URL_OR_ALIAS (before the command), or the saved swarm.default. Neither means an error.",
1043
+ ]),
1044
+ ]
1045
+ : topic.notes
1046
+ ? [section("Notes", topic.notes)]
1047
+ : []),
410
1048
  `\n\n-h, --help shows this help. Global options: see 'ipab --help'.\n${footer}`,
411
1049
  ].join("");
412
1050
  }
@@ -435,6 +1073,25 @@ function printable(text: string): string {
435
1073
  .join("");
436
1074
  }
437
1075
 
1076
+ export function formatSearchResults(
1077
+ matches: Awaited<ReturnType<typeof searchNames>>["matches"],
1078
+ ): string {
1079
+ return matches.length
1080
+ ? alignedRows(
1081
+ matches.map((match) => [
1082
+ match.alias ?? match.swarm,
1083
+ match.name,
1084
+ match.targetCid,
1085
+ ]),
1086
+ )
1087
+ .map((row, index) => {
1088
+ const match = matches[index]!;
1089
+ return `${row}\n ipab get ${formatNameReference(match.alias ?? match.swarm, match.name)}`;
1090
+ })
1091
+ .join("\n")
1092
+ : "No matching Names.";
1093
+ }
1094
+
438
1095
  function runTime(value: string, field: "start" | "end"): string {
439
1096
  const date = new Date(value);
440
1097
  if (!Number.isFinite(date.getTime()))
@@ -477,26 +1134,24 @@ function storageBytes(bytes: number): string {
477
1134
  : `${scaled.toLocaleString("en-US", { maximumFractionDigits: 2 })} ${units[unit]} (${exact} bytes)`;
478
1135
  }
479
1136
 
480
- function table(headers: string[], rows: string[][], empty: string): string {
481
- if (!rows.length) return empty;
1137
+ function alignedRows(rows: string[][]): string[] {
482
1138
  const cells = rows.map((row) => row.map(printable));
483
- const widths = headers.map((header, column) =>
484
- cells.reduce(
485
- (width, row) => Math.max(width, stringWidth(row[column]!)),
486
- stringWidth(header),
487
- ),
1139
+ const widths = (cells[0] ?? []).map((_, column) =>
1140
+ cells.reduce((width, row) => Math.max(width, stringWidth(row[column]!)), 0),
488
1141
  );
489
- return [headers, ...cells]
490
- .map((row) =>
491
- row
492
- .map((cell, column) =>
493
- column === headers.length - 1
494
- ? cell
495
- : cell.padEnd(cell.length + widths[column]! - stringWidth(cell)),
496
- )
497
- .join(" "),
498
- )
499
- .join("\n");
1142
+ return cells.map((row) =>
1143
+ row
1144
+ .map((cell, column) =>
1145
+ column === widths.length - 1
1146
+ ? cell
1147
+ : cell.padEnd(cell.length + widths[column]! - stringWidth(cell)),
1148
+ )
1149
+ .join(" "),
1150
+ );
1151
+ }
1152
+
1153
+ function table(headers: string[], rows: string[][], empty: string): string {
1154
+ return rows.length ? alignedRows([headers, ...rows]).join("\n") : empty;
500
1155
  }
501
1156
 
502
1157
  function runDetails(record: RunRecord): string {
@@ -536,9 +1191,17 @@ interface Parsed {
536
1191
  options: Record<string, string | boolean>;
537
1192
  template?: string[];
538
1193
  parameters?: string[];
1194
+ registrySwarms?: string[];
1195
+ agents?: string[];
539
1196
  help: boolean;
540
1197
  version: boolean;
541
1198
  }
1199
+ function validateRefreshOptions(options: Parsed["options"]): void {
1200
+ const positive = ["refresh", "force"].find((key) => options[key]);
1201
+ const negative = ["no-refresh", "no-force"].find((key) => options[key]);
1202
+ if (positive && negative)
1203
+ syntax(`--${positive} and --${negative} are mutually exclusive.`);
1204
+ }
542
1205
 
543
1206
  async function closeStore(
544
1207
  store: IpfsStore | undefined,
@@ -559,6 +1222,7 @@ async function closeStore(
559
1222
  export function parse(argv: readonly string[]): Parsed {
560
1223
  const tokens = [...argv];
561
1224
  const flags: GlobalOptions = { json: false };
1225
+ const swarms: string[] = [];
562
1226
  while (tokens[0]?.startsWith("-")) {
563
1227
  const flag = tokens.shift()!;
564
1228
  if (flag === "-h" || flag === "--help")
@@ -586,16 +1250,31 @@ export function parse(argv: readonly string[]): Parsed {
586
1250
  syntax(
587
1251
  "Store RPC is no longer supported. Use --store-gateway with an HTTP gateway URL; existing Kubo pins are not migrated.",
588
1252
  );
589
- else if (flag === "--state-dir" || flag === "--store-gateway") {
1253
+ else if (
1254
+ flag === "--state-dir" ||
1255
+ flag === "--store-gateway" ||
1256
+ flag === "--swarm"
1257
+ ) {
590
1258
  const value = tokens.shift();
591
1259
  if (!value || value.startsWith("-")) syntax(`${flag} needs a value.`);
592
1260
  if (flag === "--state-dir") flags.stateDir = value;
593
- else {
1261
+ else if (flag === "--swarm") {
1262
+ flags.swarm = value;
1263
+ swarms.push(value);
1264
+ } else {
594
1265
  flags.storeGateway = publicUrl(value);
595
1266
  }
596
1267
  } else syntax(`Unknown global option "${flag}".`);
597
1268
  }
598
1269
  const group = tokens.shift() ?? "";
1270
+ if (group === "init")
1271
+ syntax(
1272
+ "Root init was removed. Use ipab templates render TEMPLATE NAME [DIR]; TEMPLATE is the first positional argument, not --template.",
1273
+ );
1274
+ if (group === "templates" && swarms.length > 1)
1275
+ syntax("Templates accepts only one global --swarm, before the command.");
1276
+ if (group === "daemon" && swarms.length)
1277
+ syntax("daemon manages all registered Swarms and does not accept --swarm.");
599
1278
  const result: Parsed = {
600
1279
  flags,
601
1280
  path: group,
@@ -603,14 +1282,22 @@ export function parse(argv: readonly string[]): Parsed {
603
1282
  options: {},
604
1283
  help: !group,
605
1284
  version: false,
1285
+ ...(group === "register" ? { registrySwarms: swarms } : {}),
606
1286
  };
607
1287
  if (!group) return result;
608
1288
  if (group === "exec") {
609
1289
  if (flags.json) syntax("--json is not supported for exec/open.");
610
- if (tokens[0] === "--log") {
611
- result.options.log = true;
612
- tokens.shift();
1290
+ while (
1291
+ ["--log", "--force", "--no-force", "--refresh", "--no-refresh"].includes(
1292
+ tokens[0] ?? "",
1293
+ )
1294
+ ) {
1295
+ const option = tokens.shift()!.slice(2);
1296
+ if (Object.hasOwn(result.options, option))
1297
+ syntax(`Duplicate option --${option}.`);
1298
+ result.options[option] = true;
613
1299
  }
1300
+ validateRefreshOptions(result.options);
614
1301
  if (tokens[0] === "-h" || tokens[0] === "--help") {
615
1302
  result.help = true;
616
1303
  return result;
@@ -620,21 +1307,66 @@ export function parse(argv: readonly string[]): Parsed {
620
1307
  result.positional = tokens;
621
1308
  return result;
622
1309
  }
623
- if (!["open", "init", "build"].includes(group)) {
1310
+ if (
1311
+ ![
1312
+ "open",
1313
+ "build",
1314
+ "publish",
1315
+ "get",
1316
+ "search",
1317
+ "doctor",
1318
+ "daemon",
1319
+ "profile",
1320
+ "unpin",
1321
+ ].includes(group)
1322
+ ) {
624
1323
  if (
625
- !["bundle", "pin", "register", "config", "history", "store"].includes(
626
- group,
627
- )
1324
+ ![
1325
+ "bundle",
1326
+ "pin",
1327
+ "register",
1328
+ "templates",
1329
+ "config",
1330
+ "history",
1331
+ "store",
1332
+ "swarm",
1333
+ "skills",
1334
+ ].includes(group)
628
1335
  )
629
- syntax(`Unknown command "${group}".`);
630
- if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
1336
+ syntax(
1337
+ `Unknown command "${group}".${group === "setup" ? " Run ipab doctor to inspect, or ipab doctor --fix to prepare this device." : " Run ipab --help."}`,
1338
+ );
1339
+ if (group === "pin" && !["list", "show"].includes(tokens[0] ?? "")) {
1340
+ if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
1341
+ result.help = true;
1342
+ return result;
1343
+ }
1344
+ } else if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
631
1345
  result.help = true;
632
1346
  return result;
1347
+ } else result.path = `${group} ${tokens.shift()!}`;
1348
+ if (result.path === "swarm pivot") {
1349
+ if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
1350
+ result.help = true;
1351
+ return result;
1352
+ }
1353
+ result.path = `swarm pivot ${tokens.shift()!}`;
633
1354
  }
634
- result.path = `${group} ${tokens.shift()!}`;
635
1355
  } else if (group === "open" && flags.json)
636
1356
  syntax("--json is not supported for exec/open.");
1357
+ else if (group === "daemon" && tokens[0] === "ui") {
1358
+ tokens.shift();
1359
+ result.path = "daemon ui";
1360
+ }
1361
+ if (result.path === "swarm add")
1362
+ syntax(
1363
+ "swarm add was removed. Use ipab swarm set ALIAS CONFIG_URL for local naming, then ipab swarm request ALIAS to request membership.",
1364
+ );
637
1365
  if (!commands[result.path]) syntax(`Unknown command "${result.path}".`);
1366
+ if (group === "skills" && swarms.length > 1)
1367
+ syntax(
1368
+ "Skills operations select exactly one Swarm; repeated --swarm is not supported.",
1369
+ );
638
1370
  const separator = result.path === "register set" ? tokens.indexOf("--") : -1;
639
1371
  if (separator >= 0) result.template = tokens.splice(separator + 1);
640
1372
  if (separator >= 0) tokens.splice(separator);
@@ -642,66 +1374,230 @@ export function parse(argv: readonly string[]): Parsed {
642
1374
  result.help = true;
643
1375
  return result;
644
1376
  }
645
- const booleans =
646
- result.path === "bundle build"
647
- ? ["replace", "schema-only", "no-import"]
648
- : result.path === "build"
649
- ? ["replace", "no-import", "with-source", "without-source"]
650
- : result.path === "register set"
651
- ? ["replace"]
652
- : result.path === "history remove"
653
- ? ["yes"]
654
- : result.path === "open"
655
- ? ["log"]
656
- : [];
1377
+ if (
1378
+ result.path === "config set" &&
1379
+ tokens.includes("pointers.apiKey") &&
1380
+ !(tokens.length === 2 && tokens[1] === "-")
1381
+ )
1382
+ syntax(
1383
+ "API key must be provided through '-' and piped stdin; never pass it in command arguments.",
1384
+ );
1385
+ const booleans = result.path.startsWith("skills ")
1386
+ ? result.path === "skills sync"
1387
+ ? ["dry-run", "yes", "override-existing", "force", "no-force"]
1388
+ : ["force", "no-force"]
1389
+ : result.path === "doctor"
1390
+ ? ["fix", "yes"]
1391
+ : result.path === "bundle build"
1392
+ ? ["replace", "schema-only", "no-import"]
1393
+ : result.path === "build"
1394
+ ? ["replace", "no-import"]
1395
+ : result.path === "publish"
1396
+ ? ["snapshot"]
1397
+ : [
1398
+ "get",
1399
+ "templates render",
1400
+ "templates list",
1401
+ "templates show",
1402
+ ].includes(result.path)
1403
+ ? result.path === "templates render"
1404
+ ? ["force", "no-force"]
1405
+ : result.path === "get"
1406
+ ? ["raw", "force", "no-force"]
1407
+ : ["force", "no-force"]
1408
+ : result.path === "search"
1409
+ ? ["all", "current", "force", "no-force"]
1410
+ : result.path === "swarm request"
1411
+ ? ["pivot"]
1412
+ : result.path === "swarm approve"
1413
+ ? ["yes", "again", "pivot"]
1414
+ : ["swarm status", "swarm members"].includes(result.path)
1415
+ ? ["local", "force", "no-force"]
1416
+ : [
1417
+ "swarm exclude",
1418
+ "swarm set",
1419
+ "swarm pivot grant",
1420
+ ].includes(result.path)
1421
+ ? ["yes"]
1422
+ : result.path === "register set"
1423
+ ? ["replace"]
1424
+ : result.path === "history remove"
1425
+ ? ["yes"]
1426
+ : result.path === "open"
1427
+ ? ["log", "raw", "force", "no-force"]
1428
+ : result.path === "pin"
1429
+ ? ["force", "no-force"]
1430
+ : result.path === "daemon ui"
1431
+ ? ["open"]
1432
+ : [];
1433
+ if (booleans.includes("force")) booleans.push("refresh", "no-refresh");
657
1434
  const values =
658
- result.path === "init"
659
- ? ["template"]
660
- : result.path === "bundle build" || result.path === "build"
1435
+ result.path === "swarm create"
1436
+ ? ["service", "resume", "name", "description", "alias"]
1437
+ : result.path === "swarm request"
661
1438
  ? ["output"]
662
- : result.path === "history list"
663
- ? ["app", "status", "since", "until", "limit", "before"]
664
- : result.path === "history remove"
665
- ? ["app", "status", "since", "until"]
666
- : result.path === "pin list"
667
- ? ["type"]
668
- : [];
1439
+ : result.path === "swarm export"
1440
+ ? ["output"]
1441
+ : result.path === "swarm profile"
1442
+ ? ["address", "pivot"]
1443
+ : result.path === "swarm update" || result.path === "profile"
1444
+ ? ["name", "description"]
1445
+ : result.path === "swarm approve"
1446
+ ? []
1447
+ : ["publish", "templates set", "templates remove"].includes(
1448
+ result.path,
1449
+ )
1450
+ ? ["expect"]
1451
+ : result.path === "get"
1452
+ ? ["output"]
1453
+ : result.path === "search"
1454
+ ? ["prefix", "kind", "schema", "limit", "offset"]
1455
+ : result.path === "templates render"
1456
+ ? ["description"]
1457
+ : result.path === "bundle build" ||
1458
+ result.path === "build"
1459
+ ? ["output"]
1460
+ : result.path === "history list"
1461
+ ? [
1462
+ "app",
1463
+ "status",
1464
+ "since",
1465
+ "until",
1466
+ "limit",
1467
+ "before",
1468
+ ]
1469
+ : result.path === "history remove"
1470
+ ? ["app", "status", "since", "until"]
1471
+ : [];
669
1472
  while (tokens.length) {
670
1473
  const value = tokens.shift()!;
671
- if (value.startsWith("--") || value === "-o") {
1474
+ if (
1475
+ result.path === "swarm exclude" &&
1476
+ /^--[A-Za-z0-9_-]{41}$/.test(value)
1477
+ ) {
1478
+ result.positional.push(value);
1479
+ } else if (value.startsWith("--") || value === "-o") {
672
1480
  const option = value === "-o" ? "output" : value.slice(2);
673
- if (result.path === "init" && option === "param") {
1481
+ if (result.path.startsWith("daemon") && option === "swarm")
1482
+ syntax(
1483
+ "daemon manages all registered Swarms and does not accept --swarm.",
1484
+ );
1485
+ if (result.path === "skills sync" && option === "agent") {
1486
+ const input = tokens.shift();
1487
+ if (!input || input.startsWith("-")) syntax("--agent needs a value.");
1488
+ (result.agents ??= []).push(input);
1489
+ continue;
1490
+ }
1491
+ if (result.path.startsWith("register ") && option === "swarm") {
1492
+ const input = tokens.shift();
1493
+ if (!input || input.startsWith("-")) syntax("--swarm needs a value.");
1494
+ result.registrySwarms!.push(input);
1495
+ flags.swarm = input;
1496
+ continue;
1497
+ }
1498
+ if (result.path === "templates render" && option === "template")
1499
+ syntax(
1500
+ "--template was removed. Use ipab templates render TEMPLATE NAME [DIR], with TEMPLATE first.",
1501
+ );
1502
+ if (result.path === "templates render" && option === "param") {
674
1503
  const input = tokens.shift();
675
1504
  if (!input || input.startsWith("--") || input.indexOf("=") < 1)
676
1505
  syntax("--param requires KEY=VALUE.");
677
1506
  (result.parameters ??= []).push(input);
678
1507
  continue;
679
1508
  }
1509
+ if (result.path === "swarm request" && option === "alias")
1510
+ syntax(
1511
+ "swarm request --alias was removed. First run ipab swarm set ALIAS CONFIG_URL, then ipab swarm request ALIAS.",
1512
+ );
680
1513
  if (Object.hasOwn(result.options, option))
681
1514
  syntax(`Duplicate option ${value}.`);
682
1515
  if (booleans.includes(option)) result.options[option] = true;
683
1516
  else if (values.includes(option)) {
684
1517
  const input = tokens.shift();
685
- if (!input || input.startsWith("--")) syntax(`${value} needs a value.`);
1518
+ if (
1519
+ input === undefined ||
1520
+ (input.startsWith("--") &&
1521
+ !(option === "resume" && /^[A-Za-z0-9_-]{43}$/.test(input))) ||
1522
+ (input === "" &&
1523
+ !["swarm update", "profile", "templates render"].includes(
1524
+ result.path,
1525
+ ))
1526
+ )
1527
+ syntax(`${value} needs a value.`);
686
1528
  result.options[option] = input;
687
- } else syntax(`Unknown option "${value}".`);
1529
+ } else if (
1530
+ option === "name" &&
1531
+ ["swarm profile", "swarm request"].includes(result.path)
1532
+ )
1533
+ syntax(
1534
+ `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." : ""}`,
1535
+ );
1536
+ else syntax(`Unknown option "${value}".`);
688
1537
  } else result.positional.push(value);
689
1538
  }
690
- const counts: Record<string, [number, number]> = {
691
- init: [1, 2],
692
- build: [0, 1],
693
- "bundle build": [1, 1],
694
- "bundle inspect": [1, 1],
695
- "bundle import": [1, 1],
696
- open: [1, 1],
697
- "pin add": [2, 2],
698
- "pin delete": [1, 1],
1539
+ validateRefreshOptions(result.options);
1540
+ if (
1541
+ result.path === "search" &&
1542
+ result.options.current &&
1543
+ flags.swarm !== undefined
1544
+ )
1545
+ syntax("--current and --swarm are mutually exclusive.");
1546
+ if (
1547
+ result.path === "search" &&
1548
+ result.options.all &&
1549
+ (result.options.current || flags.swarm !== undefined)
1550
+ )
1551
+ syntax("--all is mutually exclusive with --current and --swarm.");
1552
+ if (
1553
+ result.path === "register list" &&
1554
+ (result.registrySwarms?.length ?? 0) > 1
1555
+ )
1556
+ syntax(
1557
+ "register list accepts --swarm at most once. Select one Swarm or omit it to use the current Swarm.",
1558
+ );
1559
+ const counts: Record<string, [number, number]> = {
1560
+ daemon: [0, 0],
1561
+ "daemon ui": [0, 0],
1562
+ doctor: [0, 0],
1563
+ "skills list": [0, 0],
1564
+ "skills sync": [0, Number.MAX_SAFE_INTEGER],
1565
+ profile: [0, 0],
1566
+ "swarm create": [0, 0],
1567
+ "swarm request": [1, 1],
1568
+ "swarm approve": [1, 1],
1569
+ "swarm pivot grant": [1, 1],
1570
+ "swarm export": [0, 0],
1571
+ "swarm exclude": [1, 1],
1572
+ "swarm resume": [0, 0],
1573
+ "swarm profile": [0, 0],
1574
+ "swarm status": [0, 0],
1575
+ "swarm members": [0, 0],
1576
+ "swarm list": [0, 0],
1577
+ "swarm set": [2, 2],
1578
+ "swarm use": [1, 1],
1579
+ "swarm remove": [1, 1],
1580
+ "swarm update": [0, 0],
1581
+ publish: [2, 2],
1582
+ get: [1, 1],
1583
+ search: [1, 1],
1584
+ "templates render": [2, 3],
1585
+ build: [0, 1],
1586
+ "bundle build": [1, 1],
1587
+ "bundle inspect": [1, 1],
1588
+ "bundle import": [1, 1],
1589
+ open: [1, 1],
1590
+ pin: [1, 1],
1591
+ unpin: [1, 1],
699
1592
  "pin list": [0, 0],
700
1593
  "pin show": [1, 1],
701
- "pin rename": [2, 2],
702
1594
  "register list": [0, 0],
703
1595
  "register set": [2, 2],
704
1596
  "register remove": [1, 1],
1597
+ "templates list": [0, 0],
1598
+ "templates show": [1, 1],
1599
+ "templates set": [2, 2],
1600
+ "templates remove": [1, 1],
705
1601
  "config get": [0, 1],
706
1602
  "config set": [2, 2],
707
1603
  "config reset": [1, 1],
@@ -714,13 +1610,28 @@ export function parse(argv: readonly string[]): Parsed {
714
1610
  if (result.options["with-source"] && result.options["without-source"])
715
1611
  syntax("--with-source and --without-source are mutually exclusive.");
716
1612
  const [minimum, maximum] = counts[result.path]!;
717
- if (result.positional.length < minimum || result.positional.length > maximum)
718
- syntax(`Invalid arguments.\n${help(result.path)}`);
1613
+ if (result.path === "profile" && flags.swarm !== undefined)
1614
+ syntax("Personal profile is account-wide; do not pass --swarm.");
719
1615
  if (
720
- result.template &&
721
- (!result.template.length || !result.template.includes("%"))
1616
+ result.positional.length &&
1617
+ [
1618
+ "swarm status",
1619
+ "swarm update",
1620
+ "swarm resume",
1621
+ "swarm profile",
1622
+ "swarm export",
1623
+ "swarm members",
1624
+ ].includes(result.path)
722
1625
  )
723
- syntax('Argument template must contain a whole "%" token.');
1626
+ syntax(
1627
+ `Swarm target positionals are no longer supported. Use ipab --swarm URL_OR_ALIAS ${result.path} instead.`,
1628
+ );
1629
+ if (result.positional.length < minimum || result.positional.length > maximum)
1630
+ syntax(`Invalid arguments.\n${help(result.path)}`);
1631
+ if (result.template)
1632
+ syntax(
1633
+ 'Custom per-association argv is unsupported. Remove "-- TEMPLATE..."; open passes only the content CID. Adapt the App or use ipab exec APP_CID ARGS.',
1634
+ );
724
1635
  if (result.path === "history remove") {
725
1636
  const selected = values.some((value) =>
726
1637
  Object.hasOwn(result.options, value),
@@ -732,10 +1643,36 @@ export function parse(argv: readonly string[]): Parsed {
732
1643
  syntax("history remove requires explicit IDs OR filters, not both.");
733
1644
  }
734
1645
  // Validate syntactic values before state access, let alone a backend connection.
735
- if (result.path.startsWith("pin ") && result.path !== "pin list") {
736
- pinName(result.positional[0]!, result.path === "pin show");
737
- if (result.path === "pin add") exactCid(result.positional[1]!);
738
- if (result.path === "pin rename") pinName(result.positional[1]!);
1646
+ if (["pin", "unpin", "pin show"].includes(result.path)) {
1647
+ const reference = result.positional[0]!;
1648
+ if (reference.startsWith("builtin:") && result.path !== "pin show")
1649
+ syntax(
1650
+ "Packaged builtin references are read-only; they cannot be pinned or unpinned.",
1651
+ );
1652
+ if (
1653
+ !(result.path === "pin show" && reference.startsWith("builtin:")) &&
1654
+ !parseNameReference(reference)
1655
+ )
1656
+ exactCid(reference);
1657
+ }
1658
+ if (result.path === "publish") {
1659
+ formalName(result.positional[0]!);
1660
+ if (typeof result.options.expect === "string")
1661
+ exactCid(result.options.expect);
1662
+ if (result.options.expect && result.options.snapshot)
1663
+ syntax(
1664
+ "--snapshot is initial-only and cannot be combined with --expect.",
1665
+ );
1666
+ }
1667
+ if (
1668
+ result.path.startsWith("templates ") &&
1669
+ result.path !== "templates render"
1670
+ ) {
1671
+ if (result.positional[0] !== undefined) templateName(result.positional[0]);
1672
+ if (typeof result.options.expect === "string")
1673
+ exactCid(result.options.expect);
1674
+ if (result.path === "templates remove" && !result.options.expect)
1675
+ syntax("templates remove requires --expect OLD_TARGET_CID.");
739
1676
  }
740
1677
  if (result.path.startsWith("config ") && result.positional[0]) {
741
1678
  if (
@@ -743,13 +1680,22 @@ export function parse(argv: readonly string[]): Parsed {
743
1680
  !(result.path === "config reset" && result.positional[0] === "store.rpc")
744
1681
  )
745
1682
  configKey(result.positional[0]);
746
- if (result.path === "config set")
747
- parseValue(configKey(result.positional[0]), result.positional[1], true);
1683
+ if (result.path === "config set") {
1684
+ if (result.positional[0] === "pointers.apiKey") {
1685
+ if (result.positional[1] !== "-")
1686
+ syntax(
1687
+ "Set pointers.apiKey using '-' and piped stdin; never put the key in command-line arguments.",
1688
+ );
1689
+ } else
1690
+ parseValue(configKey(result.positional[0]), result.positional[1], true);
1691
+ }
748
1692
  }
749
1693
  if (typeof result.options.limit === "string")
750
1694
  parseValue("history.limit", result.options.limit, true);
751
1695
  if (result.options.output === "-")
752
1696
  syntax("CAR output requires a file path; binary stdout is not supported.");
1697
+ if (result.path === "doctor" && result.options.yes && !result.options.fix)
1698
+ syntax("doctor --yes requires --fix.");
753
1699
  return result;
754
1700
  }
755
1701
 
@@ -761,6 +1707,7 @@ async function performCli(
761
1707
  let state: State | undefined;
762
1708
  let store: IpfsStore | undefined;
763
1709
  let appExitCode: number | undefined;
1710
+ let readContext: SwarmContext | undefined;
764
1711
  try {
765
1712
  const parsed = parse(argv);
766
1713
  if (parsed.help) {
@@ -781,8 +1728,62 @@ async function performCli(
781
1728
  }
782
1729
  if (parsed.path === "history remove" && !parsed.options.yes && !io.tty)
783
1730
  syntax("Non-interactive history remove requires --yes.");
1731
+ if (parsed.path === "doctor") {
1732
+ const controller = new AbortController();
1733
+ const interrupt = () => {
1734
+ controller.abort(new HostError("Doctor interrupted.", 130, "ABORTED"));
1735
+ };
1736
+ const terminate = () => {
1737
+ controller.abort(new HostError("Doctor terminated.", 143, "ABORTED"));
1738
+ };
1739
+ process.once("SIGINT", interrupt);
1740
+ process.once("SIGTERM", terminate);
1741
+ try {
1742
+ const result = await doctorDevice(
1743
+ stateLocation(parsed.flags, env).path,
1744
+ env,
1745
+ {
1746
+ diagnostic: (text, progress) => {
1747
+ io.err(text, progress);
1748
+ },
1749
+ signal: controller.signal,
1750
+ fix: Boolean(parsed.options.fix),
1751
+ yes: Boolean(parsed.options.yes),
1752
+ tty: io.tty,
1753
+ confirm: (text, signal) => io.confirm(text, signal),
1754
+ },
1755
+ );
1756
+ io.out(parsed.flags.json ? JSON.stringify(result) : doctorText(result));
1757
+ return result.ready ? 0 : 1;
1758
+ } finally {
1759
+ process.removeListener("SIGINT", interrupt);
1760
+ process.removeListener("SIGTERM", terminate);
1761
+ }
1762
+ }
1763
+ if (parsed.path === "daemon ui") {
1764
+ const stateDir = stateLocation(parsed.flags, env).path;
1765
+ const endpoint = await daemonEndpoint(stateDir);
1766
+ if (!endpoint)
1767
+ throw new HostError(
1768
+ "IPAB daemon is not running for this state directory. Start it with `ipab daemon` or run a Swarm network command.",
1769
+ );
1770
+ const opened = Boolean(parsed.options.open);
1771
+ if (opened) openLoopbackUrl(endpoint.url);
1772
+ io.out(
1773
+ parsed.flags.json
1774
+ ? JSON.stringify({ ...endpoint, opened })
1775
+ : opened
1776
+ ? `Opened daemon status UI: ${endpoint.url}`
1777
+ : endpoint.url,
1778
+ );
1779
+ return 0;
1780
+ }
784
1781
  const builtins = await builtinContent();
785
- state = new State(stateLocation(parsed.flags, env).path, builtins.pins);
1782
+ state = new State(
1783
+ stateLocation(parsed.flags, env).path,
1784
+ builtins.pins,
1785
+ env,
1786
+ );
786
1787
  if (
787
1788
  parsed.path === "config reset" &&
788
1789
  parsed.positional[0] === "store.rpc"
@@ -795,17 +1796,1030 @@ async function performCli(
795
1796
  );
796
1797
  return 0;
797
1798
  }
798
- const items = effectiveConfig(state.config(), parsed.flags, env);
1799
+ const items = effectiveConfig(
1800
+ state.config({
1801
+ includeSecrets: ![
1802
+ "swarm members",
1803
+ "profile",
1804
+ "swarm status",
1805
+ "swarm set",
1806
+ ].includes(parsed.path),
1807
+ }),
1808
+ parsed.flags,
1809
+ env,
1810
+ (reference) => state!.resolveSwarm(reference),
1811
+ );
799
1812
  const value = (key: string) =>
800
1813
  items.find((item) => item.key === key)!.value;
801
1814
  const emit = (result: unknown, human: string) => {
802
1815
  io.out(parsed.flags.json ? JSON.stringify(result) : human);
803
1816
  };
804
1817
  const [first, second] = parsed.positional;
1818
+ const selectedSwarm =
1819
+ value("swarm.default") === null
1820
+ ? undefined
1821
+ : String(value("swarm.default"));
1822
+ const requireSwarm = () => {
1823
+ if (!selectedSwarm)
1824
+ syntax(
1825
+ "Select a Swarm with ipab --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.",
1826
+ );
1827
+ return selectedSwarm;
1828
+ };
1829
+ const swarmContext = (): SwarmContext => ({
1830
+ get store() {
1831
+ return store!;
1832
+ },
1833
+ set store(next) {
1834
+ store = next;
1835
+ },
1836
+ state: state!,
1837
+ env,
1838
+ stateDir: stateLocation(parsed.flags, env).path,
1839
+ cacheTtl: Number(value("swarm.cacheTtl")),
1840
+ syncInterval: Number(value("swarm.syncInterval")),
1841
+ listen: value("swarm.listen") === "loopback" ? "loopback" : "lan",
1842
+ ...(items.find((item) => item.key === "swarm.pivot")!.source === "default"
1843
+ ? {}
1844
+ : { pivot: Boolean(value("swarm.pivot")) }),
1845
+ ...(parsed.path === "daemon"
1846
+ ? {
1847
+ daemonReady: (status, onListen) =>
1848
+ serveDaemon(stateLocation(parsed.flags, env).path, {
1849
+ port: Number(value("daemon.uiPort")),
1850
+ ...(status ? { status } : {}),
1851
+ ...(onListen ? { onListen } : {}),
1852
+ }),
1853
+ }
1854
+ : {
1855
+ ensureDaemon: () =>
1856
+ ensureDaemon(
1857
+ stateLocation(parsed.flags, env).path,
1858
+ env,
1859
+ (text) => {
1860
+ io.err(text);
1861
+ },
1862
+ ),
1863
+ }),
1864
+ forceRefresh:
1865
+ parsed.options.refresh || parsed.options.force
1866
+ ? true
1867
+ : parsed.options["no-refresh"] || parsed.options["no-force"]
1868
+ ? false
1869
+ : Boolean(value("swarm.forceRefresh")),
1870
+ diagnostic: (text) => {
1871
+ io.err(text);
1872
+ },
1873
+ ...(typeof value("pointers.service") === "string"
1874
+ ? { pointerService: String(value("pointers.service")) }
1875
+ : {}),
1876
+ ...(typeof value("pointers.apiKey") === "string"
1877
+ ? { pointerApiKey: String(value("pointers.apiKey")) }
1878
+ : {}),
1879
+ });
805
1880
  const filter = parsed.path.startsWith("history ")
806
1881
  ? filters(state, parsed.options)
807
1882
  : {};
1883
+ const selection = () => {
1884
+ const saved = state!.config({ includeSecrets: false });
1885
+ const current = effectiveConfig(saved, parsed.flags, env, (reference) =>
1886
+ state!.resolveSwarm(reference),
1887
+ ).find((item) => item.key === "swarm.default")!;
1888
+ return {
1889
+ savedCurrent: saved["swarm.default"] ?? null,
1890
+ effectiveCurrent: current.value,
1891
+ source: current.source,
1892
+ };
1893
+ };
1894
+ if (parsed.path === "open" || parsed.path.startsWith("register ")) {
1895
+ if (state.legacyRegistrationCount)
1896
+ io.err(
1897
+ `Legacy User registrations are inactive. ${state.legacyRegistrationCount} entries are preserved in legacy_user_registrations in the state database under ${state.directory}; nothing was uploaded or deleted. Custom per-association argv is unsupported. Review the archived values and explicitly run ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS to publish only intended associations.`,
1898
+ );
1899
+ }
1900
+ if (state.legacyPinCount)
1901
+ io.err(
1902
+ `Legacy local pin names are inactive: ${state.legacyPinCount} records are preserved in legacy_named_pins under ${state.directory}. Retention and original Store owners are unchanged; inspect ipab pin list and release intended archived holders with ipab unpin EXACT_CID.`,
1903
+ );
1904
+ if (
1905
+ parsed.path.startsWith("templates ") &&
1906
+ parsed.path !== "templates render"
1907
+ ) {
1908
+ const configUrl = requireSwarm();
1909
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1910
+ const context = swarmContext();
1911
+ const expected =
1912
+ typeof parsed.options.expect === "string"
1913
+ ? parsed.options.expect
1914
+ : undefined;
1915
+ try {
1916
+ if (parsed.path === "templates list") {
1917
+ const items = await swarmTemplates(context, configUrl);
1918
+ const alias = state
1919
+ .allSwarms()
1920
+ .find((swarm) => swarm.cid === configUrl)?.alias;
1921
+ emit(
1922
+ { items },
1923
+ `Swarm: ${alias ? printable(alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nTemplates: ${items.length}\n\n${table(
1924
+ ["NAME", "TITLE", "TARGET CID", "TEMPLATE CID"],
1925
+ items.map((item) => [
1926
+ item.selector,
1927
+ item.title,
1928
+ item.targetCid,
1929
+ item.templateCid,
1930
+ ]),
1931
+ "No templates registered in this Swarm.\nAdd a template: ipab templates set NAME SOURCE",
1932
+ )}`,
1933
+ );
1934
+ } else if (parsed.path === "templates show") {
1935
+ const item = (await swarmTemplates(context, configUrl, first))[0]!;
1936
+ if (parsed.flags.json) io.out(JSON.stringify(item));
1937
+ else {
1938
+ const alias = state
1939
+ .allSwarms()
1940
+ .find((swarm) => swarm.cid === configUrl)?.alias;
1941
+ const swarm = alias ?? configUrl;
1942
+ const reference = formatNameReference(swarm, item.name);
1943
+ const tree = await templateOutputTree(
1944
+ context.store,
1945
+ item.templateCid,
1946
+ );
1947
+ const shell = process.platform === "win32" ? "powershell" : "posix";
1948
+ io.out(
1949
+ [
1950
+ `${printable(item.selector)} — ${printable(item.title)}`,
1951
+ printable(item.description) || "(No description.)",
1952
+ "",
1953
+ "Location",
1954
+ ` Swarm: ${printable(swarm)}`,
1955
+ ` Name: ${printable(item.name)}`,
1956
+ "",
1957
+ `Create a project (${shell === "powershell" ? "PowerShell" : "POSIX shell"})`,
1958
+ ` ${templateRenderExample(reference, swarm, item.definition, shell)}`,
1959
+ " Replace example parameter values as needed. No code is run by show.",
1960
+ "",
1961
+ "Parameters",
1962
+ table(
1963
+ ["NAME", "TYPE", "REQUIRED", "DEFAULT", "INPUT"],
1964
+ templateParameterRows(item.definition),
1965
+ "No parameters declared.",
1966
+ ),
1967
+ "Required means an input is needed when no default is declared.",
1968
+ "",
1969
+ "Output files (from project/)",
1970
+ " my-project/",
1971
+ ...tree.entries.map(
1972
+ (entry) =>
1973
+ `${" ".repeat(entry.path.split("/").length + 1)}${printable(entry.path.split("/").at(-1)!)}${entry.kind === "directory" ? "/" : ""}`,
1974
+ ),
1975
+ ...(tree.truncated
1976
+ ? [
1977
+ ` ... truncated: ${tree.truncated}; more files may exist.`,
1978
+ ]
1979
+ : tree.entries.length
1980
+ ? []
1981
+ : [" (no output files)"]),
1982
+ "",
1983
+ "Versions",
1984
+ ` Template CID: ${item.templateCid}`,
1985
+ ` Reference: ${reference}`,
1986
+ ...(item.targetCid !== item.templateCid
1987
+ ? [` Target CID (--expect): ${item.targetCid}`]
1988
+ : []),
1989
+ ].join("\n"),
1990
+ );
1991
+ }
1992
+ } else if (parsed.path === "templates set") {
1993
+ const item = await setSwarmTemplate(
1994
+ context,
1995
+ configUrl,
1996
+ first!,
1997
+ second!,
1998
+ expected,
1999
+ );
2000
+ emit(
2001
+ item,
2002
+ `${item.reference} → ${item.targetCid} (Template ${item.templateCid})`,
2003
+ );
2004
+ } else {
2005
+ const item = await removeSwarmTemplate(
2006
+ context,
2007
+ configUrl,
2008
+ first!,
2009
+ expected!,
2010
+ );
2011
+ emit(
2012
+ { removed: item },
2013
+ `Removed ${item.reference}; content and history are retained.`,
2014
+ );
2015
+ }
2016
+ } finally {
2017
+ await context.finishRead?.();
2018
+ }
2019
+ return 0;
2020
+ }
2021
+ if (parsed.path.startsWith("register ")) {
2022
+ const references = parsed.registrySwarms?.length
2023
+ ? parsed.registrySwarms
2024
+ : selectedSwarm
2025
+ ? [selectedSwarm]
2026
+ : [];
2027
+ if (!references.length)
2028
+ throw new HostError(
2029
+ "Register requires a selected Swarm. Pass --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.",
2030
+ );
2031
+ const targets = [
2032
+ ...new Set(
2033
+ references.map((reference) => state!.resolveSwarm(reference)),
2034
+ ),
2035
+ ];
2036
+ const schema = first
2037
+ ? state.resolve(schemaAlias(first), true)
2038
+ : undefined;
2039
+ const results: (
2040
+ | {
2041
+ items: Association[];
2042
+ }
2043
+ | {
2044
+ association: Association;
2045
+ }
2046
+ | {
2047
+ removed: string[];
2048
+ }
2049
+ )[] = [];
2050
+ const completed: string[] = [];
2051
+ const human: string[] = [];
2052
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2053
+ for (const configUrl of targets) {
2054
+ const context = swarmContext();
2055
+ try {
2056
+ if (parsed.path === "register list") {
2057
+ const items = await swarmRegistrations(context, configUrl);
2058
+ const alias = state
2059
+ .allSwarms()
2060
+ .find((swarm) => swarm.cid === configUrl)?.alias;
2061
+ results.push({ items });
2062
+ human.push(
2063
+ `Swarm: ${alias ? printable(alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nAssociations: ${items.length}\n\n${table(
2064
+ ["TYPE CID", "APP CID"],
2065
+ items.map((item) => [item.schemaCid, item.appCid]),
2066
+ "No associations registered in this Swarm.\nRegister an App: ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS",
2067
+ )}`,
2068
+ );
2069
+ } else if (parsed.path === "register set") {
2070
+ const appCid = parseNameReference(second!)
2071
+ ? (
2072
+ await resolveReference(
2073
+ context,
2074
+ second!,
2075
+ configUrl,
2076
+ (reference) => state!.resolve(reference),
2077
+ )
2078
+ ).cid
2079
+ : state.resolve(second!);
2080
+ const association = await setSwarmAssociation(
2081
+ context,
2082
+ configUrl,
2083
+ createAssociation(schema!, appCid, parsed.template ?? ["%"]),
2084
+ Boolean(parsed.options.replace),
2085
+ );
2086
+ results.push({ association });
2087
+ human.push(
2088
+ `${configUrl}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`,
2089
+ );
2090
+ } else {
2091
+ const removed = await removeSwarmAssociation(
2092
+ context,
2093
+ configUrl,
2094
+ schema!,
2095
+ );
2096
+ results.push({ removed: [removed] });
2097
+ human.push(`${configUrl}: removed association for ${removed}.`);
2098
+ }
2099
+ completed.push(configUrl);
2100
+ } catch (cause) {
2101
+ throw new HostError(
2102
+ parsed.path === "register list"
2103
+ ? `Cannot list associations for Swarm ${configUrl}: ${message(cause)}`
2104
+ : `Registry operation failed for ${configUrl}: ${message(cause)}. Completed Swarms: ${completed.length ? completed.join(", ") : "(none)"}. Multiple Swarm edits are not atomic.`,
2105
+ cause instanceof HostError ? cause.exitCode : 1,
2106
+ cause instanceof HostError ? cause.code : "REGISTRY_FAILED",
2107
+ "publication",
2108
+ );
2109
+ } finally {
2110
+ await context.finishRead?.();
2111
+ }
2112
+ }
2113
+ emit(
2114
+ {
2115
+ swarms: results.map((result, index) => ({
2116
+ configUrl: targets[index],
2117
+ ...result,
2118
+ })),
2119
+ },
2120
+ human.join("\n\n"),
2121
+ );
2122
+ return 0;
2123
+ }
808
2124
  switch (parsed.path) {
2125
+ case "profile": {
2126
+ const context = swarmContext();
2127
+ readContext = context;
2128
+ const changes = {
2129
+ ...(typeof parsed.options.name === "string"
2130
+ ? { name: parsed.options.name }
2131
+ : {}),
2132
+ ...(typeof parsed.options.description === "string"
2133
+ ? { description: parsed.options.description }
2134
+ : {}),
2135
+ };
2136
+ if (!Object.keys(changes).length) {
2137
+ const profile = await accountProfile(context);
2138
+ emit(
2139
+ { profile, localPersisted: profile.updatedAt !== null },
2140
+ `Name: ${printable(profile.name)}\nDescription: ${printable(profile.description)}\nPublic key: ${profile.publicKey}`,
2141
+ );
2142
+ } else {
2143
+ const result = await updateAccountProfile(context, changes);
2144
+ emit(
2145
+ result,
2146
+ [
2147
+ `Name: ${printable(result.profile.name)}`,
2148
+ `Description: ${printable(result.profile.description)}`,
2149
+ "Personal profile saved locally.",
2150
+ ...result.swarms.map(
2151
+ (entry) =>
2152
+ `${entry.configUrl}: ${entry.synchronized ? "synchronized" : `FAILED: ${entry.error}`}`,
2153
+ ),
2154
+ ].join("\n"),
2155
+ );
2156
+ if (result.swarms.some((entry) => !entry.synchronized)) {
2157
+ io.err(
2158
+ "Profile saved locally, but some Swarms failed. Retry the profile update or normally activate each failed membership to synchronize it.",
2159
+ );
2160
+ return 1;
2161
+ }
2162
+ }
2163
+ break;
2164
+ }
2165
+ case "swarm list": {
2166
+ const result = { swarms: state.allSwarms(), ...selection() };
2167
+ emit(
2168
+ {
2169
+ ...result,
2170
+ swarms: result.swarms.map((entry) => ({
2171
+ configUrl: entry.cid,
2172
+ alias: entry.alias,
2173
+ local: Boolean(entry.local),
2174
+ })),
2175
+ },
2176
+ [
2177
+ ...alignedRows(
2178
+ result.swarms.map((entry) => [
2179
+ `${entry.cid === result.effectiveCurrent ? "*" : " "} ${entry.alias ?? entry.cid}${entry.local ? " [local]" : ""}`,
2180
+ entry.cid,
2181
+ ]),
2182
+ ),
2183
+ ...(result.source === "flag" &&
2184
+ result.effectiveCurrent !== result.savedCurrent
2185
+ ? [
2186
+ `Selected via --swarm: ${printable(String(result.swarms.find((entry) => entry.cid === result.effectiveCurrent)?.alias ?? result.effectiveCurrent ?? "(none)"))}; saved default: ${printable(String(result.swarms.find((entry) => entry.cid === result.savedCurrent)?.alias ?? result.savedCurrent ?? "(none)"))}.`,
2187
+ ]
2188
+ : []),
2189
+ ].join("\n"),
2190
+ );
2191
+ break;
2192
+ }
2193
+ case "swarm use": {
2194
+ state.useSwarm(first!);
2195
+ const result = selection();
2196
+ emit(result, `Saved current swarm: ${result.savedCurrent}`);
2197
+ if (result.source === "flag" || result.source === "env")
2198
+ io.err(
2199
+ `The saved default is overridden by ${result.source}: ${result.effectiveCurrent}.`,
2200
+ );
2201
+ break;
2202
+ }
2203
+ case "swarm remove": {
2204
+ const removed = state.removeSwarm(first!);
2205
+ emit(
2206
+ {
2207
+ removed,
2208
+ savedCurrent:
2209
+ state.config({ includeSecrets: false })["swarm.default"] ?? null,
2210
+ },
2211
+ `Removed registration ${removed}. Credentials, content and remote membership are unchanged.`,
2212
+ );
2213
+ break;
2214
+ }
2215
+ case "swarm set": {
2216
+ swarmAlias(first!);
2217
+ const cid = swarmUrl(second!);
2218
+ const previous = state.swarms().find((entry) => entry.alias === first);
2219
+ if (previous && previous.cid !== cid) {
2220
+ io.err(`Swarm alias ${first}: ${previous.cid} -> ${cid}`);
2221
+ if (
2222
+ !parsed.options.yes &&
2223
+ (!io.tty ||
2224
+ !(await io.confirm(
2225
+ `Retarget local Swarm alias "${first}" from ${previous.cid} to ${cid}?`,
2226
+ )))
2227
+ )
2228
+ throw new HostError(
2229
+ "Alias unchanged. Retargeting requires --yes or interactive confirmation.",
2230
+ );
2231
+ }
2232
+ const entry = state.setSwarm(first!, cid, previous?.cid ?? null);
2233
+ emit(
2234
+ {
2235
+ configUrl: entry.cid,
2236
+ alias: entry.alias,
2237
+ savedCurrent:
2238
+ state.config({ includeSecrets: false })["swarm.default"] ?? null,
2239
+ },
2240
+ `Set local swarm alias ${entry.alias} (${cid}).`,
2241
+ );
2242
+ break;
2243
+ }
2244
+ case "daemon": {
2245
+ if (parsed.flags.json)
2246
+ syntax(
2247
+ "--json is not supported for daemon; diagnostics are written to stderr.",
2248
+ );
2249
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2250
+ const controller = new AbortController();
2251
+ const interrupt = () => {
2252
+ controller.abort();
2253
+ };
2254
+ process.once("SIGINT", interrupt);
2255
+ process.once("SIGTERM", interrupt);
2256
+ try {
2257
+ await swarmDaemon(
2258
+ swarmContext(),
2259
+ controller.signal,
2260
+ (ctx, url, report) => syncDaemonSwarm(ctx, url, undefined, report),
2261
+ );
2262
+ } catch (cause) {
2263
+ if (!controller.signal.aborted) throw cause;
2264
+ } finally {
2265
+ process.removeListener("SIGINT", interrupt);
2266
+ process.removeListener("SIGTERM", interrupt);
2267
+ }
2268
+ break;
2269
+ }
2270
+ case "swarm update":
2271
+ case "search":
2272
+ case "skills list":
2273
+ case "skills sync":
2274
+ case "swarm create":
2275
+ case "swarm request":
2276
+ case "swarm approve":
2277
+ case "swarm pivot grant":
2278
+ case "swarm export":
2279
+ case "swarm exclude":
2280
+ case "swarm resume":
2281
+ case "swarm profile":
2282
+ case "swarm members":
2283
+ case "swarm status":
2284
+ case "publish":
2285
+ case "pin":
2286
+ case "get": {
2287
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2288
+ const context = swarmContext();
2289
+ readContext = context;
2290
+ if (parsed.path.startsWith("skills ")) {
2291
+ const result = await manageSkills(context, requireSwarm(), {
2292
+ sync: parsed.path === "skills sync",
2293
+ names: parsed.positional,
2294
+ agents: parsed.agents ?? [],
2295
+ overrideExisting: Boolean(parsed.options["override-existing"]),
2296
+ dryRun: Boolean(parsed.options["dry-run"]),
2297
+ yes: Boolean(parsed.options.yes),
2298
+ tty: io.tty,
2299
+ confirm: (text) => io.confirm(text),
2300
+ preview: (text) => {
2301
+ io.err(text);
2302
+ },
2303
+ });
2304
+ store = context.store;
2305
+ emit(
2306
+ result,
2307
+ [
2308
+ table(
2309
+ ["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"],
2310
+ result.items.map((skill) => [
2311
+ skill.name,
2312
+ skill.cid,
2313
+ skill.identity,
2314
+ skill.status,
2315
+ ]),
2316
+ "No Skills.",
2317
+ ),
2318
+ ...result.items.flatMap((skill) => skill.problems),
2319
+ ...result.orphaned.map(
2320
+ (skill) =>
2321
+ `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`,
2322
+ ),
2323
+ ...result.results.map(
2324
+ (entry) =>
2325
+ `${entry.name} / ${entry.agent}: ${entry.status}${entry.error ? `: ${entry.error}` : ""}`,
2326
+ ),
2327
+ ].join("\n"),
2328
+ );
2329
+ if (!result.ok) return 1;
2330
+ break;
2331
+ }
2332
+ if (parsed.path === "pin") {
2333
+ io.err("Fetching, verifying and retaining content...");
2334
+ const result = await pinNameSubscription(
2335
+ context,
2336
+ first!,
2337
+ selectedSwarm,
2338
+ );
2339
+ store = context.store;
2340
+ emit(
2341
+ result,
2342
+ `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`,
2343
+ );
2344
+ break;
2345
+ }
2346
+ if (parsed.path === "swarm members") {
2347
+ const result = await swarmMembers(
2348
+ context,
2349
+ requireSwarm(),
2350
+ Boolean(parsed.options.refresh || parsed.options.force),
2351
+ );
2352
+ if (result.mode === "local") {
2353
+ emit(
2354
+ result,
2355
+ [
2356
+ "Swarm: local (Built-in single-machine Swarm)",
2357
+ "Mode: local",
2358
+ "Members: local user only (single-machine; no remote collaborators or HOME identity required)",
2359
+ ].join("\n"),
2360
+ );
2361
+ break;
2362
+ }
2363
+ emit(
2364
+ result,
2365
+ [
2366
+ `Directory: ${result.cache.source} (${result.cache.freshness}), observed ${result.cache.updatedAt}`,
2367
+ `Daemon: ${result.local.status}, observed ${result.local.updatedAt ?? "unknown"}; control-plane verified ${result.local.verifiedAt ?? "unknown"}`,
2368
+ table(
2369
+ ["NAME", "DESCRIPTION", "ROLE", "PIVOT", "PUBLIC KEY"],
2370
+ result.members.map((member) => [
2371
+ member.name,
2372
+ member.description,
2373
+ member.role,
2374
+ member.pivot ? (member.localStatus ?? "candidate") : "-",
2375
+ member.publicKey,
2376
+ ]),
2377
+ "No members.",
2378
+ ),
2379
+ ].join("\n"),
2380
+ );
2381
+ if (result.local.error)
2382
+ io.err(
2383
+ `Local Pivot observations (${result.local.status}): ${printable(result.local.error)}`,
2384
+ );
2385
+ break;
2386
+ }
2387
+ if (parsed.path === "swarm export") {
2388
+ const member = await exportRequest(
2389
+ context,
2390
+ requireSwarm(),
2391
+ String(parsed.options.output ?? ""),
2392
+ );
2393
+ emit({ member }, member);
2394
+ break;
2395
+ }
2396
+ if (parsed.path === "swarm pivot grant") {
2397
+ const url = requireSwarm();
2398
+ if (!parsed.options.yes)
2399
+ syntax(
2400
+ "Granting Pivot HEAD receipt authority requires --yes; revoking it requires swarm exclude.",
2401
+ );
2402
+ const result = await grantPivotAuthority(context, url, first!);
2403
+ store = context.store;
2404
+ emit(
2405
+ result,
2406
+ `Granted Pivot HEAD authority to ${result.member} on ${result.configUrl} (HEAD ${result.headId}). Revoking Pivot HEAD authority requires swarm exclude.`,
2407
+ );
2408
+ break;
2409
+ }
2410
+ if (
2411
+ ["swarm exclude", "swarm resume", "swarm profile"].includes(
2412
+ parsed.path,
2413
+ )
2414
+ ) {
2415
+ const url = requireSwarm();
2416
+ if (parsed.path === "swarm exclude") {
2417
+ if (!parsed.options.yes)
2418
+ syntax("Member removal is irreversible; --yes required.");
2419
+ await removeMember(context, url, first!);
2420
+ } else if (parsed.path === "swarm resume")
2421
+ await resumeRemoval(context, url);
2422
+ else {
2423
+ const profile = await updateProfile(context, url, {
2424
+ ...(typeof parsed.options.address === "string"
2425
+ ? { addresses: [parsed.options.address] }
2426
+ : {}),
2427
+ ...(typeof parsed.options.pivot === "string"
2428
+ ? {
2429
+ pivot: Boolean(
2430
+ parseValue("swarm.pivot", parsed.options.pivot, true),
2431
+ ),
2432
+ }
2433
+ : {}),
2434
+ });
2435
+ emit(profile, JSON.stringify(profile));
2436
+ store = context.store;
2437
+ break;
2438
+ }
2439
+ store = context.store;
2440
+ emit(
2441
+ { url, completed: true },
2442
+ `Organization switch complete: ${url}`,
2443
+ );
2444
+ break;
2445
+ }
2446
+ if (parsed.path === "swarm update") {
2447
+ const cid = requireSwarm();
2448
+ const result = await updateSwarm(context, cid, {
2449
+ ...(typeof parsed.options.name === "string"
2450
+ ? { name: parsed.options.name }
2451
+ : {}),
2452
+ ...(typeof parsed.options.description === "string"
2453
+ ? { description: parsed.options.description }
2454
+ : {}),
2455
+ });
2456
+ emit(
2457
+ result,
2458
+ `Swarm: ${result.configUrl}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD ID: ${result.headId}\nConfig content CID: ${result.valueCid}`,
2459
+ );
2460
+ break;
2461
+ }
2462
+ if (parsed.path === "search") {
2463
+ const registrations = state.allSwarms();
2464
+ const scope = parsed.options.all
2465
+ ? registrations
2466
+ : [
2467
+ {
2468
+ cid: requireSwarm(),
2469
+ alias:
2470
+ registrations.find((entry) => entry.cid === selectedSwarm)
2471
+ ?.alias ?? null,
2472
+ },
2473
+ ];
2474
+ const searchOptions: Parameters<typeof searchNames>[3] = {};
2475
+ if (typeof parsed.options.prefix === "string")
2476
+ searchOptions.prefix = parsed.options.prefix;
2477
+ if (typeof parsed.options.kind === "string")
2478
+ searchOptions.kind = parsed.options.kind as Exclude<
2479
+ NonNullable<Parameters<typeof searchNames>[3]>["kind"],
2480
+ undefined
2481
+ >;
2482
+ if (typeof parsed.options.schema === "string")
2483
+ searchOptions.schemaCid = parsed.options.schema;
2484
+ if (typeof parsed.options.limit === "string")
2485
+ searchOptions.limit = /^\d+$/.test(parsed.options.limit)
2486
+ ? Number(parsed.options.limit)
2487
+ : Number.NaN;
2488
+ if (typeof parsed.options.offset === "string")
2489
+ searchOptions.offset = /^\d+$/.test(parsed.options.offset)
2490
+ ? Number(parsed.options.offset)
2491
+ : Number.NaN;
2492
+ const result = Object.keys(searchOptions).length
2493
+ ? await searchNames(context, first!, scope, searchOptions)
2494
+ : await searchNames(context, first!, scope);
2495
+ emit(result, formatSearchResults(result.matches));
2496
+ break;
2497
+ }
2498
+ if (parsed.path === "swarm status") {
2499
+ const cid = requireSwarm();
2500
+ const status = await inspectSwarmStatus(
2501
+ context,
2502
+ cid,
2503
+ Boolean(parsed.options.refresh || parsed.options.force),
2504
+ );
2505
+ store = context.store;
2506
+ if (status.mode === "local") {
2507
+ emit(
2508
+ {
2509
+ mode: "local",
2510
+ configUrl: cid,
2511
+ root: status.head.root,
2512
+ valueCid: status.head.cid,
2513
+ properties: {
2514
+ name: status.config.name,
2515
+ description: status.config.description,
2516
+ },
2517
+ local: status.local,
2518
+ },
2519
+ [
2520
+ "Swarm",
2521
+ " Mode: local (built-in single-machine Swarm)",
2522
+ ` Name: ${printable(status.config.name)}`,
2523
+ ` Description: ${printable(status.config.description)}`,
2524
+ " Config URL:",
2525
+ ` ${cid}`,
2526
+ "",
2527
+ "Content",
2528
+ " HEAD (publication root):",
2529
+ ` ${status.head.root}`,
2530
+ " Content CID (HEAD value):",
2531
+ ` ${status.head.cid}`,
2532
+ ` Names: ${status.local.names} (Templates: ${status.local.templates}, Skills: ${status.local.skills}, Registrations: ${status.local.registrations})`,
2533
+ ].join("\n"),
2534
+ );
2535
+ break;
2536
+ }
2537
+ const {
2538
+ head,
2539
+ config,
2540
+ networking,
2541
+ cache,
2542
+ lastWriter,
2543
+ state: contentState,
2544
+ } = status;
2545
+ const fingerprint = await keyId(config.owner);
2546
+ emit(
2547
+ {
2548
+ configUrl: cid,
2549
+ owner: config.owner,
2550
+ ownerFingerprint: fingerprint,
2551
+ epoch: config.epoch,
2552
+ scopeId: config.scopeId,
2553
+ headId: config.headId,
2554
+ cache,
2555
+ state: contentState,
2556
+ networking,
2557
+ root: head.root,
2558
+ valueCid: head.cid,
2559
+ lastWriter,
2560
+ properties: {
2561
+ name: config.name,
2562
+ description: config.description,
2563
+ },
2564
+ },
2565
+ [
2566
+ "Swarm",
2567
+ ` Directory: ${cache.source} (${cache.freshness}), observed ${cache.updatedAt}`,
2568
+ ` Name: ${printable(config.name)}`,
2569
+ ` Description: ${config.description ? printable(config.description) : "(none)"}`,
2570
+ " Config URL:",
2571
+ ` ${cid}`,
2572
+ "",
2573
+ "Identity",
2574
+ " Owner fingerprint:",
2575
+ ` ${fingerprint}`,
2576
+ "",
2577
+ "Content",
2578
+ " HEAD (publication root):",
2579
+ ` ${head.root}`,
2580
+ " Content CID (HEAD value):",
2581
+ ` ${head.cid}`,
2582
+ ...(lastWriter
2583
+ ? [
2584
+ ` Last HEAD writer: ${lastWriter.name ? printable(lastWriter.name) : "(profile name unavailable)"}`,
2585
+ ` Public key: ${lastWriter.subject}`,
2586
+ ` PeerID: ${lastWriter.peerId ?? "unknown"}`,
2587
+ ` Updated: ${lastWriter.updatedAt} (service time)`,
2588
+ " Last writer is not a confirmed content holder or the only copy.",
2589
+ ]
2590
+ : [
2591
+ " Last HEAD writer/time: unknown (legacy record or service without update metadata).",
2592
+ ]),
2593
+ ` State: ${contentState.status}. ${contentState.error}`,
2594
+ "",
2595
+ "Local networking",
2596
+ ` Daemon observations: ${networking.daemon.status}`,
2597
+ ` Updated: ${networking.daemon.updatedAt ?? "unknown"}`,
2598
+ ` Control-plane verified: ${networking.daemon.verifiedAt ?? "unknown"}`,
2599
+ ...(networking.daemon.error
2600
+ ? [` Observation error: ${printable(networking.daemon.error)}`]
2601
+ : []),
2602
+ ` Connections observed: ${networking.connections.observedAt ?? "unknown"} (${networking.connections.freshness})`,
2603
+ ...(networking.connections.error
2604
+ ? [
2605
+ ` Connection error: ${printable(networking.connections.error)}`,
2606
+ ]
2607
+ : []),
2608
+ table(
2609
+ [
2610
+ "PIVOT PEER ID",
2611
+ "LOCAL",
2612
+ "PROBE",
2613
+ "PROBED AT",
2614
+ "FAILURES",
2615
+ "RETRY AT",
2616
+ "CONNECTION",
2617
+ ],
2618
+ networking.pivots.map((pivot) => [
2619
+ pivot.peerId,
2620
+ pivot.localStatus ?? "unknown",
2621
+ `${pivot.probe.result} (${pivot.probe.freshness})`,
2622
+ pivot.probe.at ?? "-",
2623
+ pivot.failures === null ? "-" : String(pivot.failures),
2624
+ pivot.retryAt ?? "-",
2625
+ pivot.connection.status,
2626
+ ]),
2627
+ "No declared Pivots.",
2628
+ ),
2629
+ ...networking.pivots.flatMap((pivot) =>
2630
+ pivot.probe.error
2631
+ ? [
2632
+ ` ${pivot.peerId} probe error: ${printable(pivot.probe.error)}`,
2633
+ ]
2634
+ : [],
2635
+ ),
2636
+ ...(networking.connections.error
2637
+ ? []
2638
+ : [
2639
+ table(
2640
+ ["CONNECTED PEER ID", "TRANSPORT", "ADDRESS"],
2641
+ networking.connections.peers.map((peer) => [
2642
+ peer.peerId,
2643
+ peer.transport,
2644
+ peer.address,
2645
+ ]),
2646
+ "No observed peer connections.",
2647
+ ),
2648
+ ]),
2649
+ " Selected is configuration, not connection success. Relay connectivity does not guarantee content availability.",
2650
+ ].join("\n"),
2651
+ );
2652
+ break;
2653
+ }
2654
+ if (parsed.path === "get") {
2655
+ const localCid = /^(ipab|name):/i.test(first!)
2656
+ ? undefined
2657
+ : state.resolve(first!);
2658
+ const builtin = builtins.pins.find((pin) => pin.cid === localCid);
2659
+ const selected = builtin
2660
+ ? { cid: builtin.cid, targetCid: builtin.cid }
2661
+ : await resolveReference(
2662
+ context,
2663
+ first!,
2664
+ selectedSwarm,
2665
+ (reference) => state!.resolve(reference),
2666
+ Boolean(parsed.options.raw),
2667
+ "local-first",
2668
+ );
2669
+ const contentStore = context.store;
2670
+ const source = IpfsStore.fromClient(
2671
+ {
2672
+ block: {
2673
+ get: (key, options) => {
2674
+ options?.signal?.throwIfAborted();
2675
+ const builtin = builtins.blocks.get(
2676
+ CID.parse(key).toV1().toString(),
2677
+ );
2678
+ return builtin
2679
+ ? Promise.resolve(builtin.slice())
2680
+ : contentStore.block.get(key, options);
2681
+ },
2682
+ },
2683
+ },
2684
+ contentStore.limits,
2685
+ );
2686
+ let directory: string;
2687
+ try {
2688
+ directory = await getBundle(
2689
+ source,
2690
+ selected.cid,
2691
+ typeof parsed.options.output === "string"
2692
+ ? parsed.options.output
2693
+ : undefined,
2694
+ );
2695
+ } finally {
2696
+ await source.close();
2697
+ }
2698
+ try {
2699
+ await context.finishRead?.();
2700
+ } finally {
2701
+ readContext = undefined;
2702
+ }
2703
+ const closing = store;
2704
+ store = undefined;
2705
+ await closeStore(closing, undefined);
2706
+ state.close();
2707
+ state = undefined;
2708
+ emit({ ...selected, directory }, directory);
2709
+ break;
2710
+ }
2711
+ let cid: string;
2712
+ let contentCid: string | undefined;
2713
+ if (parsed.path === "swarm create") {
2714
+ cid = await createSwarm(context, {
2715
+ ...(typeof parsed.options.service === "string"
2716
+ ? { service: parsed.options.service }
2717
+ : {}),
2718
+ ...(typeof parsed.options.resume === "string"
2719
+ ? { resume: parsed.options.resume }
2720
+ : {}),
2721
+ properties: {
2722
+ name: String(parsed.options.name ?? ""),
2723
+ description: String(parsed.options.description ?? ""),
2724
+ },
2725
+ ...(typeof parsed.options.alias === "string"
2726
+ ? { alias: parsed.options.alias }
2727
+ : {}),
2728
+ });
2729
+ } else if (parsed.path === "swarm request") {
2730
+ const result = await requestMembership(
2731
+ context,
2732
+ state.resolveSwarm(first!),
2733
+ {
2734
+ ...(typeof parsed.options.output === "string"
2735
+ ? { output: parsed.options.output }
2736
+ : {}),
2737
+ ...(parsed.options.pivot ? { role: "pivot" as const } : {}),
2738
+ },
2739
+ );
2740
+ store = context.store;
2741
+ io.err(
2742
+ `Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`,
2743
+ );
2744
+ if (result.file === undefined)
2745
+ io.out(JSON.stringify(result.request, null, 2));
2746
+ else {
2747
+ io.err(`Request saved to: ${result.file}`);
2748
+ if (parsed.flags.json)
2749
+ emit(
2750
+ {
2751
+ file: result.file,
2752
+ member: result.request.member,
2753
+ ownerFingerprint: result.ownerFingerprint,
2754
+ },
2755
+ "",
2756
+ );
2757
+ }
2758
+ break;
2759
+ } else if (parsed.path === "swarm approve") {
2760
+ const selected = requireSwarm();
2761
+ if (isLocalSwarm(selected))
2762
+ throw new HostError(
2763
+ `The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support swarm approve.`,
2764
+ );
2765
+ if (first === "-" && !parsed.options.yes)
2766
+ syntax(
2767
+ "Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.",
2768
+ );
2769
+ const request =
2770
+ first === "-"
2771
+ ? await verifiedRequestStream(
2772
+ (io.requestInput ?? processIO.requestInput!)(),
2773
+ )
2774
+ : await verifiedRequest(first!);
2775
+ if (request.configUrl !== selected)
2776
+ syntax(
2777
+ `Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`,
2778
+ );
2779
+ io.err(await membershipRequestSummary(request));
2780
+ if (
2781
+ !parsed.options.yes &&
2782
+ (!io.tty ||
2783
+ !(await io.confirm(
2784
+ `Approve the verified ${parsed.options.pivot || request.role === "pivot" ? "pivot" : "ordinary"} Request from ${request.member} above? This grants ${parsed.options.pivot || request.role === "pivot" ? "current HEAD and " : ""}the member's profile write access; all reads are public.`,
2785
+ )))
2786
+ )
2787
+ throw new HostError(
2788
+ "Approval requires explicit --yes or interactive confirmation.",
2789
+ );
2790
+ cid = await approveMembership(context, request, {
2791
+ again: Boolean(parsed.options.again),
2792
+ pivot: Boolean(parsed.options.pivot),
2793
+ });
2794
+ } else {
2795
+ const content = await publicationSource(second!, store);
2796
+ contentCid = content;
2797
+ cid = await publish(context, content, {
2798
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
2799
+ name: first!,
2800
+ ...(typeof parsed.options.expect === "string"
2801
+ ? { expect: parsed.options.expect }
2802
+ : {}),
2803
+ snapshot: Boolean(parsed.options.snapshot),
2804
+ });
2805
+ }
2806
+ store = context.store;
2807
+ if (parsed.path === "swarm create")
2808
+ io.err(
2809
+ `Registered swarm ${state.registeredSwarm(cid).alias ?? cid}. Saved current: ${state.config({ includeSecrets: false })["swarm.default"] ?? "(none)"}.`,
2810
+ );
2811
+ if (contentCid)
2812
+ io.err(
2813
+ `Locally protected payload: ${contentCid}. Use ipab unpin ${contentCid} to release this CID pin only; Name subscriptions and publication/history owners remain. --snapshot links payloads directly into retained publication history, so unpin cannot release that protection.`,
2814
+ );
2815
+ emit(
2816
+ parsed.path === "swarm create" || parsed.path === "swarm approve"
2817
+ ? { configUrl: cid }
2818
+ : { cid, ...(contentCid ? { contentCid } : {}) },
2819
+ cid,
2820
+ );
2821
+ break;
2822
+ }
809
2823
  case "store usage":
810
2824
  case "store gc": {
811
2825
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
@@ -824,7 +2838,7 @@ async function performCli(
824
2838
  }
825
2839
  break;
826
2840
  }
827
- case "init":
2841
+ case "templates render":
828
2842
  case "build":
829
2843
  case "bundle build":
830
2844
  case "bundle inspect":
@@ -861,7 +2875,10 @@ async function performCli(
861
2875
  options.signal?.throwIfAborted();
862
2876
  const builtin = builtins.blocks.get(cid.toV1().toString());
863
2877
  if (builtin) return builtin.slice();
864
- return (await getStore()).block.get(cid.toString(), options);
2878
+ return (store ?? (await getStore())).block.get(
2879
+ cid.toString(),
2880
+ options,
2881
+ );
865
2882
  },
866
2883
  };
867
2884
  const builtinSource = first ? state.pin(first) : undefined;
@@ -869,40 +2886,88 @@ async function performCli(
869
2886
  builtinSource?.builtin && builtinSource.metadata?.kind === "bundle"
870
2887
  ? builtinSource.cid
871
2888
  : first;
2889
+ let selectedTemplate: string | undefined;
2890
+ if (parsed.path === "templates render") {
2891
+ const selector = first!;
2892
+ selectedTemplate = selector;
2893
+ if (parseNameReference(selector)) {
2894
+ await getStore();
2895
+ const context = swarmContext();
2896
+ readContext = context;
2897
+ selectedTemplate = (
2898
+ await resolveReference(
2899
+ context,
2900
+ selector,
2901
+ selectedSwarm,
2902
+ (reference) => state!.resolve(reference),
2903
+ false,
2904
+ "local-first",
2905
+ )
2906
+ ).cid;
2907
+ store = context.store;
2908
+ } else {
2909
+ let explicit = false;
2910
+ try {
2911
+ CID.parse(selector);
2912
+ explicit = true;
2913
+ } catch {
2914
+ /* Not a CID. */
2915
+ }
2916
+ explicit ||= selector.toLowerCase().endsWith(".car");
2917
+ if (!explicit) {
2918
+ try {
2919
+ await lstat(selector);
2920
+ explicit = true;
2921
+ } catch (cause) {
2922
+ if (
2923
+ !nodeError(cause, "ENOENT") &&
2924
+ !nodeError(cause, "ENOTDIR")
2925
+ )
2926
+ throw cause;
2927
+ }
2928
+ }
2929
+ if (!explicit) {
2930
+ templateName(selector);
2931
+ if (!selectedSwarm)
2932
+ throw new HostError(
2933
+ "Template selectors require a selected Swarm. Use --swarm or swarm use, or supply an explicit Bundle directory, CAR, exact CID or IPAB URI.",
2934
+ );
2935
+ await getStore();
2936
+ const context = swarmContext();
2937
+ readContext = context;
2938
+ selectedTemplate = await resolveTemplateSelector(
2939
+ context,
2940
+ selector,
2941
+ selectedSwarm,
2942
+ );
2943
+ store = context.store;
2944
+ }
2945
+ }
2946
+ }
872
2947
  if (parsed.path === "bundle build" || parsed.path === "build")
873
2948
  io.err(
874
2949
  parsed.path === "build"
875
- ? "Typechecking, bundling and building App..."
2950
+ ? "Assembling and validating Bundle (no compilation)..."
876
2951
  : "Validating and building bundle...",
877
2952
  );
878
2953
  if (parsed.path === "bundle import")
879
2954
  io.err("Validating and importing CAR into Store...");
880
2955
  const result =
881
- parsed.path === "init"
882
- ? await initApp(first!, second, {
2956
+ parsed.path === "templates render"
2957
+ ? await initApp(second!, parsed.positional[2], {
883
2958
  ...request,
884
- ...(typeof parsed.options.template === "string"
885
- ? {
886
- template: state.pin(parsed.options.template)?.builtin
887
- ? parsed.options.template
888
- : state.pin(parsed.options.template)
889
- ? state.resolve(parsed.options.template)
890
- : parsed.options.template,
891
- }
892
- : {}),
893
- ...(parsed.parameters
894
- ? { parameters: parsed.parameters }
895
- : {}),
2959
+ ...(selectedTemplate ? { template: selectedTemplate } : {}),
2960
+ parameters: [
2961
+ ...(parsed.parameters ?? []),
2962
+ ...(typeof parsed.options.description === "string"
2963
+ ? [`description=${parsed.options.description}`]
2964
+ : []),
2965
+ ],
896
2966
  })
897
2967
  : parsed.path === "build"
898
- ? await buildApp(first, {
2968
+ ? await assembleBundle(first, {
899
2969
  ...request,
900
2970
  replace: Boolean(parsed.options.replace),
901
- ...(parsed.options["with-source"]
902
- ? { includeSource: true }
903
- : parsed.options["without-source"]
904
- ? { includeSource: false }
905
- : {}),
906
2971
  ...(typeof parsed.options.output === "string"
907
2972
  ? { output: parsed.options.output }
908
2973
  : {}),
@@ -944,7 +3009,7 @@ async function performCli(
944
3009
  if ("output" in result)
945
3010
  emit(
946
3011
  { ...result, imported: importing },
947
- `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)"}`,
3012
+ `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${result.validation !== undefined ? `\nEntry validation: ${result.validation?.status ?? "not-applicable"}` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`,
948
3013
  );
949
3014
  else if (result.kind === "bundle-import")
950
3015
  emit(
@@ -962,7 +3027,7 @@ async function performCli(
962
3027
  result.files.includes("ipab.json"))
963
3028
  )
964
3029
  io.err(
965
- `Next: install declared dependencies in ${JSON.stringify(result.directory)}; then ipab build ${JSON.stringify(result.directory)} (requires locally linked ipab).`,
3030
+ `Next: install declared dependencies in ${JSON.stringify(result.directory)}; if your template does not declare @ipab/cli, add or link it as a development dependency. Run pnpm build to prepare and package the App. Root ipab build does not compile.`,
966
3031
  );
967
3032
  else if (result.files.includes(".bundle.yaml"))
968
3033
  io.err(
@@ -971,7 +3036,7 @@ async function performCli(
971
3036
  } else
972
3037
  emit(
973
3038
  result,
974
- `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"}`,
3039
+ `Kind: ${result.kind}\n${result.manifest ? `Title: ${printable(result.manifest.title)}\nEntry: ${result.manifest.entry}\nType file: ${result.manifest.type}\n` : ""}Type CID: ${result.schemaCid}\nContent type: ${result.type.contentType}\nDefinition validation: passed\nStorage verification: ${result.validation.storage}\nEntry validation: ${result.validation.entry?.status ?? "not-applicable"}`,
975
3040
  );
976
3041
  } catch (cause) {
977
3042
  if (cancelled)
@@ -989,133 +3054,80 @@ async function performCli(
989
3054
  break;
990
3055
  }
991
3056
  case "pin list": {
992
- const type =
993
- typeof parsed.options.type === "string"
994
- ? state.resolve(parsed.options.type, true)
995
- : undefined;
996
- const pins = state.pins();
997
- const listed = pins
998
- .filter(
999
- (pin) => pin.status === "ready" && pin.metadata?.kind === "bundle",
1000
- )
1001
- .map(pinDetails)
1002
- .filter((pin) => type === undefined || pin.schemaCid === type);
1003
- const invalid = pins
1004
- .filter(
1005
- (pin) => pin.status === "ready" && pin.metadata?.kind !== "bundle",
1006
- )
1007
- .map(({ name, cid, metadata }) => ({
1008
- name,
1009
- cid,
1010
- kind: metadata?.kind,
1011
- reason:
1012
- "Not a Bundle pin; retention is preserved. Use pin delete to release it.",
1013
- }));
1014
- const pending = pins
1015
- .filter((pin) => pin.status !== "ready")
1016
- .map(({ name, cid, status }) => ({ name, cid, status }));
1017
- if (pending.length)
1018
- io.err(
1019
- `Unfinished pin operations (not usable pins): ${JSON.stringify(pending)}. Retry pin add/delete.`,
1020
- );
1021
- if (invalid.length)
1022
- io.err(
1023
- `Legacy non-Bundle pins (not usable pins): ${JSON.stringify(invalid)}. Retention is unchanged; delete explicitly and wrap content in a Bundle before pinning again.`,
1024
- );
3057
+ const listed = state.contentPins();
3058
+ const archived = state.archivedPins();
3059
+ const builtins = state.pins().map(pinDetails);
1025
3060
  emit(
1026
- { items: listed, pending, invalid },
3061
+ { items: listed, builtins, archived },
1027
3062
  table(
1028
- ["NAME", "CID", "KIND", "BUNDLE TYPE", "SOURCE"],
1029
- listed.map((pin) => [
1030
- pin.name,
1031
- pin.cid,
1032
- pin.kind,
1033
- pin.typeName,
1034
- pin.builtin ? "built-in (read-only)" : "user",
1035
- ]),
1036
- "No named pins.",
3063
+ ["REFERENCE", "CID", "STATUS", "SOURCE"],
3064
+ [
3065
+ ...listed.map((pin) => [
3066
+ pin.reference,
3067
+ pin.cid ?? "(none)",
3068
+ `${pin.status}/${pin.freshness}${pin.error ? `: ${pin.error}` : ""}`,
3069
+ pin.swarm ? "following shared Name" : "fixed CID",
3070
+ ]),
3071
+ ...builtins.map((pin) => [
3072
+ pin.name,
3073
+ pin.cid,
3074
+ "read-only",
3075
+ "built-in",
3076
+ ]),
3077
+ ...archived.map((pin) => [
3078
+ pin.cid,
3079
+ pin.cid,
3080
+ pin.status,
3081
+ `inactive archive (${pin.name}); unpin exact CID`,
3082
+ ]),
3083
+ ],
3084
+ "No pins.",
1037
3085
  ),
1038
3086
  );
1039
3087
  break;
1040
3088
  }
1041
- case "pin add": {
1042
- io.err("Fetching, verifying and retaining content in Store...");
1043
- const result = await addPin(
1044
- state,
1045
- first!,
1046
- second!,
1047
- await storeConfiguration(value("store.gateway")),
1048
- );
1049
- emit(
1050
- result,
1051
- `${result.name} → ${result.cid}\nBundle type: ${printable(result.typeName)}`,
1052
- );
1053
- break;
1054
- }
1055
- case "pin delete": {
1056
- const result = await deletePin(state, first!);
3089
+ case "unpin": {
3090
+ const canonical = pinReference(state, first!, selectedSwarm);
3091
+ const result = await unpin(state, canonical.reference);
1057
3092
  emit(
1058
3093
  result,
1059
- `Deleted ${first}; released only its retention responsibility. No blocks deleted or GC requested.`,
3094
+ `Unpinned ${canonical.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`,
1060
3095
  );
1061
3096
  break;
1062
3097
  }
1063
3098
  case "pin show": {
1064
- const pin = state.pin(first!);
1065
- if (!pin)
3099
+ const builtin = first!.startsWith("builtin:")
3100
+ ? state.pin(first!)
3101
+ : undefined;
3102
+ const canonical = builtin
3103
+ ? undefined
3104
+ : pinReference(state, first!, selectedSwarm);
3105
+ const pin = canonical
3106
+ ? state.contentPin(canonical.reference)
3107
+ : undefined;
3108
+ const archived = canonical
3109
+ ? state
3110
+ .archivedPins()
3111
+ .filter((pin) => pin.cid === canonical.reference)
3112
+ : [];
3113
+ if (!pin && !builtin && !archived.length)
1066
3114
  throw new HostError(
1067
3115
  `Pin "${first}" does not exist. Run ipab pin list.`,
1068
3116
  );
1069
- const result = pinDetails(pin);
1070
- emit(
1071
- result,
1072
- `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)"}`,
1073
- );
1074
- break;
1075
- }
1076
- case "pin rename": {
1077
- const result = renamePin(state, first!, second!);
1078
- emit(result, `${first} → ${result.name} (${result.cid})`);
1079
- break;
1080
- }
1081
- case "register list": {
1082
- const associations = state.registrations();
1083
- emit(
1084
- { items: associations },
1085
- table(
1086
- ["SCHEMA CID", "APP CID", "ARGV"],
1087
- associations.map((association) => [
1088
- association.schemaCid,
1089
- association.appCid,
1090
- JSON.stringify(association.argv),
1091
- ]),
1092
- "No associations.",
1093
- ),
1094
- );
1095
- break;
1096
- }
1097
- case "register set": {
1098
- const association = state.setAssociation(
1099
- schemaAlias(first!),
1100
- second!,
1101
- parsed.template ?? ["%"],
1102
- Boolean(parsed.options.replace),
1103
- );
1104
- emit(
1105
- association,
1106
- `${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`,
1107
- );
1108
- break;
1109
- }
1110
- case "register remove": {
1111
- const removed = state.removeAssociation(schemaAlias(first!));
1112
- emit({ removed: [removed] }, `Removed association for ${removed}.`);
3117
+ const result = builtin
3118
+ ? pinDetails(builtin)
3119
+ : {
3120
+ pin: pin ?? null,
3121
+ roots: pin ? state.hold(pin.owner)?.roots : [],
3122
+ archived,
3123
+ };
3124
+ emit(result, JSON.stringify(result, null, 2));
1113
3125
  break;
1114
3126
  }
1115
3127
  case "config get": {
1116
- const selected = first
1117
- ? items.filter((item) => item.key === first)
1118
- : items;
3128
+ const selected = (
3129
+ first ? items.filter((item) => item.key === first) : items
3130
+ ).map(visibleConfig);
1119
3131
  emit(
1120
3132
  { items: selected },
1121
3133
  table(
@@ -1128,14 +3140,21 @@ async function performCli(
1128
3140
  }
1129
3141
  case "config set": {
1130
3142
  const key = configKey(first!);
1131
- const saved = parseValue(key, second, true);
3143
+ const saved = parseValue(
3144
+ key,
3145
+ key === "pointers.apiKey"
3146
+ ? await (io.readSecret ?? processIO.readSecret!)()
3147
+ : second,
3148
+ true,
3149
+ );
1132
3150
  state.setConfig(key, saved);
1133
3151
  const source = items.find((item) => item.key === key)!.source;
1134
3152
  if (source === "env" || source === "flag")
1135
3153
  io.err(`Warning: saved user value is masked by ${source}.`);
3154
+ const display = visibleConfig({ key, value: saved, source: "user" });
1136
3155
  emit(
1137
- { key, value: saved, source: "user" },
1138
- `Saved ${key} = ${printable(String(saved))} (user).`,
3156
+ display,
3157
+ `Saved ${key} = ${printable(String(display.value))} (user).`,
1139
3158
  );
1140
3159
  break;
1141
3160
  }
@@ -1230,35 +3249,148 @@ async function performCli(
1230
3249
  }
1231
3250
  case "exec":
1232
3251
  case "open": {
3252
+ const named =
3253
+ parsed.path === "open" ? parseNameReference(first!) : undefined;
3254
+ const registrySwarm = named?.swarm
3255
+ ? state.resolveSwarm(named.swarm)
3256
+ : selectedSwarm;
3257
+ if (parsed.path === "open" && !registrySwarm)
3258
+ throw new HostError(
3259
+ "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.",
3260
+ );
1233
3261
  if (parsed.options.log && !value("history.enabled"))
1234
3262
  throw new HostError(
1235
3263
  "Execution logging requires history.enabled=true.",
1236
3264
  );
1237
- const target = state.resolve(first!);
1238
3265
  await recoverInactive(state);
1239
3266
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
3267
+ const context = swarmContext();
3268
+ readContext = context;
3269
+ const directory =
3270
+ parsed.path === "open"
3271
+ ? await localBundleDirectory(first!)
3272
+ : undefined;
3273
+ const target = directory
3274
+ ? undefined
3275
+ : (
3276
+ await resolveReference(
3277
+ context,
3278
+ first!,
3279
+ selectedSwarm,
3280
+ (reference) => state!.resolve(reference),
3281
+ Boolean(parsed.options.raw),
3282
+ "local-first",
3283
+ )
3284
+ ).cid;
3285
+ store = context.store;
3286
+ const resolveBundleReference = async (
3287
+ reference: string,
3288
+ signal: AbortSignal,
3289
+ preferredSwarm?: string,
3290
+ ) => {
3291
+ signal.throwIfAborted();
3292
+ const lookup: SwarmContext = {
3293
+ ...swarmContext(),
3294
+ store: new IpfsStore(
3295
+ await storeConfiguration(value("store.gateway")),
3296
+ ),
3297
+ };
3298
+ try {
3299
+ const named = parseNameReference(reference);
3300
+ const swarm = named?.swarm
3301
+ ? state!.resolveSwarm(named.swarm)
3302
+ : preferredSwarm
3303
+ ? state!.resolveSwarm(preferredSwarm)
3304
+ : selectedSwarm;
3305
+ const resolve = (source: string | undefined) =>
3306
+ resolveReference(
3307
+ lookup,
3308
+ reference,
3309
+ source,
3310
+ (input) => state!.resolve(input),
3311
+ false,
3312
+ "local-first",
3313
+ );
3314
+ let resolved;
3315
+ try {
3316
+ resolved = await resolve(named ? swarm : undefined);
3317
+ } catch (cause) {
3318
+ let failure: unknown = cause;
3319
+ for (
3320
+ let depth = 0;
3321
+ depth < 8 && failure instanceof ContentBundleError;
3322
+ depth++
3323
+ )
3324
+ failure = failure.cause;
3325
+ if (
3326
+ named ||
3327
+ !swarm ||
3328
+ !(failure instanceof ContentError) ||
3329
+ failure.code !== "missing_block"
3330
+ )
3331
+ throw cause;
3332
+ signal.throwIfAborted();
3333
+ resolved = await resolve(swarm);
3334
+ }
3335
+ signal.throwIfAborted();
3336
+ return { ...resolved, ...(swarm ? { swarm } : {}) };
3337
+ } finally {
3338
+ try {
3339
+ await lookup.finishRead?.();
3340
+ } finally {
3341
+ await lookup.store.close();
3342
+ }
3343
+ }
3344
+ };
1240
3345
  let appCid: string;
1241
3346
  let appArgv: string[];
1242
3347
  if (parsed.path === "open") {
1243
- const root = target;
3348
+ const session = directory ? `open:${randomUUID()}` : null;
1244
3349
  const owner = await Ownership.create(
1245
3350
  state,
1246
3351
  store,
1247
3352
  `open:${randomUUID()}`,
1248
- null,
3353
+ session,
1249
3354
  );
1250
3355
  try {
3356
+ const root = directory
3357
+ ? await snapshotBundle(directory, owner, session!)
3358
+ : target!;
1251
3359
  const content = await validatedBundle(root, store, owner);
1252
3360
  const schema = content.schemaKey;
1253
- const association = state.association(schema);
3361
+ let association: Association | undefined;
3362
+ if (registrySwarm) {
3363
+ const lookup: SwarmContext = {
3364
+ ...swarmContext(),
3365
+ store: new IpfsStore(
3366
+ await storeConfiguration(value("store.gateway")),
3367
+ ),
3368
+ };
3369
+ try {
3370
+ association = await swarmAssociation(
3371
+ lookup,
3372
+ registrySwarm,
3373
+ schema,
3374
+ "local-first",
3375
+ );
3376
+ } finally {
3377
+ try {
3378
+ await lookup.finishRead?.();
3379
+ } finally {
3380
+ await lookup.store.close();
3381
+ }
3382
+ }
3383
+ }
1254
3384
  if (!association)
1255
3385
  throw new HostError(
1256
- `No App registered for Schema ${schema}. Use ipab register set or ipab exec.`,
3386
+ `No App registered for Schema ${schema} in Swarm ${registrySwarm}. Use ipab register set ${schema} APP_CID --swarm ${registrySwarm} or ipab exec.`,
1257
3387
  );
1258
3388
  appCid = association.appCid;
1259
- appArgv = association.argv.map((argument) =>
1260
- argument === "%" ? root : argument,
1261
- );
3389
+ if (association.argv.length !== 1 || association.argv[0] !== "%")
3390
+ throw new HostError(
3391
+ "Custom per-association argv is unsupported; adapt the App to accept only the content CID or use ipab exec APP_CID ARGS.",
3392
+ );
3393
+ appArgv = [root];
1262
3394
  // execute owns the App/input context before this validation owner's eventual release.
1263
3395
  const result = await execute(
1264
3396
  state,
@@ -1266,6 +3398,7 @@ async function performCli(
1266
3398
  { origin: "open", appCid, argv: appArgv },
1267
3399
  {
1268
3400
  inputSchema: schema,
3401
+ resolveBundleReference,
1269
3402
  history: Boolean(value("history.enabled")),
1270
3403
  retain: value("output.retention") === "history",
1271
3404
  log: Boolean(parsed.options.log),
@@ -1280,7 +3413,7 @@ async function performCli(
1280
3413
  await owner.release();
1281
3414
  }
1282
3415
  } else {
1283
- appCid = target;
3416
+ appCid = target!;
1284
3417
  appArgv = parsed.positional.slice(1);
1285
3418
  }
1286
3419
  appExitCode = (
@@ -1289,6 +3422,7 @@ async function performCli(
1289
3422
  store,
1290
3423
  { origin: "exec", appCid, argv: appArgv },
1291
3424
  {
3425
+ resolveBundleReference,
1292
3426
  history: Boolean(value("history.enabled")),
1293
3427
  retain: value("output.retention") === "history",
1294
3428
  log: Boolean(parsed.options.log),
@@ -1309,7 +3443,11 @@ async function performCli(
1309
3443
  return error instanceof HostError ? error.exitCode : 1;
1310
3444
  } finally {
1311
3445
  try {
1312
- await closeStore(store, appExitCode);
3446
+ try {
3447
+ await readContext?.finishRead?.();
3448
+ } finally {
3449
+ await closeStore(store, appExitCode);
3450
+ }
1313
3451
  } finally {
1314
3452
  state?.close();
1315
3453
  }