@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
@@ -0,0 +1,2411 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, rmdir, unlink, writeFile } from "node:fs/promises";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
+ import { CID } from "multiformats/cid";
5
+ import { ContentBundleError, openBundle } from "@ipab/bundle";
6
+ import { ScopeApiError } from "@ipab/bundle/pointer/scope";
7
+ import { ContentError, IpfsStore, } from "@ipab/ipfs-store";
8
+ import { assembleBundle } from "./assembly.js";
9
+ import { initApp } from "./app-authoring.js";
10
+ import { buildBundle, importBundle, inspectBundle, nodeError, resolveLocalBundleInput, snapshotLocalBundle, } from "./authoring.js";
11
+ import { builtinContent } from "./builtins.js";
12
+ import { configKey, effectiveConfig, isLocalSwarm, LOCAL_SWARM_ALIAS, LOCAL_SWARM_URL, parseValue, storeConfiguration, visibleConfig, } from "./config.js";
13
+ import { DaemonTelemetry } from "./daemon-telemetry.js";
14
+ import { decodeIpcValue, encodeIpcValue, } from "./daemon-protocol.js";
15
+ export { decodeIpcValue, encodeIpcValue, };
16
+ import { HostError, message, object, syntax } from "./errors.js";
17
+ import { getBundle } from "./get.js";
18
+ import { filters, listHistory, Ownership, recoverInactive, removeHistory, saveHistory, selectedIds, } from "./history.js";
19
+ import { ContextHandler } from "./ipc.js";
20
+ import { logFiles } from "./logs.js";
21
+ import { parseNameReference, templateName } from "./name-reference.js";
22
+ import { pinDetails, unpin } from "./pins.js";
23
+ import { publicationSource } from "./publish-source.js";
24
+ import { listSwarmFsPath, removeSwarmFsPath, setSwarmFsPath, statSwarmFsPath, } from "./swarm-fs.js";
25
+ import { accountProfile, approveMembership, artifactValue, createSwarm, exportRequest, grantPivotAuthority, inspectSwarmStatus, pinNameSubscription, pinReference, publish, removeMember, removeSwarmAssociation, removeSwarmSkill, removeSwarmTemplate, replicateSwarm, requestMembership, resolveReference, resolveTemplateSelector, resumeRemoval, searchNames, setSwarmAssociation, setSwarmSkill, setSwarmTemplate, swarmAssociation, swarmHeader, swarmMembers, swarmMeta, swarmRegistrations, swarmTemplates, swarmTypeSkill, swarmTypeSkills, updateAccountProfile, updateProfile, updateSwarm, } from "./swarm.js";
26
+ import { loadApp, OutputSpace, validatedBundle } from "./space.js";
27
+ import { createAssociation, exactCid, State } from "./state.js";
28
+ import { manageSkills, syncDaemonSkills } from "./skills.js";
29
+ import { inspectTemplate } from "./templates.js";
30
+ import { templateOutputTree } from "./template-presentation.js";
31
+ import { appSchemaCid, schemaAlias } from "./app-definition.js";
32
+ export class KeyedMutex {
33
+ queues = new Map();
34
+ async run(key, action) {
35
+ const previous = this.queues.get(key) ?? Promise.resolve();
36
+ let release;
37
+ const current = new Promise((resolveRelease) => {
38
+ release = resolveRelease;
39
+ });
40
+ const tail = previous.then(() => current);
41
+ this.queues.set(key, tail);
42
+ await previous;
43
+ try {
44
+ return await action();
45
+ }
46
+ finally {
47
+ release();
48
+ if (this.queues.get(key) === tail) {
49
+ this.queues.delete(key);
50
+ }
51
+ }
52
+ }
53
+ }
54
+ const MAX_JSON_BODY_BYTES = 16 * 1024 * 1024;
55
+ function normalizeStoreConfig(configuration) {
56
+ return JSON.stringify({
57
+ backend: configuration.backend,
58
+ dataDir: configuration.dataDir,
59
+ ...(configuration.coordinationDir !== undefined
60
+ ? { coordinationDir: configuration.coordinationDir }
61
+ : {}),
62
+ ...(configuration.gateway !== undefined
63
+ ? { gateway: configuration.gateway }
64
+ : {}),
65
+ ...(configuration.limits !== undefined
66
+ ? { limits: configuration.limits }
67
+ : {}),
68
+ });
69
+ }
70
+ function storeFactoryFor(shared) {
71
+ const sharedConfig = normalizeStoreConfig(shared.configuration);
72
+ return (configuration) => {
73
+ if (normalizeStoreConfig(configuration) === sharedConfig) {
74
+ return shared.scope();
75
+ }
76
+ return new IpfsStore(configuration);
77
+ };
78
+ }
79
+ function requireSwarmParam(body) {
80
+ const value = body.swarm;
81
+ if (typeof value !== "string" || !value.trim()) {
82
+ syntax("Explicit swarm parameter is required; daemon has no implicit current swarm.");
83
+ }
84
+ return value.trim();
85
+ }
86
+ function defined(entries) {
87
+ const out = {};
88
+ for (const [k, v] of Object.entries(entries)) {
89
+ if (v !== undefined)
90
+ out[k] = v;
91
+ }
92
+ return out;
93
+ }
94
+ function optionalString(body, key) {
95
+ const value = body[key];
96
+ if (value === undefined || value === null)
97
+ return undefined;
98
+ if (typeof value !== "string") {
99
+ syntax(`Field "${key}" must be a string.`);
100
+ }
101
+ return value;
102
+ }
103
+ function requireString(body, key) {
104
+ const value = body[key];
105
+ if (typeof value !== "string" || !value.length) {
106
+ syntax(`Field "${key}" must be a non-empty string.`);
107
+ }
108
+ return value;
109
+ }
110
+ function optionalBoolean(body, key) {
111
+ const value = body[key];
112
+ if (value === undefined)
113
+ return undefined;
114
+ if (typeof value !== "boolean") {
115
+ syntax(`Field "${key}" must be a boolean.`);
116
+ }
117
+ return value;
118
+ }
119
+ function optionalNumber(body, key) {
120
+ const value = body[key];
121
+ if (value === undefined)
122
+ return undefined;
123
+ if (typeof value !== "number" || !Number.isFinite(value)) {
124
+ syntax(`Field "${key}" must be a finite number.`);
125
+ }
126
+ return value;
127
+ }
128
+ function optionalStringArray(body, key) {
129
+ const value = body[key];
130
+ if (value === undefined)
131
+ return undefined;
132
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
133
+ syntax(`Field "${key}" must be an array of strings.`);
134
+ }
135
+ return value;
136
+ }
137
+ function decodePathSegment(raw) {
138
+ try {
139
+ return decodeURIComponent(raw);
140
+ }
141
+ catch {
142
+ syntax("Invalid URL-encoded path segment.");
143
+ }
144
+ }
145
+ async function readJsonBody(request, maxBytes = MAX_JSON_BODY_BYTES) {
146
+ const chunks = [];
147
+ let total = 0;
148
+ for await (const chunk of request) {
149
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
150
+ total += buf.byteLength;
151
+ if (total > maxBytes) {
152
+ throw new HostError("Request body exceeds maximum allowed size.", 2, "PAYLOAD_TOO_LARGE", "daemon");
153
+ }
154
+ chunks.push(buf);
155
+ }
156
+ if (total === 0)
157
+ return {};
158
+ let parsed;
159
+ try {
160
+ parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
161
+ }
162
+ catch {
163
+ syntax("Request body must be valid JSON.");
164
+ }
165
+ return object(parsed, "request body");
166
+ }
167
+ function errorToPayload(cause) {
168
+ if (cause instanceof HostError) {
169
+ const status = cause.exitCode === 2 || cause.code === "SYNTAX"
170
+ ? 400
171
+ : cause.code === "NOT_FOUND"
172
+ ? 404
173
+ : cause.code === "CAS_CONFLICT" || cause.code === "CONFLICT"
174
+ ? 409
175
+ : 400;
176
+ return {
177
+ status,
178
+ payload: {
179
+ code: cause.code,
180
+ message: cause.message,
181
+ exitCode: cause.exitCode,
182
+ phase: cause.phase,
183
+ },
184
+ };
185
+ }
186
+ if (cause instanceof ScopeApiError) {
187
+ const status = cause.status === 412 ? 409 : cause.status >= 400 ? cause.status : 500;
188
+ return {
189
+ status,
190
+ payload: {
191
+ code: cause.status === 412 ? "CAS_CONFLICT" : "SCOPE_API_ERROR",
192
+ message: message(cause),
193
+ exitCode: 1,
194
+ phase: "swarm",
195
+ },
196
+ };
197
+ }
198
+ if (cause instanceof Error && cause.name === "AbortError") {
199
+ return {
200
+ status: 499,
201
+ payload: {
202
+ code: "CANCELLED",
203
+ message: message(cause),
204
+ exitCode: 130,
205
+ phase: "daemon",
206
+ },
207
+ };
208
+ }
209
+ return {
210
+ status: 500,
211
+ payload: {
212
+ code: "INTERNAL_ERROR",
213
+ message: message(cause),
214
+ exitCode: 1,
215
+ phase: "daemon",
216
+ },
217
+ };
218
+ }
219
+ export class DaemonService {
220
+ stateDir;
221
+ env;
222
+ state;
223
+ telemetry;
224
+ mutex;
225
+ builtins;
226
+ sharedStore;
227
+ storeInit;
228
+ ownsState;
229
+ ownsStore;
230
+ customFetch;
231
+ diagnostic;
232
+ ensureDaemonFn;
233
+ onSwarmChange;
234
+ activeRuns = new Map();
235
+ activeRequests = new Map();
236
+ constructor(stateDir, env, state, ownsState, store, ownsStore, telemetry, mutex, builtins, customFetch, diagnostic, ensureDaemonFn, onSwarmChange) {
237
+ this.stateDir = stateDir;
238
+ this.env = env;
239
+ this.state = state;
240
+ this.ownsState = ownsState;
241
+ this.sharedStore = store;
242
+ this.ownsStore = ownsStore;
243
+ this.telemetry = telemetry;
244
+ this.mutex = mutex;
245
+ this.builtins = builtins;
246
+ this.customFetch = customFetch;
247
+ this.diagnostic = diagnostic;
248
+ this.ensureDaemonFn = ensureDaemonFn;
249
+ this.onSwarmChange = onSwarmChange;
250
+ }
251
+ static async create(options) {
252
+ const stateDir = resolve(options.stateDir);
253
+ const env = options.env ?? process.env;
254
+ const telemetry = options.telemetry ??
255
+ new DaemonTelemetry({
256
+ env,
257
+ logPath: join(stateDir, "swarm-daemon", "telemetry.log"),
258
+ });
259
+ const ownsState = !options.state;
260
+ const builtins = await builtinContent();
261
+ const state = options.state ??
262
+ new State(stateDir, builtins.pins, env, (db) => telemetry.wrapDatabase(db, "state"));
263
+ const ownsStore = !options.store;
264
+ return new DaemonService(stateDir, env, state, ownsState, options.store, ownsStore, telemetry, options.inProcessMutex ?? new KeyedMutex(), builtins, options.fetch, options.diagnostic, options.ensureDaemon, options.onSwarmChange);
265
+ }
266
+ async getStore() {
267
+ if (this.sharedStore)
268
+ return this.sharedStore;
269
+ if (!this.storeInit) {
270
+ this.storeInit = (async () => {
271
+ const items = effectiveConfig(this.state.config({ includeSecrets: false }), { json: false, stateDir: this.stateDir }, this.env);
272
+ const gateway = items.find((item) => item.key === "store.gateway")?.value;
273
+ const baseConfig = await storeConfiguration(gateway ?? null);
274
+ const created = new IpfsStore({
275
+ ...baseConfig,
276
+ singleProcessCoordination: true,
277
+ onCoordinationEvent: (event) => {
278
+ this.telemetry.recordCoordination(event);
279
+ },
280
+ onSqlEvent: (event) => {
281
+ this.telemetry.recordSql(event);
282
+ },
283
+ });
284
+ this.sharedStore = created;
285
+ return created;
286
+ })().catch((cause) => {
287
+ this.storeInit = undefined;
288
+ throw cause;
289
+ });
290
+ }
291
+ return this.storeInit;
292
+ }
293
+ abortActiveRequests(reason) {
294
+ const error = reason ?? new HostError("Request cancelled.", 130, "CANCELLED", "daemon");
295
+ for (const controller of this.activeRequests.keys()) {
296
+ if (!controller.signal.aborted) {
297
+ controller.abort(error);
298
+ }
299
+ }
300
+ }
301
+ hasActiveRuns() {
302
+ return this.activeRuns.size > 0;
303
+ }
304
+ async close() {
305
+ this.abortActiveRequests(new HostError("Daemon shutting down.", 143, "CANCELLED", "daemon"));
306
+ if (this.activeRequests.size > 0) {
307
+ await Promise.allSettled([...this.activeRequests.values()]);
308
+ }
309
+ for (const runId of [...this.activeRuns.keys()]) {
310
+ await this.cancelRunSession(runId, 143, "Daemon shutting down.").catch(() => { });
311
+ }
312
+ try {
313
+ if (this.ownsStore) {
314
+ const store = this.sharedStore ??
315
+ (this.storeInit
316
+ ? await this.storeInit.catch(() => undefined)
317
+ : undefined);
318
+ if (store) {
319
+ try {
320
+ await store.close();
321
+ }
322
+ catch (error) {
323
+ throw new HostError(`Store cleanup failed: ${message(error)}`, 1, "CLEANUP_FAILED", "cleanup");
324
+ }
325
+ }
326
+ }
327
+ }
328
+ finally {
329
+ try {
330
+ if (this.ownsState)
331
+ this.state.close();
332
+ }
333
+ finally {
334
+ await this.telemetry.flush();
335
+ }
336
+ }
337
+ }
338
+ effectiveItems(options = {}) {
339
+ return effectiveConfig(this.state.config({ includeSecrets: options.includeSecrets ?? true }), { json: false, stateDir: this.stateDir }, this.env);
340
+ }
341
+ configValue(key) {
342
+ return this.effectiveItems({ includeSecrets: false }).find((item) => item.key === key).value;
343
+ }
344
+ async createSwarmContext(diagnostic, options = {}) {
345
+ const includeSecrets = options.includeSecrets ?? true;
346
+ const items = this.effectiveItems({ includeSecrets });
347
+ const value = (key) => items.find((item) => item.key === key).value;
348
+ const pointerServiceValue = value("pointers.service");
349
+ const pointerApiKeyValue = includeSecrets ? value("pointers.apiKey") : null;
350
+ const pivotItem = items.find((item) => item.key === "swarm.pivot");
351
+ const store = await this.getStore();
352
+ return {
353
+ store: store.scope(),
354
+ state: this.state,
355
+ env: this.env,
356
+ stateDir: this.stateDir,
357
+ cacheTtl: Number(value("swarm.cacheTtl")),
358
+ syncInterval: Number(value("swarm.syncInterval")),
359
+ listen: value("swarm.listen") === "loopback" ? "loopback" : "lan",
360
+ ...(pivotItem.source === "default"
361
+ ? {}
362
+ : { pivot: Boolean(pivotItem.value) }),
363
+ forceRefresh: options.forceRefresh ?? Boolean(value("swarm.forceRefresh")),
364
+ diagnostic: (text) => {
365
+ diagnostic?.(text);
366
+ this.diagnostic?.(text);
367
+ },
368
+ ...(this.customFetch ? { fetch: this.customFetch } : {}),
369
+ ...(this.ensureDaemonFn ? { ensureDaemon: this.ensureDaemonFn } : {}),
370
+ ...(typeof pointerServiceValue === "string"
371
+ ? { pointerService: pointerServiceValue }
372
+ : {}),
373
+ ...(typeof pointerApiKeyValue === "string"
374
+ ? { pointerApiKey: pointerApiKeyValue }
375
+ : {}),
376
+ };
377
+ }
378
+ async finishSwarmContext(ctx) {
379
+ try {
380
+ await ctx.finishRead?.();
381
+ }
382
+ finally {
383
+ if (ctx.store !== this.sharedStore) {
384
+ await ctx.store.close();
385
+ }
386
+ }
387
+ }
388
+ async withSwarmContext(fn, diagnostic, options = {}) {
389
+ const ctx = await this.createSwarmContext(diagnostic, options);
390
+ try {
391
+ return await fn(ctx);
392
+ }
393
+ finally {
394
+ await this.finishSwarmContext(ctx);
395
+ }
396
+ }
397
+ async handleRequest(request, response) {
398
+ const method = (request.method ?? "GET").toUpperCase();
399
+ const parsedUrl = new URL(request.url ?? "/", "http://127.0.0.1");
400
+ const pathname = parsedUrl.pathname;
401
+ let route;
402
+ try {
403
+ route = this.matchRoute(method, pathname);
404
+ }
405
+ catch (cause) {
406
+ const { status, payload } = errorToPayload(cause);
407
+ response.writeHead(status, {
408
+ "content-type": "application/json; charset=utf-8",
409
+ "cache-control": "no-store",
410
+ "x-content-type-options": "nosniff",
411
+ });
412
+ response.end(JSON.stringify(payload));
413
+ return true;
414
+ }
415
+ if (!route)
416
+ return false;
417
+ const acceptsNdjson = (request.headers.accept ?? "")
418
+ .toLowerCase()
419
+ .includes("application/x-ndjson");
420
+ const controller = new AbortController();
421
+ response.on("close", () => {
422
+ if (!response.writableEnded && !controller.signal.aborted) {
423
+ controller.abort(new HostError("Client disconnected.", 130, "CANCELLED", "daemon"));
424
+ }
425
+ });
426
+ let finishRequest;
427
+ const done = new Promise((resolveDone) => {
428
+ finishRequest = resolveDone;
429
+ });
430
+ this.activeRequests.set(controller, done);
431
+ let body = {};
432
+ let ndjsonStarted = false;
433
+ const writeNdjson = (frame) => {
434
+ if (response.writableEnded)
435
+ return;
436
+ if (!ndjsonStarted) {
437
+ ndjsonStarted = true;
438
+ response.writeHead(200, {
439
+ "content-type": "application/x-ndjson; charset=utf-8",
440
+ "cache-control": "no-store",
441
+ "x-content-type-options": "nosniff",
442
+ });
443
+ }
444
+ response.write(`${JSON.stringify(frame)}\n`);
445
+ };
446
+ const emitDiagnostic = (text, progress) => {
447
+ if (acceptsNdjson) {
448
+ writeNdjson({
449
+ type: "diagnostic",
450
+ text,
451
+ ...(progress ? { progress: true } : {}),
452
+ });
453
+ }
454
+ };
455
+ try {
456
+ if (method === "POST" || method === "PUT" || method === "PATCH") {
457
+ body = await readJsonBody(request);
458
+ }
459
+ const swarmLabel = typeof body.swarm === "string" && body.swarm.trim()
460
+ ? body.swarm.trim()
461
+ : (route.swarmParam ?? null);
462
+ const data = await this.telemetry.runWithContext({
463
+ source: "cli",
464
+ operation: `${method} ${route.pattern}`,
465
+ swarm: swarmLabel,
466
+ }, () => route.handler({
467
+ method,
468
+ pathname,
469
+ searchParams: parsedUrl.searchParams,
470
+ params: route.params,
471
+ body,
472
+ signal: controller.signal,
473
+ diagnostic: emitDiagnostic,
474
+ }));
475
+ if (acceptsNdjson) {
476
+ writeNdjson({ type: "result", data });
477
+ response.end();
478
+ }
479
+ else if (!response.writableEnded) {
480
+ response.writeHead(200, {
481
+ "content-type": "application/json; charset=utf-8",
482
+ "cache-control": "no-store",
483
+ "x-content-type-options": "nosniff",
484
+ });
485
+ response.end(JSON.stringify(data));
486
+ }
487
+ }
488
+ catch (cause) {
489
+ const { status, payload } = errorToPayload(cause);
490
+ if (acceptsNdjson) {
491
+ writeNdjson({ type: "error", ...payload });
492
+ if (!response.writableEnded)
493
+ response.end();
494
+ }
495
+ else if (!response.headersSent) {
496
+ response.writeHead(status, {
497
+ "content-type": "application/json; charset=utf-8",
498
+ "cache-control": "no-store",
499
+ "x-content-type-options": "nosniff",
500
+ });
501
+ response.end(JSON.stringify(payload));
502
+ }
503
+ else if (!response.writableEnded) {
504
+ response.end();
505
+ }
506
+ }
507
+ finally {
508
+ this.activeRequests.delete(controller);
509
+ finishRequest();
510
+ }
511
+ return true;
512
+ }
513
+ matchRoute(method, pathname) {
514
+ // 1. /v1/store/*
515
+ if (method === "POST" && pathname === "/v1/store/inspect") {
516
+ return {
517
+ pattern: "/v1/store/inspect",
518
+ params: {},
519
+ handler: ({ body, signal, diagnostic }) => this.handleStoreInspect(body, signal, diagnostic),
520
+ };
521
+ }
522
+ if (method === "POST" && pathname === "/v1/store/import") {
523
+ return {
524
+ pattern: "/v1/store/import",
525
+ params: {},
526
+ handler: ({ body, signal, diagnostic }) => this.handleStoreImport(body, signal, diagnostic),
527
+ };
528
+ }
529
+ if (method === "POST" && pathname === "/v1/store/export") {
530
+ return {
531
+ pattern: "/v1/store/export",
532
+ params: {},
533
+ handler: ({ body, signal, diagnostic }) => this.handleStoreExport(body, signal, diagnostic),
534
+ };
535
+ }
536
+ if (method === "GET" && pathname === "/v1/store/pins") {
537
+ return {
538
+ pattern: "/v1/store/pins",
539
+ params: {},
540
+ handler: () => ({
541
+ pins: this.state.contentPins(),
542
+ archived: this.state.archivedPins(),
543
+ builtins: this.state.pins().map(pinDetails),
544
+ }),
545
+ };
546
+ }
547
+ if (method === "POST" && pathname === "/v1/store/pins") {
548
+ return {
549
+ pattern: "/v1/store/pins",
550
+ params: {},
551
+ handler: ({ body, diagnostic }) => this.handleStorePinAdd(body, diagnostic),
552
+ };
553
+ }
554
+ if (pathname.startsWith("/v1/store/pins/")) {
555
+ const ref = decodePathSegment(pathname.slice("/v1/store/pins/".length));
556
+ if (!ref)
557
+ return null;
558
+ if (method === "GET") {
559
+ return {
560
+ pattern: "/v1/store/pins/:ref",
561
+ params: { ref },
562
+ handler: ({ searchParams }) => {
563
+ const details = searchParams.get("details") === "true";
564
+ const swarm = searchParams.get("swarm") ?? undefined;
565
+ if (details) {
566
+ const builtin = ref.startsWith("builtin:")
567
+ ? this.state.pin(ref)
568
+ : undefined;
569
+ const canonical = builtin
570
+ ? undefined
571
+ : pinReference(this.state, ref, swarm);
572
+ const pin = canonical
573
+ ? this.state.contentPin(canonical.reference)
574
+ : undefined;
575
+ const archived = canonical
576
+ ? this.state
577
+ .archivedPins()
578
+ .filter((entry) => entry.cid === canonical.reference)
579
+ : [];
580
+ if (!pin && !builtin && !archived.length) {
581
+ throw new HostError(`Pin "${ref}" does not exist. Run ipab pin list.`, 1, "NOT_FOUND", "store");
582
+ }
583
+ return builtin
584
+ ? pinDetails(builtin)
585
+ : {
586
+ pin: pin ?? null,
587
+ roots: pin ? this.state.hold(pin.owner)?.roots : [],
588
+ archived,
589
+ };
590
+ }
591
+ const pin = this.state.contentPin(ref);
592
+ if (pin)
593
+ return pin;
594
+ const builtin = this.state.pin(ref);
595
+ if (builtin)
596
+ return builtin;
597
+ throw new HostError(`Pin "${ref}" not found.`, 1, "NOT_FOUND", "store");
598
+ },
599
+ };
600
+ }
601
+ if (method === "DELETE") {
602
+ return {
603
+ pattern: "/v1/store/pins/:ref",
604
+ params: { ref },
605
+ handler: async ({ searchParams }) => {
606
+ const swarm = searchParams.get("swarm") ?? undefined;
607
+ const canonical = pinReference(this.state, ref, swarm);
608
+ const store = await this.getStore();
609
+ return unpin(this.state, canonical.reference, storeFactoryFor(store));
610
+ },
611
+ };
612
+ }
613
+ }
614
+ if (method === "GET" && pathname === "/v1/store/usage") {
615
+ return {
616
+ pattern: "/v1/store/usage",
617
+ params: {},
618
+ handler: async () => (await this.getStore()).usage(),
619
+ };
620
+ }
621
+ if (method === "POST" && pathname === "/v1/store/gc") {
622
+ return {
623
+ pattern: "/v1/store/gc",
624
+ params: {},
625
+ handler: async () => {
626
+ const store = await this.getStore();
627
+ await recoverInactive(this.state, storeFactoryFor(store));
628
+ return store.gc();
629
+ },
630
+ };
631
+ }
632
+ // 2. /v1/swarms/*
633
+ if (method === "GET" && pathname === "/v1/swarms") {
634
+ return {
635
+ pattern: "/v1/swarms",
636
+ params: {},
637
+ handler: () => ({
638
+ swarms: [
639
+ { cid: LOCAL_SWARM_URL, alias: LOCAL_SWARM_ALIAS, local: true },
640
+ ...this.state.swarms(),
641
+ ],
642
+ }),
643
+ };
644
+ }
645
+ if (method === "GET" && pathname === "/v1/swarms/identity") {
646
+ return {
647
+ pattern: "/v1/swarms/identity",
648
+ params: {},
649
+ handler: ({ diagnostic }) => this.withSwarmContext((ctx) => accountProfile(ctx), diagnostic, {
650
+ includeSecrets: false,
651
+ }),
652
+ };
653
+ }
654
+ if (method === "GET" &&
655
+ pathname.startsWith("/v1/swarms/") &&
656
+ pathname.endsWith("/meta")) {
657
+ const encodedRef = pathname.slice("/v1/swarms/".length, pathname.length - "/meta".length);
658
+ if (!encodedRef || encodedRef.includes("/"))
659
+ return null;
660
+ const ref = decodePathSegment(encodedRef);
661
+ if (!ref)
662
+ return null;
663
+ return {
664
+ pattern: "/v1/swarms/:ref/meta",
665
+ params: { ref },
666
+ swarmParam: ref,
667
+ handler: async ({ diagnostic, searchParams }) => {
668
+ const url = this.state.resolveSwarm(ref);
669
+ const refresh = searchParams.get("refresh") === "true";
670
+ return this.withSwarmContext(async (ctx) => {
671
+ const header = await swarmHeader(ctx, url, refresh);
672
+ const meta = await swarmMeta(ctx, header);
673
+ return {
674
+ swarm: url,
675
+ headCid: header.head.root,
676
+ stateCid: header.stateCid,
677
+ meta,
678
+ };
679
+ }, diagnostic, { forceRefresh: refresh });
680
+ },
681
+ };
682
+ }
683
+ if (method === "POST" && pathname === "/v1/swarms/set") {
684
+ return {
685
+ pattern: "/v1/swarms/set",
686
+ params: {},
687
+ handler: ({ body }) => {
688
+ const alias = requireString(body, "alias");
689
+ const url = requireString(body, "url");
690
+ let expectedTarget;
691
+ if ("expectedTarget" in body) {
692
+ if (body.expectedTarget !== null &&
693
+ typeof body.expectedTarget !== "string") {
694
+ syntax('Field "expectedTarget" must be a string or null.');
695
+ }
696
+ expectedTarget = body.expectedTarget;
697
+ }
698
+ else {
699
+ const previous = this.state
700
+ .swarms()
701
+ .find((entry) => entry.alias === alias);
702
+ expectedTarget = previous?.cid ?? null;
703
+ }
704
+ const entry = this.state.setSwarm(alias, url, expectedTarget);
705
+ this.onSwarmChange?.(entry.cid);
706
+ return {
707
+ configUrl: entry.cid,
708
+ alias: entry.alias,
709
+ savedCurrent: this.state.config({ includeSecrets: false })["swarm.default"] ??
710
+ null,
711
+ };
712
+ },
713
+ };
714
+ }
715
+ if (method === "POST" && pathname === "/v1/swarms/remove") {
716
+ return {
717
+ pattern: "/v1/swarms/remove",
718
+ params: {},
719
+ handler: ({ body }) => {
720
+ const swarm = requireSwarmParam(body);
721
+ const removed = this.state.removeSwarm(swarm);
722
+ this.onSwarmChange?.();
723
+ return {
724
+ removed,
725
+ savedCurrent: this.state.config({ includeSecrets: false })["swarm.default"] ??
726
+ null,
727
+ };
728
+ },
729
+ };
730
+ }
731
+ if (method === "POST" && pathname === "/v1/swarms/fs/ls") {
732
+ return {
733
+ pattern: "/v1/swarms/fs/ls",
734
+ params: {},
735
+ handler: ({ body, diagnostic }) => this.handleSwarmFsLs(body, diagnostic),
736
+ };
737
+ }
738
+ if (method === "POST" && pathname === "/v1/swarms/fs/stat") {
739
+ return {
740
+ pattern: "/v1/swarms/fs/stat",
741
+ params: {},
742
+ handler: ({ body, diagnostic }) => this.handleSwarmFsStat(body, diagnostic),
743
+ };
744
+ }
745
+ if (method === "POST" && pathname === "/v1/swarms/fs/set") {
746
+ return {
747
+ pattern: "/v1/swarms/fs/set",
748
+ params: {},
749
+ handler: ({ body, diagnostic }) => this.handleSwarmFsSet(body, diagnostic),
750
+ };
751
+ }
752
+ if (method === "POST" && pathname === "/v1/swarms/fs/rm") {
753
+ return {
754
+ pattern: "/v1/swarms/fs/rm",
755
+ params: {},
756
+ handler: ({ body, diagnostic }) => this.handleSwarmFsRm(body, diagnostic),
757
+ };
758
+ }
759
+ if (method === "POST" && pathname === "/v1/swarms/search") {
760
+ return {
761
+ pattern: "/v1/swarms/search",
762
+ params: {},
763
+ handler: ({ body, diagnostic }) => this.handleSwarmSearch(body, diagnostic),
764
+ };
765
+ }
766
+ if (method === "POST" && pathname === "/v1/swarms/members") {
767
+ return {
768
+ pattern: "/v1/swarms/members",
769
+ params: {},
770
+ handler: async ({ body, diagnostic }) => {
771
+ const swarm = requireSwarmParam(body);
772
+ const url = this.state.resolveSwarm(swarm);
773
+ const refresh = optionalBoolean(body, "refresh");
774
+ const ctx = await this.createSwarmContext(diagnostic, {
775
+ forceRefresh: refresh,
776
+ includeSecrets: false,
777
+ });
778
+ try {
779
+ return await swarmMembers(ctx, url, refresh ?? false);
780
+ }
781
+ finally {
782
+ await this.finishSwarmContext(ctx);
783
+ }
784
+ },
785
+ };
786
+ }
787
+ if (method === "POST" && pathname === "/v1/swarms/status") {
788
+ return {
789
+ pattern: "/v1/swarms/status",
790
+ params: {},
791
+ handler: async ({ body, diagnostic }) => {
792
+ const swarm = requireSwarmParam(body);
793
+ const url = this.state.resolveSwarm(swarm);
794
+ const refresh = optionalBoolean(body, "refresh");
795
+ const ctx = await this.createSwarmContext(diagnostic, {
796
+ forceRefresh: refresh,
797
+ includeSecrets: false,
798
+ });
799
+ try {
800
+ return await inspectSwarmStatus(ctx, url, refresh ?? false);
801
+ }
802
+ finally {
803
+ await this.finishSwarmContext(ctx);
804
+ }
805
+ },
806
+ };
807
+ }
808
+ if (method === "POST" && pathname === "/v1/swarms/update") {
809
+ return {
810
+ pattern: "/v1/swarms/update",
811
+ params: {},
812
+ handler: async ({ body, diagnostic }) => {
813
+ const swarm = requireSwarmParam(body);
814
+ const url = this.state.resolveSwarm(swarm);
815
+ const name = optionalString(body, "name");
816
+ const description = optionalString(body, "description");
817
+ return this.withSwarmContext(async (ctx) => {
818
+ const updated = await updateSwarm(ctx, url, {
819
+ ...(name !== undefined ? { name } : {}),
820
+ ...(description !== undefined ? { description } : {}),
821
+ });
822
+ this.onSwarmChange?.(url);
823
+ return updated;
824
+ }, diagnostic);
825
+ },
826
+ };
827
+ }
828
+ if (method === "POST" && pathname === "/v1/swarms/replicate") {
829
+ return {
830
+ pattern: "/v1/swarms/replicate",
831
+ params: {},
832
+ handler: async ({ body, signal, diagnostic }) => {
833
+ const swarm = requireSwarmParam(body);
834
+ const url = this.state.resolveSwarm(swarm);
835
+ const pivot = optionalString(body, "pivot");
836
+ return this.withSwarmContext((ctx) => replicateSwarm(ctx, url, signal, {
837
+ ...(pivot !== undefined ? { pivot } : {}),
838
+ }), diagnostic);
839
+ },
840
+ };
841
+ }
842
+ if (method === "POST" && pathname.startsWith("/v1/swarms/governance/")) {
843
+ const action = decodePathSegment(pathname.slice("/v1/swarms/governance/".length));
844
+ if (!action || action.includes("/"))
845
+ return null;
846
+ return {
847
+ pattern: "/v1/swarms/governance/:action",
848
+ params: { action },
849
+ handler: ({ body, diagnostic }) => this.handleSwarmGovernance(action, body, diagnostic),
850
+ };
851
+ }
852
+ // 3. /v1/runs/*
853
+ if (method === "POST" && pathname === "/v1/runs/prepare") {
854
+ return {
855
+ pattern: "/v1/runs/prepare",
856
+ params: {},
857
+ handler: ({ body, signal, diagnostic }) => this.handleRunPrepare(body, signal, diagnostic),
858
+ };
859
+ }
860
+ if (method === "POST" && pathname === "/v1/runs/list") {
861
+ return {
862
+ pattern: "/v1/runs/list",
863
+ params: {},
864
+ handler: ({ body }) => this.handleRunsList(body),
865
+ };
866
+ }
867
+ if (method === "POST" && pathname === "/v1/runs/remove") {
868
+ return {
869
+ pattern: "/v1/runs/remove",
870
+ params: {},
871
+ handler: ({ body }) => this.handleRunsRemove(body),
872
+ };
873
+ }
874
+ if (pathname.startsWith("/v1/runs/")) {
875
+ const rest = pathname.slice("/v1/runs/".length);
876
+ const parts = rest.split("/");
877
+ if (parts.length === 1 && method === "GET") {
878
+ const runId = decodePathSegment(parts[0]);
879
+ return {
880
+ pattern: "/v1/runs/:runId",
881
+ params: { runId },
882
+ handler: async () => {
883
+ const resolved = this.state.resolveRunId(runId);
884
+ const record = this.state.run(resolved);
885
+ if (!record.log)
886
+ return record;
887
+ const logs = await logFiles(this.state.directory, record.id);
888
+ return { ...record, logs };
889
+ },
890
+ };
891
+ }
892
+ if (parts.length === 2 && method === "POST") {
893
+ const runId = decodePathSegment(parts[0]);
894
+ const sub = parts[1];
895
+ if (sub === "ipc") {
896
+ return {
897
+ pattern: "/v1/runs/:runId/ipc",
898
+ params: { runId },
899
+ handler: ({ body, signal }) => this.handleRunIpc(runId, body, signal),
900
+ };
901
+ }
902
+ if (sub === "finish") {
903
+ return {
904
+ pattern: "/v1/runs/:runId/finish",
905
+ params: { runId },
906
+ handler: ({ body, diagnostic }) => this.handleRunFinish(runId, body, diagnostic),
907
+ };
908
+ }
909
+ if (sub === "cancel") {
910
+ return {
911
+ pattern: "/v1/runs/:runId/cancel",
912
+ params: { runId },
913
+ handler: ({ body, diagnostic }) => this.handleRunCancel(runId, body, diagnostic),
914
+ };
915
+ }
916
+ }
917
+ }
918
+ // 4. /v1/host/*
919
+ if (method === "GET" && pathname === "/v1/host/config") {
920
+ return {
921
+ pattern: "/v1/host/config",
922
+ params: {},
923
+ handler: ({ searchParams }) => {
924
+ const keyParam = searchParams.get("key");
925
+ const includeSecrets = searchParams.get("includeSecrets") !== "false";
926
+ const saved = this.state.config({ includeSecrets });
927
+ const items = effectiveConfig(saved, { json: false, stateDir: this.stateDir }, this.env, (reference) => this.state.resolveSwarm(reference)).map(visibleConfig);
928
+ if (keyParam) {
929
+ const key = keyParam === "state-dir" ? "state-dir" : configKey(keyParam);
930
+ const item = items.find((entry) => entry.key === key);
931
+ return item;
932
+ }
933
+ return {
934
+ items,
935
+ saved: this.state.config({ includeSecrets: false }),
936
+ legacyPinCount: this.state.legacyPinCount,
937
+ legacyRegistrationCount: this.state.legacyRegistrationCount,
938
+ stateDir: this.state.directory,
939
+ };
940
+ },
941
+ };
942
+ }
943
+ if (pathname.startsWith("/v1/host/config/")) {
944
+ const rawKey = decodePathSegment(pathname.slice("/v1/host/config/".length));
945
+ if (!rawKey)
946
+ return null;
947
+ if (method === "PUT") {
948
+ return {
949
+ pattern: "/v1/host/config/:key",
950
+ params: { key: rawKey },
951
+ handler: ({ body }) => {
952
+ const key = configKey(rawKey);
953
+ const rawValue = body.value;
954
+ if (rawValue !== null &&
955
+ typeof rawValue !== "string" &&
956
+ typeof rawValue !== "boolean" &&
957
+ typeof rawValue !== "number") {
958
+ syntax("Config value must be a string, boolean, number, or null.");
959
+ }
960
+ const normalized = key === "swarm.default" &&
961
+ typeof rawValue === "string" &&
962
+ rawValue !== "default"
963
+ ? this.state.resolveSwarm(rawValue)
964
+ : rawValue;
965
+ const fromString = optionalBoolean(body, "fromString") ??
966
+ typeof normalized === "string";
967
+ const parsed = parseValue(key, normalized, fromString);
968
+ this.state.setConfig(key, parsed);
969
+ const updated = this.effectiveItems().find((entry) => entry.key === key);
970
+ const savedVisible = visibleConfig({
971
+ key,
972
+ value: parsed,
973
+ source: "user",
974
+ });
975
+ return {
976
+ ...savedVisible,
977
+ effectiveSource: updated.source,
978
+ effectiveValue: visibleConfig(updated).value,
979
+ };
980
+ },
981
+ };
982
+ }
983
+ if (method === "DELETE") {
984
+ return {
985
+ pattern: "/v1/host/config/:key",
986
+ params: { key: rawKey },
987
+ handler: () => {
988
+ if (rawKey === "store.rpc") {
989
+ this.state.resetConfig("store.rpc");
990
+ return {
991
+ key: "store.rpc",
992
+ value: null,
993
+ source: "default",
994
+ legacyReset: true,
995
+ };
996
+ }
997
+ const key = configKey(rawKey);
998
+ this.state.resetConfig(key);
999
+ const updated = this.effectiveItems().find((entry) => entry.key === key);
1000
+ return visibleConfig(updated);
1001
+ },
1002
+ };
1003
+ }
1004
+ }
1005
+ if (method === "POST" && pathname === "/v1/host/skills/sync") {
1006
+ return {
1007
+ pattern: "/v1/host/skills/sync",
1008
+ params: {},
1009
+ handler: async ({ body, diagnostic }) => {
1010
+ const swarm = requireSwarmParam(body);
1011
+ const url = this.state.resolveSwarm(swarm);
1012
+ const refresh = optionalBoolean(body, "refresh");
1013
+ const ctx = await this.createSwarmContext(diagnostic, {
1014
+ forceRefresh: refresh,
1015
+ });
1016
+ try {
1017
+ if (body.daemonSync === true) {
1018
+ return await syncDaemonSkills(ctx, url);
1019
+ }
1020
+ const names = optionalStringArray(body, "names") ?? [];
1021
+ const agents = optionalStringArray(body, "agents") ?? [];
1022
+ const overrideExisting = optionalBoolean(body, "overrideExisting") ?? false;
1023
+ const dryRun = optionalBoolean(body, "dryRun") ?? false;
1024
+ const yes = optionalBoolean(body, "yes") ?? false;
1025
+ const quietPreview = optionalBoolean(body, "quietPreview") ?? false;
1026
+ return await manageSkills(ctx, url, {
1027
+ sync: true,
1028
+ names,
1029
+ agents,
1030
+ overrideExisting,
1031
+ dryRun,
1032
+ yes,
1033
+ tty: false,
1034
+ confirm: () => Promise.resolve(false),
1035
+ preview: (text) => {
1036
+ if (!quietPreview)
1037
+ diagnostic(text);
1038
+ },
1039
+ });
1040
+ }
1041
+ finally {
1042
+ await this.finishSwarmContext(ctx);
1043
+ }
1044
+ },
1045
+ };
1046
+ }
1047
+ return null;
1048
+ }
1049
+ // ---- Store domain handlers ----
1050
+ async resolveCidWithBuiltins(cid, options, store) {
1051
+ options?.signal?.throwIfAborted();
1052
+ const builtin = this.builtins.blocks.get(cid.toV1().toString());
1053
+ if (builtin)
1054
+ return builtin.slice();
1055
+ const activeStore = store ?? (await this.getStore());
1056
+ return activeStore.block.get(cid.toString(), options);
1057
+ }
1058
+ async handleStoreInspect(body, signal, diagnostic) {
1059
+ const ref = requireString(body, "ref");
1060
+ const swarm = optionalString(body, "swarm");
1061
+ const builtinSource = this.state.pin(ref);
1062
+ const targetRef = builtinSource?.builtin && builtinSource.metadata?.kind === "bundle"
1063
+ ? builtinSource.cid
1064
+ : ref;
1065
+ const named = parseNameReference(targetRef);
1066
+ if (named) {
1067
+ if (!named.swarm && !swarm) {
1068
+ syntax("Explicit swarm parameter is required when inspecting a name reference without an embedded swarm.");
1069
+ }
1070
+ const swarmUrl = this.state.resolveSwarm(named.swarm ?? swarm);
1071
+ const ctx = await this.createSwarmContext(diagnostic);
1072
+ try {
1073
+ const resolved = await resolveReference(ctx, targetRef, swarmUrl, (localRef) => this.state.resolve(localRef));
1074
+ return await inspectBundle(resolved.cid, {
1075
+ resolveCid: (cid, options) => this.resolveCidWithBuiltins(cid, options, ctx.store),
1076
+ signal,
1077
+ diagnostic: (text) => {
1078
+ diagnostic(text);
1079
+ },
1080
+ });
1081
+ }
1082
+ finally {
1083
+ await this.finishSwarmContext(ctx);
1084
+ }
1085
+ }
1086
+ let scopedStore;
1087
+ try {
1088
+ const inspected = await inspectBundle(targetRef, {
1089
+ resolveCid: async (cid, options) => {
1090
+ options.signal?.throwIfAborted();
1091
+ const builtin = this.builtins.blocks.get(cid.toV1().toString());
1092
+ if (builtin)
1093
+ return builtin.slice();
1094
+ const active = (scopedStore ??= (await this.getStore()).scope());
1095
+ return active.block.get(cid.toString(), options);
1096
+ },
1097
+ signal,
1098
+ diagnostic: (text) => {
1099
+ diagnostic(text);
1100
+ },
1101
+ });
1102
+ await scopedStore?.close();
1103
+ scopedStore = undefined;
1104
+ return inspected;
1105
+ }
1106
+ finally {
1107
+ if (scopedStore) {
1108
+ await scopedStore.close().catch(() => { });
1109
+ }
1110
+ }
1111
+ }
1112
+ async importBuiltCar(outputPath, requestOptions, diagnostic) {
1113
+ diagnostic("Importing build result into Store (without pinning)...");
1114
+ let importStore;
1115
+ try {
1116
+ await importBundle(outputPath, async () => {
1117
+ importStore ??= (await this.getStore()).scope();
1118
+ return importStore;
1119
+ }, requestOptions);
1120
+ await importStore?.close();
1121
+ importStore = undefined;
1122
+ }
1123
+ catch (cause) {
1124
+ if (importStore)
1125
+ await importStore.close().catch(() => { });
1126
+ throw new HostError(`${message(cause)} CAR remains at ${JSON.stringify(outputPath)}; retry with ipab bundle import ${JSON.stringify(outputPath)}, or build with --no-import.`, 1, "IMPORT_FAILED", "authoring");
1127
+ }
1128
+ }
1129
+ async handleStoreImport(body, signal, diagnostic) {
1130
+ const mode = optionalString(body, "mode") ?? "car";
1131
+ const requestOptions = {
1132
+ signal,
1133
+ diagnostic: (text) => {
1134
+ diagnostic(text);
1135
+ },
1136
+ resolveCid: (cid, options) => this.resolveCidWithBuiltins(cid, options),
1137
+ };
1138
+ if (mode === "assemble") {
1139
+ const path = optionalString(body, "path");
1140
+ const output = optionalString(body, "output");
1141
+ const outputDir = optionalString(body, "outputDir") ??
1142
+ String(this.configValue("bundle.outputDir"));
1143
+ const replace = optionalBoolean(body, "replace") ?? false;
1144
+ const autoImport = optionalBoolean(body, "autoImport") ?? false;
1145
+ diagnostic("Assembling and validating Bundle (no compilation)...");
1146
+ const result = await assembleBundle(path, {
1147
+ ...requestOptions,
1148
+ replace,
1149
+ ...defined({ output }),
1150
+ outputDir,
1151
+ });
1152
+ if (autoImport) {
1153
+ await this.importBuiltCar(result.output, requestOptions, diagnostic);
1154
+ }
1155
+ return { ...result, imported: autoImport };
1156
+ }
1157
+ const path = requireString(body, "path");
1158
+ if (mode === "build") {
1159
+ const builtinSource = this.state.pin(path);
1160
+ const source = builtinSource?.builtin && builtinSource.metadata?.kind === "bundle"
1161
+ ? builtinSource.cid
1162
+ : path;
1163
+ const schemaOnly = optionalBoolean(body, "schemaOnly");
1164
+ const output = optionalString(body, "output");
1165
+ const outputDir = optionalString(body, "outputDir") ??
1166
+ String(this.configValue("bundle.outputDir"));
1167
+ const replace = optionalBoolean(body, "replace");
1168
+ const autoImport = optionalBoolean(body, "autoImport") ?? false;
1169
+ diagnostic("Validating and building bundle...");
1170
+ const result = await buildBundle(source, {
1171
+ ...requestOptions,
1172
+ ...defined({ schemaOnly, output, replace }),
1173
+ outputDir,
1174
+ });
1175
+ if (autoImport) {
1176
+ await this.importBuiltCar(result.output, requestOptions, diagnostic);
1177
+ }
1178
+ return { ...result, imported: autoImport };
1179
+ }
1180
+ if (mode === "snapshot") {
1181
+ const localInput = await resolveLocalBundleInput(path);
1182
+ if (!localInput) {
1183
+ throw new HostError(`Path "${path}" is not a valid local Bundle directory or CAR file.`, 2, "INVALID_INPUT", "store");
1184
+ }
1185
+ const store = await this.getStore();
1186
+ const session = `ipab-snapshot:${this.state.identity}:${randomUUID()}`;
1187
+ const owner = await Ownership.create(this.state, store, `snapshot:${randomUUID()}`, session);
1188
+ try {
1189
+ const cid = await snapshotLocalBundle(localInput, owner, session, {
1190
+ signal,
1191
+ diagnostic: (text) => {
1192
+ diagnostic(text);
1193
+ },
1194
+ });
1195
+ return { cid };
1196
+ }
1197
+ finally {
1198
+ await owner.release();
1199
+ }
1200
+ }
1201
+ diagnostic(path.toLowerCase().endsWith(".car")
1202
+ ? "Validating and importing CAR into Store..."
1203
+ : "Validating and importing Bundle into Store...");
1204
+ let importStore;
1205
+ try {
1206
+ const imported = await importBundle(path, async () => {
1207
+ importStore ??= (await this.getStore()).scope();
1208
+ return importStore;
1209
+ }, requestOptions);
1210
+ await importStore?.close();
1211
+ importStore = undefined;
1212
+ return imported;
1213
+ }
1214
+ finally {
1215
+ if (importStore) {
1216
+ await importStore.close().catch(() => { });
1217
+ }
1218
+ }
1219
+ }
1220
+ async handleStoreExport(body, signal, diagnostic) {
1221
+ const mode = optionalString(body, "mode") ?? "get";
1222
+ const swarm = optionalString(body, "swarm");
1223
+ const refresh = optionalBoolean(body, "refresh");
1224
+ if (mode === "render-template") {
1225
+ const selector = requireString(body, "template");
1226
+ const name = requireString(body, "name");
1227
+ const destination = optionalString(body, "destination");
1228
+ const parameters = optionalStringArray(body, "parameters") ?? [];
1229
+ const ctx = await this.createSwarmContext(diagnostic, {
1230
+ forceRefresh: refresh,
1231
+ });
1232
+ try {
1233
+ let selectedTemplate = selector;
1234
+ if (parseNameReference(selector)) {
1235
+ const swarmUrl = swarm ? this.state.resolveSwarm(swarm) : undefined;
1236
+ selectedTemplate = (await resolveReference(ctx, selector, swarmUrl, (localRef) => this.state.resolve(localRef), false, "local-first")).cid;
1237
+ }
1238
+ else {
1239
+ let explicit = false;
1240
+ try {
1241
+ CID.parse(selector);
1242
+ explicit = true;
1243
+ }
1244
+ catch {
1245
+ /* Not a CID. */
1246
+ }
1247
+ explicit ||= selector.toLowerCase().endsWith(".car");
1248
+ if (!explicit) {
1249
+ try {
1250
+ await lstat(selector);
1251
+ explicit = true;
1252
+ }
1253
+ catch (cause) {
1254
+ if (!nodeError(cause, "ENOENT") && !nodeError(cause, "ENOTDIR")) {
1255
+ throw cause;
1256
+ }
1257
+ }
1258
+ }
1259
+ if (!explicit) {
1260
+ templateName(selector);
1261
+ if (!swarm) {
1262
+ throw new HostError("Template selectors require a selected Swarm. Use --swarm or swarm use, or supply an explicit Bundle directory, CAR, exact CID or IPAB URI.");
1263
+ }
1264
+ const swarmUrl = this.state.resolveSwarm(swarm);
1265
+ selectedTemplate = await resolveTemplateSelector(ctx, selector, swarmUrl);
1266
+ }
1267
+ }
1268
+ return await initApp(name, destination, {
1269
+ signal,
1270
+ diagnostic: (text) => {
1271
+ diagnostic(text);
1272
+ },
1273
+ resolveCid: (cid, options) => this.resolveCidWithBuiltins(cid, options, ctx.store),
1274
+ template: selectedTemplate,
1275
+ parameters,
1276
+ });
1277
+ }
1278
+ finally {
1279
+ await this.finishSwarmContext(ctx);
1280
+ }
1281
+ }
1282
+ const ref = requireString(body, "ref");
1283
+ const destination = optionalString(body, "destination");
1284
+ const raw = optionalBoolean(body, "raw") ?? false;
1285
+ const named = parseNameReference(ref);
1286
+ if (named && !named.swarm && !swarm) {
1287
+ syntax("Explicit swarm parameter is required when exporting a name reference without an embedded swarm.");
1288
+ }
1289
+ const localCid = /^(ipab|name):/i.test(ref)
1290
+ ? undefined
1291
+ : this.state.resolve(ref);
1292
+ const builtin = this.builtins.pins.find((pin) => pin.cid === localCid);
1293
+ const ctx = await this.createSwarmContext(diagnostic, {
1294
+ forceRefresh: refresh,
1295
+ });
1296
+ try {
1297
+ const selected = builtin
1298
+ ? { cid: builtin.cid, targetCid: builtin.cid }
1299
+ : await resolveReference(ctx, ref, swarm ? this.state.resolveSwarm(swarm) : undefined, (localRef) => this.state.resolve(localRef), raw, "local-first");
1300
+ const source = IpfsStore.fromClient({
1301
+ block: {
1302
+ get: (key, options) => {
1303
+ options?.signal?.throwIfAborted();
1304
+ const builtinBlock = this.builtins.blocks.get(CID.parse(key).toV1().toString());
1305
+ return builtinBlock
1306
+ ? Promise.resolve(builtinBlock.slice())
1307
+ : ctx.store.block.get(key, options);
1308
+ },
1309
+ },
1310
+ }, ctx.store.limits);
1311
+ let directory;
1312
+ try {
1313
+ directory = await getBundle(source, selected.cid, destination);
1314
+ }
1315
+ finally {
1316
+ await source.close();
1317
+ }
1318
+ return { ...selected, directory, destination: directory };
1319
+ }
1320
+ finally {
1321
+ await this.finishSwarmContext(ctx);
1322
+ }
1323
+ }
1324
+ async handleStorePinAdd(body, diagnostic) {
1325
+ const ref = requireString(body, "ref");
1326
+ const swarm = optionalString(body, "swarm");
1327
+ const refresh = optionalBoolean(body, "refresh");
1328
+ const named = parseNameReference(ref);
1329
+ if (named && !named.swarm && !swarm) {
1330
+ syntax("Explicit swarm parameter is required when pinning a name reference without an embedded swarm.");
1331
+ }
1332
+ const ctx = await this.createSwarmContext(diagnostic, {
1333
+ forceRefresh: refresh,
1334
+ });
1335
+ try {
1336
+ const selectedSwarm = swarm ? this.state.resolveSwarm(swarm) : undefined;
1337
+ return await pinNameSubscription(ctx, ref, selectedSwarm);
1338
+ }
1339
+ finally {
1340
+ await this.finishSwarmContext(ctx);
1341
+ }
1342
+ }
1343
+ // ---- Swarm domain handlers ----
1344
+ async handleSwarmFsLs(body, diagnostic) {
1345
+ const swarm = requireSwarmParam(body);
1346
+ const url = this.state.resolveSwarm(swarm);
1347
+ const kind = optionalString(body, "kind") ?? "fs";
1348
+ const refresh = optionalBoolean(body, "refresh");
1349
+ const ctx = await this.createSwarmContext(diagnostic, {
1350
+ forceRefresh: refresh,
1351
+ });
1352
+ try {
1353
+ if (kind === "templates") {
1354
+ const items = await swarmTemplates(ctx, url);
1355
+ const alias = this.state.allSwarms().find((entry) => entry.cid === url)?.alias ??
1356
+ null;
1357
+ return { items, alias };
1358
+ }
1359
+ if (kind === "register") {
1360
+ const items = await swarmRegistrations(ctx, url);
1361
+ const alias = this.state.allSwarms().find((entry) => entry.cid === url)?.alias ??
1362
+ null;
1363
+ return { items, alias };
1364
+ }
1365
+ if (kind === "skills") {
1366
+ const names = optionalStringArray(body, "names") ?? [];
1367
+ const agents = optionalStringArray(body, "agents") ?? [];
1368
+ const managed = await manageSkills(ctx, url, {
1369
+ sync: false,
1370
+ names,
1371
+ agents,
1372
+ overrideExisting: false,
1373
+ dryRun: false,
1374
+ yes: false,
1375
+ tty: false,
1376
+ confirm: () => Promise.resolve(false),
1377
+ preview: (text) => {
1378
+ diagnostic(text);
1379
+ },
1380
+ });
1381
+ const typeSkills = await swarmTypeSkills(ctx, url, {
1382
+ mode: "local-first",
1383
+ ...defined({ forceRefresh: refresh }),
1384
+ });
1385
+ return {
1386
+ swarm: managed.swarm,
1387
+ installer: managed.installer,
1388
+ agents: managed.agents,
1389
+ dryRun: managed.dryRun,
1390
+ items: managed.items,
1391
+ typeSkills,
1392
+ orphaned: managed.orphaned,
1393
+ results: managed.results,
1394
+ ok: managed.ok,
1395
+ };
1396
+ }
1397
+ const path = optionalString(body, "path");
1398
+ const recursive = optionalBoolean(body, "recursive") ?? false;
1399
+ const all = optionalBoolean(body, "all") ?? false;
1400
+ return await listSwarmFsPath(ctx, url, path, {
1401
+ recursive,
1402
+ all,
1403
+ mode: "local-first",
1404
+ ...defined({ forceRefresh: refresh }),
1405
+ });
1406
+ }
1407
+ finally {
1408
+ await this.finishSwarmContext(ctx);
1409
+ }
1410
+ }
1411
+ async handleSwarmFsStat(body, diagnostic) {
1412
+ const swarm = requireSwarmParam(body);
1413
+ const url = this.state.resolveSwarm(swarm);
1414
+ const kind = optionalString(body, "kind") ?? "fs";
1415
+ const refresh = optionalBoolean(body, "refresh");
1416
+ const ctx = await this.createSwarmContext(diagnostic, {
1417
+ forceRefresh: refresh,
1418
+ });
1419
+ try {
1420
+ if (kind === "template") {
1421
+ const name = requireString(body, "name");
1422
+ const includeTree = optionalBoolean(body, "includeTree") ?? true;
1423
+ const item = (await swarmTemplates(ctx, url, name))[0];
1424
+ const tree = includeTree
1425
+ ? await templateOutputTree(ctx.store, item.templateCid)
1426
+ : undefined;
1427
+ const alias = this.state.allSwarms().find((entry) => entry.cid === url)?.alias ??
1428
+ null;
1429
+ return { item, ...(tree !== undefined ? { tree } : {}), alias };
1430
+ }
1431
+ if (kind === "skill") {
1432
+ const ref = requireString(body, "ref");
1433
+ const refreshOption = defined({ forceRefresh: refresh });
1434
+ const named = parseNameReference(ref);
1435
+ let targetSwarm = url;
1436
+ let schemaCid;
1437
+ let resolvedFrom;
1438
+ let contentCid;
1439
+ let reference;
1440
+ let association;
1441
+ if (named) {
1442
+ targetSwarm = named.swarm
1443
+ ? this.state.resolveSwarm(named.swarm)
1444
+ : url;
1445
+ const resolved = await resolveReference(ctx, ref, targetSwarm, (localRef) => this.state.resolve(localRef), false, "local-first");
1446
+ contentCid = resolved.cid;
1447
+ reference = ref;
1448
+ const bundle = await openBundle(CID.parse(contentCid), {
1449
+ resolveCid: (key) => ctx.store.block.get(key.toString()),
1450
+ });
1451
+ schemaCid = bundle.schemaKey;
1452
+ resolvedFrom = "uri";
1453
+ association = await swarmTypeSkill(ctx, targetSwarm, schemaCid, {
1454
+ mode: "local-first",
1455
+ ...refreshOption,
1456
+ });
1457
+ }
1458
+ else {
1459
+ const localInput = await resolveLocalBundleInput(ref);
1460
+ if (localInput) {
1461
+ const store = await this.getStore();
1462
+ const session = `skills-show:${randomUUID()}`;
1463
+ const owner = await Ownership.create(this.state, store, `skills-show:${randomUUID()}`, session);
1464
+ try {
1465
+ const root = await snapshotLocalBundle(localInput, owner, session, {
1466
+ diagnostic: (text) => {
1467
+ diagnostic(text);
1468
+ },
1469
+ });
1470
+ contentCid = await artifactValue(store, root);
1471
+ const bundle = await openBundle(CID.parse(contentCid), {
1472
+ resolveCid: (key) => store.block.get(key.toString()),
1473
+ });
1474
+ schemaCid = bundle.schemaKey;
1475
+ resolvedFrom = "local";
1476
+ association = await swarmTypeSkill(ctx, targetSwarm, schemaCid, {
1477
+ mode: "local-first",
1478
+ ...refreshOption,
1479
+ });
1480
+ }
1481
+ finally {
1482
+ await owner.release();
1483
+ }
1484
+ }
1485
+ else {
1486
+ const resolved = this.state.resolve(schemaAlias(ref));
1487
+ const parsedCid = CID.parse(resolved);
1488
+ const isSchemaCid = parsedCid.code === 0x71 && parsedCid.multihash.code === 0x12;
1489
+ schemaCid = resolved;
1490
+ resolvedFrom = "schema";
1491
+ if (isSchemaCid) {
1492
+ association = await swarmTypeSkill(ctx, targetSwarm, resolved, {
1493
+ mode: "local-first",
1494
+ ...refreshOption,
1495
+ });
1496
+ }
1497
+ else {
1498
+ const refResolved = await resolveReference(ctx, resolved, targetSwarm, (localRef) => this.state.resolve(localRef), false, "local-first");
1499
+ const bundle = await openBundle(CID.parse(refResolved.cid), {
1500
+ resolveCid: (key) => ctx.store.block.get(key.toString()),
1501
+ });
1502
+ schemaCid = bundle.schemaKey;
1503
+ contentCid = refResolved.cid;
1504
+ resolvedFrom = "content";
1505
+ association = await swarmTypeSkill(ctx, targetSwarm, schemaCid, {
1506
+ mode: "local-first",
1507
+ ...refreshOption,
1508
+ });
1509
+ }
1510
+ }
1511
+ }
1512
+ if (!association) {
1513
+ throw new HostError(`No Skill associated with Schema ${schemaCid} in Swarm ${targetSwarm}. Associate one with: ipab skills set SKILL --type ${schemaCid}`, 1, "SKILL_NOT_FOUND", "state");
1514
+ }
1515
+ return {
1516
+ swarm: targetSwarm,
1517
+ schemaCid,
1518
+ resolvedFrom,
1519
+ ...(contentCid ? { contentCid } : {}),
1520
+ ...(reference ? { reference } : {}),
1521
+ name: association.name,
1522
+ cid: association.cid,
1523
+ identity: association.identity,
1524
+ description: association.description,
1525
+ };
1526
+ }
1527
+ const path = optionalString(body, "path") ?? "/";
1528
+ return await statSwarmFsPath(ctx, url, path, {
1529
+ mode: "local-first",
1530
+ ...defined({ forceRefresh: refresh }),
1531
+ });
1532
+ }
1533
+ finally {
1534
+ await this.finishSwarmContext(ctx);
1535
+ }
1536
+ }
1537
+ async handleSwarmFsSet(body, diagnostic) {
1538
+ const swarm = requireSwarmParam(body);
1539
+ const url = this.state.resolveSwarm(swarm);
1540
+ const kind = optionalString(body, "kind") ?? "fs";
1541
+ if (kind === "publish") {
1542
+ const name = requireString(body, "name");
1543
+ const source = requireString(body, "source");
1544
+ const expect = optionalString(body, "expect");
1545
+ const snapshot = optionalBoolean(body, "snapshot") ?? false;
1546
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext(async (ctx) => {
1547
+ const store = await this.getStore();
1548
+ const contentCid = await publicationSource(source, store);
1549
+ const cid = await publish(ctx, contentCid, {
1550
+ swarm: url,
1551
+ name,
1552
+ ...(expect !== undefined ? { expect } : {}),
1553
+ snapshot,
1554
+ });
1555
+ return { cid, contentCid };
1556
+ }, diagnostic));
1557
+ }
1558
+ if (kind === "template") {
1559
+ const name = requireString(body, "name");
1560
+ const source = requireString(body, "source");
1561
+ const expect = optionalString(body, "expect");
1562
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext((ctx) => setSwarmTemplate(ctx, url, name, source, expect), diagnostic));
1563
+ }
1564
+ if (kind === "register") {
1565
+ const schemaRaw = requireString(body, "schema");
1566
+ const appRaw = requireString(body, "app");
1567
+ const argv = optionalStringArray(body, "argv") ?? ["%"];
1568
+ const replace = optionalBoolean(body, "replace") ?? false;
1569
+ const batchSwarms = optionalStringArray(body, "swarms");
1570
+ const schema = this.state.resolve(schemaAlias(schemaRaw), true);
1571
+ if (batchSwarms && batchSwarms.length > 0) {
1572
+ const targets = batchSwarms.map((ref) => this.state.resolveSwarm(ref));
1573
+ const localApp = !parseNameReference(appRaw)
1574
+ ? await resolveLocalBundleInput(appRaw)
1575
+ : undefined;
1576
+ let owner;
1577
+ const associations = [];
1578
+ const completed = [];
1579
+ try {
1580
+ let localAppCid;
1581
+ if (localApp) {
1582
+ const store = await this.getStore();
1583
+ const session = `register:${randomUUID()}`;
1584
+ owner = await Ownership.create(this.state, store, `register:${randomUUID()}`, session);
1585
+ localAppCid = await snapshotLocalBundle(localApp, owner, session, {
1586
+ diagnostic: (text) => {
1587
+ diagnostic(text);
1588
+ },
1589
+ });
1590
+ }
1591
+ for (const targetUrl of targets) {
1592
+ const ctx = await this.createSwarmContext(diagnostic);
1593
+ try {
1594
+ const appCid = localAppCid ??
1595
+ (parseNameReference(appRaw)
1596
+ ? (await resolveReference(ctx, appRaw, targetUrl, (ref) => this.state.resolve(ref))).cid
1597
+ : this.state.resolve(appRaw));
1598
+ const association = await this.mutex.run(`swarm-fs:${targetUrl}`, () => setSwarmAssociation(ctx, targetUrl, createAssociation(schema, appCid, argv), replace));
1599
+ associations.push(association);
1600
+ completed.push(targetUrl);
1601
+ }
1602
+ catch (cause) {
1603
+ throw new HostError(`Registry operation failed for ${targetUrl}: ${message(cause)}. Completed Swarms: ${completed.length ? completed.join(", ") : "(none)"}. Multiple Swarm edits are not atomic.`, cause instanceof HostError ? cause.exitCode : 1, cause instanceof HostError ? cause.code : "REGISTRY_FAILED", "publication");
1604
+ }
1605
+ finally {
1606
+ await this.finishSwarmContext(ctx);
1607
+ }
1608
+ }
1609
+ return { associations };
1610
+ }
1611
+ finally {
1612
+ await owner?.release();
1613
+ }
1614
+ }
1615
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext(async (ctx) => {
1616
+ const localApp = !parseNameReference(appRaw)
1617
+ ? await resolveLocalBundleInput(appRaw)
1618
+ : undefined;
1619
+ let owner;
1620
+ try {
1621
+ let appCid;
1622
+ if (localApp) {
1623
+ const store = await this.getStore();
1624
+ const session = `register:${randomUUID()}`;
1625
+ owner = await Ownership.create(this.state, store, `register:${randomUUID()}`, session);
1626
+ appCid = await snapshotLocalBundle(localApp, owner, session, {
1627
+ diagnostic: (text) => {
1628
+ diagnostic(text);
1629
+ },
1630
+ });
1631
+ }
1632
+ else if (parseNameReference(appRaw)) {
1633
+ appCid = (await resolveReference(ctx, appRaw, url, (ref) => this.state.resolve(ref))).cid;
1634
+ }
1635
+ else {
1636
+ appCid = this.state.resolve(appRaw);
1637
+ }
1638
+ return await setSwarmAssociation(ctx, url, createAssociation(schema, appCid, argv), replace);
1639
+ }
1640
+ finally {
1641
+ await owner?.release();
1642
+ }
1643
+ }, diagnostic));
1644
+ }
1645
+ if (kind === "skill") {
1646
+ const skillRaw = requireString(body, "skill");
1647
+ const globalFlag = optionalBoolean(body, "global") ?? false;
1648
+ const typesRaw = optionalStringArray(body, "types") ?? [];
1649
+ const replace = optionalBoolean(body, "replace") ?? false;
1650
+ const types = typesRaw.map((schema) => this.state.resolve(schemaAlias(schema), true));
1651
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext(async (ctx) => {
1652
+ const localSkill = !parseNameReference(skillRaw)
1653
+ ? await resolveLocalBundleInput(skillRaw)
1654
+ : undefined;
1655
+ let owner;
1656
+ try {
1657
+ let skillCid;
1658
+ if (localSkill) {
1659
+ const store = await this.getStore();
1660
+ const session = `skills-set:${randomUUID()}`;
1661
+ owner = await Ownership.create(this.state, store, `skills-set:${randomUUID()}`, session);
1662
+ skillCid = await snapshotLocalBundle(localSkill, owner, session, {
1663
+ diagnostic: (text) => {
1664
+ diagnostic(text);
1665
+ },
1666
+ });
1667
+ }
1668
+ else if (parseNameReference(skillRaw)) {
1669
+ skillCid = (await resolveReference(ctx, skillRaw, url, (ref) => this.state.resolve(ref), false)).cid;
1670
+ }
1671
+ else {
1672
+ skillCid = this.state.resolve(skillRaw);
1673
+ }
1674
+ return await setSwarmSkill(ctx, url, {
1675
+ skillCid,
1676
+ global: globalFlag,
1677
+ types,
1678
+ replace,
1679
+ });
1680
+ }
1681
+ finally {
1682
+ await owner?.release();
1683
+ }
1684
+ }, diagnostic));
1685
+ }
1686
+ const path = requireString(body, "path");
1687
+ const cid = exactCid(requireString(body, "cid"));
1688
+ const expect = optionalString(body, "expect");
1689
+ const replace = optionalBoolean(body, "replace");
1690
+ const validator = optionalString(body, "validator");
1691
+ const wrapArtifact = optionalBoolean(body, "wrapArtifact") ?? false;
1692
+ if (expect !== undefined && replace) {
1693
+ syntax("Options expect and replace are mutually exclusive.");
1694
+ }
1695
+ if (validator === "template") {
1696
+ const store = await this.getStore();
1697
+ await inspectTemplate(store, cid);
1698
+ }
1699
+ else if (validator === "app") {
1700
+ const store = await this.getStore();
1701
+ const bundle = await openBundle(CID.parse(cid), {
1702
+ resolveCid: (key) => store.block.get(key.toString()),
1703
+ });
1704
+ if (bundle.schemaKey !== appSchemaCid.toString()) {
1705
+ throw new HostError(`Expected an App Bundle (${appSchemaCid.toString()}), got ${bundle.schemaKey}.`, 2, "INVALID_APP_BUNDLE", "validation");
1706
+ }
1707
+ }
1708
+ else if (validator === "bundle") {
1709
+ const store = await this.getStore();
1710
+ await openBundle(CID.parse(cid), {
1711
+ resolveCid: (key) => store.block.get(key.toString()),
1712
+ });
1713
+ }
1714
+ else if (validator !== undefined) {
1715
+ syntax(`Unknown validator "${validator}".`);
1716
+ }
1717
+ // If wrapArtifact is requested, validate the target exists as a block/bundle before committing.
1718
+ if (wrapArtifact) {
1719
+ const store = await this.getStore();
1720
+ await store.block.get(cid);
1721
+ }
1722
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext((ctx) => setSwarmFsPath(ctx, url, path, cid, {
1723
+ ...(expect !== undefined ? { expect: exactCid(expect) } : {}),
1724
+ ...(replace !== undefined ? { replace } : {}),
1725
+ }), diagnostic));
1726
+ }
1727
+ async handleSwarmFsRm(body, diagnostic) {
1728
+ const swarm = requireSwarmParam(body);
1729
+ const url = this.state.resolveSwarm(swarm);
1730
+ const kind = optionalString(body, "kind") ?? "fs";
1731
+ if (kind === "template") {
1732
+ const name = requireString(body, "name");
1733
+ const expect = requireString(body, "expect");
1734
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext((ctx) => removeSwarmTemplate(ctx, url, name, expect), diagnostic));
1735
+ }
1736
+ if (kind === "register") {
1737
+ const schemaRaw = requireString(body, "schema");
1738
+ const schema = this.state.resolve(schemaAlias(schemaRaw), true);
1739
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext(async (ctx) => {
1740
+ const removed = await removeSwarmAssociation(ctx, url, schema);
1741
+ return { removed };
1742
+ }, diagnostic));
1743
+ }
1744
+ if (kind === "skill") {
1745
+ const globalName = optionalString(body, "globalName");
1746
+ const typesRaw = optionalStringArray(body, "types") ?? [];
1747
+ const types = typesRaw.map((schema) => this.state.resolve(schemaAlias(schema), true));
1748
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext((ctx) => removeSwarmSkill(ctx, url, {
1749
+ ...(globalName !== undefined ? { globalName } : {}),
1750
+ types,
1751
+ }), diagnostic));
1752
+ }
1753
+ const path = requireString(body, "path");
1754
+ const expect = optionalString(body, "expect");
1755
+ return this.mutex.run(`swarm-fs:${url}`, () => this.withSwarmContext((ctx) => removeSwarmFsPath(ctx, url, path, {
1756
+ ...(expect !== undefined ? { expect: exactCid(expect) } : {}),
1757
+ }), diagnostic));
1758
+ }
1759
+ async handleSwarmSearch(body, diagnostic) {
1760
+ const swarmsParam = optionalStringArray(body, "swarms");
1761
+ const singleSwarm = optionalString(body, "swarm");
1762
+ if (!swarmsParam?.length && (!singleSwarm || !singleSwarm.trim())) {
1763
+ syntax("Explicit swarm parameter is required; daemon has no implicit current swarm.");
1764
+ }
1765
+ const allRegistered = this.state.allSwarms();
1766
+ const scope = swarmsParam?.length
1767
+ ? swarmsParam.map((ref) => {
1768
+ const url = this.state.resolveSwarm(ref);
1769
+ const found = allRegistered.find((entry) => entry.cid === url);
1770
+ return found
1771
+ ? {
1772
+ cid: found.cid,
1773
+ alias: found.alias,
1774
+ ...(found.local ? { local: true } : {}),
1775
+ }
1776
+ : { cid: url, alias: null };
1777
+ })
1778
+ : (() => {
1779
+ const url = this.state.resolveSwarm(singleSwarm.trim());
1780
+ const found = allRegistered.find((entry) => entry.cid === url);
1781
+ return [{ cid: url, alias: found?.alias ?? null }];
1782
+ })();
1783
+ const q = optionalString(body, "q") ?? "";
1784
+ const prefix = optionalString(body, "prefix");
1785
+ const kind = optionalString(body, "kind");
1786
+ const schemaCid = optionalString(body, "schemaCid");
1787
+ const limitRaw = body.limit;
1788
+ const offsetRaw = body.offset;
1789
+ const limit = limitRaw === undefined
1790
+ ? undefined
1791
+ : typeof limitRaw === "number"
1792
+ ? limitRaw
1793
+ : typeof limitRaw === "string"
1794
+ ? /^\d+$/.test(limitRaw)
1795
+ ? Number(limitRaw)
1796
+ : Number.NaN
1797
+ : syntax('Field "limit" must be a number.');
1798
+ const offset = offsetRaw === undefined
1799
+ ? undefined
1800
+ : typeof offsetRaw === "number"
1801
+ ? offsetRaw
1802
+ : typeof offsetRaw === "string"
1803
+ ? /^\d+$/.test(offsetRaw)
1804
+ ? Number(offsetRaw)
1805
+ : Number.NaN
1806
+ : syntax('Field "offset" must be a number.');
1807
+ const refresh = optionalBoolean(body, "refresh");
1808
+ const ctx = await this.createSwarmContext(diagnostic, {
1809
+ forceRefresh: refresh,
1810
+ });
1811
+ try {
1812
+ const searchOptions = {};
1813
+ if (prefix !== undefined)
1814
+ searchOptions.prefix = prefix;
1815
+ if (kind !== undefined)
1816
+ searchOptions.kind = kind;
1817
+ if (schemaCid !== undefined)
1818
+ searchOptions.schemaCid = schemaCid;
1819
+ if (limit !== undefined)
1820
+ searchOptions.limit = limit;
1821
+ if (offset !== undefined)
1822
+ searchOptions.offset = offset;
1823
+ return Object.keys(searchOptions).length
1824
+ ? await searchNames(ctx, q, scope, searchOptions)
1825
+ : await searchNames(ctx, q, scope);
1826
+ }
1827
+ finally {
1828
+ await this.finishSwarmContext(ctx);
1829
+ }
1830
+ }
1831
+ async handleSwarmGovernance(action, body, diagnostic) {
1832
+ const includeSecrets = !(action === "profile" && !optionalString(body, "swarm"));
1833
+ const ctx = await this.createSwarmContext(diagnostic, { includeSecrets });
1834
+ try {
1835
+ switch (action) {
1836
+ case "create": {
1837
+ const service = optionalString(body, "service");
1838
+ const resume = optionalString(body, "resume");
1839
+ const alias = optionalString(body, "alias");
1840
+ const addresses = optionalStringArray(body, "addresses");
1841
+ const name = optionalString(body, "name");
1842
+ const description = optionalString(body, "description");
1843
+ const configUrl = await createSwarm(ctx, {
1844
+ ...defined({ service, resume, alias, addresses }),
1845
+ properties: {
1846
+ name: name ?? "",
1847
+ description: description ?? "",
1848
+ },
1849
+ });
1850
+ this.onSwarmChange?.(configUrl);
1851
+ return {
1852
+ configUrl,
1853
+ alias: this.state.registeredSwarm(configUrl).alias,
1854
+ savedCurrent: this.state.config({ includeSecrets: false })["swarm.default"] ??
1855
+ null,
1856
+ };
1857
+ }
1858
+ case "request": {
1859
+ const swarm = requireSwarmParam(body);
1860
+ const url = this.state.resolveSwarm(swarm);
1861
+ const rawOutput = optionalString(body, "output");
1862
+ const cwd = optionalString(body, "cwd");
1863
+ const output = rawOutput !== undefined &&
1864
+ cwd !== undefined &&
1865
+ !isAbsolute(rawOutput) &&
1866
+ resolve(cwd) !== process.cwd()
1867
+ ? resolve(cwd, rawOutput)
1868
+ : rawOutput;
1869
+ const roleRaw = optionalString(body, "role");
1870
+ const role = roleRaw === undefined
1871
+ ? undefined
1872
+ : roleRaw === "pivot" || roleRaw === "ordinary"
1873
+ ? roleRaw
1874
+ : syntax('Field "role" must be "ordinary" or "pivot".');
1875
+ return requestMembership(ctx, url, defined({ output, role }));
1876
+ }
1877
+ case "approve": {
1878
+ const input = body.request ?? body.input;
1879
+ if (typeof input !== "string" &&
1880
+ (!input || typeof input !== "object")) {
1881
+ syntax('Field "input" or "request" is required for approve.');
1882
+ }
1883
+ const again = optionalBoolean(body, "again");
1884
+ const pivot = optionalBoolean(body, "pivot");
1885
+ const approved = await approveMembership(ctx, input, defined({ again, pivot }));
1886
+ this.onSwarmChange?.();
1887
+ return { approved };
1888
+ }
1889
+ case "pivot-grant": {
1890
+ const swarm = requireSwarmParam(body);
1891
+ const url = this.state.resolveSwarm(swarm);
1892
+ const member = requireString(body, "member");
1893
+ const granted = await grantPivotAuthority(ctx, url, member);
1894
+ this.onSwarmChange?.(url);
1895
+ return granted;
1896
+ }
1897
+ case "export": {
1898
+ const swarm = requireSwarmParam(body);
1899
+ const url = this.state.resolveSwarm(swarm);
1900
+ const output = optionalString(body, "output") ?? "";
1901
+ const member = await exportRequest(ctx, url, output);
1902
+ return { member, file: member };
1903
+ }
1904
+ case "exclude": {
1905
+ const swarm = requireSwarmParam(body);
1906
+ const url = this.state.resolveSwarm(swarm);
1907
+ const member = requireString(body, "member");
1908
+ await removeMember(ctx, url, member);
1909
+ this.onSwarmChange?.(url);
1910
+ return { swarm: url, excluded: member };
1911
+ }
1912
+ case "resume": {
1913
+ const swarm = requireSwarmParam(body);
1914
+ const url = this.state.resolveSwarm(swarm);
1915
+ await resumeRemoval(ctx, url);
1916
+ this.onSwarmChange?.(url);
1917
+ return { swarm: url, resumed: true };
1918
+ }
1919
+ case "profile": {
1920
+ const swarm = optionalString(body, "swarm");
1921
+ if (swarm) {
1922
+ const url = this.state.resolveSwarm(swarm);
1923
+ const addresses = optionalStringArray(body, "addresses");
1924
+ const pivot = optionalBoolean(body, "pivot");
1925
+ const updated = await updateProfile(ctx, url, defined({ addresses, pivot }));
1926
+ this.onSwarmChange?.(url);
1927
+ return updated;
1928
+ }
1929
+ const name = optionalString(body, "name");
1930
+ const description = optionalString(body, "description");
1931
+ const updated = await updateAccountProfile(ctx, defined({ name, description }));
1932
+ this.onSwarmChange?.();
1933
+ return updated;
1934
+ }
1935
+ default:
1936
+ throw new HostError(`Unknown swarm governance action "${action}".`, 2, "UNKNOWN_ACTION", "swarm");
1937
+ }
1938
+ }
1939
+ finally {
1940
+ await this.finishSwarmContext(ctx);
1941
+ }
1942
+ }
1943
+ // ---- Runs domain handlers ----
1944
+ async handleRunPrepare(body, signal, diagnostic) {
1945
+ const origin = optionalString(body, "origin");
1946
+ if (origin !== "open" && origin !== "exec") {
1947
+ syntax('Field "origin" must be "open" or "exec".');
1948
+ }
1949
+ const history = optionalBoolean(body, "history") ??
1950
+ Boolean(this.configValue("history.enabled"));
1951
+ const retain = optionalBoolean(body, "retain") ??
1952
+ this.configValue("output.retention") === "history";
1953
+ const log = optionalBoolean(body, "log") ?? false;
1954
+ if (log && !history) {
1955
+ throw new HostError("Execution logging requires history.enabled=true.");
1956
+ }
1957
+ const raw = optionalBoolean(body, "raw") ?? false;
1958
+ const refresh = optionalBoolean(body, "refresh");
1959
+ const swarm = optionalString(body, "swarm");
1960
+ const rawTarget = optionalString(body, "target");
1961
+ let appCid = optionalString(body, "appCid");
1962
+ let argv = optionalStringArray(body, "argv") ?? [];
1963
+ let inputSchema = optionalString(body, "inputSchema");
1964
+ const store = await this.getStore();
1965
+ await recoverInactive(this.state, storeFactoryFor(store));
1966
+ const id = randomUUID();
1967
+ const session = `ipab-output:${this.state.identity}:${id}`;
1968
+ const owner = await Ownership.create(this.state, store, `run:${id}`, session);
1969
+ const controller = new AbortController();
1970
+ const output = new OutputSpace(store, owner, session, controller.signal);
1971
+ const directory = join(this.state.directory, "runtime", id);
1972
+ const entryPath = join(directory, "app.cjs");
1973
+ let directoryCreated = false;
1974
+ let entryCreated = false;
1975
+ let localInputUsed = false;
1976
+ let resolvedAppCidForHistory;
1977
+ const startedAt = new Date().toISOString();
1978
+ const cleanupOnFailure = async (cause) => {
1979
+ if (entryCreated)
1980
+ await unlink(entryPath).catch(() => { });
1981
+ if (directoryCreated)
1982
+ await rmdir(directory).catch(() => { });
1983
+ if (history && resolvedAppCidForHistory) {
1984
+ const failedRecord = {
1985
+ id,
1986
+ origin,
1987
+ appCid: resolvedAppCidForHistory,
1988
+ argv,
1989
+ startedAt,
1990
+ endedAt: new Date().toISOString(),
1991
+ status: "failed",
1992
+ outputCid: null,
1993
+ appExitCode: null,
1994
+ error: {
1995
+ phase: cause instanceof HostError ? cause.phase : "validation",
1996
+ code: cause instanceof HostError ? cause.code : "OPERATION_FAILED",
1997
+ message: message(cause),
1998
+ },
1999
+ retention: { owned: false, state: "none" },
2000
+ };
2001
+ await saveHistory(this.state, store, failedRecord, retain).catch(() => { });
2002
+ }
2003
+ await owner.release().catch(() => { });
2004
+ };
2005
+ const swarmCtx = await this.createSwarmContext(diagnostic, {
2006
+ forceRefresh: refresh,
2007
+ });
2008
+ try {
2009
+ signal.throwIfAborted();
2010
+ // Resolve target if origin === "open"
2011
+ let resolvedTargetCid;
2012
+ if (origin === "open" && rawTarget) {
2013
+ const named = parseNameReference(rawTarget);
2014
+ const registrySwarm = named?.swarm
2015
+ ? this.state.resolveSwarm(named.swarm)
2016
+ : swarm
2017
+ ? this.state.resolveSwarm(swarm)
2018
+ : undefined;
2019
+ if (!appCid && !registrySwarm) {
2020
+ throw new HostError("Open requires a selected Swarm. Use ipab://URL_OR_ALIAS/PATH, pass --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS. To select an App directly, use ipab exec.");
2021
+ }
2022
+ const localInput = await resolveLocalBundleInput(rawTarget);
2023
+ if (localInput) {
2024
+ localInputUsed = true;
2025
+ resolvedTargetCid = await snapshotLocalBundle(localInput, owner, session, {
2026
+ signal,
2027
+ diagnostic: (text) => {
2028
+ diagnostic(text);
2029
+ },
2030
+ });
2031
+ }
2032
+ else {
2033
+ const resolved = await resolveReference(swarmCtx, rawTarget, swarm ? this.state.resolveSwarm(swarm) : undefined, (localRef) => this.state.resolve(localRef), raw, "local-first");
2034
+ resolvedTargetCid = resolved.cid;
2035
+ }
2036
+ const content = await validatedBundle(resolvedTargetCid, swarmCtx.store, owner);
2037
+ inputSchema ??= content.schemaKey;
2038
+ if (!appCid) {
2039
+ const association = await swarmAssociation(swarmCtx, registrySwarm, inputSchema, "local-first");
2040
+ if (!association) {
2041
+ throw new HostError(`No App registered for Schema ${inputSchema} in Swarm ${registrySwarm}. Use ipab register set ${inputSchema} APP_CID --swarm ${registrySwarm} or ipab exec.`, 1, "NO_ASSOCIATION", "validation");
2042
+ }
2043
+ if (association.argv.length !== 1 || association.argv[0] !== "%") {
2044
+ throw new HostError("Custom per-association argv is unsupported; adapt the App to accept only the content CID or use ipab exec APP_CID ARGS.");
2045
+ }
2046
+ appCid = association.appCid;
2047
+ if (!argv.length) {
2048
+ argv = [resolvedTargetCid];
2049
+ }
2050
+ }
2051
+ }
2052
+ if (!appCid) {
2053
+ syntax('Field "appCid" is required for exec (or open without registration).');
2054
+ }
2055
+ // Support local directory, CAR, Swarm URI, builtin alias, or exact CID for exec appCid
2056
+ if (origin === "exec") {
2057
+ const localApp = await resolveLocalBundleInput(appCid);
2058
+ if (localApp) {
2059
+ localInputUsed = true;
2060
+ appCid = await snapshotLocalBundle(localApp, owner, session, {
2061
+ signal,
2062
+ diagnostic: (text) => {
2063
+ diagnostic(text);
2064
+ },
2065
+ });
2066
+ }
2067
+ else {
2068
+ appCid = (await resolveReference(swarmCtx, appCid, swarm ? this.state.resolveSwarm(swarm) : undefined, (localRef) => this.state.resolve(localRef), raw, "local-first")).cid;
2069
+ }
2070
+ }
2071
+ else {
2072
+ appCid = exactCid(appCid);
2073
+ }
2074
+ resolvedAppCidForHistory = appCid;
2075
+ const app = await loadApp(appCid, swarmCtx.store, owner, signal);
2076
+ if (origin === "open" && !app.supportedSchemas.has(inputSchema ?? "")) {
2077
+ throw new HostError(`Registered App ${appCid} does not declare support for Schema ${inputSchema ?? "(missing)"}. Rebuild the App with this complete definition in ipab.yaml supportedSchemas and update its pin/register association, or use ipab exec explicitly.`, 1, "APP_SCHEMA_UNSUPPORTED", "validation");
2078
+ }
2079
+ const runtimeDir = join(this.state.directory, "runtime");
2080
+ await mkdir(runtimeDir, { recursive: true, mode: 0o700 });
2081
+ await mkdir(directory, { mode: 0o700 });
2082
+ directoryCreated = true;
2083
+ await writeFile(entryPath, app.source, { flag: "wx", mode: 0o600 });
2084
+ entryCreated = true;
2085
+ const selectedSwarmUrl = swarm
2086
+ ? this.state.resolveSwarm(swarm)
2087
+ : undefined;
2088
+ const resolveBundleRef = async (reference, reqSignal, preferredSwarm) => {
2089
+ reqSignal.throwIfAborted();
2090
+ const lookup = await this.createSwarmContext(diagnostic, {
2091
+ forceRefresh: refresh,
2092
+ });
2093
+ try {
2094
+ const named = parseNameReference(reference);
2095
+ const targetSwarm = named?.swarm
2096
+ ? this.state.resolveSwarm(named.swarm)
2097
+ : preferredSwarm
2098
+ ? this.state.resolveSwarm(preferredSwarm)
2099
+ : selectedSwarmUrl;
2100
+ const doResolve = (source) => resolveReference(lookup, reference, source, (localRef) => this.state.resolve(localRef), false, "local-first");
2101
+ let resolved;
2102
+ try {
2103
+ resolved = await doResolve(named ? targetSwarm : undefined);
2104
+ }
2105
+ catch (cause) {
2106
+ let failure = cause;
2107
+ for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++) {
2108
+ failure = failure.cause;
2109
+ }
2110
+ if (named ||
2111
+ !targetSwarm ||
2112
+ !(failure instanceof ContentError) ||
2113
+ failure.code !== "missing_block") {
2114
+ throw cause;
2115
+ }
2116
+ reqSignal.throwIfAborted();
2117
+ resolved = await doResolve(targetSwarm);
2118
+ }
2119
+ reqSignal.throwIfAborted();
2120
+ return {
2121
+ ...resolved,
2122
+ ...(targetSwarm ? { swarm: targetSwarm } : {}),
2123
+ };
2124
+ }
2125
+ finally {
2126
+ await this.finishSwarmContext(lookup);
2127
+ }
2128
+ };
2129
+ const handler = new ContextHandler(store, owner, output, appCid, resolveBundleRef, app.supportedSchemas);
2130
+ const record = {
2131
+ id,
2132
+ origin,
2133
+ appCid,
2134
+ argv,
2135
+ startedAt,
2136
+ endedAt: "",
2137
+ status: "failed",
2138
+ outputCid: null,
2139
+ appExitCode: null,
2140
+ ...(log ? { log: "incomplete" } : {}),
2141
+ error: null,
2142
+ retention: { owned: false, state: "none" },
2143
+ };
2144
+ this.activeRuns.set(id, {
2145
+ id,
2146
+ record,
2147
+ owner,
2148
+ output,
2149
+ handler,
2150
+ controller,
2151
+ directory,
2152
+ entryPath,
2153
+ directoryCreated,
2154
+ entryCreated,
2155
+ history,
2156
+ retain,
2157
+ log,
2158
+ finished: false,
2159
+ });
2160
+ return {
2161
+ runId: id,
2162
+ origin,
2163
+ appCid,
2164
+ entryPath,
2165
+ argv,
2166
+ localInput: localInputUsed,
2167
+ ...(resolvedTargetCid ? { targetCid: resolvedTargetCid } : {}),
2168
+ ...(inputSchema ? { inputSchema } : {}),
2169
+ supportedSchemas: [...app.supportedSchemas],
2170
+ logConfig: log
2171
+ ? { enabled: true, stateDir: this.state.directory, runId: id }
2172
+ : { enabled: false },
2173
+ };
2174
+ }
2175
+ catch (cause) {
2176
+ await cleanupOnFailure(cause);
2177
+ throw cause;
2178
+ }
2179
+ finally {
2180
+ await this.finishSwarmContext(swarmCtx);
2181
+ }
2182
+ }
2183
+ async handleRunIpc(runId, body, signal) {
2184
+ const session = this.activeRuns.get(runId);
2185
+ if (!session || session.finished) {
2186
+ throw new HostError(`Active run "${runId}" not found.`, 1, "NOT_FOUND", "execution");
2187
+ }
2188
+ const operation = requireString(body, "operation");
2189
+ const args = decodeIpcValue(body.args);
2190
+ const combinedSignal = AbortSignal.any([signal, session.controller.signal]);
2191
+ const result = await session.handler.handle(operation, args, combinedSignal);
2192
+ if (combinedSignal.aborted) {
2193
+ if (operation === "read") {
2194
+ await session.handler.cancelRead(Number(result), combinedSignal.reason);
2195
+ }
2196
+ if (["link", "beginOpenSession", "cancelOpenSession"].includes(operation)) {
2197
+ session.output.fail(combinedSignal.reason);
2198
+ }
2199
+ if (operation === "submitBundleResult") {
2200
+ session.output.discardBundleResult();
2201
+ }
2202
+ combinedSignal.throwIfAborted();
2203
+ }
2204
+ return { result: encodeIpcValue(result) };
2205
+ }
2206
+ async handleRunFinish(runId, body, diagnostic) {
2207
+ const session = this.activeRuns.get(runId);
2208
+ if (!session || session.finished) {
2209
+ throw new HostError(`Active run "${runId}" not found.`, 1, "NOT_FOUND", "execution");
2210
+ }
2211
+ const code = body.code === null || body.code === undefined
2212
+ ? null
2213
+ : typeof body.code === "number"
2214
+ ? body.code
2215
+ : syntax('Field "code" must be a number or null.');
2216
+ const procSignal = optionalString(body, "signal") ?? null;
2217
+ const logComplete = optionalBoolean(body, "logComplete");
2218
+ const logFailure = optionalString(body, "logFailure");
2219
+ const fatalError = optionalString(body, "fatalError");
2220
+ const cancellation = optionalNumber(body, "cancellation") ?? 0;
2221
+ session.finished = true;
2222
+ const { record, output, handler } = session;
2223
+ record.appExitCode = code;
2224
+ let exitCode;
2225
+ let phase = "execution";
2226
+ try {
2227
+ if (session.log) {
2228
+ if (logFailure) {
2229
+ throw new HostError(`Execution logging failed: ${logFailure}`, 1, "LOG_FAILED", "logging");
2230
+ }
2231
+ record.log = logComplete ? "complete" : "incomplete";
2232
+ }
2233
+ await handler.close();
2234
+ if (fatalError && !cancellation) {
2235
+ throw new HostError(fatalError, 1, "EXECUTION_FAILED", "execution");
2236
+ }
2237
+ if (cancellation || procSignal) {
2238
+ const cancelCode = cancellation || (procSignal === "SIGINT" ? 130 : 143);
2239
+ throw new HostError("Execution cancelled.", cancelCode, "CANCELLED", "execution");
2240
+ }
2241
+ if (code !== 0) {
2242
+ throw new HostError(`App exited with code ${code}.`, code ?? 1, "APP_EXIT", "execution");
2243
+ }
2244
+ phase = "commit";
2245
+ const outputCid = await output.finalize();
2246
+ record.outputCid = outputCid;
2247
+ record.status = "succeeded";
2248
+ exitCode = 0;
2249
+ }
2250
+ catch (error) {
2251
+ const failure = error instanceof HostError
2252
+ ? error
2253
+ : new HostError(message(error), 1, "EXECUTION_FAILED", phase);
2254
+ record.status =
2255
+ cancellation || failure.code === "CANCELLED" ? "cancelled" : "failed";
2256
+ record.error = {
2257
+ phase: failure.phase === "state" ? phase : failure.phase,
2258
+ code: failure.code,
2259
+ message: message(failure),
2260
+ };
2261
+ exitCode =
2262
+ cancellation ||
2263
+ (record.appExitCode && record.appExitCode !== 0
2264
+ ? record.appExitCode
2265
+ : failure.exitCode);
2266
+ diagnostic(`Error: ${message(failure)}`);
2267
+ }
2268
+ finally {
2269
+ await this.finalizeRunCleanup(session, diagnostic);
2270
+ }
2271
+ return { exitCode, record };
2272
+ }
2273
+ async handleRunCancel(runId, body, diagnostic) {
2274
+ const code = optionalNumber(body, "exitCode") ?? 130;
2275
+ const reason = optionalString(body, "reason") ?? "Execution cancelled.";
2276
+ return this.cancelRunSession(runId, code, reason, diagnostic);
2277
+ }
2278
+ async cancelRunSession(runId, cancelCode, reason, diagnostic) {
2279
+ const session = this.activeRuns.get(runId);
2280
+ if (!session || session.finished) {
2281
+ throw new HostError(`Active run "${runId}" not found.`, 1, "NOT_FOUND", "execution");
2282
+ }
2283
+ session.finished = true;
2284
+ const error = new HostError(reason, cancelCode, "CANCELLED", "execution");
2285
+ session.controller.abort(error);
2286
+ session.record.status = "cancelled";
2287
+ session.record.error = {
2288
+ phase: "execution",
2289
+ code: "CANCELLED",
2290
+ message: reason,
2291
+ };
2292
+ diagnostic?.(`Error: ${reason}`);
2293
+ await this.finalizeRunCleanup(session, diagnostic);
2294
+ return { exitCode: cancelCode, record: session.record };
2295
+ }
2296
+ async finalizeRunCleanup(session, diagnostic) {
2297
+ const { record, owner, handler } = session;
2298
+ this.activeRuns.delete(session.id);
2299
+ try {
2300
+ await handler.close();
2301
+ }
2302
+ catch {
2303
+ // Best-effort close.
2304
+ }
2305
+ try {
2306
+ if (session.entryCreated)
2307
+ await unlink(session.entryPath);
2308
+ if (session.directoryCreated)
2309
+ await rmdir(session.directory);
2310
+ }
2311
+ catch (cause) {
2312
+ diagnostic?.(`Error: cleanup failed: ${message(cause)}`);
2313
+ }
2314
+ record.endedAt = new Date().toISOString();
2315
+ if (session.history) {
2316
+ const store = await this.getStore();
2317
+ await saveHistory(this.state, store, record, session.retain);
2318
+ }
2319
+ else if (record.outputCid && session.retain) {
2320
+ diagnostic?.("History is disabled: output has no history-owned retention and may be reclaimed by its backend.");
2321
+ }
2322
+ await owner.release();
2323
+ if (session.history) {
2324
+ this.state.transaction(() => {
2325
+ if (this.state.db
2326
+ .prepare("SELECT id FROM runs WHERE id=?")
2327
+ .get(session.id)) {
2328
+ const current = this.state.run(session.id);
2329
+ if (current.retention.state === "releasing") {
2330
+ record.retention = current.retention;
2331
+ }
2332
+ this.state.saveRun(record);
2333
+ }
2334
+ });
2335
+ diagnostic?.(`Execution: ${session.id}`);
2336
+ }
2337
+ if (record.outputCid) {
2338
+ diagnostic?.(`Output: ${record.outputCid}`);
2339
+ }
2340
+ }
2341
+ handleRunsList(body) {
2342
+ const filterOptions = {};
2343
+ const app = optionalString(body, "app");
2344
+ const status = optionalString(body, "status");
2345
+ const since = optionalString(body, "since");
2346
+ const until = optionalString(body, "until");
2347
+ if (app !== undefined)
2348
+ filterOptions.app = app;
2349
+ if (status !== undefined)
2350
+ filterOptions.status = status;
2351
+ if (since !== undefined)
2352
+ filterOptions.since = since;
2353
+ if (until !== undefined)
2354
+ filterOptions.until = until;
2355
+ const filter = filters(this.state, filterOptions);
2356
+ const limit = optionalNumber(body, "limit") ??
2357
+ Number(this.configValue("history.limit"));
2358
+ const rawBefore = optionalString(body, "before");
2359
+ const before = rawBefore !== undefined ? this.state.resolveRunId(rawBefore) : undefined;
2360
+ const page = listHistory(this.state, filter, limit, before);
2361
+ const pinNames = {};
2362
+ for (const pin of this.state.pins()) {
2363
+ if (pin.status === "ready" && !pinNames[pin.cid]) {
2364
+ pinNames[pin.cid] = pin.name;
2365
+ }
2366
+ }
2367
+ return {
2368
+ ...page,
2369
+ shortNextBefore: page.nextBefore
2370
+ ? this.state.shortRunId(page.nextBefore)
2371
+ : null,
2372
+ pinNames,
2373
+ };
2374
+ }
2375
+ async handleRunsRemove(body) {
2376
+ const explicitIds = optionalStringArray(body, "ids");
2377
+ let ids;
2378
+ if (explicitIds && explicitIds.length > 0) {
2379
+ ids = [...new Set(explicitIds.map((id) => this.state.resolveRunId(id)))];
2380
+ }
2381
+ else {
2382
+ const filterOptions = {};
2383
+ const app = optionalString(body, "app");
2384
+ const status = optionalString(body, "status");
2385
+ const since = optionalString(body, "since");
2386
+ const until = optionalString(body, "until");
2387
+ if (app !== undefined)
2388
+ filterOptions.app = app;
2389
+ if (status !== undefined)
2390
+ filterOptions.status = status;
2391
+ if (since !== undefined)
2392
+ filterOptions.since = since;
2393
+ if (until !== undefined)
2394
+ filterOptions.until = until;
2395
+ const filter = filters(this.state, filterOptions);
2396
+ ids = selectedIds(this.state, filter);
2397
+ }
2398
+ for (const id of ids)
2399
+ this.state.run(id);
2400
+ if (optionalBoolean(body, "dryRun")) {
2401
+ return { ids };
2402
+ }
2403
+ const store = await this.getStore();
2404
+ return removeHistory(this.state, ids, storeFactoryFor(store));
2405
+ }
2406
+ }
2407
+ export function createDaemonApiHandler(service) {
2408
+ return (request, response) => service.handleRequest(request, response);
2409
+ }
2410
+ export { isLocalSwarm };
2411
+ //# sourceMappingURL=daemon-api.js.map