@ipab/cli 0.1.0-rc.12 → 0.1.0-rc.14

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 (72) hide show
  1. package/dist/builtins/skill.ipab.car +0 -0
  2. package/dist/cli-daemon.d.ts +14 -0
  3. package/dist/cli-daemon.d.ts.map +1 -0
  4. package/dist/cli-daemon.js +400 -0
  5. package/dist/cli-daemon.js.map +1 -0
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js +1260 -1404
  8. package/dist/cli.js.map +1 -1
  9. package/dist/daemon-api.d.ts +80 -0
  10. package/dist/daemon-api.d.ts.map +1 -0
  11. package/dist/daemon-api.js +2411 -0
  12. package/dist/daemon-api.js.map +1 -0
  13. package/dist/daemon-client.d.ts +322 -0
  14. package/dist/daemon-client.d.ts.map +1 -0
  15. package/dist/daemon-client.js +400 -0
  16. package/dist/daemon-client.js.map +1 -0
  17. package/dist/daemon-protocol.d.ts +22 -0
  18. package/dist/daemon-protocol.d.ts.map +1 -0
  19. package/dist/daemon-protocol.js +39 -0
  20. package/dist/daemon-protocol.js.map +1 -0
  21. package/dist/daemon-telemetry.d.ts +86 -0
  22. package/dist/daemon-telemetry.d.ts.map +1 -0
  23. package/dist/daemon-telemetry.js +502 -0
  24. package/dist/daemon-telemetry.js.map +1 -0
  25. package/dist/daemon-ui.d.ts +68 -0
  26. package/dist/daemon-ui.d.ts.map +1 -1
  27. package/dist/daemon-ui.js +283 -4
  28. package/dist/daemon-ui.js.map +1 -1
  29. package/dist/daemon.d.ts +10 -0
  30. package/dist/daemon.d.ts.map +1 -1
  31. package/dist/daemon.js +289 -38
  32. package/dist/daemon.js.map +1 -1
  33. package/dist/identity.d.ts.map +1 -1
  34. package/dist/identity.js +7 -2
  35. package/dist/identity.js.map +1 -1
  36. package/dist/ipc.d.ts +19 -7
  37. package/dist/ipc.d.ts.map +1 -1
  38. package/dist/ipc.js +96 -70
  39. package/dist/ipc.js.map +1 -1
  40. package/dist/pins.d.ts.map +1 -1
  41. package/dist/pins.js +18 -3
  42. package/dist/pins.js.map +1 -1
  43. package/dist/state-storage.d.ts.map +1 -1
  44. package/dist/state-storage.js +2 -1
  45. package/dist/state-storage.js.map +1 -1
  46. package/dist/state.d.ts +1 -1
  47. package/dist/state.d.ts.map +1 -1
  48. package/dist/state.js +3 -2
  49. package/dist/state.js.map +1 -1
  50. package/dist/swarm-files.d.ts.map +1 -1
  51. package/dist/swarm-files.js +7 -2
  52. package/dist/swarm-files.js.map +1 -1
  53. package/dist/swarm.d.ts +10 -1
  54. package/dist/swarm.d.ts.map +1 -1
  55. package/dist/swarm.js +247 -76
  56. package/dist/swarm.js.map +1 -1
  57. package/package.json +4 -4
  58. package/src/cli-daemon.ts +482 -0
  59. package/src/cli.ts +1689 -1948
  60. package/src/daemon-api.ts +3148 -0
  61. package/src/daemon-client.ts +975 -0
  62. package/src/daemon-protocol.ts +61 -0
  63. package/src/daemon-telemetry.ts +656 -0
  64. package/src/daemon-ui.ts +361 -4
  65. package/src/daemon.ts +337 -43
  66. package/src/identity.ts +10 -2
  67. package/src/ipc.ts +113 -79
  68. package/src/pins.ts +23 -3
  69. package/src/state-storage.ts +5 -1
  70. package/src/state.ts +3 -1
  71. package/src/swarm-files.ts +10 -2
  72. package/src/swarm.ts +727 -497
package/src/cli.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { createInterface } from "node:readline/promises";
2
+ import { existsSync } from "node:fs";
2
3
  import { lstat, readFile } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
3
5
  import type { IpfsStore } from "@ipab/ipfs-store";
4
- import { randomUUID } from "node:crypto";
5
- import { CID } from "multiformats/cid";
6
6
  import stringWidth from "string-width";
7
7
  import {
8
8
  LOCAL_SWARM_ALIAS,
@@ -15,19 +15,37 @@ import {
15
15
  storeConfiguration,
16
16
  swarmUrl,
17
17
  visibleConfig,
18
+ type ConfigKey,
18
19
  type GlobalOptions,
19
20
  } from "./config.js";
20
21
  import { HostError, object, syntax } from "./host-error.js";
21
- import type { Ownership as HistoryOwnership } from "./history.js";
22
22
  import {
23
- createAssociation,
24
23
  exactCid,
25
24
  swarmAlias,
26
25
  State,
27
26
  type Association,
27
+ type RegisteredSwarm,
28
28
  type RunRecord,
29
29
  } from "./state.js";
30
- import type { searchNames, SwarmContext } from "./swarm.js";
30
+ import type {
31
+ inspectSwarmStatus,
32
+ searchNames,
33
+ swarmMembers,
34
+ swarmTemplates,
35
+ updateAccountProfile,
36
+ updateSwarm,
37
+ replicateSwarm,
38
+ requestMembership,
39
+ grantPivotAuthority,
40
+ setSwarmTemplate,
41
+ removeSwarmTemplate,
42
+ setSwarmSkill,
43
+ removeSwarmSkill,
44
+ swarmTypeSkills,
45
+ SwarmContext,
46
+ } from "./swarm.js";
47
+ import type { manageSkills } from "./skills.js";
48
+ import type { templateOutputTree } from "./template-presentation.js";
31
49
  import {
32
50
  formatNameReference,
33
51
  parseNameReference,
@@ -36,6 +54,13 @@ import {
36
54
  } from "./name-reference.js";
37
55
  import { normalizeSwarmFsPath } from "./swarm-fs-path.js";
38
56
  import { readSecretStream } from "./config-secret.js";
57
+ import {
58
+ openCliClient,
59
+ resolveLocalPathIfPresent,
60
+ resolveSwarmFromList,
61
+ runPreparedApp,
62
+ type CliClientHandle,
63
+ } from "./cli-daemon.js";
39
64
 
40
65
  export interface IO {
41
66
  out(text: string): void;
@@ -209,7 +234,7 @@ const commandHelp: Record<
209
234
  "ipab --json daemon ui",
210
235
  ],
211
236
  notes: [
212
- "Inspects the protected loopback endpoint for the selected state-dir without starting a daemon.",
237
+ "Ensures the local daemon is running for the selected state-dir, then shows or opens its protected loopback status WebUI.",
213
238
  "The WebUI binds strictly to 127.0.0.1, validates Host/Origin headers against DNS rebinding, and never exposes private keys, swarm.key or Kubo Bearer tokens.",
214
239
  ],
215
240
  },
@@ -1912,10 +1937,8 @@ async function performCli(
1912
1937
  io: IO,
1913
1938
  env: NodeJS.ProcessEnv,
1914
1939
  ): Promise<number> {
1915
- let state: State | undefined;
1916
- let store: IpfsStore | undefined;
1917
- let appExitCode: number | undefined;
1918
- let readContext: SwarmContext | undefined;
1940
+ let cliHandle: CliClientHandle | undefined;
1941
+ let daemonStore: IpfsStore | undefined;
1919
1942
  try {
1920
1943
  const parsed = parse(argv);
1921
1944
  if (parsed.help) {
@@ -1936,6 +1959,10 @@ async function performCli(
1936
1959
  }
1937
1960
  if (parsed.path === "history remove" && !parsed.options.yes && !io.tty)
1938
1961
  syntax("Non-interactive history remove requires --yes.");
1962
+
1963
+ const stateDir = stateLocation(parsed.flags, env).path;
1964
+
1965
+ // Exempt command #3: doctor (never auto-starts Daemon)
1939
1966
  if (parsed.path === "doctor") {
1940
1967
  const { doctorDevice, doctorText } = await import("./doctor.js");
1941
1968
  const controller = new AbortController();
@@ -1948,20 +1975,16 @@ async function performCli(
1948
1975
  process.once("SIGINT", interrupt);
1949
1976
  process.once("SIGTERM", terminate);
1950
1977
  try {
1951
- const result = await doctorDevice(
1952
- stateLocation(parsed.flags, env).path,
1953
- env,
1954
- {
1955
- diagnostic: (text, progress) => {
1956
- io.err(text, progress);
1957
- },
1958
- signal: controller.signal,
1959
- fix: Boolean(parsed.options.fix),
1960
- yes: Boolean(parsed.options.yes),
1961
- tty: io.tty,
1962
- confirm: (text, signal) => io.confirm(text, signal),
1978
+ const result = await doctorDevice(stateDir, env, {
1979
+ diagnostic: (text, progress) => {
1980
+ io.err(text, progress);
1963
1981
  },
1964
- );
1982
+ signal: controller.signal,
1983
+ fix: Boolean(parsed.options.fix),
1984
+ yes: Boolean(parsed.options.yes),
1985
+ tty: io.tty,
1986
+ confirm: (text, signal) => io.confirm(text, signal),
1987
+ });
1965
1988
  io.out(parsed.flags.json ? JSON.stringify(result) : doctorText(result));
1966
1989
  return result.ready ? 0 : 1;
1967
1990
  } finally {
@@ -1969,39 +1992,110 @@ async function performCli(
1969
1992
  process.removeListener("SIGTERM", terminate);
1970
1993
  }
1971
1994
  }
1972
- if (parsed.path === "daemon ui") {
1973
- const { daemonEndpoint, openLoopbackUrl } = await import("./daemon.js");
1974
- const stateDir = stateLocation(parsed.flags, env).path;
1975
- const endpoint = await daemonEndpoint(stateDir);
1976
- if (!endpoint)
1977
- throw new HostError(
1978
- "IPAB daemon is not running for this state directory. Start it with `ipab daemon` or run a Swarm network command.",
1995
+
1996
+ // Exempt command #4: daemon (foreground daemon host itself)
1997
+ if (parsed.path === "daemon") {
1998
+ if (parsed.flags.json)
1999
+ syntax(
2000
+ "--json is not supported for daemon; diagnostics are written to stderr.",
1979
2001
  );
1980
- const opened = Boolean(parsed.options.open);
1981
- if (opened) openLoopbackUrl(endpoint.url);
1982
- io.out(
1983
- parsed.flags.json
1984
- ? JSON.stringify({ ...endpoint, opened })
1985
- : opened
1986
- ? `Opened daemon status UI: ${endpoint.url}`
1987
- : endpoint.url,
2002
+ const [
2003
+ { IpfsStore },
2004
+ { builtinContent },
2005
+ { serveDaemon },
2006
+ { swarmDaemon },
2007
+ { syncDaemonSwarm },
2008
+ ] = await Promise.all([
2009
+ import("@ipab/ipfs-store"),
2010
+ import("./builtins.js"),
2011
+ import("./daemon.js"),
2012
+ import("./swarm.js"),
2013
+ import("./skills.js"),
2014
+ ]);
2015
+ const builtins = await builtinContent();
2016
+ const bootState = new State(stateDir, builtins.pins, env);
2017
+ let items;
2018
+ try {
2019
+ items = effectiveConfig(
2020
+ bootState.config({ includeSecrets: true }),
2021
+ parsed.flags,
2022
+ env,
2023
+ (reference) => bootState.resolveSwarm(reference),
2024
+ );
2025
+ } finally {
2026
+ bootState.close();
2027
+ }
2028
+ const val = (key: ConfigKey) =>
2029
+ items.find((item) => item.key === key)!.value;
2030
+ daemonStore = new IpfsStore(
2031
+ await storeConfiguration(val("store.gateway")),
1988
2032
  );
2033
+ const context: SwarmContext = {
2034
+ get store() {
2035
+ return daemonStore!;
2036
+ },
2037
+ set store(next) {
2038
+ daemonStore = next;
2039
+ },
2040
+ env,
2041
+ stateDir,
2042
+ cacheTtl: Number(val("swarm.cacheTtl")),
2043
+ syncInterval: Number(val("swarm.syncInterval")),
2044
+ listen: val("swarm.listen") === "loopback" ? "loopback" : "lan",
2045
+ ...(items.find((item) => item.key === "swarm.pivot")!.source ===
2046
+ "default"
2047
+ ? {}
2048
+ : { pivot: Boolean(val("swarm.pivot")) }),
2049
+ daemonReady: (status, onListen, extra) =>
2050
+ serveDaemon(stateDir, {
2051
+ port: Number(val("daemon.uiPort")),
2052
+ env,
2053
+ ...(status ? { status } : {}),
2054
+ ...(onListen ? { onListen } : {}),
2055
+ ...(extra ?? {}),
2056
+ }),
2057
+ forceRefresh: Boolean(val("swarm.forceRefresh")),
2058
+ diagnostic: (text) => {
2059
+ io.err(text);
2060
+ },
2061
+ ...(typeof val("pointers.service") === "string"
2062
+ ? { pointerService: String(val("pointers.service")) }
2063
+ : {}),
2064
+ ...(typeof val("pointers.apiKey") === "string"
2065
+ ? { pointerApiKey: String(val("pointers.apiKey")) }
2066
+ : {}),
2067
+ };
2068
+ const controller = new AbortController();
2069
+ const interrupt = () => {
2070
+ controller.abort();
2071
+ };
2072
+ process.once("SIGINT", interrupt);
2073
+ process.once("SIGTERM", interrupt);
2074
+ try {
2075
+ await swarmDaemon(context, controller.signal, (ctx, url, report) =>
2076
+ syncDaemonSwarm(ctx, url, undefined, report),
2077
+ );
2078
+ } catch (cause) {
2079
+ if (!controller.signal.aborted) throw cause;
2080
+ } finally {
2081
+ process.removeListener("SIGINT", interrupt);
2082
+ process.removeListener("SIGTERM", interrupt);
2083
+ }
1989
2084
  return 0;
1990
2085
  }
1991
- const builtins =
1992
- parsed.path === "swarm list"
1993
- ? { pins: [], blocks: new Map<string, Uint8Array>() }
1994
- : await (await import("./builtins.js")).builtinContent();
1995
- state = new State(
1996
- stateLocation(parsed.flags, env).path,
1997
- builtins.pins,
1998
- env,
1999
- );
2086
+
2087
+ // Exempt recovery: config reset store.rpc runs directly on local State so
2088
+ // legacy store.rpc recovery is never blocked by Daemon startup calling state.config().
2000
2089
  if (
2001
2090
  parsed.path === "config reset" &&
2002
2091
  parsed.positional[0] === "store.rpc"
2003
2092
  ) {
2004
- state.resetConfig("store.rpc");
2093
+ const localState = new State(stateDir, [], env);
2094
+ try {
2095
+ localState.resetConfig("store.rpc");
2096
+ } finally {
2097
+ localState.close();
2098
+ }
2005
2099
  io.out(
2006
2100
  parsed.flags.json
2007
2101
  ? JSON.stringify({ reset: ["store.rpc"] })
@@ -2009,29 +2103,251 @@ async function performCli(
2009
2103
  );
2010
2104
  return 0;
2011
2105
  }
2012
- const items = effectiveConfig(
2013
- state.config({
2014
- includeSecrets: ![
2015
- "swarm members",
2016
- "profile",
2017
- "swarm status",
2018
- "swarm set",
2019
- ].includes(parsed.path),
2106
+
2107
+ // Stateless local build when --no-import is set (never touches IpfsStore or spawns a Daemon).
2108
+ if (
2109
+ (parsed.path === "build" || parsed.path === "bundle build") &&
2110
+ Boolean(parsed.options["no-import"])
2111
+ ) {
2112
+ const [{ assembleBundle }, { buildBundle }, { message }] =
2113
+ await Promise.all([
2114
+ import("./assembly.js"),
2115
+ import("./authoring.js"),
2116
+ import("./errors.js"),
2117
+ ]);
2118
+ let savedConfig: Partial<
2119
+ Record<ConfigKey, string | number | boolean | null>
2120
+ > = {};
2121
+ if (existsSync(join(stateDir, "state.sqlite"))) {
2122
+ const localState = new State(stateDir, [], env);
2123
+ try {
2124
+ savedConfig = localState.config({ includeSecrets: false });
2125
+ } finally {
2126
+ localState.close();
2127
+ }
2128
+ }
2129
+ const outputDirOpt = String(
2130
+ effectiveConfig(savedConfig, parsed.flags, env).find(
2131
+ (item) => item.key === "bundle.outputDir",
2132
+ )!.value,
2133
+ );
2134
+ const outputOpt =
2135
+ typeof parsed.options.output === "string"
2136
+ ? resolve(parsed.options.output)
2137
+ : undefined;
2138
+ const controller = new AbortController();
2139
+ let cancelled = 0;
2140
+ const interrupt = () => {
2141
+ cancelled = 130;
2142
+ controller.abort(new Error("Interrupted."));
2143
+ };
2144
+ const terminate = () => {
2145
+ cancelled = 143;
2146
+ controller.abort(new Error("Terminated."));
2147
+ };
2148
+ process.once("SIGINT", interrupt);
2149
+ process.once("SIGTERM", terminate);
2150
+ try {
2151
+ const commonOpts = {
2152
+ signal: controller.signal,
2153
+ diagnostic: (text: string) => {
2154
+ io.err(text);
2155
+ },
2156
+ replace: Boolean(parsed.options.replace),
2157
+ ...(outputOpt !== undefined ? { output: outputOpt } : {}),
2158
+ outputDir: outputDirOpt,
2159
+ };
2160
+ let built;
2161
+ if (parsed.path === "build") {
2162
+ const sourcePath = parsed.positional[0]
2163
+ ? resolve(parsed.positional[0])
2164
+ : process.cwd();
2165
+ io.err("Assembling and validating Bundle (no compilation)...");
2166
+ built = await assembleBundle(sourcePath, commonOpts);
2167
+ } else {
2168
+ const sourcePath = await resolveLocalPathIfPresent(
2169
+ parsed.positional[0]!,
2170
+ );
2171
+ io.err("Validating and building bundle...");
2172
+ built = await buildBundle(sourcePath, {
2173
+ ...commonOpts,
2174
+ schemaOnly: Boolean(parsed.options["schema-only"]),
2175
+ });
2176
+ }
2177
+ controller.signal.throwIfAborted();
2178
+ const result = { ...built, imported: false };
2179
+ const validation = (
2180
+ result as { validation?: { status?: string } | null }
2181
+ ).validation;
2182
+ const human = `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${validation !== undefined ? `\nEntry validation: ${validation?.status ?? "not-applicable"}` : ""}\nStore: not imported (--no-import)`;
2183
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
2184
+ return 0;
2185
+ } catch (cause) {
2186
+ if (cancelled) {
2187
+ io.err(message(cause));
2188
+ return cancelled;
2189
+ }
2190
+ throw cause;
2191
+ } finally {
2192
+ process.removeListener("SIGINT", interrupt);
2193
+ process.removeListener("SIGTERM", terminate);
2194
+ }
2195
+ }
2196
+
2197
+ // Stateless local CAR inspection (never touches state.sqlite, IpfsStore, or spawns a Daemon).
2198
+ if (parsed.path === "bundle inspect") {
2199
+ const target = parsed.positional[0]!;
2200
+ const looksLikeCarPath =
2201
+ !target.startsWith("ipab://") &&
2202
+ !target.startsWith("builtin:") &&
2203
+ target.toLowerCase().endsWith(".car");
2204
+ if (looksLikeCarPath) {
2205
+ const resolvedCar = resolve(target);
2206
+ let isLocalFile = false;
2207
+ try {
2208
+ isLocalFile = (await lstat(resolvedCar)).isFile();
2209
+ } catch {
2210
+ isLocalFile = false;
2211
+ }
2212
+ if (isLocalFile) {
2213
+ const [{ inspectBundle }, { message }] = await Promise.all([
2214
+ import("./authoring.js"),
2215
+ import("./errors.js"),
2216
+ ]);
2217
+ const controller = new AbortController();
2218
+ let cancelled = 0;
2219
+ const interrupt = () => {
2220
+ cancelled = 130;
2221
+ controller.abort(new Error("Interrupted."));
2222
+ };
2223
+ const terminate = () => {
2224
+ cancelled = 143;
2225
+ controller.abort(new Error("Terminated."));
2226
+ };
2227
+ process.once("SIGINT", interrupt);
2228
+ process.once("SIGTERM", terminate);
2229
+ try {
2230
+ const result = await inspectBundle(resolvedCar, {
2231
+ signal: controller.signal,
2232
+ diagnostic: (text: string) => {
2233
+ io.err(text);
2234
+ },
2235
+ });
2236
+ controller.signal.throwIfAborted();
2237
+ const manifest = result.manifest;
2238
+ const human = `Kind: ${result.kind}\n${manifest ? `Title: ${printable(manifest.title)}\nEntry: ${manifest.entry}\nType file: ${manifest.type}\n` : ""}Type CID: ${result.schemaCid}\nContent type: ${result.type.contentType}\nDefinition validation: passed\nStorage verification: ${result.validation.storage}\nEntry validation: ${result.validation.entry?.status ?? "not-applicable"}`;
2239
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
2240
+ return 0;
2241
+ } catch (cause) {
2242
+ if (cancelled) {
2243
+ io.err(message(cause));
2244
+ return cancelled;
2245
+ }
2246
+ throw cause;
2247
+ } finally {
2248
+ process.removeListener("SIGINT", interrupt);
2249
+ process.removeListener("SIGTERM", terminate);
2250
+ }
2251
+ }
2252
+ }
2253
+ }
2254
+
2255
+ // All remaining commands go through the local Daemon HTTP loopback API.
2256
+ cliHandle = await openCliClient(
2257
+ stateDir,
2258
+ env,
2259
+ parsed.flags,
2260
+ (text, prog) => {
2261
+ io.err(text, prog);
2262
+ },
2263
+ { lightweight: parsed.path === "swarm list" },
2264
+ );
2265
+ const { client } = cliHandle;
2266
+ const emit = (result: unknown, human: string) => {
2267
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
2268
+ };
2269
+
2270
+ if (parsed.path === "daemon ui") {
2271
+ const { openLoopbackUrl } = await import("./daemon.js");
2272
+ const live = await client.resolveEndpoint();
2273
+ const endpoint = {
2274
+ pid: live.pid,
2275
+ port: live.port,
2276
+ url: live.url,
2277
+ stateDir: live.stateDir,
2278
+ };
2279
+ const opened = Boolean(parsed.options.open);
2280
+ if (opened) openLoopbackUrl(endpoint.url);
2281
+ emit(
2282
+ { ...endpoint, opened },
2283
+ opened ? `Opened daemon status UI: ${endpoint.url}` : endpoint.url,
2284
+ );
2285
+ return 0;
2286
+ }
2287
+
2288
+ const includeConfigSecrets = ![
2289
+ "swarm members",
2290
+ "profile",
2291
+ "swarm status",
2292
+ "swarm set",
2293
+ ].includes(parsed.path);
2294
+ const [configSnapshot, swarmsSnapshot] = await Promise.all([
2295
+ client.host.getConfig(undefined, {
2296
+ includeSecrets: includeConfigSecrets,
2020
2297
  }),
2298
+ client.swarms.list(),
2299
+ ]);
2300
+ const registeredSwarms: RegisteredSwarm[] = swarmsSnapshot.swarms;
2301
+ const resolveSwarm = (reference: string) =>
2302
+ resolveSwarmFromList(registeredSwarms, reference);
2303
+
2304
+ const savedConfig = configSnapshot.saved ?? {};
2305
+ const computedItems = effectiveConfig(
2306
+ savedConfig,
2021
2307
  parsed.flags,
2022
2308
  env,
2023
- (reference) => state!.resolveSwarm(reference),
2309
+ resolveSwarm,
2024
2310
  );
2025
- const value = (key: string) =>
2311
+ const items = computedItems.map((item) => {
2312
+ if (item.key === "pointers.apiKey") {
2313
+ const fromDaemon = configSnapshot.items.find(
2314
+ (entry) => entry.key === "pointers.apiKey",
2315
+ );
2316
+ if (fromDaemon && item.source === "default") return fromDaemon;
2317
+ }
2318
+ return visibleConfig(item);
2319
+ });
2320
+ const value = (key: ConfigKey) =>
2026
2321
  items.find((item) => item.key === key)!.value;
2027
- const emit = (result: unknown, human: string) => {
2028
- io.out(parsed.flags.json ? JSON.stringify(result) : human);
2322
+
2323
+ const selection = (
2324
+ savedOverride?: string | null,
2325
+ ): {
2326
+ savedCurrent: string | null;
2327
+ effectiveCurrent: string | null;
2328
+ source: string;
2329
+ } => {
2330
+ const saved =
2331
+ savedOverride !== undefined
2332
+ ? { ...savedConfig, "swarm.default": savedOverride }
2333
+ : savedConfig;
2334
+ const current = effectiveConfig(
2335
+ saved,
2336
+ parsed.flags,
2337
+ env,
2338
+ resolveSwarm,
2339
+ ).find((item) => item.key === "swarm.default")!;
2340
+ return {
2341
+ savedCurrent:
2342
+ saved["swarm.default"] === undefined
2343
+ ? null
2344
+ : (saved["swarm.default"] as string | null),
2345
+ effectiveCurrent: current.value === null ? null : String(current.value),
2346
+ source: current.source,
2347
+ };
2029
2348
  };
2030
- const [first, second] = parsed.positional;
2031
- const selectedSwarm =
2032
- value("swarm.default") === null
2033
- ? undefined
2034
- : String(value("swarm.default"));
2349
+
2350
+ const selectedSwarm = selection().effectiveCurrent ?? undefined;
2035
2351
  const requireSwarm = () => {
2036
2352
  if (!selectedSwarm)
2037
2353
  syntax(
@@ -2039,80 +2355,30 @@ async function performCli(
2039
2355
  );
2040
2356
  return selectedSwarm;
2041
2357
  };
2042
- const swarmContext = (): SwarmContext => ({
2043
- get store() {
2044
- return store!;
2045
- },
2046
- set store(next) {
2047
- store = next;
2048
- },
2049
- state: state!,
2050
- env,
2051
- stateDir: stateLocation(parsed.flags, env).path,
2052
- cacheTtl: Number(value("swarm.cacheTtl")),
2053
- syncInterval: Number(value("swarm.syncInterval")),
2054
- listen: value("swarm.listen") === "loopback" ? "loopback" : "lan",
2055
- ...(items.find((item) => item.key === "swarm.pivot")!.source === "default"
2056
- ? {}
2057
- : { pivot: Boolean(value("swarm.pivot")) }),
2058
- ...(parsed.path === "daemon"
2059
- ? {
2060
- daemonReady: (status, onListen) =>
2061
- serveDaemon(stateLocation(parsed.flags, env).path, {
2062
- port: Number(value("daemon.uiPort")),
2063
- ...(status ? { status } : {}),
2064
- ...(onListen ? { onListen } : {}),
2065
- }),
2066
- }
2067
- : {
2068
- ensureDaemon: () =>
2069
- ensureDaemon(
2070
- stateLocation(parsed.flags, env).path,
2071
- env,
2072
- (text) => {
2073
- io.err(text);
2074
- },
2075
- ),
2076
- }),
2077
- forceRefresh:
2078
- parsed.options.refresh || parsed.options.force
2079
- ? true
2080
- : parsed.options["no-refresh"] || parsed.options["no-force"]
2081
- ? false
2082
- : Boolean(value("swarm.forceRefresh")),
2083
- diagnostic: (text) => {
2084
- io.err(text);
2085
- },
2086
- ...(typeof value("pointers.service") === "string"
2087
- ? { pointerService: String(value("pointers.service")) }
2088
- : {}),
2089
- ...(typeof value("pointers.apiKey") === "string"
2090
- ? { pointerApiKey: String(value("pointers.apiKey")) }
2091
- : {}),
2092
- });
2093
- const selection = () => {
2094
- const saved = state!.config({ includeSecrets: false });
2095
- const current = effectiveConfig(saved, parsed.flags, env, (reference) =>
2096
- state!.resolveSwarm(reference),
2097
- ).find((item) => item.key === "swarm.default")!;
2098
- return {
2099
- savedCurrent: saved["swarm.default"] ?? null,
2100
- effectiveCurrent: current.value,
2101
- source: current.source,
2102
- };
2103
- };
2358
+
2359
+ const explicitRefresh: boolean | undefined =
2360
+ parsed.options.refresh || parsed.options.force
2361
+ ? true
2362
+ : parsed.options["no-refresh"] || parsed.options["no-force"]
2363
+ ? false
2364
+ : undefined;
2365
+
2366
+ const stateDirectory = configSnapshot.stateDir ?? stateDir;
2104
2367
  if (parsed.path === "open" || parsed.path.startsWith("register ")) {
2105
- if (state.legacyRegistrationCount)
2368
+ if (configSnapshot.legacyRegistrationCount)
2106
2369
  io.err(
2107
- `Legacy User registrations are inactive. ${state.legacyRegistrationCount} entries are preserved in legacy_user_registrations in the state database under ${state.directory}; nothing was uploaded or deleted. Custom per-association argv is unsupported. Review the archived values and explicitly run ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS to publish only intended associations.`,
2370
+ `Legacy User registrations are inactive. ${configSnapshot.legacyRegistrationCount} entries are preserved in legacy_user_registrations in the state database under ${stateDirectory}; nothing was uploaded or deleted. Custom per-association argv is unsupported. Review the archived values and explicitly run ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS to publish only intended associations.`,
2108
2371
  );
2109
2372
  }
2110
- if (state.legacyPinCount)
2373
+ if (configSnapshot.legacyPinCount)
2111
2374
  io.err(
2112
- `Legacy local pin names are inactive: ${state.legacyPinCount} records are preserved in legacy_named_pins under ${state.directory}. Retention and original Store owners are unchanged; inspect ipab pin list and release intended archived holders with ipab unpin EXACT_CID.`,
2375
+ `Legacy local pin names are inactive: ${configSnapshot.legacyPinCount} records are preserved in legacy_named_pins under ${stateDirectory}. Retention and original Store owners are unchanged; inspect ipab pin list and release intended archived holders with ipab unpin EXACT_CID.`,
2113
2376
  );
2377
+
2378
+ const [first, second] = parsed.positional;
2379
+
2114
2380
  if (parsed.path === "swarm list") {
2115
- const result = { swarms: state.allSwarms(), ...selection() };
2381
+ const result = { swarms: registeredSwarms, ...selection() };
2116
2382
  emit(
2117
2383
  {
2118
2384
  ...result,
@@ -2139,218 +2405,145 @@ async function performCli(
2139
2405
  );
2140
2406
  return 0;
2141
2407
  }
2142
- const [
2143
- { ContentError, IpfsStore },
2144
- { ContentBundleError, openBundle },
2145
- { message },
2146
- {
2147
- filters,
2148
- listHistory,
2149
- selectedIds,
2150
- Ownership,
2151
- recoverInactive,
2152
- removeHistory,
2153
- },
2154
- { execute },
2155
- { validatedBundle },
2156
- {
2157
- buildBundle,
2158
- inspectBundle,
2159
- importBundle,
2160
- nodeError,
2161
- resolveLocalBundleInput,
2162
- snapshotLocalBundle,
2163
- },
2164
- { initApp },
2165
- { assembleBundle },
2166
- { getBundle },
2167
- { ensureDaemon, serveDaemon },
2168
- { keyId },
2169
- {
2170
- createSwarm,
2171
- swarmDaemon,
2172
- requestMembership,
2173
- approveMembership,
2174
- grantPivotAuthority,
2175
- exportRequest,
2176
- removeMember,
2177
- resumeRemoval,
2178
- updateProfile,
2179
- accountProfile,
2180
- updateAccountProfile,
2181
- swarmMembers,
2182
- inspectSwarmStatus,
2183
- verifiedRequest,
2184
- verifiedRequestStream,
2185
- membershipRequestSummary,
2186
- updateSwarm,
2187
- searchNames,
2188
- resolveReference,
2189
- publish,
2190
- pinNameSubscription,
2191
- pinReference,
2192
- swarmRegistrations,
2193
- swarmAssociation,
2194
- setSwarmAssociation,
2195
- removeSwarmAssociation,
2196
- resolveTemplateSelector,
2197
- swarmTemplates,
2198
- setSwarmTemplate,
2199
- removeSwarmTemplate,
2200
- artifactValue,
2201
- swarmTypeSkills,
2202
- swarmTypeSkill,
2203
- setSwarmSkill,
2204
- removeSwarmSkill,
2205
- },
2206
- { schemaAlias },
2207
- { unpin, pinDetails },
2208
- { publicationSource },
2209
- { templateRenderExample, templateOutputTree, templateParameterRows },
2210
- { logFiles },
2211
- { manageSkills, syncDaemonSwarm },
2212
- ] = await Promise.all([
2213
- import("@ipab/ipfs-store"),
2214
- import("@ipab/bundle"),
2215
- import("./errors.js"),
2216
- import("./history.js"),
2217
- import("./runtime.js"),
2218
- import("./space.js"),
2219
- import("./authoring.js"),
2220
- import("./app-authoring.js"),
2221
- import("./assembly.js"),
2222
- import("./get.js"),
2223
- import("./daemon.js"),
2224
- import("@ipab/bundle/pointer/crypto"),
2225
- import("./swarm.js"),
2226
- import("./app-definition.js"),
2227
- import("./pins.js"),
2228
- import("./publish-source.js"),
2229
- import("./template-presentation.js"),
2230
- import("./logs.js"),
2231
- import("./skills.js"),
2232
- ]);
2233
- const filter = parsed.path.startsWith("history ")
2234
- ? filters(state, parsed.options)
2235
- : {};
2408
+
2236
2409
  if (
2237
2410
  parsed.path.startsWith("templates ") &&
2238
2411
  parsed.path !== "templates render"
2239
2412
  ) {
2240
2413
  const configUrl = requireSwarm();
2241
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2242
- const context = swarmContext();
2243
2414
  const expected =
2244
2415
  typeof parsed.options.expect === "string"
2245
2416
  ? parsed.options.expect
2246
2417
  : undefined;
2247
- try {
2248
- if (parsed.path === "templates list") {
2249
- const items = await swarmTemplates(context, configUrl);
2250
- const alias = state
2251
- .allSwarms()
2252
- .find((swarm) => swarm.cid === configUrl)?.alias;
2253
- emit(
2254
- { items },
2255
- `Swarm: ${alias ? printable(alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nTemplates: ${items.length}\n\n${table(
2256
- ["NAME", "TITLE", "TARGET CID", "TEMPLATE CID"],
2257
- items.map((item) => [
2258
- item.selector,
2259
- item.title,
2260
- item.targetCid,
2261
- item.templateCid,
2262
- ]),
2263
- "No templates registered in this Swarm.\nAdd a template: ipab templates set NAME SOURCE",
2264
- )}`,
2265
- );
2266
- } else if (parsed.path === "templates show") {
2267
- const item = (await swarmTemplates(context, configUrl, first))[0]!;
2268
- if (parsed.flags.json) io.out(JSON.stringify(item));
2269
- else {
2270
- const alias = state
2271
- .allSwarms()
2272
- .find((swarm) => swarm.cid === configUrl)?.alias;
2273
- const swarm = alias ?? configUrl;
2274
- const reference = formatNameReference(swarm, item.name);
2275
- const tree = await templateOutputTree(
2276
- context.store,
2418
+ if (parsed.path === "templates list") {
2419
+ const response = (await client.swarms.fsLs(
2420
+ {
2421
+ swarm: configUrl,
2422
+ kind: "templates",
2423
+ refresh: explicitRefresh,
2424
+ },
2425
+ { ndjson: true },
2426
+ )) as unknown as {
2427
+ items: Awaited<ReturnType<typeof swarmTemplates>>;
2428
+ alias: string | null;
2429
+ };
2430
+ emit(
2431
+ { items: response.items },
2432
+ `Swarm: ${response.alias ? printable(response.alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nTemplates: ${response.items.length}\n\n${table(
2433
+ ["NAME", "TITLE", "TARGET CID", "TEMPLATE CID"],
2434
+ response.items.map((item) => [
2435
+ item.selector,
2436
+ item.title,
2437
+ item.targetCid,
2277
2438
  item.templateCid,
2278
- );
2279
- const shell = process.platform === "win32" ? "powershell" : "posix";
2280
- io.out(
2281
- [
2282
- `${printable(item.selector)} — ${printable(item.title)}`,
2283
- printable(item.description) || "(No description.)",
2284
- "",
2285
- "Location",
2286
- ` Swarm: ${printable(swarm)}`,
2287
- ` Name: ${printable(item.name)}`,
2288
- "",
2289
- `Create a project (${shell === "powershell" ? "PowerShell" : "POSIX shell"})`,
2290
- ` ${templateRenderExample(reference, swarm, item.definition, shell)}`,
2291
- " Replace example parameter values as needed. No code is run by show.",
2292
- "",
2293
- "Parameters",
2294
- table(
2295
- ["NAME", "TYPE", "REQUIRED", "DEFAULT", "INPUT"],
2296
- templateParameterRows(item.definition),
2297
- "No parameters declared.",
2298
- ),
2299
- "Required means an input is needed when no default is declared.",
2300
- "",
2301
- "Output files (from project/)",
2302
- " my-project/",
2303
- ...tree.entries.map(
2304
- (entry) =>
2305
- `${" ".repeat(entry.path.split("/").length + 1)}${printable(entry.path.split("/").at(-1)!)}${entry.kind === "directory" ? "/" : ""}`,
2306
- ),
2307
- ...(tree.truncated
2308
- ? [
2309
- ` ... truncated: ${tree.truncated}; more files may exist.`,
2310
- ]
2311
- : tree.entries.length
2312
- ? []
2313
- : [" (no output files)"]),
2314
- "",
2315
- "Versions",
2316
- ` Template CID: ${item.templateCid}`,
2317
- ` Reference: ${reference}`,
2318
- ...(item.targetCid !== item.templateCid
2319
- ? [` Target CID (--expect): ${item.targetCid}`]
2320
- : []),
2321
- ].join("\n"),
2322
- );
2323
- }
2324
- } else if (parsed.path === "templates set") {
2325
- const item = await setSwarmTemplate(
2326
- context,
2327
- configUrl,
2328
- first!,
2329
- second!,
2330
- expected,
2331
- );
2332
- emit(
2333
- item,
2334
- `${item.reference} → ${item.targetCid} (Template ${item.templateCid})`,
2335
- );
2336
- } else {
2337
- const item = await removeSwarmTemplate(
2338
- context,
2339
- configUrl,
2340
- first!,
2341
- expected!,
2342
- );
2343
- emit(
2344
- { removed: item },
2345
- `Removed ${item.reference}; content and history are retained.`,
2439
+ ]),
2440
+ "No templates registered in this Swarm.\nAdd a template: ipab templates set NAME SOURCE",
2441
+ )}`,
2442
+ );
2443
+ } else if (parsed.path === "templates show") {
2444
+ const { templateRenderExample, templateParameterRows } =
2445
+ await import("./template-presentation.js");
2446
+ const response = (await client.swarms.fsStat(
2447
+ {
2448
+ swarm: configUrl,
2449
+ kind: "template",
2450
+ name: first!,
2451
+ includeTree: !parsed.flags.json,
2452
+ refresh: explicitRefresh,
2453
+ },
2454
+ { ndjson: true },
2455
+ )) as unknown as {
2456
+ item: Awaited<ReturnType<typeof swarmTemplates>>[number];
2457
+ tree?: Awaited<ReturnType<typeof templateOutputTree>>;
2458
+ alias: string | null;
2459
+ };
2460
+ const { item, tree, alias } = response;
2461
+ if (parsed.flags.json) io.out(JSON.stringify(item));
2462
+ else {
2463
+ const previewTree = tree ?? { entries: [], truncated: null };
2464
+ const swarm = alias ?? configUrl;
2465
+ const reference = formatNameReference(swarm, item.name);
2466
+ const shell = process.platform === "win32" ? "powershell" : "posix";
2467
+ io.out(
2468
+ [
2469
+ `${printable(item.selector)} — ${printable(item.title)}`,
2470
+ printable(item.description) || "(No description.)",
2471
+ "",
2472
+ "Location",
2473
+ ` Swarm: ${printable(swarm)}`,
2474
+ ` Name: ${printable(item.name)}`,
2475
+ "",
2476
+ `Create a project (${shell === "powershell" ? "PowerShell" : "POSIX shell"})`,
2477
+ ` ${templateRenderExample(reference, swarm, item.definition, shell)}`,
2478
+ " Replace example parameter values as needed. No code is run by show.",
2479
+ "",
2480
+ "Parameters",
2481
+ table(
2482
+ ["NAME", "TYPE", "REQUIRED", "DEFAULT", "INPUT"],
2483
+ templateParameterRows(item.definition),
2484
+ "No parameters declared.",
2485
+ ),
2486
+ "Required means an input is needed when no default is declared.",
2487
+ "",
2488
+ "Output files (from project/)",
2489
+ " my-project/",
2490
+ ...previewTree.entries.map(
2491
+ (entry) =>
2492
+ `${" ".repeat(entry.path.split("/").length + 1)}${printable(entry.path.split("/").at(-1)!)}${entry.kind === "directory" ? "/" : ""}`,
2493
+ ),
2494
+ ...(previewTree.truncated
2495
+ ? [
2496
+ ` ... truncated: ${previewTree.truncated}; more files may exist.`,
2497
+ ]
2498
+ : previewTree.entries.length
2499
+ ? []
2500
+ : [" (no output files)"]),
2501
+ "",
2502
+ "Versions",
2503
+ ` Template CID: ${item.templateCid}`,
2504
+ ` Reference: ${reference}`,
2505
+ ...(item.targetCid !== item.templateCid
2506
+ ? [` Target CID (--expect): ${item.targetCid}`]
2507
+ : []),
2508
+ ].join("\n"),
2346
2509
  );
2347
2510
  }
2348
- } finally {
2349
- await context.finishRead?.();
2511
+ } else if (parsed.path === "templates set") {
2512
+ const source = await resolveLocalPathIfPresent(second!);
2513
+ const item = (await client.swarms.fsSet(
2514
+ {
2515
+ swarm: configUrl,
2516
+ kind: "template",
2517
+ name: first!,
2518
+ source,
2519
+ expect: expected,
2520
+ },
2521
+ { ndjson: true },
2522
+ )) as unknown as Awaited<ReturnType<typeof setSwarmTemplate>>;
2523
+ emit(
2524
+ item,
2525
+ `${item.reference} → ${item.targetCid} (Template ${item.templateCid})`,
2526
+ );
2527
+ } else {
2528
+ const item = (await client.swarms.fsRm(
2529
+ {
2530
+ swarm: configUrl,
2531
+ kind: "template",
2532
+ name: first!,
2533
+ expect: expected!,
2534
+ },
2535
+ { ndjson: true },
2536
+ )) as unknown as Awaited<ReturnType<typeof removeSwarmTemplate>>;
2537
+ emit(
2538
+ { removed: item },
2539
+ `Removed ${item.reference}; content and history are retained.`,
2540
+ );
2350
2541
  }
2351
2542
  return 0;
2352
2543
  }
2544
+
2353
2545
  if (parsed.path.startsWith("register ")) {
2546
+ const { message } = await import("./errors.js");
2354
2547
  const references = parsed.registrySwarms?.length
2355
2548
  ? parsed.registrySwarms
2356
2549
  : selectedSwarm
@@ -2361,117 +2554,102 @@ async function performCli(
2361
2554
  "Register requires a selected Swarm. Pass --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.",
2362
2555
  );
2363
2556
  const targets = [
2364
- ...new Set(
2365
- references.map((reference) => state!.resolveSwarm(reference)),
2366
- ),
2557
+ ...new Set(references.map((reference) => resolveSwarm(reference))),
2367
2558
  ];
2368
- const schema = first
2369
- ? state.resolve(schemaAlias(first), true)
2370
- : undefined;
2371
2559
  const results: (
2372
- | {
2373
- items: Association[];
2374
- }
2375
- | {
2376
- association: Association;
2377
- }
2378
- | {
2379
- removed: string[];
2380
- }
2560
+ | { items: Association[] }
2561
+ | { association: Association }
2562
+ | { removed: string[] }
2381
2563
  )[] = [];
2382
2564
  const completed: string[] = [];
2383
2565
  const human: string[] = [];
2384
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2385
- const localApp =
2386
- parsed.path === "register set" && !parseNameReference(second!)
2387
- ? await resolveLocalBundleInput(second!)
2566
+ const resolvedApp =
2567
+ parsed.path === "register set"
2568
+ ? await resolveLocalPathIfPresent(second!)
2388
2569
  : undefined;
2389
- let registerOwner: HistoryOwnership | undefined;
2390
- let localAppCid: string | undefined;
2391
- try {
2392
- if (localApp) {
2393
- const session = `register:${randomUUID()}`;
2394
- registerOwner = await Ownership.create(
2395
- state,
2396
- store,
2397
- `register:${randomUUID()}`,
2398
- session,
2399
- );
2400
- localAppCid = await snapshotLocalBundle(
2401
- localApp,
2402
- registerOwner,
2403
- session,
2404
- {
2405
- diagnostic: (text) => {
2406
- io.err(text);
2407
- },
2408
- },
2570
+ if (parsed.path === "register set" && targets.length > 1) {
2571
+ const batch = (await client.swarms.fsSet(
2572
+ {
2573
+ swarm: targets[0]!,
2574
+ swarms: targets,
2575
+ kind: "register",
2576
+ schema: first!,
2577
+ app: resolvedApp!,
2578
+ argv: parsed.template ?? ["%"],
2579
+ replace: Boolean(parsed.options.replace),
2580
+ },
2581
+ { ndjson: true },
2582
+ )) as unknown as { associations: Association[] };
2583
+ for (let i = 0; i < targets.length; i++) {
2584
+ const association = batch.associations[i]!;
2585
+ results.push({ association });
2586
+ human.push(
2587
+ `${targets[i]}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`,
2409
2588
  );
2410
2589
  }
2411
- for (const configUrl of targets) {
2412
- const context = swarmContext();
2413
- try {
2414
- if (parsed.path === "register list") {
2415
- const items = await swarmRegistrations(context, configUrl);
2416
- const alias = state
2417
- .allSwarms()
2418
- .find((swarm) => swarm.cid === configUrl)?.alias;
2419
- results.push({ items });
2420
- human.push(
2421
- `Swarm: ${alias ? printable(alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nAssociations: ${items.length}\n\n${table(
2422
- ["TYPE CID", "APP CID"],
2423
- items.map((item) => [item.schemaCid, item.appCid]),
2424
- "No associations registered in this Swarm.\nRegister an App: ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS",
2425
- )}`,
2426
- );
2427
- } else if (parsed.path === "register set") {
2428
- const appCid =
2429
- localAppCid ??
2430
- (parseNameReference(second!)
2431
- ? (
2432
- await resolveReference(
2433
- context,
2434
- second!,
2435
- configUrl,
2436
- (reference) => state!.resolve(reference),
2437
- )
2438
- ).cid
2439
- : state.resolve(second!));
2440
- const association = await setSwarmAssociation(
2441
- context,
2442
- configUrl,
2443
- createAssociation(schema!, appCid, parsed.template ?? ["%"]),
2444
- Boolean(parsed.options.replace),
2445
- );
2446
- results.push({ association });
2447
- human.push(
2448
- `${configUrl}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`,
2449
- );
2450
- } else {
2451
- const removed = await removeSwarmAssociation(
2452
- context,
2453
- configUrl,
2454
- schema!,
2455
- );
2456
- results.push({ removed: [removed] });
2457
- human.push(`${configUrl}: removed association for ${removed}.`);
2458
- }
2459
- completed.push(configUrl);
2460
- } catch (cause) {
2461
- throw new HostError(
2462
- parsed.path === "register list"
2463
- ? `Cannot list associations for Swarm ${configUrl}: ${message(cause)}`
2464
- : `Registry operation failed for ${configUrl}: ${message(cause)}. Completed Swarms: ${completed.length ? completed.join(", ") : "(none)"}. Multiple Swarm edits are not atomic.`,
2465
- cause instanceof HostError ? cause.exitCode : 1,
2466
- cause instanceof HostError ? cause.code : "REGISTRY_FAILED",
2467
- "publication",
2590
+ emit(
2591
+ {
2592
+ swarms: results.map((result, index) => ({
2593
+ configUrl: targets[index],
2594
+ ...result,
2595
+ })),
2596
+ },
2597
+ human.join("\n\n"),
2598
+ );
2599
+ return 0;
2600
+ }
2601
+ for (const configUrl of targets) {
2602
+ try {
2603
+ if (parsed.path === "register list") {
2604
+ const response = (await client.swarms.fsLs(
2605
+ { swarm: configUrl, kind: "register" },
2606
+ { ndjson: true },
2607
+ )) as unknown as { items: Association[]; alias: string | null };
2608
+ results.push({ items: response.items });
2609
+ human.push(
2610
+ `Swarm: ${response.alias ? printable(response.alias) : "(no local alias)"}\nConfig URL: ${configUrl}\nAssociations: ${response.items.length}\n\n${table(
2611
+ ["TYPE CID", "APP CID"],
2612
+ response.items.map((item) => [item.schemaCid, item.appCid]),
2613
+ "No associations registered in this Swarm.\nRegister an App: ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS",
2614
+ )}`,
2615
+ );
2616
+ } else if (parsed.path === "register set") {
2617
+ const association = (await client.swarms.fsSet(
2618
+ {
2619
+ swarm: configUrl,
2620
+ kind: "register",
2621
+ schema: first!,
2622
+ app: resolvedApp!,
2623
+ argv: parsed.template ?? ["%"],
2624
+ replace: Boolean(parsed.options.replace),
2625
+ },
2626
+ { ndjson: true },
2627
+ )) as unknown as Association;
2628
+ results.push({ association });
2629
+ human.push(
2630
+ `${configUrl}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`,
2631
+ );
2632
+ } else {
2633
+ const response = (await client.swarms.fsRm(
2634
+ { swarm: configUrl, kind: "register", schema: first! },
2635
+ { ndjson: true },
2636
+ )) as unknown as { removed: string };
2637
+ results.push({ removed: [response.removed] });
2638
+ human.push(
2639
+ `${configUrl}: removed association for ${response.removed}.`,
2468
2640
  );
2469
- } finally {
2470
- await context.finishRead?.();
2471
2641
  }
2642
+ completed.push(configUrl);
2643
+ } catch (cause) {
2644
+ throw new HostError(
2645
+ parsed.path === "register list"
2646
+ ? `Cannot list associations for Swarm ${configUrl}: ${message(cause)}`
2647
+ : `Registry operation failed for ${configUrl}: ${message(cause)}. Completed Swarms: ${completed.length ? completed.join(", ") : "(none)"}. Multiple Swarm edits are not atomic.`,
2648
+ cause instanceof HostError ? cause.exitCode : 1,
2649
+ cause instanceof HostError ? cause.code : "REGISTRY_FAILED",
2650
+ "publication",
2651
+ );
2472
2652
  }
2473
- } finally {
2474
- await registerOwner?.release();
2475
2653
  }
2476
2654
  emit(
2477
2655
  {
@@ -2484,10 +2662,9 @@ async function performCli(
2484
2662
  );
2485
2663
  return 0;
2486
2664
  }
2665
+
2487
2666
  switch (parsed.path) {
2488
2667
  case "profile": {
2489
- const context = swarmContext();
2490
- readContext = context;
2491
2668
  const changes = {
2492
2669
  ...(typeof parsed.options.name === "string"
2493
2670
  ? { name: parsed.options.name }
@@ -2497,13 +2674,22 @@ async function performCli(
2497
2674
  : {}),
2498
2675
  };
2499
2676
  if (!Object.keys(changes).length) {
2500
- const profile = await accountProfile(context);
2677
+ const profile = (await client.swarms.identity({
2678
+ ndjson: true,
2679
+ })) as {
2680
+ name: string;
2681
+ description: string;
2682
+ publicKey: string;
2683
+ updatedAt: string | null;
2684
+ };
2501
2685
  emit(
2502
2686
  { profile, localPersisted: profile.updatedAt !== null },
2503
2687
  `Name: ${printable(profile.name)}\nDescription: ${printable(profile.description)}\nPublic key: ${profile.publicKey}`,
2504
2688
  );
2505
2689
  } else {
2506
- const result = await updateAccountProfile(context, changes);
2690
+ const result = (await client.swarms.governance("profile", changes, {
2691
+ ndjson: true,
2692
+ })) as Awaited<ReturnType<typeof updateAccountProfile>>;
2507
2693
  emit(
2508
2694
  result,
2509
2695
  [
@@ -2526,8 +2712,19 @@ async function performCli(
2526
2712
  break;
2527
2713
  }
2528
2714
  case "swarm use": {
2529
- state.useSwarm(first!);
2530
- const result = selection();
2715
+ const resolvedUrl = resolveSwarm(first!);
2716
+ const registered = registeredSwarms.some(
2717
+ (entry) => entry.cid === resolvedUrl,
2718
+ );
2719
+ if (!registered) {
2720
+ throw new HostError(
2721
+ `Unknown Swarm "${first!}". Run ipab swarm list or register it with ipab swarm set ALIAS CONFIG_URL.`,
2722
+ );
2723
+ }
2724
+ await client.host.setConfig("swarm.default", resolvedUrl, {
2725
+ fromString: true,
2726
+ });
2727
+ const result = selection(resolvedUrl);
2531
2728
  emit(result, `Saved current swarm: ${result.savedCurrent}`);
2532
2729
  if (result.source === "flag" || result.source === "env")
2533
2730
  io.err(
@@ -2536,21 +2733,19 @@ async function performCli(
2536
2733
  break;
2537
2734
  }
2538
2735
  case "swarm remove": {
2539
- const removed = state.removeSwarm(first!);
2736
+ const result = await client.swarms.remove({ swarm: first! });
2540
2737
  emit(
2541
- {
2542
- removed,
2543
- savedCurrent:
2544
- state.config({ includeSecrets: false })["swarm.default"] ?? null,
2545
- },
2546
- `Removed registration ${removed}. Credentials, content and remote membership are unchanged.`,
2738
+ result,
2739
+ `Removed registration ${result.removed}. Credentials, content and remote membership are unchanged.`,
2547
2740
  );
2548
2741
  break;
2549
2742
  }
2550
2743
  case "swarm set": {
2551
2744
  swarmAlias(first!);
2552
2745
  const cid = swarmUrl(second!);
2553
- const previous = state.swarms().find((entry) => entry.alias === first);
2746
+ const previous = registeredSwarms.find(
2747
+ (entry) => entry.alias === first,
2748
+ );
2554
2749
  if (previous && previous.cid !== cid) {
2555
2750
  io.err(`Swarm alias ${first}: ${previous.cid} -> ${cid}`);
2556
2751
  if (
@@ -2564,1109 +2759,888 @@ async function performCli(
2564
2759
  "Alias unchanged. Retargeting requires --yes or interactive confirmation.",
2565
2760
  );
2566
2761
  }
2567
- const entry = state.setSwarm(first!, cid, previous?.cid ?? null);
2568
- emit(
2762
+ const entry = await client.swarms.set({
2763
+ alias: first!,
2764
+ url: cid,
2765
+ expectedTarget: previous?.cid ?? null,
2766
+ });
2767
+ emit(entry, `Set local swarm alias ${entry.alias} (${cid}).`);
2768
+ break;
2769
+ }
2770
+ case "fs ls": {
2771
+ const result = await client.swarms.fsLs(
2569
2772
  {
2570
- configUrl: entry.cid,
2571
- alias: entry.alias,
2572
- savedCurrent:
2573
- state.config({ includeSecrets: false })["swarm.default"] ?? null,
2773
+ swarm: requireSwarm(),
2774
+ path: first,
2775
+ all: Boolean(parsed.options.all),
2776
+ recursive: Boolean(parsed.options.recursive),
2777
+ refresh: explicitRefresh,
2574
2778
  },
2575
- `Set local swarm alias ${entry.alias} (${cid}).`,
2779
+ { ndjson: true },
2576
2780
  );
2781
+ const text = result.entries.length
2782
+ ? result.entries
2783
+ .map(
2784
+ (entry) =>
2785
+ `${result.recursive ? entry.path : entry.name}\t${entry.cid ?? "<dir>"}\t${entry.size !== null ? String(entry.size) : entry.kind}`,
2786
+ )
2787
+ .join("\n")
2788
+ : "No entries.";
2789
+ emit(result, text);
2790
+ if (result.truncated || result.skippedSubtrees > 0) {
2791
+ io.err(
2792
+ `Listing incomplete: truncated=${String(result.truncated)}, skippedSubtrees=${String(result.skippedSubtrees)}.`,
2793
+ );
2794
+ }
2577
2795
  break;
2578
2796
  }
2579
- case "daemon": {
2580
- if (parsed.flags.json)
2581
- syntax(
2582
- "--json is not supported for daemon; diagnostics are written to stderr.",
2583
- );
2584
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2585
- const controller = new AbortController();
2586
- const interrupt = () => {
2587
- controller.abort();
2797
+ case "fs stat": {
2798
+ const result = await client.swarms.fsStat(
2799
+ {
2800
+ swarm: requireSwarm(),
2801
+ path: first!,
2802
+ ...(explicitRefresh !== undefined
2803
+ ? { refresh: explicitRefresh }
2804
+ : {}),
2805
+ },
2806
+ { ndjson: true },
2807
+ );
2808
+ const lines = [
2809
+ `Path: ${result.path || "/"}`,
2810
+ `CID: ${result.cid ?? "(virtual)"}`,
2811
+ `Kind: ${result.kind}`,
2812
+ `Size: ${result.size !== null ? String(result.size) : "unavailable"}`,
2813
+ ...(result.kind === "directory" && result.isBundle !== undefined
2814
+ ? [`Bundle: ${result.isBundle ? "yes" : "no"}`]
2815
+ : []),
2816
+ ...(result.kind === "directory" && result.entryCount !== undefined
2817
+ ? [`Entries: ${result.entryCount}`]
2818
+ : []),
2819
+ `Swarm: ${result.swarm}`,
2820
+ `Snapshot: ${result.snapshotVersion === "legacy" ? "legacy (read-only virtual)" : "v7"}`,
2821
+ ];
2822
+ emit(result, lines.join("\n"));
2823
+ break;
2824
+ }
2825
+ case "fs set": {
2826
+ const result = await client.swarms.fsSet(
2827
+ {
2828
+ swarm: requireSwarm(),
2829
+ path: first!,
2830
+ cid: second!,
2831
+ ...(typeof parsed.options.expect === "string"
2832
+ ? { expect: parsed.options.expect }
2833
+ : {}),
2834
+ ...(parsed.options.replace ? { replace: true } : {}),
2835
+ },
2836
+ { ndjson: true },
2837
+ );
2838
+ emit(
2839
+ result,
2840
+ result.changed
2841
+ ? `Set ${result.path} -> ${result.cid} (HEAD ${result.headCid})`
2842
+ : `Unchanged ${result.path} -> ${result.cid} (HEAD ${result.headCid})`,
2843
+ );
2844
+ break;
2845
+ }
2846
+ case "fs rm": {
2847
+ const result = await client.swarms.fsRm(
2848
+ {
2849
+ swarm: requireSwarm(),
2850
+ path: first!,
2851
+ ...(typeof parsed.options.expect === "string"
2852
+ ? { expect: parsed.options.expect }
2853
+ : {}),
2854
+ },
2855
+ { ndjson: true },
2856
+ );
2857
+ emit(
2858
+ result,
2859
+ `Removed ${result.path} (was ${result.removedCid}, HEAD ${result.headCid})`,
2860
+ );
2861
+ break;
2862
+ }
2863
+ case "swarm replicate": {
2864
+ const result = (await client.swarms.replicate(
2865
+ {
2866
+ swarm: requireSwarm(),
2867
+ ...(typeof parsed.options.pivot === "string"
2868
+ ? { pivot: parsed.options.pivot }
2869
+ : {}),
2870
+ },
2871
+ { ndjson: true },
2872
+ )) as Awaited<ReturnType<typeof replicateSwarm>>;
2873
+ emit(
2874
+ result,
2875
+ [
2876
+ `HEAD: ${result.headCid}`,
2877
+ ...result.results.map(
2878
+ (entry) =>
2879
+ `${entry.peerId}: ${entry.status}${entry.error ? ` (${entry.error})` : ""}`,
2880
+ ),
2881
+ ].join("\n"),
2882
+ );
2883
+ break;
2884
+ }
2885
+ case "skills show": {
2886
+ const named = parseNameReference(first!);
2887
+ const targetSwarm = named?.swarm
2888
+ ? resolveSwarm(named.swarm)
2889
+ : requireSwarm();
2890
+ const ref = await resolveLocalPathIfPresent(first!);
2891
+ const payload = (await client.swarms.fsStat(
2892
+ {
2893
+ swarm: targetSwarm,
2894
+ kind: "skill",
2895
+ ref,
2896
+ ...(explicitRefresh !== undefined
2897
+ ? { refresh: explicitRefresh }
2898
+ : {}),
2899
+ },
2900
+ { ndjson: true },
2901
+ )) as unknown as {
2902
+ swarm: string;
2903
+ schemaCid: string;
2904
+ resolvedFrom: string;
2905
+ contentCid?: string;
2906
+ reference?: string;
2907
+ name: string;
2908
+ cid: string;
2909
+ identity: string;
2910
+ description: string;
2588
2911
  };
2589
- process.once("SIGINT", interrupt);
2590
- process.once("SIGTERM", interrupt);
2591
- try {
2592
- await swarmDaemon(
2593
- swarmContext(),
2594
- controller.signal,
2595
- (ctx, url, report) => syncDaemonSwarm(ctx, url, undefined, report),
2596
- );
2597
- } catch (cause) {
2598
- if (!controller.signal.aborted) throw cause;
2599
- } finally {
2600
- process.removeListener("SIGINT", interrupt);
2601
- process.removeListener("SIGTERM", interrupt);
2602
- }
2912
+ const lines = [
2913
+ `Swarm: ${payload.swarm}`,
2914
+ `Schema: ${payload.schemaCid}`,
2915
+ ...(payload.contentCid ? [`Content CID: ${payload.contentCid}`] : []),
2916
+ `Skill: ${payload.identity}`,
2917
+ `Skill CID: ${payload.cid}`,
2918
+ `Path: ${payload.name}`,
2919
+ `Description: ${payload.description}`,
2920
+ ];
2921
+ emit(payload, lines.join("\n"));
2603
2922
  break;
2604
2923
  }
2605
- case "swarm update":
2606
- case "search":
2607
- case "skills list":
2608
- case "skills show":
2609
- case "skills set":
2610
- case "skills remove":
2611
- case "skills sync":
2612
- case "swarm create":
2613
- case "swarm request":
2614
- case "swarm approve":
2615
- case "swarm pivot grant":
2616
- case "swarm export":
2617
- case "swarm exclude":
2618
- case "swarm resume":
2619
- case "swarm profile":
2620
- case "swarm members":
2621
- case "swarm status":
2622
- case "swarm replicate":
2623
- case "fs ls":
2624
- case "fs stat":
2625
- case "fs set":
2626
- case "fs rm":
2627
- case "publish":
2628
- case "pin":
2629
- case "get": {
2630
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
2631
- const context = swarmContext();
2632
- readContext = context;
2633
- if (parsed.path.startsWith("fs ")) {
2634
- const {
2635
- listSwarmFsPath,
2636
- removeSwarmFsPath,
2637
- setSwarmFsPath,
2638
- statSwarmFsPath,
2639
- } = await import("./swarm-fs.js");
2640
- const swarmUrlSelected = requireSwarm();
2641
- const explicitRefresh: boolean | undefined =
2642
- parsed.options.refresh || parsed.options.force
2643
- ? true
2644
- : parsed.options["no-refresh"] || parsed.options["no-force"]
2645
- ? false
2646
- : value("swarm.forceRefresh")
2647
- ? true
2648
- : undefined;
2649
-
2650
- if (parsed.path === "fs ls") {
2651
- const result = await listSwarmFsPath(
2652
- context,
2653
- swarmUrlSelected,
2654
- first,
2655
- {
2656
- all: Boolean(parsed.options.all),
2657
- recursive: Boolean(parsed.options.recursive),
2658
- mode: "local-first",
2659
- ...(explicitRefresh !== undefined
2660
- ? { forceRefresh: explicitRefresh }
2661
- : {}),
2662
- },
2663
- );
2664
- store = context.store;
2665
- const text = result.entries.length
2666
- ? result.entries
2667
- .map(
2668
- (entry) =>
2669
- `${result.recursive ? entry.path : entry.name}\t${entry.cid ?? "<dir>"}\t${entry.size !== null ? String(entry.size) : entry.kind}`,
2670
- )
2671
- .join("\n")
2672
- : "No entries.";
2673
- emit(result, text);
2674
- if (result.truncated || result.skippedSubtrees > 0) {
2675
- io.err(
2676
- `Listing incomplete: truncated=${String(result.truncated)}, skippedSubtrees=${String(result.skippedSubtrees)}.`,
2677
- );
2678
- }
2679
- break;
2680
- }
2681
-
2682
- if (parsed.path === "fs stat") {
2683
- const result = await statSwarmFsPath(
2684
- context,
2685
- swarmUrlSelected,
2686
- first!,
2687
- {
2688
- mode: "local-first",
2689
- ...(explicitRefresh !== undefined
2690
- ? { forceRefresh: explicitRefresh }
2691
- : {}),
2692
- },
2693
- );
2694
- store = context.store;
2695
- const lines = [
2696
- `Path: ${result.path || "/"}`,
2697
- `CID: ${result.cid ?? "(virtual)"}`,
2698
- `Kind: ${result.kind}`,
2699
- `Size: ${result.size !== null ? String(result.size) : "unavailable"}`,
2700
- ...(result.kind === "directory" && result.isBundle !== undefined
2701
- ? [`Bundle: ${result.isBundle ? "yes" : "no"}`]
2702
- : []),
2703
- ...(result.kind === "directory" && result.entryCount !== undefined
2704
- ? [`Entries: ${result.entryCount}`]
2705
- : []),
2706
- `Swarm: ${result.swarm}`,
2707
- `Snapshot: ${result.snapshotVersion === "legacy" ? "legacy (read-only virtual)" : "v7"}`,
2708
- ];
2709
- emit(result, lines.join("\n"));
2710
- break;
2711
- }
2712
-
2713
- if (parsed.path === "fs set") {
2714
- const result = await setSwarmFsPath(
2715
- context,
2716
- swarmUrlSelected,
2717
- first!,
2718
- second!,
2719
- {
2720
- ...(typeof parsed.options.expect === "string"
2721
- ? { expect: parsed.options.expect }
2722
- : {}),
2723
- ...(parsed.options.replace ? { replace: true } : {}),
2724
- },
2725
- );
2726
- store = context.store;
2727
- emit(
2728
- result,
2729
- result.changed
2730
- ? `Set ${result.path} -> ${result.cid} (HEAD ${result.headCid})`
2731
- : `Unchanged ${result.path} -> ${result.cid} (HEAD ${result.headCid})`,
2732
- );
2733
- break;
2734
- }
2735
-
2736
- const result = await removeSwarmFsPath(
2737
- context,
2738
- swarmUrlSelected,
2739
- first!,
2924
+ case "skills set": {
2925
+ const targetSwarm = requireSwarm();
2926
+ const skill = await resolveLocalPathIfPresent(first!);
2927
+ const result = (await client.swarms.fsSet(
2928
+ {
2929
+ swarm: targetSwarm,
2930
+ kind: "skill",
2931
+ skill,
2932
+ global: Boolean(parsed.options.global),
2933
+ types: parsed.types ?? [],
2934
+ replace: Boolean(parsed.options.replace),
2935
+ },
2936
+ { ndjson: true },
2937
+ )) as unknown as Awaited<ReturnType<typeof setSwarmSkill>>;
2938
+ const text = result.changed
2939
+ ? [
2940
+ `Skill: ${result.identity} (${result.cid})`,
2941
+ `HEAD: ${result.headCid}`,
2942
+ ...result.targets.map((target) => {
2943
+ const status = !target.changed
2944
+ ? "unchanged"
2945
+ : target.previousCid
2946
+ ? "updated"
2947
+ : "created";
2948
+ return target.scope === "global"
2949
+ ? ` global -> ${target.name} (${status})`
2950
+ : ` type ${target.schemaCid} -> ${target.name} (${status})`;
2951
+ }),
2952
+ ].join("\n")
2953
+ : `Unchanged: ${result.identity} (${result.cid}) (HEAD ${result.headCid})`;
2954
+ emit(result, text);
2955
+ break;
2956
+ }
2957
+ case "skills remove": {
2958
+ const targetSwarm = requireSwarm();
2959
+ const globalName =
2960
+ typeof parsed.options.global === "string"
2961
+ ? parsed.options.global
2962
+ : undefined;
2963
+ const result = (await client.swarms.fsRm(
2964
+ {
2965
+ swarm: targetSwarm,
2966
+ kind: "skill",
2967
+ ...(globalName !== undefined ? { globalName } : {}),
2968
+ types: parsed.types ?? [],
2969
+ },
2970
+ { ndjson: true },
2971
+ )) as unknown as Awaited<ReturnType<typeof removeSwarmSkill>>;
2972
+ const lines = [
2973
+ `Removed ${result.removed.length} Skill association(s) (HEAD ${result.headCid}):`,
2974
+ ...result.removed.map((entry) =>
2975
+ entry.scope === "global"
2976
+ ? ` global ${entry.name} (was ${entry.removedCid})`
2977
+ : ` type ${entry.schemaCid} ${entry.name} (was ${entry.removedCid})`,
2978
+ ),
2979
+ ];
2980
+ emit(result, lines.join("\n"));
2981
+ break;
2982
+ }
2983
+ case "skills list": {
2984
+ const targetSwarm = requireSwarm();
2985
+ const result = (await client.swarms.fsLs(
2986
+ {
2987
+ swarm: targetSwarm,
2988
+ kind: "skills",
2989
+ names: parsed.positional,
2990
+ agents: parsed.agents ?? [],
2991
+ refresh: explicitRefresh,
2992
+ },
2993
+ { ndjson: true },
2994
+ )) as unknown as Awaited<ReturnType<typeof manageSkills>> & {
2995
+ typeSkills: Awaited<ReturnType<typeof swarmTypeSkills>>;
2996
+ };
2997
+ const globalLines = [
2998
+ table(
2999
+ ["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"],
3000
+ result.items.map((skill) => [
3001
+ skill.name,
3002
+ skill.cid,
3003
+ skill.identity,
3004
+ skill.status,
3005
+ ]),
3006
+ "No Global Skills.",
3007
+ ),
3008
+ ...result.items.flatMap((skill) => skill.problems),
3009
+ ...result.orphaned.map(
3010
+ (skill) =>
3011
+ `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`,
3012
+ ),
3013
+ ];
3014
+ const typeLines = [
3015
+ "Type Skills:",
3016
+ table(
3017
+ ["TYPE CID", "SKILL NAME", "SKILL CID"],
3018
+ result.typeSkills.map((entry) => [
3019
+ entry.schemaCid,
3020
+ entry.identity,
3021
+ entry.cid,
3022
+ ]),
3023
+ "No Type Skills.",
3024
+ ),
3025
+ ];
3026
+ emit(result, [...globalLines, "", ...typeLines].join("\n"));
3027
+ if (!result.ok) return 1;
3028
+ break;
3029
+ }
3030
+ case "skills sync": {
3031
+ const targetSwarm = requireSwarm();
3032
+ const syncParams = {
3033
+ swarm: targetSwarm,
3034
+ names: parsed.positional,
3035
+ agents: parsed.agents ?? [],
3036
+ overrideExisting: Boolean(parsed.options["override-existing"]),
3037
+ refresh: explicitRefresh,
3038
+ };
3039
+ let result: Awaited<ReturnType<typeof manageSkills>>;
3040
+ if (parsed.options["dry-run"] || parsed.options.yes || !io.tty) {
3041
+ result = (await client.host.syncSkills(
2740
3042
  {
2741
- ...(typeof parsed.options.expect === "string"
2742
- ? { expect: parsed.options.expect }
2743
- : {}),
3043
+ ...syncParams,
3044
+ dryRun: Boolean(parsed.options["dry-run"]),
3045
+ yes: Boolean(parsed.options.yes),
2744
3046
  },
2745
- );
2746
- store = context.store;
2747
- emit(
2748
- result,
2749
- `Removed ${result.path} (was ${result.removedCid}, HEAD ${result.headCid})`,
2750
- );
2751
- break;
2752
- }
2753
- if (parsed.path === "swarm replicate") {
2754
- const { replicateSwarm } = await import("./swarm.js");
2755
- context.diagnostic = (text) => {
2756
- io.err(text);
2757
- };
2758
- const result = await replicateSwarm(
2759
- context,
2760
- requireSwarm(),
2761
- undefined,
3047
+ { ndjson: true },
3048
+ )) as Awaited<ReturnType<typeof manageSkills>>;
3049
+ } else {
3050
+ const preview = (await client.host.syncSkills(
2762
3051
  {
2763
- ...(typeof parsed.options.pivot === "string"
2764
- ? { pivot: parsed.options.pivot }
2765
- : {}),
3052
+ ...syncParams,
3053
+ dryRun: true,
3054
+ yes: false,
2766
3055
  },
2767
- );
2768
- store = context.store;
2769
- emit(
2770
- result,
2771
- [
2772
- `HEAD: ${result.headCid}`,
2773
- ...result.results.map(
2774
- (entry) =>
2775
- `${entry.peerId}: ${entry.status}${entry.error ? ` (${entry.error})` : ""}`,
2776
- ),
2777
- ].join("\n"),
2778
- );
2779
- break;
2780
- }
2781
- if (parsed.path.startsWith("skills ")) {
2782
- const explicitRefresh: boolean | undefined =
2783
- parsed.options.refresh || parsed.options.force
2784
- ? true
2785
- : parsed.options["no-refresh"] || parsed.options["no-force"]
2786
- ? false
2787
- : value("swarm.forceRefresh")
2788
- ? true
2789
- : undefined;
2790
- const refreshOption =
2791
- explicitRefresh !== undefined
2792
- ? { forceRefresh: explicitRefresh }
2793
- : {};
2794
-
2795
- if (parsed.path === "skills show") {
2796
- const named = parseNameReference(first!);
2797
- let targetSwarm: string;
2798
- let schemaCid: string;
2799
- let resolvedFrom: "uri" | "local" | "schema" | "content";
2800
- let contentCid: string | undefined;
2801
- let reference: string | undefined;
2802
- let association:
2803
- Awaited<ReturnType<typeof swarmTypeSkill>> | undefined;
2804
-
2805
- if (named) {
2806
- targetSwarm = named.swarm
2807
- ? state.resolveSwarm(named.swarm)
2808
- : requireSwarm();
2809
- const resolved = await resolveReference(
2810
- context,
2811
- first!,
2812
- targetSwarm,
2813
- (ref) => state!.resolve(ref),
2814
- false,
2815
- "local-first",
2816
- );
2817
- store = context.store;
2818
- contentCid = resolved.cid;
2819
- reference = first!;
2820
- const bundle = await openBundle(CID.parse(contentCid), {
2821
- resolveCid: (key) => context.store.block.get(key.toString()),
2822
- });
2823
- schemaCid = bundle.schemaKey;
2824
- resolvedFrom = "uri";
2825
- association = await swarmTypeSkill(
2826
- context,
2827
- targetSwarm,
2828
- schemaCid,
2829
- {
2830
- mode: "local-first",
2831
- ...refreshOption,
2832
- },
2833
- );
2834
- } else {
2835
- targetSwarm = requireSwarm();
2836
- const localInput = await resolveLocalBundleInput(first!);
2837
- if (localInput) {
2838
- const session = `skills-show:${randomUUID()}`;
2839
- const owner = await Ownership.create(
2840
- state,
2841
- store,
2842
- `skills-show:${randomUUID()}`,
2843
- session,
2844
- );
2845
- try {
2846
- const root = await snapshotLocalBundle(
2847
- localInput,
2848
- owner,
2849
- session,
2850
- {
2851
- diagnostic: (text) => {
2852
- io.err(text);
2853
- },
2854
- },
2855
- );
2856
- contentCid = await artifactValue(store, root);
2857
- const bundle = await openBundle(CID.parse(contentCid), {
2858
- resolveCid: (key) => store!.block.get(key.toString()),
2859
- });
2860
- schemaCid = bundle.schemaKey;
2861
- resolvedFrom = "local";
2862
- association = await swarmTypeSkill(
2863
- context,
2864
- targetSwarm,
2865
- schemaCid,
2866
- {
2867
- mode: "local-first",
2868
- ...refreshOption,
2869
- },
2870
- );
2871
- } finally {
2872
- await owner.release();
2873
- }
2874
- } else {
2875
- const resolved = state.resolve(schemaAlias(first!));
2876
- const parsedCid = CID.parse(resolved);
2877
- const isSchemaCid =
2878
- parsedCid.code === 0x71 && parsedCid.multihash.code === 0x12;
2879
- schemaCid = resolved;
2880
- resolvedFrom = "schema";
2881
- if (isSchemaCid) {
2882
- association = await swarmTypeSkill(
2883
- context,
2884
- targetSwarm,
2885
- resolved,
2886
- {
2887
- mode: "local-first",
2888
- ...refreshOption,
2889
- },
2890
- );
2891
- } else {
2892
- const refResolved = await resolveReference(
2893
- context,
2894
- resolved,
2895
- targetSwarm,
2896
- (ref) => state!.resolve(ref),
2897
- false,
2898
- "local-first",
2899
- );
2900
- store = context.store;
2901
- const bundle = await openBundle(CID.parse(refResolved.cid), {
2902
- resolveCid: (key) =>
2903
- context.store.block.get(key.toString()),
2904
- });
2905
- schemaCid = bundle.schemaKey;
2906
- contentCid = refResolved.cid;
2907
- resolvedFrom = "content";
2908
- association = await swarmTypeSkill(
2909
- context,
2910
- targetSwarm,
2911
- schemaCid,
2912
- {
2913
- mode: "local-first",
2914
- ...refreshOption,
2915
- },
2916
- );
2917
- }
2918
- }
2919
- }
2920
- store = context.store;
2921
- if (!association)
2922
- throw new HostError(
2923
- `No Skill associated with Schema ${schemaCid} in Swarm ${targetSwarm}. Associate one with: ipab skills set SKILL --type ${schemaCid}`,
2924
- 1,
2925
- "SKILL_NOT_FOUND",
2926
- "state",
2927
- );
2928
- const payload = {
2929
- swarm: targetSwarm,
2930
- schemaCid,
2931
- resolvedFrom,
2932
- ...(contentCid ? { contentCid } : {}),
2933
- ...(reference ? { reference } : {}),
2934
- name: association.name,
2935
- cid: association.cid,
2936
- identity: association.identity,
2937
- description: association.description,
2938
- };
2939
- const lines = [
2940
- `Swarm: ${targetSwarm}`,
2941
- `Schema: ${schemaCid}`,
2942
- ...(contentCid ? [`Content CID: ${contentCid}`] : []),
2943
- `Skill: ${association.identity}`,
2944
- `Skill CID: ${association.cid}`,
2945
- `Path: ${association.name}`,
2946
- `Description: ${association.description}`,
2947
- ];
2948
- emit(payload, lines.join("\n"));
2949
- break;
2950
- }
2951
-
2952
- if (parsed.path === "skills set") {
2953
- const targetSwarm = requireSwarm();
2954
- const types = (parsed.types ?? []).map((schema) =>
2955
- state!.resolve(schemaAlias(schema), true),
3056
+ { ndjson: true },
3057
+ )) as Awaited<ReturnType<typeof manageSkills>>;
3058
+ if (!preview.ok) {
3059
+ result = preview;
3060
+ } else {
3061
+ const selected = preview.items.filter(
3062
+ (skill) =>
3063
+ !parsed.positional.length ||
3064
+ parsed.positional.includes(skill.name) ||
3065
+ parsed.positional.includes(skill.identity),
2956
3066
  );
2957
- const localSkill = !parseNameReference(first!)
2958
- ? await resolveLocalBundleInput(first!)
2959
- : undefined;
2960
- let skillOwner: HistoryOwnership | undefined;
2961
- try {
2962
- let skillCid: string;
2963
- if (localSkill) {
2964
- const session = `skills-set:${randomUUID()}`;
2965
- skillOwner = await Ownership.create(
2966
- state,
2967
- store,
2968
- `skills-set:${randomUUID()}`,
2969
- session,
2970
- );
2971
- skillCid = await snapshotLocalBundle(
2972
- localSkill,
2973
- skillOwner,
2974
- session,
2975
- {
2976
- diagnostic: (text) => {
2977
- io.err(text);
2978
- },
2979
- },
3067
+ const hasChanges = selected.some((skill) =>
3068
+ skill.agents.some((agent) => agent.status !== "current"),
3069
+ );
3070
+ if (!selected.length) {
3071
+ result = { ...preview, dryRun: false };
3072
+ } else {
3073
+ if (
3074
+ hasChanges &&
3075
+ !(await io.confirm(
3076
+ `Authorize ${preview.installer} and the changes above?`,
3077
+ ))
3078
+ ) {
3079
+ throw new HostError(
3080
+ "Skill sync requires --yes or interactive consent. Use --override-existing to authorize replacing existing Skills; source and link conflicts remain protected.",
2980
3081
  );
2981
- } else if (parseNameReference(first!)) {
2982
- skillCid = (
2983
- await resolveReference(
2984
- context,
2985
- first!,
2986
- targetSwarm,
2987
- (ref) => state!.resolve(ref),
2988
- false,
2989
- )
2990
- ).cid;
2991
- store = context.store;
2992
- } else {
2993
- skillCid = state.resolve(first!);
2994
3082
  }
2995
- const result = await setSwarmSkill(context, targetSwarm, {
2996
- skillCid,
2997
- global: Boolean(parsed.options.global),
2998
- types,
2999
- replace: Boolean(parsed.options.replace),
3000
- });
3001
- store = context.store;
3002
- const text = result.changed
3003
- ? [
3004
- `Skill: ${result.identity} (${result.cid})`,
3005
- `HEAD: ${result.headCid}`,
3006
- ...result.targets.map((target) => {
3007
- const status = !target.changed
3008
- ? "unchanged"
3009
- : target.previousCid
3010
- ? "updated"
3011
- : "created";
3012
- return target.scope === "global"
3013
- ? ` global -> ${target.name} (${status})`
3014
- : ` type ${target.schemaCid} -> ${target.name} (${status})`;
3015
- }),
3016
- ].join("\n")
3017
- : `Unchanged: ${result.identity} (${result.cid}) (HEAD ${result.headCid})`;
3018
- emit(result, text);
3019
- } finally {
3020
- await skillOwner?.release();
3083
+ result = (await client.host.syncSkills(
3084
+ {
3085
+ ...syncParams,
3086
+ dryRun: false,
3087
+ yes: true,
3088
+ quietPreview: true,
3089
+ },
3090
+ { ndjson: true },
3091
+ )) as Awaited<ReturnType<typeof manageSkills>>;
3021
3092
  }
3022
- break;
3023
- }
3024
-
3025
- if (parsed.path === "skills remove") {
3026
- const targetSwarm = requireSwarm();
3027
- const types = (parsed.types ?? []).map((schema) =>
3028
- state!.resolve(schemaAlias(schema), true),
3029
- );
3030
- const globalName =
3031
- typeof parsed.options.global === "string"
3032
- ? parsed.options.global
3033
- : undefined;
3034
- const result = await removeSwarmSkill(context, targetSwarm, {
3035
- ...(globalName !== undefined ? { globalName } : {}),
3036
- types,
3037
- });
3038
- store = context.store;
3039
- const lines = [
3040
- `Removed ${result.removed.length} Skill association(s) (HEAD ${result.headCid}):`,
3041
- ...result.removed.map((entry) =>
3042
- entry.scope === "global"
3043
- ? ` global ${entry.name} (was ${entry.removedCid})`
3044
- : ` type ${entry.schemaCid} ${entry.name} (was ${entry.removedCid})`,
3045
- ),
3046
- ];
3047
- emit(result, lines.join("\n"));
3048
- break;
3049
- }
3050
-
3051
- if (parsed.path === "skills list") {
3052
- const targetSwarm = requireSwarm();
3053
- const managed = await manageSkills(context, targetSwarm, {
3054
- sync: false,
3055
- names: parsed.positional,
3056
- agents: parsed.agents ?? [],
3057
- overrideExisting: false,
3058
- dryRun: false,
3059
- yes: false,
3060
- tty: io.tty,
3061
- confirm: (text) => io.confirm(text),
3062
- preview: (text) => {
3063
- io.err(text);
3064
- },
3065
- });
3066
- const typeSkills = await swarmTypeSkills(context, targetSwarm, {
3067
- mode: "local-first",
3068
- ...refreshOption,
3069
- });
3070
- const result = {
3071
- swarm: managed.swarm,
3072
- installer: managed.installer,
3073
- agents: managed.agents,
3074
- dryRun: managed.dryRun,
3075
- items: managed.items,
3076
- typeSkills,
3077
- orphaned: managed.orphaned,
3078
- results: managed.results,
3079
- ok: managed.ok,
3080
- };
3081
- store = context.store;
3082
- const globalLines = [
3083
- table(
3084
- ["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"],
3085
- result.items.map((skill) => [
3086
- skill.name,
3087
- skill.cid,
3088
- skill.identity,
3089
- skill.status,
3090
- ]),
3091
- "No Global Skills.",
3092
- ),
3093
- ...result.items.flatMap((skill) => skill.problems),
3094
- ...result.orphaned.map(
3095
- (skill) =>
3096
- `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`,
3097
- ),
3098
- ];
3099
- const typeLines = [
3100
- "Type Skills:",
3101
- table(
3102
- ["TYPE CID", "SKILL NAME", "SKILL CID"],
3103
- result.typeSkills.map((entry) => [
3104
- entry.schemaCid,
3105
- entry.identity,
3106
- entry.cid,
3107
- ]),
3108
- "No Type Skills.",
3109
- ),
3110
- ];
3111
- emit(result, [...globalLines, "", ...typeLines].join("\n"));
3112
- if (!result.ok) return 1;
3113
- break;
3114
3093
  }
3115
-
3116
- const result = await manageSkills(context, requireSwarm(), {
3117
- sync: true,
3118
- names: parsed.positional,
3119
- agents: parsed.agents ?? [],
3120
- overrideExisting: Boolean(parsed.options["override-existing"]),
3121
- dryRun: Boolean(parsed.options["dry-run"]),
3122
- yes: Boolean(parsed.options.yes),
3123
- tty: io.tty,
3124
- confirm: (text) => io.confirm(text),
3125
- preview: (text) => {
3126
- io.err(text);
3127
- },
3128
- });
3129
- store = context.store;
3130
- emit(
3131
- result,
3132
- [
3133
- table(
3134
- ["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"],
3135
- result.items.map((skill) => [
3136
- skill.name,
3137
- skill.cid,
3138
- skill.identity,
3139
- skill.status,
3140
- ]),
3141
- "No Skills.",
3142
- ),
3143
- ...result.items.flatMap((skill) => skill.problems),
3144
- ...result.orphaned.map(
3145
- (skill) =>
3146
- `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`,
3147
- ),
3148
- ...result.results.map(
3149
- (entry) =>
3150
- `${entry.name} / ${entry.agent}: ${entry.status}${entry.error ? `: ${entry.error}` : ""}`,
3151
- ),
3152
- ].join("\n"),
3153
- );
3154
- if (!result.ok) return 1;
3155
- break;
3156
3094
  }
3157
- if (parsed.path === "pin") {
3158
- io.err("Fetching, verifying and retaining content...");
3159
- const result = await pinNameSubscription(
3160
- context,
3161
- first!,
3162
- selectedSwarm,
3163
- );
3164
- store = context.store;
3165
- emit(
3166
- result,
3167
- `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`,
3168
- );
3169
- break;
3170
- }
3171
- if (parsed.path === "swarm members") {
3172
- const result = await swarmMembers(
3173
- context,
3174
- requireSwarm(),
3175
- Boolean(parsed.options.refresh || parsed.options.force),
3176
- );
3177
- if (result.mode === "local") {
3178
- emit(
3179
- result,
3180
- [
3181
- "Swarm: local (Built-in single-machine Swarm)",
3182
- "Mode: local",
3183
- "Members: local user only (single-machine; no remote collaborators or HOME identity required)",
3184
- ].join("\n"),
3185
- );
3186
- break;
3187
- }
3095
+ emit(
3096
+ result,
3097
+ [
3098
+ table(
3099
+ ["NAME", "PAYLOAD CID", "INSTALL NAME", "STATUS"],
3100
+ result.items.map((skill) => [
3101
+ skill.name,
3102
+ skill.cid,
3103
+ skill.identity,
3104
+ skill.status,
3105
+ ]),
3106
+ "No Skills.",
3107
+ ),
3108
+ ...result.items.flatMap((skill) => skill.problems),
3109
+ ...result.orphaned.map(
3110
+ (skill) =>
3111
+ `Source removed: ${skill.name} ${skill.cid} (${skill.path}); installation retained.`,
3112
+ ),
3113
+ ...result.results.map(
3114
+ (entry) =>
3115
+ `${entry.name} / ${entry.agent}: ${entry.status}${entry.error ? `: ${entry.error}` : ""}`,
3116
+ ),
3117
+ ].join("\n"),
3118
+ );
3119
+ if (!result.ok) return 1;
3120
+ break;
3121
+ }
3122
+ case "pin": {
3123
+ io.err("Fetching, verifying and retaining content...");
3124
+ const result = await client.store.addPin(
3125
+ {
3126
+ ref: first!,
3127
+ swarm: selectedSwarm,
3128
+ refresh: explicitRefresh,
3129
+ },
3130
+ { ndjson: true },
3131
+ );
3132
+ emit(
3133
+ result,
3134
+ `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`,
3135
+ );
3136
+ break;
3137
+ }
3138
+ case "swarm members": {
3139
+ const result = (await client.swarms.members(
3140
+ {
3141
+ swarm: requireSwarm(),
3142
+ refresh: Boolean(parsed.options.refresh || parsed.options.force),
3143
+ },
3144
+ { ndjson: true },
3145
+ )) as Awaited<ReturnType<typeof swarmMembers>>;
3146
+ if (result.mode === "local") {
3188
3147
  emit(
3189
3148
  result,
3190
3149
  [
3191
- `Directory: ${result.cache.source} (${result.cache.freshness}), observed ${result.cache.updatedAt}`,
3192
- `Daemon: ${result.local.status}, observed ${result.local.updatedAt ?? "unknown"}; control-plane verified ${result.local.verifiedAt ?? "unknown"}`,
3193
- table(
3194
- ["NAME", "DESCRIPTION", "ROLE", "PIVOT", "PUBLIC KEY"],
3195
- result.members.map((member) => [
3196
- member.name,
3197
- member.description,
3198
- member.role,
3199
- member.pivot ? (member.localStatus ?? "candidate") : "-",
3200
- member.publicKey,
3201
- ]),
3202
- "No members.",
3203
- ),
3150
+ "Swarm: local (Built-in single-machine Swarm)",
3151
+ "Mode: local",
3152
+ "Members: local user only (single-machine; no remote collaborators or HOME identity required)",
3204
3153
  ].join("\n"),
3205
3154
  );
3206
- if (result.local.error)
3207
- io.err(
3208
- `Local Pivot observations (${result.local.status}): ${printable(result.local.error)}`,
3209
- );
3210
3155
  break;
3211
3156
  }
3212
- if (parsed.path === "swarm export") {
3213
- const member = await exportRequest(
3214
- context,
3215
- requireSwarm(),
3216
- String(parsed.options.output ?? ""),
3217
- );
3218
- emit({ member }, member);
3219
- break;
3220
- }
3221
- if (parsed.path === "swarm pivot grant") {
3222
- const url = requireSwarm();
3223
- if (!parsed.options.yes)
3224
- syntax(
3225
- "Granting Pivot HEAD receipt authority requires --yes; revoking it requires swarm exclude.",
3226
- );
3227
- const result = await grantPivotAuthority(context, url, first!);
3228
- store = context.store;
3229
- emit(
3230
- result,
3231
- `Granted Pivot HEAD authority to ${result.member} on ${result.configUrl} (HEAD ${result.headId}). Revoking Pivot HEAD authority requires swarm exclude.`,
3157
+ emit(
3158
+ result,
3159
+ [
3160
+ `Directory: ${result.cache.source} (${result.cache.freshness}), observed ${result.cache.updatedAt}`,
3161
+ `Daemon: ${result.local.status}, observed ${result.local.updatedAt ?? "unknown"}; control-plane verified ${result.local.verifiedAt ?? "unknown"}`,
3162
+ table(
3163
+ ["NAME", "DESCRIPTION", "ROLE", "PIVOT", "PUBLIC KEY"],
3164
+ result.members.map((member) => [
3165
+ member.name,
3166
+ member.description,
3167
+ member.role,
3168
+ member.pivot ? (member.localStatus ?? "candidate") : "-",
3169
+ member.publicKey,
3170
+ ]),
3171
+ "No members.",
3172
+ ),
3173
+ ].join("\n"),
3174
+ );
3175
+ if (result.local.error)
3176
+ io.err(
3177
+ `Local Pivot observations (${result.local.status}): ${printable(result.local.error)}`,
3232
3178
  );
3233
- break;
3234
- }
3235
- if (
3236
- ["swarm exclude", "swarm resume", "swarm profile"].includes(
3237
- parsed.path,
3238
- )
3239
- ) {
3240
- const url = requireSwarm();
3241
- if (parsed.path === "swarm exclude") {
3242
- if (!parsed.options.yes)
3243
- syntax("Member removal is irreversible; --yes required.");
3244
- await removeMember(context, url, first!);
3245
- } else if (parsed.path === "swarm resume")
3246
- await resumeRemoval(context, url);
3247
- else {
3248
- const profile = await updateProfile(context, url, {
3249
- ...(typeof parsed.options.address === "string"
3250
- ? { addresses: [parsed.options.address] }
3251
- : {}),
3252
- ...(typeof parsed.options.pivot === "string"
3253
- ? {
3254
- pivot: Boolean(
3255
- parseValue("swarm.pivot", parsed.options.pivot, true),
3256
- ),
3257
- }
3258
- : {}),
3259
- });
3260
- emit(profile, JSON.stringify(profile));
3261
- store = context.store;
3262
- break;
3263
- }
3264
- store = context.store;
3265
- emit(
3266
- { url, completed: true },
3267
- `Organization switch complete: ${url}`,
3179
+ break;
3180
+ }
3181
+ case "swarm export": {
3182
+ const output =
3183
+ typeof parsed.options.output === "string"
3184
+ ? resolve(parsed.options.output)
3185
+ : "";
3186
+ const result = (await client.swarms.governance(
3187
+ "export",
3188
+ { swarm: requireSwarm(), output },
3189
+ { ndjson: true },
3190
+ )) as { member: string };
3191
+ emit({ member: result.member }, result.member);
3192
+ break;
3193
+ }
3194
+ case "swarm pivot grant": {
3195
+ const url = requireSwarm();
3196
+ if (!parsed.options.yes)
3197
+ syntax(
3198
+ "Granting Pivot HEAD receipt authority requires --yes; revoking it requires swarm exclude.",
3268
3199
  );
3269
- break;
3270
- }
3271
- if (parsed.path === "swarm update") {
3272
- const cid = requireSwarm();
3273
- const result = await updateSwarm(context, cid, {
3200
+ const result = (await client.swarms.governance(
3201
+ "pivot-grant",
3202
+ { swarm: url, member: first! },
3203
+ { ndjson: true },
3204
+ )) as Awaited<ReturnType<typeof grantPivotAuthority>>;
3205
+ emit(
3206
+ result,
3207
+ `Granted Pivot HEAD authority to ${result.member} on ${result.configUrl} (HEAD ${result.headId}). Revoking Pivot HEAD authority requires swarm exclude.`,
3208
+ );
3209
+ break;
3210
+ }
3211
+ case "swarm exclude": {
3212
+ const url = requireSwarm();
3213
+ if (!parsed.options.yes)
3214
+ syntax("Member removal is irreversible; --yes required.");
3215
+ await client.swarms.governance(
3216
+ "exclude",
3217
+ { swarm: url, member: first! },
3218
+ { ndjson: true },
3219
+ );
3220
+ emit({ url, completed: true }, `Organization switch complete: ${url}`);
3221
+ break;
3222
+ }
3223
+ case "swarm resume": {
3224
+ const url = requireSwarm();
3225
+ await client.swarms.governance(
3226
+ "resume",
3227
+ { swarm: url },
3228
+ { ndjson: true },
3229
+ );
3230
+ emit({ url, completed: true }, `Organization switch complete: ${url}`);
3231
+ break;
3232
+ }
3233
+ case "swarm profile": {
3234
+ const url = requireSwarm();
3235
+ const profile = await client.swarms.governance(
3236
+ "profile",
3237
+ {
3238
+ swarm: url,
3239
+ ...(typeof parsed.options.address === "string"
3240
+ ? { addresses: [parsed.options.address] }
3241
+ : {}),
3242
+ ...(typeof parsed.options.pivot === "string"
3243
+ ? {
3244
+ pivot: Boolean(
3245
+ parseValue("swarm.pivot", parsed.options.pivot, true),
3246
+ ),
3247
+ }
3248
+ : {}),
3249
+ },
3250
+ { ndjson: true },
3251
+ );
3252
+ emit(profile, JSON.stringify(profile));
3253
+ break;
3254
+ }
3255
+ case "swarm update": {
3256
+ const cid = requireSwarm();
3257
+ const result = (await client.swarms.update(
3258
+ {
3259
+ swarm: cid,
3274
3260
  ...(typeof parsed.options.name === "string"
3275
3261
  ? { name: parsed.options.name }
3276
3262
  : {}),
3277
3263
  ...(typeof parsed.options.description === "string"
3278
3264
  ? { description: parsed.options.description }
3279
3265
  : {}),
3280
- });
3281
- emit(
3282
- result,
3283
- `Swarm: ${result.configUrl}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD ID: ${result.headId}\nConfig content CID: ${result.valueCid}`,
3284
- );
3285
- break;
3286
- }
3287
- if (parsed.path === "search") {
3288
- const registrations = state.allSwarms();
3289
- const scope = parsed.options.all
3290
- ? registrations
3291
- : [
3292
- {
3293
- cid: requireSwarm(),
3294
- alias:
3295
- registrations.find((entry) => entry.cid === selectedSwarm)
3296
- ?.alias ?? null,
3297
- },
3298
- ];
3299
- const searchOptions: Parameters<typeof searchNames>[3] = {};
3300
- if (typeof parsed.options.prefix === "string")
3301
- searchOptions.prefix = parsed.options.prefix;
3302
- if (typeof parsed.options.kind === "string")
3303
- searchOptions.kind = parsed.options.kind as Exclude<
3304
- NonNullable<Parameters<typeof searchNames>[3]>["kind"],
3305
- undefined
3306
- >;
3307
- if (typeof parsed.options.schema === "string")
3308
- searchOptions.schemaCid = parsed.options.schema;
3309
- if (typeof parsed.options.limit === "string")
3310
- searchOptions.limit = /^\d+$/.test(parsed.options.limit)
3311
- ? Number(parsed.options.limit)
3312
- : Number.NaN;
3313
- if (typeof parsed.options.offset === "string")
3314
- searchOptions.offset = /^\d+$/.test(parsed.options.offset)
3315
- ? Number(parsed.options.offset)
3316
- : Number.NaN;
3317
- const result = Object.keys(searchOptions).length
3318
- ? await searchNames(context, first!, scope, searchOptions)
3319
- : await searchNames(context, first!, scope);
3320
- emit(result, formatSearchResults(result.matches));
3321
- break;
3322
- }
3323
- if (parsed.path === "swarm status") {
3324
- const cid = requireSwarm();
3325
- const status = await inspectSwarmStatus(
3326
- context,
3327
- cid,
3328
- Boolean(parsed.options.refresh || parsed.options.force),
3329
- );
3330
- store = context.store;
3331
- if (status.mode === "local") {
3332
- emit(
3333
- {
3334
- mode: "local",
3335
- configUrl: cid,
3336
- root: status.head.root,
3337
- valueCid: status.head.cid,
3338
- properties: {
3339
- name: status.config.name,
3340
- description: status.config.description,
3341
- },
3342
- local: status.local,
3343
- },
3344
- [
3345
- "Swarm",
3346
- " Mode: local (built-in single-machine Swarm)",
3347
- ` Name: ${printable(status.config.name)}`,
3348
- ` Description: ${printable(status.config.description)}`,
3349
- " Config URL:",
3350
- ` ${cid}`,
3351
- "",
3352
- "Content",
3353
- " HEAD (publication root):",
3354
- ` ${status.head.root}`,
3355
- " Content CID (HEAD value):",
3356
- ` ${status.head.cid}`,
3357
- ` Names: ${status.local.names} (Templates: ${status.local.templates}, Skills: ${status.local.skills} [global: ${status.local.globalSkills}, types: ${status.local.typeSkills}], Registrations: ${status.local.registrations})`,
3358
- ].join("\n"),
3359
- );
3360
- break;
3361
- }
3362
- const {
3363
- head,
3364
- config,
3365
- networking,
3366
- cache,
3367
- lastWriter,
3368
- state: contentState,
3369
- } = status;
3370
- const fingerprint = await keyId(config.owner);
3266
+ },
3267
+ { ndjson: true },
3268
+ )) as Awaited<ReturnType<typeof updateSwarm>>;
3269
+ emit(
3270
+ result,
3271
+ `Swarm: ${result.configUrl}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD ID: ${result.headId}\nConfig content CID: ${result.valueCid}`,
3272
+ );
3273
+ break;
3274
+ }
3275
+ case "search": {
3276
+ const result = (await client.swarms.search(
3277
+ {
3278
+ ...(parsed.options.all
3279
+ ? { swarms: registeredSwarms.map((entry) => entry.cid) }
3280
+ : { swarm: requireSwarm() }),
3281
+ q: first!,
3282
+ ...(typeof parsed.options.prefix === "string"
3283
+ ? { prefix: parsed.options.prefix }
3284
+ : {}),
3285
+ ...(typeof parsed.options.kind === "string"
3286
+ ? {
3287
+ kind: parsed.options.kind as
3288
+ "all" | "bundle" | "dir" | "file",
3289
+ }
3290
+ : {}),
3291
+ ...(typeof parsed.options.schema === "string"
3292
+ ? { schemaCid: parsed.options.schema }
3293
+ : {}),
3294
+ ...(typeof parsed.options.limit === "string"
3295
+ ? { limit: parsed.options.limit }
3296
+ : {}),
3297
+ ...(typeof parsed.options.offset === "string"
3298
+ ? { offset: parsed.options.offset }
3299
+ : {}),
3300
+ refresh: explicitRefresh,
3301
+ },
3302
+ { ndjson: true },
3303
+ )) as Awaited<ReturnType<typeof searchNames>>;
3304
+ emit(result, formatSearchResults(result.matches));
3305
+ break;
3306
+ }
3307
+ case "swarm status": {
3308
+ const { keyId } = await import("@ipab/bundle/pointer/crypto");
3309
+ const cid = requireSwarm();
3310
+ const status = (await client.swarms.status(
3311
+ {
3312
+ swarm: cid,
3313
+ refresh: Boolean(parsed.options.refresh || parsed.options.force),
3314
+ },
3315
+ { ndjson: true },
3316
+ )) as Awaited<ReturnType<typeof inspectSwarmStatus>>;
3317
+ if (status.mode === "local") {
3371
3318
  emit(
3372
3319
  {
3320
+ mode: "local",
3373
3321
  configUrl: cid,
3374
- owner: config.owner,
3375
- ownerFingerprint: fingerprint,
3376
- epoch: config.epoch,
3377
- scopeId: config.scopeId,
3378
- headId: config.headId,
3379
- cache,
3380
- state: contentState,
3381
- networking,
3382
- root: head.root,
3383
- valueCid: head.cid,
3384
- lastWriter,
3322
+ root: status.head.root,
3323
+ valueCid: status.head.cid,
3385
3324
  properties: {
3386
- name: config.name,
3387
- description: config.description,
3325
+ name: status.config.name,
3326
+ description: status.config.description,
3388
3327
  },
3328
+ local: status.local,
3389
3329
  },
3390
3330
  [
3391
3331
  "Swarm",
3392
- ` Directory: ${cache.source} (${cache.freshness}), observed ${cache.updatedAt}`,
3393
- ` Name: ${printable(config.name)}`,
3394
- ` Description: ${config.description ? printable(config.description) : "(none)"}`,
3332
+ " Mode: local (built-in single-machine Swarm)",
3333
+ ` Name: ${printable(status.config.name)}`,
3334
+ ` Description: ${printable(status.config.description)}`,
3395
3335
  " Config URL:",
3396
3336
  ` ${cid}`,
3397
3337
  "",
3398
- "Identity",
3399
- " Owner fingerprint:",
3400
- ` ${fingerprint}`,
3401
- "",
3402
- "Content",
3403
- " HEAD (publication root):",
3404
- ` ${head.root}`,
3405
- " Content CID (HEAD value):",
3406
- ` ${head.cid}`,
3407
- ...(lastWriter
3408
- ? [
3409
- ` Last HEAD writer: ${lastWriter.name ? printable(lastWriter.name) : "(profile name unavailable)"}`,
3410
- ` Public key: ${lastWriter.subject}`,
3411
- ` PeerID: ${lastWriter.peerId ?? "unknown"}`,
3412
- ` Updated: ${lastWriter.updatedAt} (service time)`,
3413
- " Last writer is not a confirmed content holder or the only copy.",
3414
- ]
3415
- : [
3416
- " Last HEAD writer/time: unknown (legacy record or service without update metadata).",
3417
- ]),
3418
- ` State: ${contentState.status}. ${contentState.error}`,
3419
- "",
3420
- "Local networking",
3421
- ` Daemon observations: ${networking.daemon.status}`,
3422
- ` Updated: ${networking.daemon.updatedAt ?? "unknown"}`,
3423
- ` Control-plane verified: ${networking.daemon.verifiedAt ?? "unknown"}`,
3424
- ...(networking.daemon.error
3425
- ? [` Observation error: ${printable(networking.daemon.error)}`]
3426
- : []),
3427
- ` Connections observed: ${networking.connections.observedAt ?? "unknown"} (${networking.connections.freshness})`,
3428
- ...(networking.connections.error
3429
- ? [
3430
- ` Connection error: ${printable(networking.connections.error)}`,
3431
- ]
3432
- : []),
3433
- table(
3434
- [
3435
- "PIVOT PEER ID",
3436
- "LOCAL",
3437
- "PROBE",
3438
- "PROBED AT",
3439
- "FAILURES",
3440
- "RETRY AT",
3441
- "CONNECTION",
3442
- "READINESS",
3443
- ],
3444
- networking.pivots.map((pivot) => [
3445
- pivot.peerId,
3446
- pivot.localStatus ?? "unknown",
3447
- `${pivot.probe.result} (${pivot.probe.freshness})`,
3448
- pivot.probe.at ?? "-",
3449
- pivot.failures === null ? "-" : String(pivot.failures),
3450
- pivot.retryAt ?? "-",
3451
- pivot.connection.status,
3452
- pivot.readiness.status,
3453
- ]),
3454
- "No declared Pivots.",
3455
- ),
3456
- ...networking.pivots.flatMap((pivot) =>
3457
- pivot.probe.error
3458
- ? [
3459
- ` ${pivot.peerId} probe error: ${printable(pivot.probe.error)}`,
3460
- ]
3461
- : [],
3462
- ),
3463
- ...(networking.connections.error
3464
- ? []
3465
- : [
3466
- table(
3467
- ["CONNECTED PEER ID", "TRANSPORT", "ADDRESS"],
3468
- networking.connections.peers.map((peer) => [
3469
- peer.peerId,
3470
- peer.transport,
3471
- peer.address,
3472
- ]),
3473
- "No observed peer connections.",
3474
- ),
3475
- ]),
3476
- " Selected is configuration, not connection success. Relay connectivity does not guarantee content availability.",
3477
- ].join("\n"),
3478
- );
3479
- break;
3480
- }
3481
- if (parsed.path === "get") {
3482
- const localCid = /^(ipab|name):/i.test(first!)
3483
- ? undefined
3484
- : state.resolve(first!);
3485
- const builtin = builtins.pins.find((pin) => pin.cid === localCid);
3486
- const selected = builtin
3487
- ? { cid: builtin.cid, targetCid: builtin.cid }
3488
- : await resolveReference(
3489
- context,
3490
- first!,
3491
- selectedSwarm,
3492
- (reference) => state!.resolve(reference),
3493
- Boolean(parsed.options.raw),
3494
- "local-first",
3495
- );
3496
- const contentStore = context.store;
3497
- const source = IpfsStore.fromClient(
3498
- {
3499
- block: {
3500
- get: (key, options) => {
3501
- options?.signal?.throwIfAborted();
3502
- const builtin = builtins.blocks.get(
3503
- CID.parse(key).toV1().toString(),
3504
- );
3505
- return builtin
3506
- ? Promise.resolve(builtin.slice())
3507
- : contentStore.block.get(key, options);
3508
- },
3509
- },
3510
- },
3511
- contentStore.limits,
3338
+ "Content",
3339
+ " HEAD (publication root):",
3340
+ ` ${status.head.root}`,
3341
+ " Content CID (HEAD value):",
3342
+ ` ${status.head.cid}`,
3343
+ ` Names: ${status.local.names} (Templates: ${status.local.templates}, Skills: ${status.local.skills} [global: ${status.local.globalSkills}, types: ${status.local.typeSkills}], Registrations: ${status.local.registrations})`,
3344
+ ].join("\n"),
3512
3345
  );
3513
- let directory: string;
3514
- try {
3515
- directory = await getBundle(
3516
- source,
3517
- selected.cid,
3518
- typeof parsed.options.output === "string"
3519
- ? parsed.options.output
3520
- : undefined,
3521
- );
3522
- } finally {
3523
- await source.close();
3524
- }
3525
- try {
3526
- await context.finishRead?.();
3527
- } finally {
3528
- readContext = undefined;
3529
- }
3530
- const closing = store;
3531
- store = undefined;
3532
- await closeStore(closing, undefined);
3533
- state.close();
3534
- state = undefined;
3535
- emit({ ...selected, directory }, directory);
3536
3346
  break;
3537
3347
  }
3538
- let cid: string;
3539
- let contentCid: string | undefined;
3540
- if (parsed.path === "swarm create") {
3541
- cid = await createSwarm(context, {
3348
+ const {
3349
+ head,
3350
+ config,
3351
+ networking,
3352
+ cache,
3353
+ lastWriter,
3354
+ state: contentState,
3355
+ } = status;
3356
+ const fingerprint = await keyId(config.owner);
3357
+ emit(
3358
+ {
3359
+ configUrl: cid,
3360
+ owner: config.owner,
3361
+ ownerFingerprint: fingerprint,
3362
+ epoch: config.epoch,
3363
+ scopeId: config.scopeId,
3364
+ headId: config.headId,
3365
+ cache,
3366
+ state: contentState,
3367
+ networking,
3368
+ root: head.root,
3369
+ valueCid: head.cid,
3370
+ lastWriter,
3371
+ properties: {
3372
+ name: config.name,
3373
+ description: config.description,
3374
+ },
3375
+ },
3376
+ [
3377
+ "Swarm",
3378
+ ` Directory: ${cache.source} (${cache.freshness}), observed ${cache.updatedAt}`,
3379
+ ` Name: ${printable(config.name)}`,
3380
+ ` Description: ${config.description ? printable(config.description) : "(none)"}`,
3381
+ " Config URL:",
3382
+ ` ${cid}`,
3383
+ "",
3384
+ "Identity",
3385
+ " Owner fingerprint:",
3386
+ ` ${fingerprint}`,
3387
+ "",
3388
+ "Content",
3389
+ " HEAD (publication root):",
3390
+ ` ${head.root}`,
3391
+ " Content CID (HEAD value):",
3392
+ ` ${head.cid}`,
3393
+ ...(lastWriter
3394
+ ? [
3395
+ ` Last HEAD writer: ${lastWriter.name ? printable(lastWriter.name) : "(profile name unavailable)"}`,
3396
+ ` Public key: ${lastWriter.subject}`,
3397
+ ` PeerID: ${lastWriter.peerId ?? "unknown"}`,
3398
+ ` Updated: ${lastWriter.updatedAt} (service time)`,
3399
+ " Last writer is not a confirmed content holder or the only copy.",
3400
+ ]
3401
+ : [
3402
+ " Last HEAD writer/time: unknown (legacy record or service without update metadata).",
3403
+ ]),
3404
+ ` State: ${contentState.status}. ${contentState.error}`,
3405
+ "",
3406
+ "Local networking",
3407
+ ` Daemon observations: ${networking.daemon.status}`,
3408
+ ` Updated: ${networking.daemon.updatedAt ?? "unknown"}`,
3409
+ ` Control-plane verified: ${networking.daemon.verifiedAt ?? "unknown"}`,
3410
+ ...(networking.daemon.error
3411
+ ? [` Observation error: ${printable(networking.daemon.error)}`]
3412
+ : []),
3413
+ ` Connections observed: ${networking.connections.observedAt ?? "unknown"} (${networking.connections.freshness})`,
3414
+ ...(networking.connections.error
3415
+ ? [
3416
+ ` Connection error: ${printable(networking.connections.error)}`,
3417
+ ]
3418
+ : []),
3419
+ table(
3420
+ [
3421
+ "PIVOT PEER ID",
3422
+ "LOCAL",
3423
+ "PROBE",
3424
+ "PROBED AT",
3425
+ "FAILURES",
3426
+ "RETRY AT",
3427
+ "CONNECTION",
3428
+ "READINESS",
3429
+ ],
3430
+ networking.pivots.map((pivot) => [
3431
+ pivot.peerId,
3432
+ pivot.localStatus ?? "unknown",
3433
+ `${pivot.probe.result} (${pivot.probe.freshness})`,
3434
+ pivot.probe.at ?? "-",
3435
+ pivot.failures === null ? "-" : String(pivot.failures),
3436
+ pivot.retryAt ?? "-",
3437
+ pivot.connection.status,
3438
+ pivot.readiness.status,
3439
+ ]),
3440
+ "No declared Pivots.",
3441
+ ),
3442
+ ...networking.pivots.flatMap((pivot) =>
3443
+ pivot.probe.error
3444
+ ? [
3445
+ ` ${pivot.peerId} probe error: ${printable(pivot.probe.error)}`,
3446
+ ]
3447
+ : [],
3448
+ ),
3449
+ ...(networking.connections.error
3450
+ ? []
3451
+ : [
3452
+ table(
3453
+ ["CONNECTED PEER ID", "TRANSPORT", "ADDRESS"],
3454
+ networking.connections.peers.map((peer) => [
3455
+ peer.peerId,
3456
+ peer.transport,
3457
+ peer.address,
3458
+ ]),
3459
+ "No observed peer connections.",
3460
+ ),
3461
+ ]),
3462
+ " Selected is configuration, not connection success. Relay connectivity does not guarantee content availability.",
3463
+ ].join("\n"),
3464
+ );
3465
+ break;
3466
+ }
3467
+ case "get": {
3468
+ const destination =
3469
+ typeof parsed.options.output === "string"
3470
+ ? resolve(parsed.options.output)
3471
+ : undefined;
3472
+ const result = (await client.store.export(
3473
+ {
3474
+ mode: "get",
3475
+ ref: first!,
3476
+ ...(destination !== undefined ? { destination } : {}),
3477
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3478
+ raw: Boolean(parsed.options.raw),
3479
+ ...(explicitRefresh !== undefined
3480
+ ? { refresh: explicitRefresh }
3481
+ : {}),
3482
+ },
3483
+ { ndjson: true },
3484
+ )) as unknown as Record<string, unknown> & { directory: string };
3485
+ const payload = { ...result };
3486
+ delete payload.destination;
3487
+ const closing = cliHandle;
3488
+ cliHandle = undefined;
3489
+ await closing.close();
3490
+ emit(payload, result.directory);
3491
+ break;
3492
+ }
3493
+ case "swarm create": {
3494
+ const created = (await client.swarms.governance(
3495
+ "create",
3496
+ {
3542
3497
  ...(typeof parsed.options.service === "string"
3543
3498
  ? { service: parsed.options.service }
3544
3499
  : {}),
3545
3500
  ...(typeof parsed.options.resume === "string"
3546
3501
  ? { resume: parsed.options.resume }
3547
3502
  : {}),
3548
- properties: {
3549
- name: String(parsed.options.name ?? ""),
3550
- description: String(parsed.options.description ?? ""),
3551
- },
3503
+ name: String(parsed.options.name ?? ""),
3504
+ description: String(parsed.options.description ?? ""),
3552
3505
  ...(typeof parsed.options.alias === "string"
3553
3506
  ? { alias: parsed.options.alias }
3554
3507
  : {}),
3555
- });
3556
- } else if (parsed.path === "swarm request") {
3557
- const result = await requestMembership(
3558
- context,
3559
- state.resolveSwarm(first!),
3560
- {
3561
- ...(typeof parsed.options.output === "string"
3562
- ? { output: parsed.options.output }
3563
- : {}),
3564
- ...(parsed.options.pivot ? { role: "pivot" as const } : {}),
3565
- },
3508
+ },
3509
+ { ndjson: true },
3510
+ )) as {
3511
+ configUrl: string;
3512
+ alias: string | null;
3513
+ savedCurrent: string | null;
3514
+ };
3515
+ io.err(
3516
+ `Registered swarm ${created.alias ?? created.configUrl}. Saved current: ${created.savedCurrent ?? "(none)"}.`,
3517
+ );
3518
+ io.err(
3519
+ "Pivot replication is not yet confirmed. Keep this member online until a Pivot is ready; daemon will replicate automatically. Manual retry: ipab swarm replicate. Inspect readiness with ipab swarm status.",
3520
+ );
3521
+ emit({ configUrl: created.configUrl }, created.configUrl);
3522
+ break;
3523
+ }
3524
+ case "swarm request": {
3525
+ const output =
3526
+ typeof parsed.options.output === "string"
3527
+ ? parsed.options.output
3528
+ : undefined;
3529
+ const result = (await client.swarms.governance(
3530
+ "request",
3531
+ {
3532
+ swarm: first!,
3533
+ ...(output !== undefined ? { output, cwd: process.cwd() } : {}),
3534
+ ...(parsed.options.pivot ? { role: "pivot" } : {}),
3535
+ },
3536
+ { ndjson: true },
3537
+ )) as Awaited<ReturnType<typeof requestMembership>>;
3538
+ io.err(
3539
+ `Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`,
3540
+ );
3541
+ if (result.file === undefined)
3542
+ io.out(JSON.stringify(result.request, null, 2));
3543
+ else {
3544
+ io.err(`Request saved to: ${result.file}`);
3545
+ if (parsed.flags.json)
3546
+ emit(
3547
+ {
3548
+ file: result.file,
3549
+ member: result.request.member,
3550
+ ownerFingerprint: result.ownerFingerprint,
3551
+ },
3552
+ "",
3553
+ );
3554
+ }
3555
+ break;
3556
+ }
3557
+ case "swarm approve": {
3558
+ const {
3559
+ verifiedRequest,
3560
+ verifiedRequestStream,
3561
+ membershipRequestSummary,
3562
+ } = await import("./swarm.js");
3563
+ const selected = requireSwarm();
3564
+ if (isLocalSwarm(selected))
3565
+ throw new HostError(
3566
+ `The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support swarm approve.`,
3566
3567
  );
3567
- store = context.store;
3568
- io.err(
3569
- `Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`,
3568
+ if (first === "-" && !parsed.options.yes)
3569
+ syntax(
3570
+ "Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.",
3570
3571
  );
3571
- if (result.file === undefined)
3572
- io.out(JSON.stringify(result.request, null, 2));
3573
- else {
3574
- io.err(`Request saved to: ${result.file}`);
3575
- if (parsed.flags.json)
3576
- emit(
3577
- {
3578
- file: result.file,
3579
- member: result.request.member,
3580
- ownerFingerprint: result.ownerFingerprint,
3581
- },
3582
- "",
3583
- );
3584
- }
3585
- break;
3586
- } else if (parsed.path === "swarm approve") {
3587
- const selected = requireSwarm();
3588
- if (isLocalSwarm(selected))
3589
- throw new HostError(
3590
- `The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support swarm approve.`,
3591
- );
3592
- if (first === "-" && !parsed.options.yes)
3593
- syntax(
3594
- "Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.",
3595
- );
3596
- const request =
3597
- first === "-"
3598
- ? await verifiedRequestStream(
3599
- (io.requestInput ?? processIO.requestInput!)(),
3600
- )
3601
- : await verifiedRequest(first!);
3602
- if (request.configUrl !== selected)
3603
- syntax(
3604
- `Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`,
3605
- );
3606
- io.err(await membershipRequestSummary(request));
3607
- if (
3608
- !parsed.options.yes &&
3609
- (!io.tty ||
3610
- !(await io.confirm(
3611
- `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.`,
3612
- )))
3613
- )
3614
- throw new HostError(
3615
- "Approval requires explicit --yes or interactive confirmation.",
3616
- );
3617
- cid = await approveMembership(context, request, {
3572
+ const request =
3573
+ first === "-"
3574
+ ? await verifiedRequestStream(
3575
+ (io.requestInput ?? processIO.requestInput!)(),
3576
+ )
3577
+ : await verifiedRequest(resolve(first!));
3578
+ if (request.configUrl !== selected)
3579
+ syntax(
3580
+ `Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`,
3581
+ );
3582
+ io.err(await membershipRequestSummary(request));
3583
+ if (
3584
+ !parsed.options.yes &&
3585
+ (!io.tty ||
3586
+ !(await io.confirm(
3587
+ `Approve the verified ${parsed.options.pivot || request.role === "pivot" ? "pivot" : "ordinary"} Request from ${request.member} above? This grants ${parsed.options.pivot || request.role === "pivot" ? "current HEAD and " : ""}the member's profile write access; all reads are public.`,
3588
+ )))
3589
+ )
3590
+ throw new HostError(
3591
+ "Approval requires explicit --yes or interactive confirmation.",
3592
+ );
3593
+ const result = (await client.swarms.governance(
3594
+ "approve",
3595
+ {
3596
+ request,
3618
3597
  again: Boolean(parsed.options.again),
3619
3598
  pivot: Boolean(parsed.options.pivot),
3620
- });
3621
- } else {
3622
- const content = await publicationSource(second!, store);
3623
- contentCid = content;
3624
- cid = await publish(context, content, {
3625
- ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3599
+ },
3600
+ { ndjson: true },
3601
+ )) as { approved: string };
3602
+ emit({ configUrl: result.approved }, result.approved);
3603
+ break;
3604
+ }
3605
+ case "publish": {
3606
+ const named = parseNameReference(first!);
3607
+ const targetSwarm = named?.swarm
3608
+ ? resolveSwarm(named.swarm)
3609
+ : requireSwarm();
3610
+ const source = await resolveLocalPathIfPresent(second!);
3611
+ const result = (await client.swarms.fsSet(
3612
+ {
3613
+ swarm: targetSwarm,
3614
+ kind: "publish",
3626
3615
  name: first!,
3616
+ source,
3627
3617
  ...(typeof parsed.options.expect === "string"
3628
3618
  ? { expect: parsed.options.expect }
3629
3619
  : {}),
3630
3620
  snapshot: Boolean(parsed.options.snapshot),
3631
- });
3632
- }
3633
- store = context.store;
3634
- if (parsed.path === "swarm create") {
3635
- io.err(
3636
- `Registered swarm ${state.registeredSwarm(cid).alias ?? cid}. Saved current: ${state.config({ includeSecrets: false })["swarm.default"] ?? "(none)"}.`,
3637
- );
3638
- io.err(
3639
- "Pivot replication is not yet confirmed. Keep this member online until a Pivot is ready; daemon will replicate automatically. Manual retry: ipab swarm replicate. Inspect readiness with ipab swarm status.",
3640
- );
3641
- }
3642
- if (contentCid)
3643
- io.err(
3644
- `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.`,
3645
- );
3621
+ },
3622
+ { ndjson: true },
3623
+ )) as unknown as { cid: string; contentCid: string };
3624
+ io.err(
3625
+ `Locally protected payload: ${result.contentCid}. Use ipab unpin ${result.contentCid} to release this CID pin only; Name subscriptions and publication/history owners remain. --snapshot links payloads directly into retained publication history, so unpin cannot release that protection.`,
3626
+ );
3627
+ emit(result, result.cid);
3628
+ break;
3629
+ }
3630
+ case "store usage": {
3631
+ const result = await client.store.usage();
3646
3632
  emit(
3647
- parsed.path === "swarm create" || parsed.path === "swarm approve"
3648
- ? { configUrl: cid }
3649
- : { cid, ...(contentCid ? { contentCid } : {}) },
3650
- cid,
3633
+ result,
3634
+ `Cached blocks: ${storageBytes(result.cachedBytes)}\nPinned blocks (deduplicated): ${storageBytes(result.pinnedBytes)}`,
3651
3635
  );
3652
3636
  break;
3653
3637
  }
3654
- case "store usage":
3655
3638
  case "store gc": {
3656
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
3657
- if (parsed.path === "store usage") {
3658
- const result = await store.usage();
3659
- emit(
3660
- result,
3661
- `Cached blocks: ${storageBytes(result.cachedBytes)}\nPinned blocks (deduplicated): ${storageBytes(result.pinnedBytes)}`,
3662
- );
3663
- } else {
3664
- const result = await store.gc();
3665
- emit(
3666
- result,
3667
- `Removed ${result.removedBlocks} blocks; reclaimed ${storageBytes(result.reclaimedBytes)}.`,
3668
- );
3669
- }
3639
+ const result = await client.store.gc({ ndjson: true });
3640
+ emit(
3641
+ result,
3642
+ `Removed ${result.removedBlocks} blocks; reclaimed ${storageBytes(result.reclaimedBytes)}.`,
3643
+ );
3670
3644
  break;
3671
3645
  }
3672
3646
  case "templates render":
@@ -3674,6 +3648,7 @@ async function performCli(
3674
3648
  case "bundle build":
3675
3649
  case "bundle inspect":
3676
3650
  case "bundle import": {
3651
+ const { message } = await import("./errors.js");
3677
3652
  const controller = new AbortController();
3678
3653
  let cancelled = 0;
3679
3654
  const interrupt = () => {
@@ -3687,192 +3662,131 @@ async function performCli(
3687
3662
  process.once("SIGINT", interrupt);
3688
3663
  process.once("SIGTERM", terminate);
3689
3664
  try {
3690
- let pendingStore: Promise<IpfsStore> | undefined;
3691
- const getStore = () => {
3692
- pendingStore ??= storeConfiguration(value("store.gateway")).then(
3693
- (configuration) => {
3694
- store = new IpfsStore(configuration);
3695
- return store;
3696
- },
3697
- );
3698
- return pendingStore;
3699
- };
3700
- const request = {
3701
- signal: controller.signal,
3702
- diagnostic: (text: string) => {
3703
- io.err(text);
3704
- },
3705
- resolveCid: async (cid: CID, options: { signal?: AbortSignal }) => {
3706
- options.signal?.throwIfAborted();
3707
- const builtin = builtins.blocks.get(cid.toV1().toString());
3708
- if (builtin) return builtin.slice();
3709
- return (store ?? (await getStore())).block.get(
3710
- cid.toString(),
3711
- options,
3712
- );
3713
- },
3714
- };
3715
- const builtinSource = first ? state.pin(first) : undefined;
3716
- const source =
3717
- builtinSource?.builtin && builtinSource.metadata?.kind === "bundle"
3718
- ? builtinSource.cid
3719
- : first;
3720
- let selectedTemplate: string | undefined;
3665
+ const requestOpts = { signal: controller.signal, ndjson: true };
3666
+ const outputOpt =
3667
+ typeof parsed.options.output === "string"
3668
+ ? resolve(parsed.options.output)
3669
+ : undefined;
3670
+ const outputDirOpt = String(value("bundle.outputDir"));
3671
+ let result: Record<string, unknown>;
3721
3672
  if (parsed.path === "templates render") {
3722
- const selector = first!;
3723
- selectedTemplate = selector;
3724
- if (parseNameReference(selector)) {
3725
- await getStore();
3726
- const context = swarmContext();
3727
- readContext = context;
3728
- selectedTemplate = (
3729
- await resolveReference(
3730
- context,
3731
- selector,
3732
- selectedSwarm,
3733
- (reference) => state!.resolve(reference),
3734
- false,
3735
- "local-first",
3736
- )
3737
- ).cid;
3738
- store = context.store;
3739
- } else {
3740
- let explicit = false;
3741
- try {
3742
- CID.parse(selector);
3743
- explicit = true;
3744
- } catch {
3745
- /* Not a CID. */
3746
- }
3747
- explicit ||= selector.toLowerCase().endsWith(".car");
3748
- if (!explicit) {
3749
- try {
3750
- await lstat(selector);
3751
- explicit = true;
3752
- } catch (cause) {
3753
- if (
3754
- !nodeError(cause, "ENOENT") &&
3755
- !nodeError(cause, "ENOTDIR")
3756
- )
3757
- throw cause;
3758
- }
3759
- }
3760
- if (!explicit) {
3761
- templateName(selector);
3762
- if (!selectedSwarm)
3763
- throw new HostError(
3764
- "Template selectors require a selected Swarm. Use --swarm or swarm use, or supply an explicit Bundle directory, CAR, exact CID or IPAB URI.",
3765
- );
3766
- await getStore();
3767
- const context = swarmContext();
3768
- readContext = context;
3769
- selectedTemplate = await resolveTemplateSelector(
3770
- context,
3771
- selector,
3772
- selectedSwarm,
3773
- );
3774
- store = context.store;
3775
- }
3776
- }
3777
- }
3778
- if (parsed.path === "bundle build" || parsed.path === "build")
3779
- io.err(
3780
- parsed.path === "build"
3781
- ? "Assembling and validating Bundle (no compilation)..."
3782
- : "Validating and building bundle...",
3783
- );
3784
- if (parsed.path === "bundle import")
3785
- io.err(
3786
- first!.toLowerCase().endsWith(".car")
3787
- ? "Validating and importing CAR into Store..."
3788
- : "Validating and importing Bundle into Store...",
3673
+ const template = await resolveLocalPathIfPresent(first!);
3674
+ const destination = resolve(parsed.positional[2] ?? second!);
3675
+ const parameters = [
3676
+ ...(parsed.parameters ?? []),
3677
+ ...(typeof parsed.options.description === "string"
3678
+ ? [`description=${parsed.options.description}`]
3679
+ : []),
3680
+ ];
3681
+ result = await client.store.export(
3682
+ {
3683
+ mode: "render-template",
3684
+ template,
3685
+ name: second!,
3686
+ destination,
3687
+ parameters,
3688
+ swarm: selectedSwarm,
3689
+ refresh: explicitRefresh,
3690
+ },
3691
+ requestOpts,
3789
3692
  );
3790
- const result =
3791
- parsed.path === "templates render"
3792
- ? await initApp(second!, parsed.positional[2], {
3793
- ...request,
3794
- ...(selectedTemplate ? { template: selectedTemplate } : {}),
3795
- parameters: [
3796
- ...(parsed.parameters ?? []),
3797
- ...(typeof parsed.options.description === "string"
3798
- ? [`description=${parsed.options.description}`]
3799
- : []),
3800
- ],
3801
- })
3802
- : parsed.path === "build"
3803
- ? await assembleBundle(first, {
3804
- ...request,
3805
- replace: Boolean(parsed.options.replace),
3806
- ...(typeof parsed.options.output === "string"
3807
- ? { output: parsed.options.output }
3808
- : {}),
3809
- outputDir: String(value("bundle.outputDir")),
3810
- })
3811
- : parsed.path === "bundle build"
3812
- ? await buildBundle(source!, {
3813
- ...request,
3814
- schemaOnly: Boolean(parsed.options["schema-only"]),
3815
- replace: Boolean(parsed.options.replace),
3816
- ...(typeof parsed.options.output === "string"
3817
- ? { output: parsed.options.output }
3818
- : {}),
3819
- outputDir: String(value("bundle.outputDir")),
3820
- })
3821
- : parsed.path === "bundle import"
3822
- ? await importBundle(first!, getStore, request)
3823
- : await inspectBundle(source!, request);
3824
- const importing = "output" in result && !parsed.options["no-import"];
3825
- if (importing) {
3826
- io.err("Importing build result into Store (without pinning)...");
3827
- try {
3828
- await importBundle(result.output, getStore, request);
3829
- } catch (cause) {
3830
- throw new HostError(
3831
- `${message(cause)} CAR remains at ${JSON.stringify(result.output)}; retry with ipab bundle import ${JSON.stringify(result.output)}, or build with --no-import.`,
3832
- 1,
3833
- "IMPORT_FAILED",
3834
- "authoring",
3835
- );
3836
- }
3693
+ } else if (parsed.path === "build") {
3694
+ const sourcePath = first ? resolve(first) : process.cwd();
3695
+ result = (await client.store.import(
3696
+ {
3697
+ mode: "assemble",
3698
+ path: sourcePath,
3699
+ replace: Boolean(parsed.options.replace),
3700
+ output: outputOpt,
3701
+ outputDir: outputDirOpt,
3702
+ autoImport: !parsed.options["no-import"],
3703
+ },
3704
+ requestOpts,
3705
+ )) as Record<string, unknown>;
3706
+ } else if (parsed.path === "bundle build") {
3707
+ const sourcePath = await resolveLocalPathIfPresent(first!);
3708
+ result = (await client.store.import(
3709
+ {
3710
+ mode: "build",
3711
+ path: sourcePath,
3712
+ schemaOnly: Boolean(parsed.options["schema-only"]),
3713
+ replace: Boolean(parsed.options.replace),
3714
+ output: outputOpt,
3715
+ outputDir: outputDirOpt,
3716
+ autoImport: !parsed.options["no-import"],
3717
+ },
3718
+ requestOpts,
3719
+ )) as Record<string, unknown>;
3720
+ } else if (parsed.path === "bundle import") {
3721
+ const sourcePath = resolve(first!);
3722
+ result = (await client.store.import(
3723
+ { mode: "car", path: sourcePath },
3724
+ requestOpts,
3725
+ )) as Record<string, unknown>;
3726
+ } else {
3727
+ const sourceRef = await resolveLocalPathIfPresent(first!);
3728
+ result = (await client.store.inspect(
3729
+ {
3730
+ ref: sourceRef,
3731
+ swarm: selectedSwarm,
3732
+ },
3733
+ requestOpts,
3734
+ )) as Record<string, unknown>;
3837
3735
  }
3838
- const closing = store;
3839
- store = undefined;
3840
- await closeStore(closing, undefined);
3841
- state.close();
3842
- state = undefined;
3736
+
3843
3737
  controller.signal.throwIfAborted();
3844
- if ("output" in result)
3738
+
3739
+ if ("output" in result) {
3740
+ const importing = Boolean(result.imported);
3741
+ const validation = result.validation as
3742
+ { status?: string } | null | undefined;
3845
3743
  emit(
3846
- { ...result, imported: importing },
3847
- `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${result.validation !== undefined ? `\nEntry validation: ${result.validation?.status ?? "not-applicable"}` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`,
3744
+ result,
3745
+ `CID: ${String(result.cid)}\nSchema CID: ${String(result.schemaCid)}\nCAR: ${String(result.output)}${validation !== undefined ? `\nEntry validation: ${validation?.status ?? "not-applicable"}` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`,
3848
3746
  );
3849
- else if (result.kind === "bundle-import")
3747
+ } else if (result.kind === "bundle-import") {
3748
+ const source = String(result.source);
3749
+ const validation = result.validation as
3750
+ { status?: string } | null | undefined;
3850
3751
  emit(
3851
3752
  result,
3852
- `Imported CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nBlocks: ${result.blocks}\n${result.source.toLowerCase().endsWith(".car") ? "CAR" : "Source"}: ${result.source}\nEntry validation: ${result.validation?.status ?? "not-applicable"}`,
3753
+ `Imported CID: ${String(result.cid)}\nSchema CID: ${String(result.schemaCid)}\nBlocks: ${String(result.blocks)}\n${source.toLowerCase().endsWith(".car") ? "CAR" : "Source"}: ${source}\nEntry validation: ${validation?.status ?? "not-applicable"}`,
3853
3754
  );
3854
- else if (result.kind === "project-init") {
3755
+ } else if (result.kind === "project-init") {
3756
+ const directory = String(result.directory);
3757
+ const files = Array.isArray(result.files)
3758
+ ? (result.files as string[])
3759
+ : [];
3760
+ const templateCid =
3761
+ typeof result.templateCid === "string"
3762
+ ? result.templateCid
3763
+ : undefined;
3855
3764
  emit(
3856
3765
  result,
3857
- `Created project: ${result.directory}${result.templateCid ? `\nTemplate CID: ${result.templateCid}` : ""}`,
3766
+ `Created project: ${directory}${templateCid ? `\nTemplate CID: ${templateCid}` : ""}`,
3858
3767
  );
3859
3768
  if (
3860
- result.files.includes("package.json") &&
3861
- (result.files.includes("ipab.yaml") ||
3862
- result.files.includes("ipab.json"))
3769
+ files.includes("package.json") &&
3770
+ (files.includes("ipab.yaml") || files.includes("ipab.json"))
3863
3771
  )
3864
3772
  io.err(
3865
- `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.`,
3866
- );
3867
- else if (result.files.includes(".bundle.yaml"))
3868
- io.err(
3869
- `Next: ipab bundle build ${JSON.stringify(result.directory)}`,
3773
+ `Next: install declared dependencies in ${JSON.stringify(directory)}; if your template does not declare @ipab/cli, add or link it as a development dependency. Run pnpm build to prepare and package the App. Root ipab build does not compile.`,
3870
3774
  );
3871
- } else
3775
+ else if (files.includes(".bundle.yaml"))
3776
+ io.err(`Next: ipab bundle build ${JSON.stringify(directory)}`);
3777
+ } else {
3778
+ const manifest = result.manifest as
3779
+ { title: string; entry: string; type: string } | undefined;
3780
+ const type = result.type as { contentType: string };
3781
+ const validation = result.validation as {
3782
+ storage: string;
3783
+ entry?: { status: string } | null;
3784
+ };
3872
3785
  emit(
3873
3786
  result,
3874
- `Kind: ${result.kind}\n${result.manifest ? `Title: ${printable(result.manifest.title)}\nEntry: ${result.manifest.entry}\nType file: ${result.manifest.type}\n` : ""}Type CID: ${result.schemaCid}\nContent type: ${result.type.contentType}\nDefinition validation: passed\nStorage verification: ${result.validation.storage}\nEntry validation: ${result.validation.entry?.status ?? "not-applicable"}`,
3787
+ `Kind: ${String(result.kind)}\n${manifest ? `Title: ${printable(manifest.title)}\nEntry: ${manifest.entry}\nType file: ${manifest.type}\n` : ""}Type CID: ${String(result.schemaCid)}\nContent type: ${type.contentType}\nDefinition validation: passed\nStorage verification: ${validation.storage}\nEntry validation: ${validation.entry?.status ?? "not-applicable"}`,
3875
3788
  );
3789
+ }
3876
3790
  } catch (cause) {
3877
3791
  if (cancelled)
3878
3792
  throw new HostError(
@@ -3889,27 +3803,29 @@ async function performCli(
3889
3803
  break;
3890
3804
  }
3891
3805
  case "pin list": {
3892
- const listed = state.contentPins();
3893
- const archived = state.archivedPins();
3894
- const builtins = state.pins().map(pinDetails);
3806
+ const listed = await client.store.listPins();
3895
3807
  emit(
3896
- { items: listed, builtins, archived },
3808
+ {
3809
+ items: listed.pins,
3810
+ builtins: listed.builtins,
3811
+ archived: listed.archived,
3812
+ },
3897
3813
  table(
3898
3814
  ["REFERENCE", "CID", "STATUS", "SOURCE"],
3899
3815
  [
3900
- ...listed.map((pin) => [
3816
+ ...listed.pins.map((pin) => [
3901
3817
  pin.reference,
3902
3818
  pin.cid ?? "(none)",
3903
3819
  `${pin.status}/${pin.freshness}${pin.error ? `: ${pin.error}` : ""}`,
3904
3820
  pin.swarm ? "following shared Name" : "fixed CID",
3905
3821
  ]),
3906
- ...builtins.map((pin) => [
3907
- pin.name,
3908
- pin.cid,
3822
+ ...listed.builtins.map((pin) => [
3823
+ String(pin.name),
3824
+ String(pin.cid),
3909
3825
  "read-only",
3910
3826
  "built-in",
3911
3827
  ]),
3912
- ...archived.map((pin) => [
3828
+ ...listed.archived.map((pin) => [
3913
3829
  pin.cid,
3914
3830
  pin.cid,
3915
3831
  pin.status,
@@ -3922,47 +3838,27 @@ async function performCli(
3922
3838
  break;
3923
3839
  }
3924
3840
  case "unpin": {
3925
- const canonical = pinReference(state, first!, selectedSwarm);
3926
- const result = await unpin(state, canonical.reference);
3841
+ const result = await client.store.removePin(first!, {
3842
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3843
+ });
3927
3844
  emit(
3928
3845
  result,
3929
- `Unpinned ${canonical.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`,
3846
+ `Unpinned ${result.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`,
3930
3847
  );
3931
3848
  break;
3932
3849
  }
3933
3850
  case "pin show": {
3934
- const builtin = first!.startsWith("builtin:")
3935
- ? state.pin(first!)
3936
- : undefined;
3937
- const canonical = builtin
3938
- ? undefined
3939
- : pinReference(state, first!, selectedSwarm);
3940
- const pin = canonical
3941
- ? state.contentPin(canonical.reference)
3942
- : undefined;
3943
- const archived = canonical
3944
- ? state
3945
- .archivedPins()
3946
- .filter((pin) => pin.cid === canonical.reference)
3947
- : [];
3948
- if (!pin && !builtin && !archived.length)
3949
- throw new HostError(
3950
- `Pin "${first}" does not exist. Run ipab pin list.`,
3951
- );
3952
- const result = builtin
3953
- ? pinDetails(builtin)
3954
- : {
3955
- pin: pin ?? null,
3956
- roots: pin ? state.hold(pin.owner)?.roots : [],
3957
- archived,
3958
- };
3851
+ const result = await client.store.getPin(first!, {
3852
+ details: true,
3853
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
3854
+ });
3959
3855
  emit(result, JSON.stringify(result, null, 2));
3960
3856
  break;
3961
3857
  }
3962
3858
  case "config get": {
3963
- const selected = (
3964
- first ? items.filter((item) => item.key === first) : items
3965
- ).map(visibleConfig);
3859
+ const selected = first
3860
+ ? items.filter((item) => item.key === first)
3861
+ : items;
3966
3862
  emit(
3967
3863
  { items: selected },
3968
3864
  table(
@@ -3975,50 +3871,69 @@ async function performCli(
3975
3871
  }
3976
3872
  case "config set": {
3977
3873
  const key = configKey(first!);
3978
- const saved = parseValue(
3979
- key,
3874
+ const rawInput =
3980
3875
  key === "pointers.apiKey"
3981
3876
  ? await (io.readSecret ?? processIO.readSecret!)()
3982
- : second,
3983
- true,
3984
- );
3985
- state.setConfig(key, saved);
3986
- const source = items.find((item) => item.key === key)!.source;
3987
- if (source === "env" || source === "flag")
3988
- io.err(`Warning: saved user value is masked by ${source}.`);
3989
- const display = visibleConfig({ key, value: saved, source: "user" });
3877
+ : second!;
3878
+ parseValue(key, rawInput, true);
3879
+ const updated = await client.host.setConfig(key, rawInput, {
3880
+ fromString: true,
3881
+ });
3882
+ const currentSource = items.find((item) => item.key === key)!.source;
3883
+ const maskSource =
3884
+ currentSource === "env" || currentSource === "flag"
3885
+ ? currentSource
3886
+ : updated.effectiveSource === "env" ||
3887
+ updated.effectiveSource === "flag"
3888
+ ? updated.effectiveSource
3889
+ : undefined;
3890
+ if (maskSource)
3891
+ io.err(`Warning: saved user value is masked by ${maskSource}.`);
3892
+ const display = {
3893
+ key: updated.key,
3894
+ value: updated.value,
3895
+ source: updated.source,
3896
+ };
3990
3897
  emit(
3991
3898
  display,
3992
3899
  `Saved ${key} = ${printable(String(display.value))} (user).`,
3993
3900
  );
3994
3901
  break;
3995
3902
  }
3996
- case "config reset":
3997
- state.resetConfig(configKey(first!));
3903
+ case "config reset": {
3904
+ await client.host.resetConfig(configKey(first!));
3998
3905
  emit({ reset: [first] }, `Reset user override: ${first}.`);
3999
3906
  break;
3907
+ }
4000
3908
  case "history list": {
4001
- const page = listHistory(
4002
- state,
4003
- filter,
4004
- Number(parsed.options.limit ?? value("history.limit")),
4005
- typeof parsed.options.before === "string"
4006
- ? state.resolveRunId(parsed.options.before)
4007
- : undefined,
4008
- );
3909
+ const page = await client.runs.list({
3910
+ ...(typeof parsed.options.app === "string"
3911
+ ? { app: parsed.options.app }
3912
+ : {}),
3913
+ ...(typeof parsed.options.status === "string"
3914
+ ? { status: parsed.options.status as RunRecord["status"] }
3915
+ : {}),
3916
+ ...(typeof parsed.options.since === "string"
3917
+ ? { since: parsed.options.since }
3918
+ : {}),
3919
+ ...(typeof parsed.options.until === "string"
3920
+ ? { until: parsed.options.until }
3921
+ : {}),
3922
+ limit: Number(parsed.options.limit ?? value("history.limit")),
3923
+ ...(typeof parsed.options.before === "string"
3924
+ ? { before: parsed.options.before }
3925
+ : {}),
3926
+ });
3927
+ const jsonPage = { items: page.items, nextBefore: page.nextBefore };
4009
3928
  if (parsed.flags.json) {
4010
- emit(page, "");
3929
+ emit(jsonPage, "");
4011
3930
  break;
4012
3931
  }
4013
- const names = new Map<string, string>();
4014
- for (const pin of state.pins())
4015
- if (pin.status === "ready" && !names.has(pin.cid))
4016
- names.set(pin.cid, pin.name);
3932
+ const pinNames = page.pinNames ?? {};
4017
3933
  const reference = (cid: string | null): string =>
4018
3934
  cid === null
4019
3935
  ? "none"
4020
- : cid + (names.has(cid) ? ` (${names.get(cid)!})` : "");
4021
- const shortId = state.shortRunId.bind(state);
3936
+ : cid + (pinNames[cid] ? ` (${pinNames[cid]})` : "");
4022
3937
  const rows = page.items.length
4023
3938
  ? page.items
4024
3939
  .map((record) =>
@@ -4038,21 +3953,19 @@ async function performCli(
4038
3953
  .join("\n\n")
4039
3954
  : "No ended executions.";
4040
3955
  emit(
4041
- page,
3956
+ jsonPage,
4042
3957
  rows +
4043
3958
  (page.nextBefore
4044
- ? `\nMore matches; use --before ${shortId(page.nextBefore)} with the same filters.`
3959
+ ? `\nMore matches; use --before ${page.shortNextBefore ?? page.nextBefore} with the same filters.`
4045
3960
  : ""),
4046
3961
  );
4047
3962
  break;
4048
3963
  }
4049
3964
  case "history show": {
4050
- const record = state.run(state.resolveRunId(first!));
4051
- const logs = record.log
4052
- ? await logFiles(state.directory, record.id)
4053
- : undefined;
3965
+ const record = await client.runs.show(first!);
3966
+ const logs = record.logs;
4054
3967
  emit(
4055
- logs ? { ...record, logs } : record,
3968
+ record,
4056
3969
  runDetails(record) +
4057
3970
  (logs
4058
3971
  ? `\nLog recording: ${record.log!}\nStdout log: ${printable(logs.stdout ?? "unavailable")}\nStderr log: ${printable(logs.stderr ?? "unavailable")}`
@@ -4061,24 +3974,46 @@ async function performCli(
4061
3974
  break;
4062
3975
  }
4063
3976
  case "history remove": {
4064
- const ids = parsed.positional.length
4065
- ? [...new Set(parsed.positional.map(state.resolveRunId.bind(state)))]
4066
- : selectedIds(state, filter);
4067
- for (const id of ids) state.run(id);
4068
- if (
4069
- ids.length &&
4070
- !parsed.options.yes &&
4071
- !(await io.confirm(
4072
- `Remove ${ids.length} ended records selected by ${JSON.stringify(
4073
- parsed.positional.length ? { ids } : parsed.options,
4074
- )}? Release only their retention; no GC or disk reclamation is guaranteed.`,
4075
- ))
4076
- )
4077
- throw new HostError("History removal cancelled.");
4078
- const result = await removeHistory(state, ids);
3977
+ const removeParams = parsed.positional.length
3978
+ ? { ids: parsed.positional }
3979
+ : {
3980
+ ...(typeof parsed.options.app === "string"
3981
+ ? { app: parsed.options.app }
3982
+ : {}),
3983
+ ...(typeof parsed.options.status === "string"
3984
+ ? { status: parsed.options.status as RunRecord["status"] }
3985
+ : {}),
3986
+ ...(typeof parsed.options.since === "string"
3987
+ ? { since: parsed.options.since }
3988
+ : {}),
3989
+ ...(typeof parsed.options.until === "string"
3990
+ ? { until: parsed.options.until }
3991
+ : {}),
3992
+ };
3993
+ let idsToRemove: string[] | undefined;
3994
+ if (!parsed.options.yes) {
3995
+ const preview = await client.runs.remove({
3996
+ ...removeParams,
3997
+ dryRun: true,
3998
+ });
3999
+ const ids = preview.ids ?? [];
4000
+ if (
4001
+ ids.length &&
4002
+ !(await io.confirm(
4003
+ `Remove ${ids.length} ended records selected by ${JSON.stringify(
4004
+ parsed.positional.length ? { ids } : parsed.options,
4005
+ )}? Release only their retention; no GC or disk reclamation is guaranteed.`,
4006
+ ))
4007
+ )
4008
+ throw new HostError("History removal cancelled.");
4009
+ idsToRemove = ids;
4010
+ }
4011
+ const result = await client.runs.remove(
4012
+ idsToRemove !== undefined ? { ids: idsToRemove } : removeParams,
4013
+ );
4079
4014
  emit(
4080
4015
  result,
4081
- `Removed ${result.removed.length} records; garbage collection is not guaranteed.`,
4016
+ `Removed ${(result.removed ?? []).length} records; garbage collection is not guaranteed.`,
4082
4017
  );
4083
4018
  break;
4084
4019
  }
@@ -4087,7 +4022,7 @@ async function performCli(
4087
4022
  const named =
4088
4023
  parsed.path === "open" ? parseNameReference(first!) : undefined;
4089
4024
  const registrySwarm = named?.swarm
4090
- ? state.resolveSwarm(named.swarm)
4025
+ ? resolveSwarm(named.swarm)
4091
4026
  : selectedSwarm;
4092
4027
  if (parsed.path === "open" && !registrySwarm)
4093
4028
  throw new HostError(
@@ -4097,215 +4032,25 @@ async function performCli(
4097
4032
  throw new HostError(
4098
4033
  "Execution logging requires history.enabled=true.",
4099
4034
  );
4100
- await recoverInactive(state);
4101
- store = new IpfsStore(await storeConfiguration(value("store.gateway")));
4102
- const context = swarmContext();
4103
- readContext = context;
4104
- const localInput = await resolveLocalBundleInput(first!);
4105
- const target = localInput
4106
- ? undefined
4107
- : (
4108
- await resolveReference(
4109
- context,
4110
- first!,
4111
- selectedSwarm,
4112
- (reference) => state!.resolve(reference),
4113
- Boolean(parsed.options.raw),
4114
- "local-first",
4115
- )
4116
- ).cid;
4117
- store = context.store;
4118
- const resolveBundleReference = async (
4119
- reference: string,
4120
- signal: AbortSignal,
4121
- preferredSwarm?: string,
4122
- ) => {
4123
- signal.throwIfAborted();
4124
- const lookup: SwarmContext = {
4125
- ...swarmContext(),
4126
- store: new IpfsStore(
4127
- await storeConfiguration(value("store.gateway")),
4128
- ),
4129
- };
4130
- try {
4131
- const named = parseNameReference(reference);
4132
- const swarm = named?.swarm
4133
- ? state!.resolveSwarm(named.swarm)
4134
- : preferredSwarm
4135
- ? state!.resolveSwarm(preferredSwarm)
4136
- : selectedSwarm;
4137
- const resolve = (source: string | undefined) =>
4138
- resolveReference(
4139
- lookup,
4140
- reference,
4141
- source,
4142
- (input) => state!.resolve(input),
4143
- false,
4144
- "local-first",
4145
- );
4146
- let resolved;
4147
- try {
4148
- resolved = await resolve(named ? swarm : undefined);
4149
- } catch (cause) {
4150
- let failure: unknown = cause;
4151
- for (
4152
- let depth = 0;
4153
- depth < 8 && failure instanceof ContentBundleError;
4154
- depth++
4155
- )
4156
- failure = failure.cause;
4157
- if (
4158
- named ||
4159
- !swarm ||
4160
- !(failure instanceof ContentError) ||
4161
- failure.code !== "missing_block"
4162
- )
4163
- throw cause;
4164
- signal.throwIfAborted();
4165
- resolved = await resolve(swarm);
4166
- }
4167
- signal.throwIfAborted();
4168
- return { ...resolved, ...(swarm ? { swarm } : {}) };
4169
- } finally {
4170
- try {
4171
- await lookup.finishRead?.();
4172
- } finally {
4173
- await lookup.store.close();
4174
- }
4175
- }
4176
- };
4177
- let appCid: string;
4178
- let appArgv: string[];
4179
- if (parsed.path === "open") {
4180
- const session = localInput ? `open:${randomUUID()}` : null;
4181
- const owner = await Ownership.create(
4182
- state,
4183
- store,
4184
- `open:${randomUUID()}`,
4185
- session,
4186
- );
4187
- try {
4188
- const root = localInput
4189
- ? await snapshotLocalBundle(localInput, owner, session!, {
4190
- diagnostic: (text) => {
4191
- io.err(text);
4192
- },
4193
- })
4194
- : target!;
4195
- const content = await validatedBundle(root, store, owner);
4196
- const schema = content.schemaKey;
4197
- let association: Association | undefined;
4198
- if (registrySwarm) {
4199
- const lookup: SwarmContext = {
4200
- ...swarmContext(),
4201
- store: new IpfsStore(
4202
- await storeConfiguration(value("store.gateway")),
4203
- ),
4204
- };
4205
- try {
4206
- association = await swarmAssociation(
4207
- lookup,
4208
- registrySwarm,
4209
- schema,
4210
- "local-first",
4211
- );
4212
- } finally {
4213
- try {
4214
- await lookup.finishRead?.();
4215
- } finally {
4216
- await lookup.store.close();
4217
- }
4218
- }
4219
- }
4220
- if (!association)
4221
- throw new HostError(
4222
- `No App registered for Schema ${schema} in Swarm ${registrySwarm}. Use ipab register set ${schema} APP_CID --swarm ${registrySwarm} or ipab exec.`,
4223
- );
4224
- appCid = association.appCid;
4225
- if (association.argv.length !== 1 || association.argv[0] !== "%")
4226
- throw new HostError(
4227
- "Custom per-association argv is unsupported; adapt the App to accept only the content CID or use ipab exec APP_CID ARGS.",
4228
- );
4229
- appArgv = [root];
4230
- io.err("Starting App...");
4231
- // execute owns the App/input context before this validation owner's eventual release.
4232
- const result = await execute(
4233
- state,
4234
- store,
4235
- { origin: "open", appCid, argv: appArgv },
4236
- {
4237
- inputSchema: schema,
4238
- resolveBundleReference,
4239
- history: Boolean(value("history.enabled")),
4240
- retain: value("output.retention") === "history",
4241
- log: Boolean(parsed.options.log),
4242
- diagnostic: (text) => {
4243
- io.err(text);
4244
- },
4245
- },
4246
- );
4247
- appExitCode = result.exitCode;
4248
- return appExitCode;
4249
- } finally {
4250
- await owner.release();
4251
- }
4252
- } else if (localInput) {
4253
- const session = `exec:${randomUUID()}`;
4254
- const owner = await Ownership.create(
4255
- state,
4256
- store,
4257
- `exec:${randomUUID()}`,
4258
- session,
4259
- );
4260
- try {
4261
- appCid = await snapshotLocalBundle(localInput, owner, session, {
4262
- diagnostic: (text) => {
4263
- io.err(text);
4264
- },
4265
- });
4266
- appArgv = parsed.positional.slice(1);
4267
- io.err("Starting App...");
4268
- appExitCode = (
4269
- await execute(
4270
- state,
4271
- store,
4272
- { origin: "exec", appCid, argv: appArgv },
4273
- {
4274
- resolveBundleReference,
4275
- history: Boolean(value("history.enabled")),
4276
- retain: value("output.retention") === "history",
4277
- log: Boolean(parsed.options.log),
4278
- diagnostic: (text) => {
4279
- io.err(text);
4280
- },
4281
- },
4282
- )
4283
- ).exitCode;
4284
- return appExitCode;
4285
- } finally {
4286
- await owner.release();
4287
- }
4288
- } else {
4289
- appCid = target!;
4290
- appArgv = parsed.positional.slice(1);
4291
- }
4292
- appExitCode = (
4293
- await execute(
4294
- state,
4295
- store,
4296
- { origin: "exec", appCid, argv: appArgv },
4297
- {
4298
- resolveBundleReference,
4299
- history: Boolean(value("history.enabled")),
4300
- retain: value("output.retention") === "history",
4301
- log: Boolean(parsed.options.log),
4302
- diagnostic: (text) => {
4303
- io.err(text);
4304
- },
4305
- },
4306
- )
4307
- ).exitCode;
4308
- return appExitCode;
4035
+ const resolvedFirst = await resolveLocalPathIfPresent(first!);
4036
+ const prepared = await client.runs.prepare(
4037
+ {
4038
+ origin: parsed.path,
4039
+ ...(parsed.path === "open"
4040
+ ? { target: resolvedFirst }
4041
+ : { appCid: resolvedFirst, argv: parsed.positional.slice(1) }),
4042
+ swarm: selectedSwarm,
4043
+ history: Boolean(value("history.enabled")),
4044
+ retain: value("output.retention") === "history",
4045
+ log: Boolean(parsed.options.log),
4046
+ raw: Boolean(parsed.options.raw),
4047
+ refresh: explicitRefresh,
4048
+ },
4049
+ { ndjson: true },
4050
+ );
4051
+ return await runPreparedApp(client, prepared, (text, prog) => {
4052
+ io.err(text, prog);
4053
+ });
4309
4054
  }
4310
4055
  default:
4311
4056
  syntax("Unknown command.");
@@ -4317,13 +4062,9 @@ async function performCli(
4317
4062
  return error instanceof HostError ? error.exitCode : 1;
4318
4063
  } finally {
4319
4064
  try {
4320
- try {
4321
- await readContext?.finishRead?.();
4322
- } finally {
4323
- await closeStore(store, appExitCode);
4324
- }
4065
+ await cliHandle?.close();
4325
4066
  } finally {
4326
- state?.close();
4067
+ await closeStore(daemonStore, undefined);
4327
4068
  }
4328
4069
  }
4329
4070
  }