@ipab/cli 0.0.0 → 0.1.0-rc.1

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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -1
  3. package/dist/app-authoring.d.ts +22 -0
  4. package/dist/app-authoring.d.ts.map +1 -0
  5. package/dist/app-authoring.js +448 -0
  6. package/dist/app-authoring.js.map +1 -0
  7. package/dist/app-definition.d.ts +103 -0
  8. package/dist/app-definition.d.ts.map +1 -0
  9. package/dist/app-definition.js +201 -0
  10. package/dist/app-definition.js.map +1 -0
  11. package/dist/app-prebuild.d.ts +12 -0
  12. package/dist/app-prebuild.d.ts.map +1 -0
  13. package/dist/app-prebuild.js +231 -0
  14. package/dist/app-prebuild.js.map +1 -0
  15. package/dist/app-templates.d.ts +13 -0
  16. package/dist/app-templates.d.ts.map +1 -0
  17. package/dist/app-templates.js +295 -0
  18. package/dist/app-templates.js.map +1 -0
  19. package/dist/authoring.d.ts +63 -0
  20. package/dist/authoring.d.ts.map +1 -0
  21. package/dist/authoring.js +411 -0
  22. package/dist/authoring.js.map +1 -0
  23. package/dist/builtins/template.node.car +0 -0
  24. package/dist/builtins/template.web-app.car +0 -0
  25. package/dist/builtins.d.ts +6 -0
  26. package/dist/builtins.d.ts.map +1 -0
  27. package/dist/builtins.js +41 -0
  28. package/dist/builtins.js.map +1 -0
  29. package/dist/child.d.ts +5 -0
  30. package/dist/child.d.ts.map +1 -0
  31. package/dist/child.js +28 -0
  32. package/dist/child.js.map +1 -0
  33. package/dist/cli.d.ts +24 -0
  34. package/dist/cli.d.ts.map +1 -0
  35. package/dist/cli.js +1110 -0
  36. package/dist/cli.js.map +1 -0
  37. package/dist/config.d.ts +26 -0
  38. package/dist/config.d.ts.map +1 -0
  39. package/dist/config.js +154 -0
  40. package/dist/config.js.map +1 -0
  41. package/dist/context.d.ts +43 -0
  42. package/dist/context.d.ts.map +1 -0
  43. package/dist/context.js +174 -0
  44. package/dist/context.js.map +1 -0
  45. package/dist/errors.d.ts +10 -0
  46. package/dist/errors.d.ts.map +1 -0
  47. package/dist/errors.js +40 -0
  48. package/dist/errors.js.map +1 -0
  49. package/dist/history.d.ts +34 -0
  50. package/dist/history.d.ts.map +1 -0
  51. package/dist/history.js +286 -0
  52. package/dist/history.js.map +1 -0
  53. package/dist/ipc.d.ts +27 -0
  54. package/dist/ipc.d.ts.map +1 -0
  55. package/dist/ipc.js +341 -0
  56. package/dist/ipc.js.map +1 -0
  57. package/dist/logs.d.ts +15 -0
  58. package/dist/logs.d.ts.map +1 -0
  59. package/dist/logs.js +118 -0
  60. package/dist/logs.js.map +1 -0
  61. package/dist/main.d.ts +3 -0
  62. package/dist/main.d.ts.map +1 -0
  63. package/dist/main.js +4 -0
  64. package/dist/main.js.map +1 -0
  65. package/dist/pins.d.ts +33 -0
  66. package/dist/pins.d.ts.map +1 -0
  67. package/dist/pins.js +165 -0
  68. package/dist/pins.js.map +1 -0
  69. package/dist/runtime.d.ts +20 -0
  70. package/dist/runtime.d.ts.map +1 -0
  71. package/dist/runtime.js +237 -0
  72. package/dist/runtime.js.map +1 -0
  73. package/dist/source-bundle.d.ts +15 -0
  74. package/dist/source-bundle.d.ts.map +1 -0
  75. package/dist/source-bundle.js +102 -0
  76. package/dist/source-bundle.js.map +1 -0
  77. package/dist/space.d.ts +33 -0
  78. package/dist/space.d.ts.map +1 -0
  79. package/dist/space.js +269 -0
  80. package/dist/space.js.map +1 -0
  81. package/dist/state.d.ts +102 -0
  82. package/dist/state.d.ts.map +1 -0
  83. package/dist/state.js +335 -0
  84. package/dist/state.js.map +1 -0
  85. package/dist/supported-schemas.d.ts +5 -0
  86. package/dist/supported-schemas.d.ts.map +1 -0
  87. package/dist/supported-schemas.js +90 -0
  88. package/dist/supported-schemas.js.map +1 -0
  89. package/dist/template-definition.d.ts +98 -0
  90. package/dist/template-definition.d.ts.map +1 -0
  91. package/dist/template-definition.js +179 -0
  92. package/dist/template-definition.js.map +1 -0
  93. package/dist/template-source.d.ts +12 -0
  94. package/dist/template-source.d.ts.map +1 -0
  95. package/dist/template-source.js +97 -0
  96. package/dist/template-source.js.map +1 -0
  97. package/package.json +60 -3
  98. package/src/app-authoring.ts +616 -0
  99. package/src/app-definition.ts +250 -0
  100. package/src/app-prebuild.ts +289 -0
  101. package/src/app-templates.ts +395 -0
  102. package/src/authoring.ts +577 -0
  103. package/src/builtins.ts +49 -0
  104. package/src/child.ts +32 -0
  105. package/src/cli.ts +1330 -0
  106. package/src/config.ts +221 -0
  107. package/src/context.ts +242 -0
  108. package/src/errors.ts +46 -0
  109. package/src/history.ts +391 -0
  110. package/src/ipc.ts +366 -0
  111. package/src/logs.ts +132 -0
  112. package/src/main.ts +4 -0
  113. package/src/pins.ts +200 -0
  114. package/src/runtime.ts +301 -0
  115. package/src/source-bundle.ts +135 -0
  116. package/src/space.ts +379 -0
  117. package/src/state.ts +430 -0
  118. package/src/supported-schemas.ts +151 -0
  119. package/src/template-definition.ts +233 -0
  120. package/src/template-source.ts +128 -0
package/src/cli.ts ADDED
@@ -0,0 +1,1330 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { readFile } from "node:fs/promises";
3
+ import { IpfsStore } from "@ipab/ipfs-store";
4
+ import { randomUUID } from "node:crypto";
5
+ import type { CID } from "multiformats/cid";
6
+ import stringWidth from "string-width";
7
+ import {
8
+ configKey,
9
+ effectiveConfig,
10
+ parseValue,
11
+ publicUrl,
12
+ stateLocation,
13
+ storeConfiguration,
14
+ type GlobalOptions,
15
+ } from "./config.js";
16
+ import { HostError, message, object, syntax } from "./errors.js";
17
+ import {
18
+ filters,
19
+ listHistory,
20
+ selectedIds,
21
+ Ownership,
22
+ recoverInactive,
23
+ removeHistory,
24
+ } from "./history.js";
25
+ import { execute } from "./runtime.js";
26
+ import { validatedBundle } from "./space.js";
27
+ import { exactCid, pinName, State, type RunRecord } from "./state.js";
28
+ import { buildBundle, inspectBundle, importBundle } from "./authoring.js";
29
+ import { buildApp, initApp } from "./app-authoring.js";
30
+ import { schemaAlias } from "./app-definition.js";
31
+ import { addPin, deletePin, pinDetails, renamePin } from "./pins.js";
32
+ import { logFiles } from "./logs.js";
33
+ import { builtinContent } from "./builtins.js";
34
+
35
+ export interface IO {
36
+ out(text: string): void;
37
+ err(text: string): void;
38
+ tty: boolean;
39
+ columns?(): number | undefined;
40
+ confirm(text: string): Promise<boolean>;
41
+ }
42
+ export const processIO: IO = {
43
+ out(text) {
44
+ process.stdout.write(`${text}\n`);
45
+ },
46
+ err(text) {
47
+ process.stderr.write(`${text}\n`);
48
+ },
49
+ tty: Boolean(process.stdin.isTTY && process.stderr.isTTY),
50
+ columns() {
51
+ return process.stdout.columns;
52
+ },
53
+ async confirm(text) {
54
+ const reader = createInterface({
55
+ input: process.stdin,
56
+ output: process.stderr,
57
+ });
58
+ try {
59
+ return /^(y|yes)$/i.test(
60
+ (await reader.question(`${text} [y/N] `)).trim(),
61
+ );
62
+ } finally {
63
+ reader.close();
64
+ }
65
+ },
66
+ };
67
+ const commands: Record<string, string> = {
68
+ init: "init NAME [DIR] [OPTIONS]",
69
+ build: "build [DIR] [OPTIONS]",
70
+ "bundle build": "bundle build SOURCE [OPTIONS]",
71
+ "bundle inspect": "bundle inspect SOURCE",
72
+ "bundle import": "bundle import FILE.car",
73
+ exec: "exec [--log] APP [APP_ARGS...]",
74
+ open: "open [--log] CONTENT",
75
+ "pin add": "pin add NAME CID",
76
+ "pin delete": "pin delete NAME",
77
+ "pin list": "pin list [--type TYPE]",
78
+ "pin show": "pin show NAME",
79
+ "pin rename": "pin rename OLD_NAME NEW_NAME",
80
+ "register list": "register list",
81
+ "register set": "register set SCHEMA APP [--replace] [-- TEMPLATE...]",
82
+ "register remove": "register remove SCHEMA",
83
+ "config get": "config get [KEY]",
84
+ "config set": "config set KEY VALUE",
85
+ "config reset": "config reset KEY",
86
+ "store usage": "store usage",
87
+ "store gc": "store gc",
88
+ "history list": "history list [OPTIONS]",
89
+ "history show": "history show RUN_ID",
90
+ "history remove":
91
+ "history remove RUN_ID... [--yes]\n ipab history remove FILTERS [--yes]",
92
+ };
93
+ const groups: Record<string, string> = {
94
+ bundle: "Create, inspect and import content bundles",
95
+ pin: "Retain content and manage short names",
96
+ register: "Associate content types with Apps",
97
+ config: "Manage local configuration",
98
+ store: "Query local storage and collect unreferenced blocks",
99
+ history: "View and remove execution history",
100
+ };
101
+ const commandHelp: Record<
102
+ string,
103
+ {
104
+ summary: string;
105
+ examples: string[];
106
+ arguments?: string[];
107
+ options?: string[];
108
+ notes?: string[];
109
+ }
110
+ > = {
111
+ "store usage": {
112
+ summary: "Query cached and recursively pinned block bytes",
113
+ examples: ["ipab store usage", "ipab --json store usage"],
114
+ notes: [
115
+ "Local Store only; excludes metadata, temporary files and disk allocation overhead.",
116
+ "Pinned DAGs include all descendants, with shared blocks counted once.",
117
+ ],
118
+ },
119
+ "store gc": {
120
+ summary: "Delete unprotected blocks from the entire selected local Store",
121
+ examples: ["ipab store gc", "ipab --json store gc"],
122
+ notes: [
123
+ "Preserves pins, all participating owners, pending operations and staged imports.",
124
+ "Does not unpin, clear history, delete unknown files or request Kubo daemon GC.",
125
+ ],
126
+ },
127
+ init: {
128
+ summary: "Create files from a Template Bundle (default: Node App project)",
129
+ arguments: ["NAME Project name; DIR defaults to NAME (new/empty only)."],
130
+ options: [
131
+ "--template TEMPLATE node (default), web-app, directory, CAR, CID or pin.",
132
+ "--param KEY=VALUE Template parameter; repeatable. Strings are literal;",
133
+ " other parameter types use JSON.",
134
+ ],
135
+ examples: [
136
+ "ipab init hello",
137
+ "ipab init dashboard --template web-app",
138
+ "ipab init hello --param description=Demo",
139
+ ],
140
+ notes: ["Does not install dependencies or execute template code."],
141
+ },
142
+ build: {
143
+ summary: "Build an App CAR from a project",
144
+ arguments: ["DIR Project directory (default: current directory)."],
145
+ options: [
146
+ "-o, --output FILE Destination (default: dist/app.car).",
147
+ "--replace Allow replacing existing regular artifacts.",
148
+ "--no-import Write CAR files without importing the App into Store.",
149
+ "--with-source Include a separate source CAR (default: enabled).",
150
+ "--without-source Omit source CAR; conflicts with --with-source.",
151
+ ],
152
+ examples: ["ipab build", "ipab build hello --replace --without-source"],
153
+ notes: [
154
+ "Uses local tsc and bundles Node CommonJS; ipab.yaml configures the build.",
155
+ "Explicit ipab-prebuild strategy executes trusted project code.",
156
+ "Source follows project .gitignore rules; review private files before sharing.",
157
+ "Imports only the App, without pinning; source needs separate import/retention.",
158
+ "Store failures preserve the CAR; retry with ipab bundle import FILE.car.",
159
+ ],
160
+ },
161
+ "bundle build": {
162
+ summary: "Build a content or type CAR without compiling code",
163
+ arguments: ["SOURCE Bundle directory or definition file."],
164
+ options: [
165
+ "--schema-only Emit only the type CAR (default: dist/schema.car).",
166
+ "-o, --output FILE Destination (full build default: dist/bundle.car).",
167
+ "--replace Allow replacing an existing regular artifact.",
168
+ "--no-import Write the CAR without importing it into Store.",
169
+ ],
170
+ examples: [
171
+ "ipab bundle build note",
172
+ "ipab bundle build types\\.bundle.yaml --schema-only",
173
+ ],
174
+ notes: [
175
+ "Imports into the configured Store without pinning or executing Apps.",
176
+ "Store failures preserve the CAR; retry with ipab bundle import FILE.car.",
177
+ ],
178
+ },
179
+ "bundle inspect": {
180
+ summary: "Inspect a Bundle or type definition",
181
+ arguments: ["SOURCE Directory, definition file, CAR, CID or named pin."],
182
+ examples: ["ipab bundle inspect note\\dist\\bundle.car"],
183
+ notes: ["Does not execute Apps, import content or create pins."],
184
+ },
185
+ "bundle import": {
186
+ summary: "Validate and import a CAR into the configured Store",
187
+ arguments: ["FILE.car Self-contained single-root Bundle or type CAR."],
188
+ examples: ["ipab bundle import hello\\dist\\app.car"],
189
+ notes: [
190
+ "Repeated imports are safe; no App execution or daemon startup.",
191
+ "Does not pin or retain content. Use pin add for persistent retention.",
192
+ ],
193
+ },
194
+ exec: {
195
+ summary: "Run an App by CID or named pin",
196
+ arguments: [
197
+ "APP_ARGS Everything after APP is passed verbatim, including --help.",
198
+ ],
199
+ options: [
200
+ "--log Record stdout/stderr; must precede APP. Requires history enabled.",
201
+ ],
202
+ examples: [
203
+ "ipab exec reader",
204
+ "ipab exec reader --help",
205
+ "ipab exec --log reader",
206
+ ],
207
+ notes: [
208
+ "Apps are NOT sandboxed; run only Apps you trust.",
209
+ "History stores argv by default; do not put secrets in arguments.",
210
+ "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
211
+ "--json is not supported; App stdio is passed through.",
212
+ ],
213
+ },
214
+ open: {
215
+ summary: "Open content with its registered App",
216
+ arguments: ["CONTENT Bundle CID or named pin."],
217
+ options: ["--log Record stdout/stderr; requires history enabled."],
218
+ examples: ["ipab open CONTENT_CID", "ipab open --log my-note"],
219
+ notes: [
220
+ "Requires a saved registration and App support for the exact content type.",
221
+ "Apps are NOT sandboxed; run only Apps you trust.",
222
+ "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
223
+ "--json is not supported; App stdio is passed through.",
224
+ ],
225
+ },
226
+ "pin add": {
227
+ summary: "Verify, retain and name a Bundle",
228
+ arguments: [
229
+ "NAME Unused short name.",
230
+ "CID Exact Bundle CID, not another pin name or a standalone type block.",
231
+ ],
232
+ examples: ["ipab pin add reader APP_CID"],
233
+ notes: [
234
+ "Validates a complete Bundle and retains its full DAG in the configured Store.",
235
+ "Does not execute or trust Apps, install dependencies or start a daemon.",
236
+ "The builtin namespace is read-only.",
237
+ ],
238
+ },
239
+ "pin delete": {
240
+ summary: "Remove a user pin and release its retention",
241
+ examples: ["ipab pin delete reader"],
242
+ notes: [
243
+ "Releases only this pin's ownership on its original backend; no block deletion or GC.",
244
+ "Does not change registrations or history. Built-in pins are read-only.",
245
+ ],
246
+ },
247
+ "pin list": {
248
+ summary: "List user and built-in pins",
249
+ options: [
250
+ "--type TYPE Exact type CID or the name of a Bundle pin of that type.",
251
+ ],
252
+ examples: ["ipab pin list", "ipab pin list --type reader"],
253
+ notes: [
254
+ "Unfinished operations and legacy non-Bundle pins are reported separately.",
255
+ "Legacy retention is preserved; use pin delete to explicitly release it.",
256
+ "Reads local registrations and packaged built-ins, not live node status.",
257
+ ],
258
+ },
259
+ "pin show": {
260
+ summary: "Show a pin's CID and type metadata",
261
+ examples: ["ipab pin show reader", "ipab pin show builtin:template.node"],
262
+ notes: [
263
+ "Reads local metadata; built-in pins do not claim user Store retention.",
264
+ ],
265
+ },
266
+ "pin rename": {
267
+ summary: "Rename a user pin without changing its content",
268
+ examples: ["ipab pin rename reader my-reader"],
269
+ notes: [
270
+ "NEW_NAME must be unused. Built-in pins are read-only.",
271
+ "CID, ownership, registrations and history are unchanged.",
272
+ ],
273
+ },
274
+ "register list": {
275
+ summary: "List saved content-type associations",
276
+ examples: ["ipab register list"],
277
+ },
278
+ "register set": {
279
+ summary: "Associate a content type with an App",
280
+ arguments: [
281
+ "SCHEMA Exact type CID or builtin:node-app.v1.",
282
+ "APP App CID or named pin; the exact CID is saved.",
283
+ "TEMPLATE App argv after --; must contain a whole argument % (default: %).",
284
+ ],
285
+ options: ["--replace Allow changing an existing association."],
286
+ examples: [
287
+ "ipab register set SCHEMA_CID reader",
288
+ "ipab register set SCHEMA_CID reader '--' '--cid' '%'",
289
+ ],
290
+ notes: [
291
+ "Replaces only the whole % argument with the content CID; no shell expansion.",
292
+ "Does not verify App type support; open checks it before execution.",
293
+ ],
294
+ },
295
+ "register remove": {
296
+ summary: "Remove a saved content-type association",
297
+ arguments: ["SCHEMA Exact type CID or builtin:node-app.v1."],
298
+ examples: ["ipab register remove SCHEMA_CID"],
299
+ notes: ["Does not remove Apps, pins or content."],
300
+ },
301
+ "config get": {
302
+ summary: "Show effective configuration",
303
+ arguments: ["KEY Optional configuration key; omit to show all values."],
304
+ examples: ["ipab config get", "ipab config get store.gateway"],
305
+ },
306
+ "config set": {
307
+ summary: "Save a local configuration value",
308
+ examples: [
309
+ "ipab config set store.gateway http://127.0.0.1:8080",
310
+ "ipab config set history.enabled false",
311
+ ],
312
+ notes: [
313
+ "store.gateway is a read-only HTTP gateway; blocks, pins and GC remain local.",
314
+ ],
315
+ },
316
+ "config reset": {
317
+ summary: "Remove a saved configuration override",
318
+ examples: ["ipab config reset store.gateway"],
319
+ },
320
+ "history list": {
321
+ summary: "List execution history",
322
+ options: [
323
+ "--app APP Filter by App CID or named pin.",
324
+ "--status STATUS succeeded, failed or cancelled.",
325
+ "--since TIME Include runs ended at or after TIME.",
326
+ "--until TIME Include runs ended before TIME.",
327
+ "--limit N Maximum number of records.",
328
+ "--before RUN_ID Continue before a previous record.",
329
+ ],
330
+ examples: [
331
+ "ipab history list",
332
+ "ipab history list --status failed --limit 10",
333
+ ],
334
+ notes: [
335
+ "Filters combine with AND; times use RFC3339 with an explicit timezone.",
336
+ ],
337
+ },
338
+ "history show": {
339
+ summary: "Show an execution record and available log paths",
340
+ examples: ["ipab history show RUN_ID"],
341
+ notes: ["Only runs started with --log have recorded stdout/stderr."],
342
+ },
343
+ "history remove": {
344
+ summary: "Remove execution records and their logs",
345
+ options: [
346
+ "--app APP Filter by App CID or named pin.",
347
+ "--status STATUS succeeded, failed or cancelled.",
348
+ "--since TIME Include runs ended at or after TIME.",
349
+ "--until TIME Include runs ended before TIME.",
350
+ "--yes Skip confirmation; required outside an interactive terminal.",
351
+ ],
352
+ examples: [
353
+ "ipab history remove RUN_ID --yes",
354
+ "ipab history remove --status failed --until 2026-11-01T00:00:00Z --yes",
355
+ ],
356
+ notes: [
357
+ "Use explicit IDs OR at least one filter, not both.",
358
+ "Filters combine with AND; times use RFC3339 with an explicit timezone.",
359
+ "Deletes associated logs and releases history retention; does not request Store GC.",
360
+ ],
361
+ },
362
+ };
363
+
364
+ export function help(path = ""): string {
365
+ const globalOptions = `Global options (before COMMAND):
366
+ --state-dir PATH Set the local state directory
367
+ --store-gateway URL Use a read-only upstream HTTP gateway
368
+ --json Output management/development metadata, not App stdio`;
369
+ const footer =
370
+ "Full reference: https://github.com/silvermoon-work/ipab/blob/main/docs/reference.md";
371
+ if (!path)
372
+ return `IPAB — run Apps and open content by CID.
373
+
374
+ Usage: ipab [GLOBAL_OPTIONS] COMMAND
375
+
376
+ Run Apps:
377
+ exec ${commandHelp.exec!.summary}
378
+ open ${commandHelp.open!.summary}
379
+
380
+ Create:
381
+ init ${commandHelp.init!.summary}
382
+ build ${commandHelp.build!.summary}
383
+ bundle ${groups.bundle}
384
+
385
+ Manage:
386
+ pin ${groups.pin}
387
+ register ${groups.register}
388
+ config ${groups.config}
389
+ store ${groups.store}
390
+ history ${groups.history}
391
+
392
+ ${globalOptions}
393
+ -h, --help Show help for the current command
394
+ --version Show version
395
+
396
+ Run 'ipab COMMAND --help' for command details.
397
+ Apps are NOT sandboxed; run only Apps you trust.
398
+ ${footer}`;
399
+ const usage = commands[path];
400
+ if (usage) {
401
+ const topic = commandHelp[path]!;
402
+ const section = (title: string, lines: string[]) =>
403
+ `\n\n${title}:\n${lines.map((line) => ` ${line}`).join("\n")}`;
404
+ return [
405
+ `${topic.summary}.\n\nUsage: ipab [GLOBAL_OPTIONS] ${usage}`,
406
+ ...(topic.arguments ? [section("Arguments", topic.arguments)] : []),
407
+ ...(topic.options ? [section("Options", topic.options)] : []),
408
+ section("Examples", topic.examples),
409
+ ...(topic.notes ? [section("Notes", topic.notes)] : []),
410
+ `\n\n-h, --help shows this help. Global options: see 'ipab --help'.\n${footer}`,
411
+ ].join("");
412
+ }
413
+ const leaves = Object.keys(commands).filter((key) =>
414
+ key.startsWith(`${path} `),
415
+ );
416
+ if (!leaves.length) syntax(`Unknown command "${path}".`);
417
+ return `${groups[path]}.
418
+
419
+ Usage: ipab [GLOBAL_OPTIONS] ${path} COMMAND
420
+
421
+ Commands:
422
+ ${leaves.map((key) => ` ${key.slice(path.length + 1).padEnd(8)}${commandHelp[key]!.summary}`).join("\n")}
423
+
424
+ Run 'ipab ${path} COMMAND --help' for command details.
425
+ Global options: see 'ipab --help'.
426
+ ${footer}`;
427
+ }
428
+ function printable(text: string): string {
429
+ return [...text]
430
+ .map((char) =>
431
+ char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127
432
+ ? JSON.stringify(char).slice(1, -1)
433
+ : char,
434
+ )
435
+ .join("");
436
+ }
437
+
438
+ function runTime(value: string, field: "start" | "end"): string {
439
+ const date = new Date(value);
440
+ if (!Number.isFinite(date.getTime()))
441
+ throw new HostError(`Execution record has an invalid ${field} time.`);
442
+ const pad = (part: number): string => String(part).padStart(2, "0");
443
+ const day = [
444
+ String(date.getFullYear()).padStart(4, "0"),
445
+ pad(date.getMonth() + 1),
446
+ pad(date.getDate()),
447
+ ].join("-");
448
+ const time = [date.getHours(), date.getMinutes(), date.getSeconds()]
449
+ .map(pad)
450
+ .join(":");
451
+ const offset = -date.getTimezoneOffset();
452
+ const zone = `${offset < 0 ? "-" : "+"}${pad(Math.floor(Math.abs(offset) / 60))}${pad(Math.abs(offset) % 60)}`;
453
+ return `${day} ${time} ${zone}`;
454
+ }
455
+
456
+ function runDuration(record: Pick<RunRecord, "startedAt" | "endedAt">): string {
457
+ const started = Date.parse(record.startedAt);
458
+ if (!Number.isFinite(started))
459
+ throw new HostError("Execution record has an invalid start time.");
460
+ const duration = Date.parse(record.endedAt) - started;
461
+ if (!Number.isFinite(duration) || duration < 0)
462
+ throw new HostError("Execution record has an invalid duration.");
463
+ return `${Math.floor(duration / 1000)}s`;
464
+ }
465
+
466
+ function storageBytes(bytes: number): string {
467
+ const units = ["B", "KB", "MB", "GB", "TB", "PB"];
468
+ let scaled = bytes;
469
+ let unit = 0;
470
+ while (scaled >= 1000 && unit < units.length - 1) {
471
+ scaled /= 1000;
472
+ unit++;
473
+ }
474
+ const exact = bytes.toLocaleString("en-US");
475
+ return unit === 0
476
+ ? `${exact} bytes`
477
+ : `${scaled.toLocaleString("en-US", { maximumFractionDigits: 2 })} ${units[unit]} (${exact} bytes)`;
478
+ }
479
+
480
+ function table(headers: string[], rows: string[][], empty: string): string {
481
+ if (!rows.length) return empty;
482
+ const cells = rows.map((row) => row.map(printable));
483
+ const widths = headers.map((header, column) =>
484
+ cells.reduce(
485
+ (width, row) => Math.max(width, stringWidth(row[column]!)),
486
+ stringWidth(header),
487
+ ),
488
+ );
489
+ return [headers, ...cells]
490
+ .map((row) =>
491
+ row
492
+ .map((cell, column) =>
493
+ column === headers.length - 1
494
+ ? cell
495
+ : cell.padEnd(cell.length + widths[column]! - stringWidth(cell)),
496
+ )
497
+ .join(" "),
498
+ )
499
+ .join("\n");
500
+ }
501
+
502
+ function runDetails(record: RunRecord): string {
503
+ const fields: [string, string][] = [
504
+ ["Run", record.id],
505
+ ["Origin", record.origin],
506
+ ["App CID", record.appCid],
507
+ ["Argv", JSON.stringify(record.argv)],
508
+ ["Started", runTime(record.startedAt, "start")],
509
+ ["Ended", runTime(record.endedAt, "end")],
510
+ ["Status", record.status],
511
+ [
512
+ "App exit",
513
+ record.appExitCode === null ? "unavailable" : String(record.appExitCode),
514
+ ],
515
+ ["Output CID", record.outputCid ?? "none"],
516
+ [
517
+ "Retention",
518
+ `${record.retention.state} (${record.retention.owned ? "record-owned" : "not record-owned"})`,
519
+ ],
520
+ [
521
+ "Error",
522
+ record.error
523
+ ? `${record.error.phase}/${record.error.code}: ${record.error.message}`
524
+ : "none",
525
+ ],
526
+ ];
527
+ if (record.retention.owner)
528
+ fields.push(["Retention owner", record.retention.owner]);
529
+ return fields.map(([key, value]) => `${key}: ${printable(value)}`).join("\n");
530
+ }
531
+
532
+ interface Parsed {
533
+ flags: GlobalOptions;
534
+ path: string;
535
+ positional: string[];
536
+ options: Record<string, string | boolean>;
537
+ template?: string[];
538
+ parameters?: string[];
539
+ help: boolean;
540
+ version: boolean;
541
+ }
542
+
543
+ async function closeStore(
544
+ store: IpfsStore | undefined,
545
+ appExitCode: number | undefined,
546
+ ): Promise<void> {
547
+ try {
548
+ await store?.close();
549
+ } catch (error) {
550
+ throw new HostError(
551
+ `Store cleanup failed: ${message(error)}`,
552
+ appExitCode || 1,
553
+ "CLEANUP_FAILED",
554
+ "cleanup",
555
+ );
556
+ }
557
+ }
558
+
559
+ export function parse(argv: readonly string[]): Parsed {
560
+ const tokens = [...argv];
561
+ const flags: GlobalOptions = { json: false };
562
+ while (tokens[0]?.startsWith("-")) {
563
+ const flag = tokens.shift()!;
564
+ if (flag === "-h" || flag === "--help")
565
+ return {
566
+ flags,
567
+ path: "",
568
+ positional: [],
569
+ options: {},
570
+ help: true,
571
+ version: false,
572
+ };
573
+ if (flag === "--version") {
574
+ if (tokens.length) syntax("--version does not accept a command.");
575
+ return {
576
+ flags,
577
+ path: "",
578
+ positional: [],
579
+ options: {},
580
+ help: false,
581
+ version: true,
582
+ };
583
+ }
584
+ if (flag === "--json") flags.json = true;
585
+ else if (flag === "--store-rpc")
586
+ syntax(
587
+ "Store RPC is no longer supported. Use --store-gateway with an HTTP gateway URL; existing Kubo pins are not migrated.",
588
+ );
589
+ else if (flag === "--state-dir" || flag === "--store-gateway") {
590
+ const value = tokens.shift();
591
+ if (!value || value.startsWith("-")) syntax(`${flag} needs a value.`);
592
+ if (flag === "--state-dir") flags.stateDir = value;
593
+ else {
594
+ flags.storeGateway = publicUrl(value);
595
+ }
596
+ } else syntax(`Unknown global option "${flag}".`);
597
+ }
598
+ const group = tokens.shift() ?? "";
599
+ const result: Parsed = {
600
+ flags,
601
+ path: group,
602
+ positional: [],
603
+ options: {},
604
+ help: !group,
605
+ version: false,
606
+ };
607
+ if (!group) return result;
608
+ if (group === "exec") {
609
+ if (flags.json) syntax("--json is not supported for exec/open.");
610
+ if (tokens[0] === "--log") {
611
+ result.options.log = true;
612
+ tokens.shift();
613
+ }
614
+ if (tokens[0] === "-h" || tokens[0] === "--help") {
615
+ result.help = true;
616
+ return result;
617
+ }
618
+ if (!tokens.length || tokens[0]!.startsWith("-"))
619
+ syntax(`Expected APP.\n${help("exec")}`);
620
+ result.positional = tokens;
621
+ return result;
622
+ }
623
+ if (!["open", "init", "build"].includes(group)) {
624
+ if (
625
+ !["bundle", "pin", "register", "config", "history", "store"].includes(
626
+ group,
627
+ )
628
+ )
629
+ syntax(`Unknown command "${group}".`);
630
+ if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
631
+ result.help = true;
632
+ return result;
633
+ }
634
+ result.path = `${group} ${tokens.shift()!}`;
635
+ } else if (group === "open" && flags.json)
636
+ syntax("--json is not supported for exec/open.");
637
+ if (!commands[result.path]) syntax(`Unknown command "${result.path}".`);
638
+ const separator = result.path === "register set" ? tokens.indexOf("--") : -1;
639
+ if (separator >= 0) result.template = tokens.splice(separator + 1);
640
+ if (separator >= 0) tokens.splice(separator);
641
+ if (tokens.includes("-h") || tokens.includes("--help")) {
642
+ result.help = true;
643
+ return result;
644
+ }
645
+ const booleans =
646
+ result.path === "bundle build"
647
+ ? ["replace", "schema-only", "no-import"]
648
+ : result.path === "build"
649
+ ? ["replace", "no-import", "with-source", "without-source"]
650
+ : result.path === "register set"
651
+ ? ["replace"]
652
+ : result.path === "history remove"
653
+ ? ["yes"]
654
+ : result.path === "open"
655
+ ? ["log"]
656
+ : [];
657
+ const values =
658
+ result.path === "init"
659
+ ? ["template"]
660
+ : result.path === "bundle build" || result.path === "build"
661
+ ? ["output"]
662
+ : result.path === "history list"
663
+ ? ["app", "status", "since", "until", "limit", "before"]
664
+ : result.path === "history remove"
665
+ ? ["app", "status", "since", "until"]
666
+ : result.path === "pin list"
667
+ ? ["type"]
668
+ : [];
669
+ while (tokens.length) {
670
+ const value = tokens.shift()!;
671
+ if (value.startsWith("--") || value === "-o") {
672
+ const option = value === "-o" ? "output" : value.slice(2);
673
+ if (result.path === "init" && option === "param") {
674
+ const input = tokens.shift();
675
+ if (!input || input.startsWith("--") || input.indexOf("=") < 1)
676
+ syntax("--param requires KEY=VALUE.");
677
+ (result.parameters ??= []).push(input);
678
+ continue;
679
+ }
680
+ if (Object.hasOwn(result.options, option))
681
+ syntax(`Duplicate option ${value}.`);
682
+ if (booleans.includes(option)) result.options[option] = true;
683
+ else if (values.includes(option)) {
684
+ const input = tokens.shift();
685
+ if (!input || input.startsWith("--")) syntax(`${value} needs a value.`);
686
+ result.options[option] = input;
687
+ } else syntax(`Unknown option "${value}".`);
688
+ } else result.positional.push(value);
689
+ }
690
+ const counts: Record<string, [number, number]> = {
691
+ init: [1, 2],
692
+ build: [0, 1],
693
+ "bundle build": [1, 1],
694
+ "bundle inspect": [1, 1],
695
+ "bundle import": [1, 1],
696
+ open: [1, 1],
697
+ "pin add": [2, 2],
698
+ "pin delete": [1, 1],
699
+ "pin list": [0, 0],
700
+ "pin show": [1, 1],
701
+ "pin rename": [2, 2],
702
+ "register list": [0, 0],
703
+ "register set": [2, 2],
704
+ "register remove": [1, 1],
705
+ "config get": [0, 1],
706
+ "config set": [2, 2],
707
+ "config reset": [1, 1],
708
+ "store usage": [0, 0],
709
+ "store gc": [0, 0],
710
+ "history list": [0, 0],
711
+ "history show": [1, 1],
712
+ "history remove": [0, Number.MAX_SAFE_INTEGER],
713
+ };
714
+ if (result.options["with-source"] && result.options["without-source"])
715
+ syntax("--with-source and --without-source are mutually exclusive.");
716
+ const [minimum, maximum] = counts[result.path]!;
717
+ if (result.positional.length < minimum || result.positional.length > maximum)
718
+ syntax(`Invalid arguments.\n${help(result.path)}`);
719
+ if (
720
+ result.template &&
721
+ (!result.template.length || !result.template.includes("%"))
722
+ )
723
+ syntax('Argument template must contain a whole "%" token.');
724
+ if (result.path === "history remove") {
725
+ const selected = values.some((value) =>
726
+ Object.hasOwn(result.options, value),
727
+ );
728
+ if (
729
+ (!selected && !result.positional.length) ||
730
+ (selected && result.positional.length)
731
+ )
732
+ syntax("history remove requires explicit IDs OR filters, not both.");
733
+ }
734
+ // Validate syntactic values before state access, let alone a backend connection.
735
+ if (result.path.startsWith("pin ") && result.path !== "pin list") {
736
+ pinName(result.positional[0]!, result.path === "pin show");
737
+ if (result.path === "pin add") exactCid(result.positional[1]!);
738
+ if (result.path === "pin rename") pinName(result.positional[1]!);
739
+ }
740
+ if (result.path.startsWith("config ") && result.positional[0]) {
741
+ if (
742
+ !(result.path === "config get" && result.positional[0] === "state-dir") &&
743
+ !(result.path === "config reset" && result.positional[0] === "store.rpc")
744
+ )
745
+ configKey(result.positional[0]);
746
+ if (result.path === "config set")
747
+ parseValue(configKey(result.positional[0]), result.positional[1], true);
748
+ }
749
+ if (typeof result.options.limit === "string")
750
+ parseValue("history.limit", result.options.limit, true);
751
+ if (result.options.output === "-")
752
+ syntax("CAR output requires a file path; binary stdout is not supported.");
753
+ return result;
754
+ }
755
+
756
+ async function performCli(
757
+ argv: readonly string[],
758
+ io: IO,
759
+ env: NodeJS.ProcessEnv,
760
+ ): Promise<number> {
761
+ let state: State | undefined;
762
+ let store: IpfsStore | undefined;
763
+ let appExitCode: number | undefined;
764
+ try {
765
+ const parsed = parse(argv);
766
+ if (parsed.help) {
767
+ io.out(help(parsed.path));
768
+ return 0;
769
+ }
770
+ if (parsed.version) {
771
+ const pkg = object(
772
+ JSON.parse(
773
+ await readFile(new URL("../package.json", import.meta.url), "utf8"),
774
+ ) as unknown,
775
+ "CLI package",
776
+ );
777
+ if (typeof pkg.version !== "string" || !pkg.version.trim())
778
+ throw new HostError("CLI package is missing its version.");
779
+ io.out(pkg.version);
780
+ return 0;
781
+ }
782
+ if (parsed.path === "history remove" && !parsed.options.yes && !io.tty)
783
+ syntax("Non-interactive history remove requires --yes.");
784
+ const builtins = await builtinContent();
785
+ state = new State(stateLocation(parsed.flags, env).path, builtins.pins);
786
+ if (
787
+ parsed.path === "config reset" &&
788
+ parsed.positional[0] === "store.rpc"
789
+ ) {
790
+ state.resetConfig("store.rpc");
791
+ io.out(
792
+ parsed.flags.json
793
+ ? JSON.stringify({ reset: ["store.rpc"] })
794
+ : "Removed legacy store.rpc configuration. Existing Kubo pins and content are unchanged.",
795
+ );
796
+ return 0;
797
+ }
798
+ const items = effectiveConfig(state.config(), parsed.flags, env);
799
+ const value = (key: string) =>
800
+ items.find((item) => item.key === key)!.value;
801
+ const emit = (result: unknown, human: string) => {
802
+ io.out(parsed.flags.json ? JSON.stringify(result) : human);
803
+ };
804
+ const [first, second] = parsed.positional;
805
+ const filter = parsed.path.startsWith("history ")
806
+ ? filters(state, parsed.options)
807
+ : {};
808
+ switch (parsed.path) {
809
+ case "store usage":
810
+ case "store gc": {
811
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
812
+ if (parsed.path === "store usage") {
813
+ const result = await store.usage();
814
+ emit(
815
+ result,
816
+ `Cached blocks: ${storageBytes(result.cachedBytes)}\nPinned blocks (deduplicated): ${storageBytes(result.pinnedBytes)}`,
817
+ );
818
+ } else {
819
+ const result = await store.gc();
820
+ emit(
821
+ result,
822
+ `Removed ${result.removedBlocks} blocks; reclaimed ${storageBytes(result.reclaimedBytes)}.`,
823
+ );
824
+ }
825
+ break;
826
+ }
827
+ case "init":
828
+ case "build":
829
+ case "bundle build":
830
+ case "bundle inspect":
831
+ case "bundle import": {
832
+ const controller = new AbortController();
833
+ let cancelled = 0;
834
+ const interrupt = () => {
835
+ cancelled = 130;
836
+ controller.abort(new Error("Interrupted."));
837
+ };
838
+ const terminate = () => {
839
+ cancelled = 143;
840
+ controller.abort(new Error("Terminated."));
841
+ };
842
+ process.once("SIGINT", interrupt);
843
+ process.once("SIGTERM", terminate);
844
+ try {
845
+ let pendingStore: Promise<IpfsStore> | undefined;
846
+ const getStore = () => {
847
+ pendingStore ??= storeConfiguration(value("store.gateway")).then(
848
+ (configuration) => {
849
+ store = new IpfsStore(configuration);
850
+ return store;
851
+ },
852
+ );
853
+ return pendingStore;
854
+ };
855
+ const request = {
856
+ signal: controller.signal,
857
+ diagnostic: (text: string) => {
858
+ io.err(text);
859
+ },
860
+ resolveCid: async (cid: CID, options: { signal?: AbortSignal }) => {
861
+ options.signal?.throwIfAborted();
862
+ const builtin = builtins.blocks.get(cid.toV1().toString());
863
+ if (builtin) return builtin.slice();
864
+ return (await getStore()).block.get(cid.toString(), options);
865
+ },
866
+ };
867
+ const builtinSource = first ? state.pin(first) : undefined;
868
+ const source =
869
+ builtinSource?.builtin && builtinSource.metadata?.kind === "bundle"
870
+ ? builtinSource.cid
871
+ : first;
872
+ if (parsed.path === "bundle build" || parsed.path === "build")
873
+ io.err(
874
+ parsed.path === "build"
875
+ ? "Typechecking, bundling and building App..."
876
+ : "Validating and building bundle...",
877
+ );
878
+ if (parsed.path === "bundle import")
879
+ io.err("Validating and importing CAR into Store...");
880
+ const result =
881
+ parsed.path === "init"
882
+ ? await initApp(first!, second, {
883
+ ...request,
884
+ ...(typeof parsed.options.template === "string"
885
+ ? {
886
+ template: state.pin(parsed.options.template)?.builtin
887
+ ? parsed.options.template
888
+ : state.pin(parsed.options.template)
889
+ ? state.resolve(parsed.options.template)
890
+ : parsed.options.template,
891
+ }
892
+ : {}),
893
+ ...(parsed.parameters
894
+ ? { parameters: parsed.parameters }
895
+ : {}),
896
+ })
897
+ : parsed.path === "build"
898
+ ? await buildApp(first, {
899
+ ...request,
900
+ replace: Boolean(parsed.options.replace),
901
+ ...(parsed.options["with-source"]
902
+ ? { includeSource: true }
903
+ : parsed.options["without-source"]
904
+ ? { includeSource: false }
905
+ : {}),
906
+ ...(typeof parsed.options.output === "string"
907
+ ? { output: parsed.options.output }
908
+ : {}),
909
+ outputDir: String(value("bundle.outputDir")),
910
+ })
911
+ : parsed.path === "bundle build"
912
+ ? await buildBundle(source!, {
913
+ ...request,
914
+ schemaOnly: Boolean(parsed.options["schema-only"]),
915
+ replace: Boolean(parsed.options.replace),
916
+ ...(typeof parsed.options.output === "string"
917
+ ? { output: parsed.options.output }
918
+ : {}),
919
+ outputDir: String(value("bundle.outputDir")),
920
+ })
921
+ : parsed.path === "bundle import"
922
+ ? await importBundle(first!, getStore, request)
923
+ : await inspectBundle(source!, request);
924
+ const importing = "output" in result && !parsed.options["no-import"];
925
+ if (importing) {
926
+ io.err("Importing build result into Store (without pinning)...");
927
+ try {
928
+ await importBundle(result.output, getStore, request);
929
+ } catch (cause) {
930
+ throw new HostError(
931
+ `${message(cause)} CAR remains at ${JSON.stringify(result.output)}; retry with ipab bundle import ${JSON.stringify(result.output)}, or build with --no-import.`,
932
+ 1,
933
+ "IMPORT_FAILED",
934
+ "authoring",
935
+ );
936
+ }
937
+ }
938
+ const closing = store;
939
+ store = undefined;
940
+ await closeStore(closing, undefined);
941
+ state.close();
942
+ state = undefined;
943
+ controller.signal.throwIfAborted();
944
+ if ("output" in result)
945
+ emit(
946
+ { ...result, imported: importing },
947
+ `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${result.validation !== undefined ? `\nEntry validation: ${result.validation?.status ?? "not-applicable"}` : ""}${"source" in result ? `\nSource CID: ${result.source.cid}\nSource CAR: ${result.source.output} (not imported or pinned)` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`,
948
+ );
949
+ else if (result.kind === "bundle-import")
950
+ emit(
951
+ result,
952
+ `Imported CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nBlocks: ${result.blocks}\nCAR: ${result.source}\nEntry validation: ${result.validation?.status ?? "not-applicable"}`,
953
+ );
954
+ else if (result.kind === "project-init") {
955
+ emit(
956
+ result,
957
+ `Created project: ${result.directory}${result.templateCid ? `\nTemplate CID: ${result.templateCid}` : ""}`,
958
+ );
959
+ if (
960
+ result.files.includes("package.json") &&
961
+ (result.files.includes("ipab.yaml") ||
962
+ result.files.includes("ipab.json"))
963
+ )
964
+ io.err(
965
+ `Next: install declared dependencies in ${JSON.stringify(result.directory)}; then ipab build ${JSON.stringify(result.directory)} (requires locally linked ipab).`,
966
+ );
967
+ else if (result.files.includes(".bundle.yaml"))
968
+ io.err(
969
+ `Next: ipab bundle build ${JSON.stringify(result.directory)}`,
970
+ );
971
+ } else
972
+ emit(
973
+ result,
974
+ `Kind: ${result.kind}\nName: ${printable(result.name)}\nSchema CID: ${result.schemaCid}\nEntry: ${result.entry.path} (${result.entry.contentType})\nDefinition validation: passed\nStorage verification: ${result.validation.storage}\nEntry validation: ${result.validation.entry?.status ?? "not-applicable"}`,
975
+ );
976
+ } catch (cause) {
977
+ if (cancelled)
978
+ throw new HostError(
979
+ message(cause),
980
+ cancelled,
981
+ "ABORTED",
982
+ "authoring",
983
+ );
984
+ throw cause;
985
+ } finally {
986
+ process.removeListener("SIGINT", interrupt);
987
+ process.removeListener("SIGTERM", terminate);
988
+ }
989
+ break;
990
+ }
991
+ case "pin list": {
992
+ const type =
993
+ typeof parsed.options.type === "string"
994
+ ? state.resolve(parsed.options.type, true)
995
+ : undefined;
996
+ const pins = state.pins();
997
+ const listed = pins
998
+ .filter(
999
+ (pin) => pin.status === "ready" && pin.metadata?.kind === "bundle",
1000
+ )
1001
+ .map(pinDetails)
1002
+ .filter((pin) => type === undefined || pin.schemaCid === type);
1003
+ const invalid = pins
1004
+ .filter(
1005
+ (pin) => pin.status === "ready" && pin.metadata?.kind !== "bundle",
1006
+ )
1007
+ .map(({ name, cid, metadata }) => ({
1008
+ name,
1009
+ cid,
1010
+ kind: metadata?.kind,
1011
+ reason:
1012
+ "Not a Bundle pin; retention is preserved. Use pin delete to release it.",
1013
+ }));
1014
+ const pending = pins
1015
+ .filter((pin) => pin.status !== "ready")
1016
+ .map(({ name, cid, status }) => ({ name, cid, status }));
1017
+ if (pending.length)
1018
+ io.err(
1019
+ `Unfinished pin operations (not usable pins): ${JSON.stringify(pending)}. Retry pin add/delete.`,
1020
+ );
1021
+ if (invalid.length)
1022
+ io.err(
1023
+ `Legacy non-Bundle pins (not usable pins): ${JSON.stringify(invalid)}. Retention is unchanged; delete explicitly and wrap content in a Bundle before pinning again.`,
1024
+ );
1025
+ emit(
1026
+ { items: listed, pending, invalid },
1027
+ table(
1028
+ ["NAME", "CID", "KIND", "BUNDLE TYPE", "SOURCE"],
1029
+ listed.map((pin) => [
1030
+ pin.name,
1031
+ pin.cid,
1032
+ pin.kind,
1033
+ pin.typeName,
1034
+ pin.builtin ? "built-in (read-only)" : "user",
1035
+ ]),
1036
+ "No named pins.",
1037
+ ),
1038
+ );
1039
+ break;
1040
+ }
1041
+ case "pin add": {
1042
+ io.err("Fetching, verifying and retaining content in Store...");
1043
+ const result = await addPin(
1044
+ state,
1045
+ first!,
1046
+ second!,
1047
+ await storeConfiguration(value("store.gateway")),
1048
+ );
1049
+ emit(
1050
+ result,
1051
+ `${result.name} → ${result.cid}\nBundle type: ${printable(result.typeName)}`,
1052
+ );
1053
+ break;
1054
+ }
1055
+ case "pin delete": {
1056
+ const result = await deletePin(state, first!);
1057
+ emit(
1058
+ result,
1059
+ `Deleted ${first}; released only its retention responsibility. No blocks deleted or GC requested.`,
1060
+ );
1061
+ break;
1062
+ }
1063
+ case "pin show": {
1064
+ const pin = state.pin(first!);
1065
+ if (!pin)
1066
+ throw new HostError(
1067
+ `Pin "${first}" does not exist. Run ipab pin list.`,
1068
+ );
1069
+ const result = pinDetails(pin);
1070
+ emit(
1071
+ result,
1072
+ `Name: ${printable(result.name)}\nCID: ${result.cid}\nBundle type: ${printable(result.typeName)}\nSchema CID: ${result.schemaCid}\nSource: ${result.builtin ? "built-in (read-only; content bundled with IPAB)" : "local registration (not live node verification)"}`,
1073
+ );
1074
+ break;
1075
+ }
1076
+ case "pin rename": {
1077
+ const result = renamePin(state, first!, second!);
1078
+ emit(result, `${first} → ${result.name} (${result.cid})`);
1079
+ break;
1080
+ }
1081
+ case "register list": {
1082
+ const associations = state.registrations();
1083
+ emit(
1084
+ { items: associations },
1085
+ table(
1086
+ ["SCHEMA CID", "APP CID", "ARGV"],
1087
+ associations.map((association) => [
1088
+ association.schemaCid,
1089
+ association.appCid,
1090
+ JSON.stringify(association.argv),
1091
+ ]),
1092
+ "No associations.",
1093
+ ),
1094
+ );
1095
+ break;
1096
+ }
1097
+ case "register set": {
1098
+ const association = state.setAssociation(
1099
+ schemaAlias(first!),
1100
+ second!,
1101
+ parsed.template ?? ["%"],
1102
+ Boolean(parsed.options.replace),
1103
+ );
1104
+ emit(
1105
+ association,
1106
+ `${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`,
1107
+ );
1108
+ break;
1109
+ }
1110
+ case "register remove": {
1111
+ const removed = state.removeAssociation(schemaAlias(first!));
1112
+ emit({ removed: [removed] }, `Removed association for ${removed}.`);
1113
+ break;
1114
+ }
1115
+ case "config get": {
1116
+ const selected = first
1117
+ ? items.filter((item) => item.key === first)
1118
+ : items;
1119
+ emit(
1120
+ { items: selected },
1121
+ table(
1122
+ ["KEY", "VALUE", "SOURCE"],
1123
+ selected.map((item) => [item.key, String(item.value), item.source]),
1124
+ "No configuration values.",
1125
+ ),
1126
+ );
1127
+ break;
1128
+ }
1129
+ case "config set": {
1130
+ const key = configKey(first!);
1131
+ const saved = parseValue(key, second, true);
1132
+ state.setConfig(key, saved);
1133
+ const source = items.find((item) => item.key === key)!.source;
1134
+ if (source === "env" || source === "flag")
1135
+ io.err(`Warning: saved user value is masked by ${source}.`);
1136
+ emit(
1137
+ { key, value: saved, source: "user" },
1138
+ `Saved ${key} = ${printable(String(saved))} (user).`,
1139
+ );
1140
+ break;
1141
+ }
1142
+ case "config reset":
1143
+ state.resetConfig(configKey(first!));
1144
+ emit({ reset: [first] }, `Reset user override: ${first}.`);
1145
+ break;
1146
+ case "history list": {
1147
+ const page = listHistory(
1148
+ state,
1149
+ filter,
1150
+ Number(parsed.options.limit ?? value("history.limit")),
1151
+ typeof parsed.options.before === "string"
1152
+ ? state.resolveRunId(parsed.options.before)
1153
+ : undefined,
1154
+ );
1155
+ if (parsed.flags.json) {
1156
+ emit(page, "");
1157
+ break;
1158
+ }
1159
+ const names = new Map<string, string>();
1160
+ for (const pin of state.pins())
1161
+ if (pin.status === "ready" && !names.has(pin.cid))
1162
+ names.set(pin.cid, pin.name);
1163
+ const reference = (cid: string | null): string =>
1164
+ cid === null
1165
+ ? "none"
1166
+ : cid + (names.has(cid) ? ` (${names.get(cid)!})` : "");
1167
+ const shortId = state.shortRunId.bind(state);
1168
+ const rows = page.items.length
1169
+ ? page.items
1170
+ .map((record) =>
1171
+ [
1172
+ `run ${record.id}`,
1173
+ ` Status: ${record.status}`,
1174
+ ` Started: ${runTime(record.startedAt, "start")}`,
1175
+ ` Ended: ${runTime(record.endedAt, "end")}`,
1176
+ ` Duration: ${runDuration(record)}`,
1177
+ ` App: ${reference(record.appCid)}`,
1178
+ ` Output: ${reference(record.outputCid)}`,
1179
+ ` Argv: ${record.argv.join(" ")}`,
1180
+ ]
1181
+ .map(printable)
1182
+ .join("\n"),
1183
+ )
1184
+ .join("\n\n")
1185
+ : "No ended executions.";
1186
+ emit(
1187
+ page,
1188
+ rows +
1189
+ (page.nextBefore
1190
+ ? `\nMore matches; use --before ${shortId(page.nextBefore)} with the same filters.`
1191
+ : ""),
1192
+ );
1193
+ break;
1194
+ }
1195
+ case "history show": {
1196
+ const record = state.run(state.resolveRunId(first!));
1197
+ const logs = record.log
1198
+ ? await logFiles(state.directory, record.id)
1199
+ : undefined;
1200
+ emit(
1201
+ logs ? { ...record, logs } : record,
1202
+ runDetails(record) +
1203
+ (logs
1204
+ ? `\nLog recording: ${record.log!}\nStdout log: ${printable(logs.stdout ?? "unavailable")}\nStderr log: ${printable(logs.stderr ?? "unavailable")}`
1205
+ : "\nLog recording: disabled"),
1206
+ );
1207
+ break;
1208
+ }
1209
+ case "history remove": {
1210
+ const ids = parsed.positional.length
1211
+ ? [...new Set(parsed.positional.map(state.resolveRunId.bind(state)))]
1212
+ : selectedIds(state, filter);
1213
+ for (const id of ids) state.run(id);
1214
+ if (
1215
+ ids.length &&
1216
+ !parsed.options.yes &&
1217
+ !(await io.confirm(
1218
+ `Remove ${ids.length} ended records selected by ${JSON.stringify(
1219
+ parsed.positional.length ? { ids } : parsed.options,
1220
+ )}? Release only their retention; no GC or disk reclamation is guaranteed.`,
1221
+ ))
1222
+ )
1223
+ throw new HostError("History removal cancelled.");
1224
+ const result = await removeHistory(state, ids);
1225
+ emit(
1226
+ result,
1227
+ `Removed ${result.removed.length} records; garbage collection is not guaranteed.`,
1228
+ );
1229
+ break;
1230
+ }
1231
+ case "exec":
1232
+ case "open": {
1233
+ if (parsed.options.log && !value("history.enabled"))
1234
+ throw new HostError(
1235
+ "Execution logging requires history.enabled=true.",
1236
+ );
1237
+ const target = state.resolve(first!);
1238
+ await recoverInactive(state);
1239
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1240
+ let appCid: string;
1241
+ let appArgv: string[];
1242
+ if (parsed.path === "open") {
1243
+ const root = target;
1244
+ const owner = await Ownership.create(
1245
+ state,
1246
+ store,
1247
+ `open:${randomUUID()}`,
1248
+ null,
1249
+ );
1250
+ try {
1251
+ const content = await validatedBundle(root, store, owner);
1252
+ const schema = content.schemaKey;
1253
+ const association = state.association(schema);
1254
+ if (!association)
1255
+ throw new HostError(
1256
+ `No App registered for Schema ${schema}. Use ipab register set or ipab exec.`,
1257
+ );
1258
+ appCid = association.appCid;
1259
+ appArgv = association.argv.map((argument) =>
1260
+ argument === "%" ? root : argument,
1261
+ );
1262
+ // execute owns the App/input context before this validation owner's eventual release.
1263
+ const result = await execute(
1264
+ state,
1265
+ store,
1266
+ { origin: "open", appCid, argv: appArgv },
1267
+ {
1268
+ inputSchema: schema,
1269
+ history: Boolean(value("history.enabled")),
1270
+ retain: value("output.retention") === "history",
1271
+ log: Boolean(parsed.options.log),
1272
+ diagnostic: (text) => {
1273
+ io.err(text);
1274
+ },
1275
+ },
1276
+ );
1277
+ appExitCode = result.exitCode;
1278
+ return appExitCode;
1279
+ } finally {
1280
+ await owner.release();
1281
+ }
1282
+ } else {
1283
+ appCid = target;
1284
+ appArgv = parsed.positional.slice(1);
1285
+ }
1286
+ appExitCode = (
1287
+ await execute(
1288
+ state,
1289
+ store,
1290
+ { origin: "exec", appCid, argv: appArgv },
1291
+ {
1292
+ history: Boolean(value("history.enabled")),
1293
+ retain: value("output.retention") === "history",
1294
+ log: Boolean(parsed.options.log),
1295
+ diagnostic: (text) => {
1296
+ io.err(text);
1297
+ },
1298
+ },
1299
+ )
1300
+ ).exitCode;
1301
+ return appExitCode;
1302
+ }
1303
+ default:
1304
+ syntax("Unknown command.");
1305
+ }
1306
+ return 0;
1307
+ } catch (error) {
1308
+ io.err(`Error: ${message(error)}`);
1309
+ return error instanceof HostError ? error.exitCode : 1;
1310
+ } finally {
1311
+ try {
1312
+ await closeStore(store, appExitCode);
1313
+ } finally {
1314
+ state?.close();
1315
+ }
1316
+ }
1317
+ }
1318
+
1319
+ export async function runCli(
1320
+ argv: readonly string[],
1321
+ io: IO = processIO,
1322
+ env: NodeJS.ProcessEnv = process.env,
1323
+ ): Promise<number> {
1324
+ try {
1325
+ return await performCli(argv, io, env);
1326
+ } catch (error) {
1327
+ io.err(`Error: ${message(error)}`);
1328
+ return error instanceof HostError ? error.exitCode : 1;
1329
+ }
1330
+ }