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

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 (71) hide show
  1. package/dist/cli-daemon.d.ts +14 -0
  2. package/dist/cli-daemon.d.ts.map +1 -0
  3. package/dist/cli-daemon.js +400 -0
  4. package/dist/cli-daemon.js.map +1 -0
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +1260 -1404
  7. package/dist/cli.js.map +1 -1
  8. package/dist/daemon-api.d.ts +80 -0
  9. package/dist/daemon-api.d.ts.map +1 -0
  10. package/dist/daemon-api.js +2411 -0
  11. package/dist/daemon-api.js.map +1 -0
  12. package/dist/daemon-client.d.ts +322 -0
  13. package/dist/daemon-client.d.ts.map +1 -0
  14. package/dist/daemon-client.js +400 -0
  15. package/dist/daemon-client.js.map +1 -0
  16. package/dist/daemon-protocol.d.ts +22 -0
  17. package/dist/daemon-protocol.d.ts.map +1 -0
  18. package/dist/daemon-protocol.js +39 -0
  19. package/dist/daemon-protocol.js.map +1 -0
  20. package/dist/daemon-telemetry.d.ts +86 -0
  21. package/dist/daemon-telemetry.d.ts.map +1 -0
  22. package/dist/daemon-telemetry.js +502 -0
  23. package/dist/daemon-telemetry.js.map +1 -0
  24. package/dist/daemon-ui.d.ts +68 -0
  25. package/dist/daemon-ui.d.ts.map +1 -1
  26. package/dist/daemon-ui.js +283 -4
  27. package/dist/daemon-ui.js.map +1 -1
  28. package/dist/daemon.d.ts +10 -0
  29. package/dist/daemon.d.ts.map +1 -1
  30. package/dist/daemon.js +289 -38
  31. package/dist/daemon.js.map +1 -1
  32. package/dist/identity.d.ts.map +1 -1
  33. package/dist/identity.js +7 -2
  34. package/dist/identity.js.map +1 -1
  35. package/dist/ipc.d.ts +19 -7
  36. package/dist/ipc.d.ts.map +1 -1
  37. package/dist/ipc.js +96 -70
  38. package/dist/ipc.js.map +1 -1
  39. package/dist/pins.d.ts.map +1 -1
  40. package/dist/pins.js +18 -3
  41. package/dist/pins.js.map +1 -1
  42. package/dist/state-storage.d.ts.map +1 -1
  43. package/dist/state-storage.js +2 -1
  44. package/dist/state-storage.js.map +1 -1
  45. package/dist/state.d.ts +1 -1
  46. package/dist/state.d.ts.map +1 -1
  47. package/dist/state.js +3 -2
  48. package/dist/state.js.map +1 -1
  49. package/dist/swarm-files.d.ts.map +1 -1
  50. package/dist/swarm-files.js +7 -2
  51. package/dist/swarm-files.js.map +1 -1
  52. package/dist/swarm.d.ts +10 -1
  53. package/dist/swarm.d.ts.map +1 -1
  54. package/dist/swarm.js +230 -56
  55. package/dist/swarm.js.map +1 -1
  56. package/package.json +4 -4
  57. package/src/cli-daemon.ts +482 -0
  58. package/src/cli.ts +1689 -1948
  59. package/src/daemon-api.ts +3148 -0
  60. package/src/daemon-client.ts +975 -0
  61. package/src/daemon-protocol.ts +61 -0
  62. package/src/daemon-telemetry.ts +656 -0
  63. package/src/daemon-ui.ts +361 -4
  64. package/src/daemon.ts +337 -43
  65. package/src/identity.ts +10 -2
  66. package/src/ipc.ts +113 -79
  67. package/src/pins.ts +23 -3
  68. package/src/state-storage.ts +5 -1
  69. package/src/state.ts +3 -1
  70. package/src/swarm-files.ts +10 -2
  71. package/src/swarm.ts +698 -464
@@ -0,0 +1,975 @@
1
+ import { request as httpRequest } from "node:http";
2
+ import {
3
+ daemonClientEndpoint,
4
+ ensureDaemon,
5
+ type DaemonClientEndpointInfo,
6
+ } from "./daemon.js";
7
+ import {
8
+ decodeIpcValue,
9
+ encodeIpcValue,
10
+ type DaemonErrorPayload,
11
+ type DaemonNdjsonFrame,
12
+ } from "./daemon-protocol.js";
13
+ import { HostError } from "./host-error.js";
14
+ import type { ConfigItem, ConfigKey, ConfigValue } from "./config.js";
15
+ import type {
16
+ ContentPin,
17
+ NamedPin,
18
+ RegisteredSwarm,
19
+ RunRecord,
20
+ } from "./state.js";
21
+ import type {
22
+ RemoveSwarmFsPathResult,
23
+ SetSwarmFsPathResult,
24
+ SwarmFsListResult,
25
+ SwarmFsStatResult,
26
+ } from "./swarm-fs-core.js";
27
+
28
+ export interface DaemonClientOptions {
29
+ stateDir: string;
30
+ env?: NodeJS.ProcessEnv;
31
+ endpoint?: DaemonClientEndpointInfo;
32
+ autoStart?: boolean;
33
+ onDiagnostic?: (text: string, progress?: boolean) => void;
34
+ onAbortRequest?: (reason: Error) => void;
35
+ fetch?: typeof fetch;
36
+ }
37
+
38
+ export interface DaemonRequestOptions {
39
+ signal?: AbortSignal;
40
+ ndjson?: boolean;
41
+ onDiagnostic?: (text: string, progress?: boolean) => void;
42
+ }
43
+
44
+ export interface PreparedRun {
45
+ runId: string;
46
+ origin: "open" | "exec";
47
+ appCid: string;
48
+ entryPath: string;
49
+ argv: string[];
50
+ localInput?: boolean;
51
+ targetCid?: string;
52
+ inputSchema?: string;
53
+ supportedSchemas: string[];
54
+ logConfig:
55
+ { enabled: false } | { enabled: true; stateDir: string; runId: string };
56
+ }
57
+
58
+ function toHostError(payload: unknown, fallbackStatus: number): HostError {
59
+ if (payload && typeof payload === "object") {
60
+ const record = payload as Partial<DaemonErrorPayload>;
61
+ if (typeof record.message === "string") {
62
+ return new HostError(
63
+ record.message,
64
+ typeof record.exitCode === "number" ? record.exitCode : 1,
65
+ typeof record.code === "string" ? record.code : "DAEMON_ERROR",
66
+ typeof record.phase === "string" ? record.phase : "daemon",
67
+ );
68
+ }
69
+ }
70
+ return new HostError(
71
+ `Daemon request failed with HTTP ${fallbackStatus}.`,
72
+ 1,
73
+ "DAEMON_ERROR",
74
+ "daemon",
75
+ );
76
+ }
77
+
78
+ export class DaemonClient {
79
+ private readonly stateDir: string;
80
+ private readonly env: NodeJS.ProcessEnv;
81
+ private readonly autoStart: boolean;
82
+ private readonly onDiagnostic:
83
+ ((text: string, progress?: boolean) => void) | undefined;
84
+ private readonly onAbortRequest: ((reason: Error) => void) | undefined;
85
+ private readonly customFetcher: typeof fetch | undefined;
86
+ private cachedEndpoint: DaemonClientEndpointInfo | undefined;
87
+
88
+ constructor(options: DaemonClientOptions) {
89
+ this.stateDir = options.stateDir;
90
+ this.env = options.env ?? process.env;
91
+ this.autoStart = options.autoStart ?? true;
92
+ this.onDiagnostic = options.onDiagnostic;
93
+ this.onAbortRequest = options.onAbortRequest;
94
+ this.customFetcher = options.fetch;
95
+ this.cachedEndpoint = options.endpoint;
96
+ }
97
+
98
+ async resolveEndpoint(): Promise<DaemonClientEndpointInfo> {
99
+ if (this.cachedEndpoint) return this.cachedEndpoint;
100
+ let endpoint = await daemonClientEndpoint(this.stateDir);
101
+ if (!endpoint && this.autoStart) {
102
+ await ensureDaemon(this.stateDir, this.env, (text) => {
103
+ this.onDiagnostic?.(text);
104
+ });
105
+ endpoint = await daemonClientEndpoint(this.stateDir);
106
+ }
107
+ if (!endpoint) {
108
+ throw new HostError(
109
+ "IPAB daemon is not running and could not be reached.",
110
+ 1,
111
+ "DAEMON_UNAVAILABLE",
112
+ "daemon",
113
+ );
114
+ }
115
+ this.cachedEndpoint = endpoint;
116
+ return endpoint;
117
+ }
118
+
119
+ invalidateEndpoint(): void {
120
+ this.cachedEndpoint = undefined;
121
+ }
122
+
123
+ async request<T = unknown>(
124
+ method: "GET" | "POST" | "PUT" | "DELETE",
125
+ path: string,
126
+ body?: unknown,
127
+ options: DaemonRequestOptions = {},
128
+ ): Promise<T> {
129
+ const endpoint = await this.resolveEndpoint();
130
+ const headers: Record<string, string> = {
131
+ host: `127.0.0.1:${endpoint.port}`,
132
+ authorization: `Bearer ${endpoint.token}`,
133
+ accept: options.ndjson
134
+ ? "application/x-ndjson, application/json"
135
+ : "application/json",
136
+ };
137
+ let serializedBody: string | undefined;
138
+ if (body !== undefined && method !== "GET" && method !== "DELETE") {
139
+ headers["content-type"] = "application/json";
140
+ serializedBody = JSON.stringify(body);
141
+ }
142
+
143
+ if (this.customFetcher) {
144
+ const url = `http://127.0.0.1:${endpoint.port}${path}`;
145
+ const init: RequestInit = {
146
+ method,
147
+ headers,
148
+ redirect: "error",
149
+ cache: "no-store",
150
+ ...(options.signal ? { signal: options.signal } : {}),
151
+ ...(serializedBody !== undefined ? { body: serializedBody } : {}),
152
+ };
153
+ const response = await this.customFetcher(url, init);
154
+ const contentType = (
155
+ response.headers.get("content-type") ?? ""
156
+ ).toLowerCase();
157
+
158
+ if (contentType.includes("application/x-ndjson")) {
159
+ return this.readNdjsonResponse<T>(
160
+ response,
161
+ options.onDiagnostic ?? this.onDiagnostic,
162
+ );
163
+ }
164
+
165
+ const text = await response.text();
166
+ return this.parseJsonResponse<T>(text, response.ok, response.status);
167
+ }
168
+
169
+ return this.requestLoopbackHttp<T>(
170
+ endpoint,
171
+ method,
172
+ path,
173
+ headers,
174
+ serializedBody,
175
+ options,
176
+ );
177
+ }
178
+
179
+ private parseJsonResponse<T>(text: string, ok: boolean, status: number): T {
180
+ let parsed: unknown;
181
+ if (text.length > 0) {
182
+ try {
183
+ parsed = JSON.parse(text) as unknown;
184
+ } catch {
185
+ if (!ok) {
186
+ throw new HostError(
187
+ text || `Daemon request failed with HTTP ${status}.`,
188
+ 1,
189
+ "DAEMON_ERROR",
190
+ "daemon",
191
+ );
192
+ }
193
+ throw new HostError(
194
+ "Daemon returned invalid JSON.",
195
+ 1,
196
+ "DAEMON_PROTOCOL_ERROR",
197
+ "daemon",
198
+ );
199
+ }
200
+ }
201
+ if (!ok) {
202
+ throw toHostError(parsed, status);
203
+ }
204
+ return parsed as T;
205
+ }
206
+
207
+ private requestLoopbackHttp<T>(
208
+ endpoint: DaemonClientEndpointInfo,
209
+ method: "GET" | "POST" | "PUT" | "DELETE",
210
+ path: string,
211
+ headers: Record<string, string>,
212
+ serializedBody: string | undefined,
213
+ options: DaemonRequestOptions,
214
+ ): Promise<T> {
215
+ if (options.signal?.aborted) {
216
+ return Promise.reject(
217
+ options.signal.reason instanceof Error
218
+ ? options.signal.reason
219
+ : new HostError("Request cancelled.", 130, "CANCELLED", "daemon"),
220
+ );
221
+ }
222
+ const onDiagnostic = options.onDiagnostic ?? this.onDiagnostic;
223
+ if (serializedBody !== undefined) {
224
+ headers["content-length"] = String(Buffer.byteLength(serializedBody));
225
+ }
226
+ return new Promise<T>((accept, reject) => {
227
+ let settled = false;
228
+ const done = (fn: () => void) => {
229
+ if (settled) return;
230
+ settled = true;
231
+ options.signal?.removeEventListener("abort", onAbort);
232
+ fn();
233
+ };
234
+
235
+ const req = httpRequest(
236
+ {
237
+ host: "127.0.0.1",
238
+ port: endpoint.port,
239
+ path,
240
+ method,
241
+ headers,
242
+ },
243
+ (res) => {
244
+ const status = res.statusCode ?? 0;
245
+ const ok = status >= 200 && status < 300;
246
+ const contentType = String(
247
+ res.headers["content-type"] ?? "",
248
+ ).toLowerCase();
249
+
250
+ if (contentType.includes("application/x-ndjson")) {
251
+ const decoder = new TextDecoder("utf-8");
252
+ let buffer = "";
253
+ const outcome: { hasResult: boolean; data: unknown } = {
254
+ hasResult: false,
255
+ data: undefined,
256
+ };
257
+ const processLine = (line: string) => {
258
+ const trimmed = line.trim();
259
+ if (!trimmed) return;
260
+ let frame: DaemonNdjsonFrame;
261
+ try {
262
+ frame = JSON.parse(trimmed) as DaemonNdjsonFrame;
263
+ } catch {
264
+ throw new HostError(
265
+ "Daemon emitted invalid NDJSON frame.",
266
+ 1,
267
+ "DAEMON_PROTOCOL_ERROR",
268
+ "daemon",
269
+ );
270
+ }
271
+ if (frame.type === "diagnostic") {
272
+ onDiagnostic?.(frame.text, frame.progress);
273
+ } else if (frame.type === "result") {
274
+ outcome.hasResult = true;
275
+ outcome.data = frame.data;
276
+ } else {
277
+ throw toHostError(frame, status);
278
+ }
279
+ };
280
+ res.on("data", (chunk: Buffer) => {
281
+ if (settled) return;
282
+ try {
283
+ buffer += decoder.decode(chunk, { stream: true });
284
+ for (;;) {
285
+ const newlineIndex = buffer.indexOf("\n");
286
+ if (newlineIndex === -1) break;
287
+ const line = buffer.slice(0, newlineIndex);
288
+ buffer = buffer.slice(newlineIndex + 1);
289
+ processLine(line);
290
+ }
291
+ } catch (cause) {
292
+ res.destroy();
293
+ done(() => {
294
+ reject(
295
+ cause instanceof Error ? cause : new Error(String(cause)),
296
+ );
297
+ });
298
+ }
299
+ });
300
+ res.on("end", () => {
301
+ if (settled) return;
302
+ try {
303
+ buffer += decoder.decode();
304
+ if (buffer.trim()) processLine(buffer);
305
+ if (!outcome.hasResult) {
306
+ throw new HostError(
307
+ "Daemon NDJSON stream ended without a result.",
308
+ 1,
309
+ "DAEMON_PROTOCOL_ERROR",
310
+ "daemon",
311
+ );
312
+ }
313
+ done(() => {
314
+ accept(outcome.data as T);
315
+ });
316
+ } catch (cause) {
317
+ done(() => {
318
+ reject(
319
+ cause instanceof Error ? cause : new Error(String(cause)),
320
+ );
321
+ });
322
+ }
323
+ });
324
+ res.on("error", (cause) => {
325
+ done(() => {
326
+ reject(cause);
327
+ });
328
+ });
329
+ return;
330
+ }
331
+
332
+ const chunks: Buffer[] = [];
333
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
334
+ res.on("end", () => {
335
+ if (settled) return;
336
+ try {
337
+ const text = Buffer.concat(chunks).toString("utf8");
338
+ const parsed = this.parseJsonResponse<T>(text, ok, status);
339
+ done(() => {
340
+ accept(parsed);
341
+ });
342
+ } catch (cause) {
343
+ done(() => {
344
+ reject(
345
+ cause instanceof Error ? cause : new Error(String(cause)),
346
+ );
347
+ });
348
+ }
349
+ });
350
+ res.on("error", (cause) => {
351
+ done(() => {
352
+ reject(cause);
353
+ });
354
+ });
355
+ },
356
+ );
357
+
358
+ const onAbort = () => {
359
+ const reason =
360
+ options.signal?.reason instanceof Error
361
+ ? options.signal.reason
362
+ : new HostError("Request cancelled.", 130, "CANCELLED", "daemon");
363
+ this.onAbortRequest?.(reason);
364
+ req.destroy(reason);
365
+ done(() => {
366
+ reject(reason);
367
+ });
368
+ };
369
+ options.signal?.addEventListener("abort", onAbort, { once: true });
370
+
371
+ req.on("error", (cause) => {
372
+ done(() => {
373
+ reject(cause);
374
+ });
375
+ });
376
+ if (serializedBody !== undefined) {
377
+ req.write(serializedBody);
378
+ }
379
+ req.end();
380
+ });
381
+ }
382
+
383
+ private async readNdjsonResponse<T>(
384
+ response: Response,
385
+ onDiagnostic?: (text: string, progress?: boolean) => void,
386
+ ): Promise<T> {
387
+ if (!response.body) {
388
+ throw new HostError(
389
+ "Daemon NDJSON response had no body.",
390
+ 1,
391
+ "DAEMON_PROTOCOL_ERROR",
392
+ "daemon",
393
+ );
394
+ }
395
+ const reader =
396
+ response.body.getReader() as ReadableStreamDefaultReader<Uint8Array>;
397
+ const decoder = new TextDecoder("utf-8");
398
+ let buffer = "";
399
+ const outcome: { hasResult: boolean; data: unknown } = {
400
+ hasResult: false,
401
+ data: undefined,
402
+ };
403
+
404
+ const processLine = (line: string) => {
405
+ const trimmed = line.trim();
406
+ if (!trimmed) return;
407
+ let frame: DaemonNdjsonFrame;
408
+ try {
409
+ frame = JSON.parse(trimmed) as DaemonNdjsonFrame;
410
+ } catch {
411
+ throw new HostError(
412
+ "Daemon emitted invalid NDJSON frame.",
413
+ 1,
414
+ "DAEMON_PROTOCOL_ERROR",
415
+ "daemon",
416
+ );
417
+ }
418
+ if (frame.type === "diagnostic") {
419
+ onDiagnostic?.(frame.text, frame.progress);
420
+ } else if (frame.type === "result") {
421
+ outcome.hasResult = true;
422
+ outcome.data = frame.data;
423
+ } else {
424
+ throw toHostError(frame, response.status);
425
+ }
426
+ };
427
+
428
+ try {
429
+ for (;;) {
430
+ const chunk = await reader.read();
431
+ if (chunk.done) break;
432
+ buffer += decoder.decode(chunk.value, { stream: true });
433
+ for (;;) {
434
+ const newlineIndex = buffer.indexOf("\n");
435
+ if (newlineIndex === -1) break;
436
+ const line = buffer.slice(0, newlineIndex);
437
+ buffer = buffer.slice(newlineIndex + 1);
438
+ processLine(line);
439
+ }
440
+ }
441
+ buffer += decoder.decode();
442
+ if (buffer.trim()) processLine(buffer);
443
+ } finally {
444
+ reader.releaseLock();
445
+ }
446
+
447
+ if (!outcome.hasResult) {
448
+ throw new HostError(
449
+ "Daemon NDJSON stream ended without a result.",
450
+ 1,
451
+ "DAEMON_PROTOCOL_ERROR",
452
+ "daemon",
453
+ );
454
+ }
455
+ return outcome.data as T;
456
+ }
457
+
458
+ // ---- 1. /v1/store/* ----
459
+
460
+ readonly store = {
461
+ inspect: (
462
+ params: { ref: string; swarm?: string | undefined },
463
+ options?: DaemonRequestOptions,
464
+ ) => this.request("POST", "/v1/store/inspect", params, options),
465
+
466
+ import: (
467
+ params: {
468
+ path?: string | undefined;
469
+ mode?: "car" | "snapshot" | "build" | "assemble";
470
+ schemaOnly?: boolean | undefined;
471
+ output?: string | undefined;
472
+ outputDir?: string | undefined;
473
+ replace?: boolean | undefined;
474
+ autoImport?: boolean | undefined;
475
+ },
476
+ options?: DaemonRequestOptions,
477
+ ) => this.request("POST", "/v1/store/import", params, options),
478
+
479
+ export: (
480
+ params: {
481
+ mode?: "get" | "render-template";
482
+ ref?: string | undefined;
483
+ destination?: string | undefined;
484
+ swarm?: string | undefined;
485
+ raw?: boolean | undefined;
486
+ refresh?: boolean | undefined;
487
+ template?: string | undefined;
488
+ name?: string | undefined;
489
+ parameters?: string[] | undefined;
490
+ },
491
+ options?: DaemonRequestOptions,
492
+ ) =>
493
+ this.request<{ cid: string; destination: string; directory?: string }>(
494
+ "POST",
495
+ "/v1/store/export",
496
+ params,
497
+ options,
498
+ ),
499
+
500
+ listPins: (options?: DaemonRequestOptions) =>
501
+ this.request<{
502
+ pins: ContentPin[];
503
+ archived: NamedPin[];
504
+ builtins: Record<string, unknown>[];
505
+ }>("GET", "/v1/store/pins", undefined, options),
506
+
507
+ getPin: (
508
+ ref: string,
509
+ params: {
510
+ swarm?: string | undefined;
511
+ details?: boolean | undefined;
512
+ } = {},
513
+ options?: DaemonRequestOptions,
514
+ ) => {
515
+ const qs = new URLSearchParams();
516
+ if (params.swarm) qs.set("swarm", params.swarm);
517
+ if (params.details) qs.set("details", "true");
518
+ const suffix = qs.size ? `?${qs.toString()}` : "";
519
+ return this.request<ContentPin | NamedPin | Record<string, unknown>>(
520
+ "GET",
521
+ `/v1/store/pins/${encodeURIComponent(ref)}${suffix}`,
522
+ undefined,
523
+ options,
524
+ );
525
+ },
526
+
527
+ addPin: (
528
+ params: {
529
+ ref: string;
530
+ swarm?: string | undefined;
531
+ refresh?: boolean | undefined;
532
+ },
533
+ options?: DaemonRequestOptions,
534
+ ) => this.request<ContentPin>("POST", "/v1/store/pins", params, options),
535
+
536
+ removePin: (
537
+ ref: string,
538
+ params: { swarm?: string | undefined } = {},
539
+ options?: DaemonRequestOptions,
540
+ ) => {
541
+ const qs = new URLSearchParams();
542
+ if (params.swarm) qs.set("swarm", params.swarm);
543
+ const suffix = qs.size ? `?${qs.toString()}` : "";
544
+ return this.request<{
545
+ reference: string;
546
+ releasedOwners: string[];
547
+ retentionClaimsReleased: boolean;
548
+ garbageCollectionGuaranteed: boolean;
549
+ }>(
550
+ "DELETE",
551
+ `/v1/store/pins/${encodeURIComponent(ref)}${suffix}`,
552
+ undefined,
553
+ options,
554
+ );
555
+ },
556
+
557
+ usage: (options?: DaemonRequestOptions) =>
558
+ this.request<{ cachedBytes: number; pinnedBytes: number }>(
559
+ "GET",
560
+ "/v1/store/usage",
561
+ undefined,
562
+ options,
563
+ ),
564
+
565
+ gc: (options?: DaemonRequestOptions) =>
566
+ this.request<{ removedBlocks: number; reclaimedBytes: number }>(
567
+ "POST",
568
+ "/v1/store/gc",
569
+ {},
570
+ options,
571
+ ),
572
+ };
573
+
574
+ // ---- 2. /v1/swarms/* ----
575
+
576
+ readonly swarms = {
577
+ list: (options?: DaemonRequestOptions) =>
578
+ this.request<{ swarms: RegisteredSwarm[] }>(
579
+ "GET",
580
+ "/v1/swarms",
581
+ undefined,
582
+ options,
583
+ ),
584
+
585
+ identity: (options?: DaemonRequestOptions) =>
586
+ this.request("GET", "/v1/swarms/identity", undefined, options),
587
+
588
+ meta: (
589
+ ref: string,
590
+ params: { refresh?: boolean } = {},
591
+ options?: DaemonRequestOptions,
592
+ ) =>
593
+ this.request(
594
+ "GET",
595
+ `/v1/swarms/${encodeURIComponent(ref)}/meta${params.refresh ? "?refresh=true" : ""}`,
596
+ undefined,
597
+ options,
598
+ ),
599
+
600
+ set: (
601
+ params: { alias: string; url: string; expectedTarget?: string | null },
602
+ options?: DaemonRequestOptions,
603
+ ) =>
604
+ this.request<{
605
+ configUrl: string;
606
+ alias: string | null;
607
+ savedCurrent: string | null;
608
+ }>("POST", "/v1/swarms/set", params, options),
609
+
610
+ remove: (params: { swarm: string }, options?: DaemonRequestOptions) =>
611
+ this.request<{ removed: string; savedCurrent: string | null }>(
612
+ "POST",
613
+ "/v1/swarms/remove",
614
+ params,
615
+ options,
616
+ ),
617
+
618
+ fsLs: (
619
+ params: {
620
+ swarm: string;
621
+ kind?: "fs" | "templates" | "register" | "skills";
622
+ path?: string | undefined;
623
+ recursive?: boolean | undefined;
624
+ all?: boolean | undefined;
625
+ refresh?: boolean | undefined;
626
+ names?: string[] | undefined;
627
+ agents?: string[] | undefined;
628
+ },
629
+ options?: DaemonRequestOptions,
630
+ ) =>
631
+ this.request<SwarmFsListResult>(
632
+ "POST",
633
+ "/v1/swarms/fs/ls",
634
+ params,
635
+ options,
636
+ ),
637
+
638
+ fsStat: (
639
+ params: {
640
+ swarm: string;
641
+ kind?: "fs" | "template" | "skill";
642
+ path?: string | undefined;
643
+ name?: string | undefined;
644
+ ref?: string | undefined;
645
+ refresh?: boolean | undefined;
646
+ includeTree?: boolean | undefined;
647
+ },
648
+ options?: DaemonRequestOptions,
649
+ ) =>
650
+ this.request<SwarmFsStatResult>(
651
+ "POST",
652
+ "/v1/swarms/fs/stat",
653
+ params,
654
+ options,
655
+ ),
656
+
657
+ fsSet: (
658
+ params: {
659
+ swarm: string;
660
+ swarms?: string[] | undefined;
661
+ kind?: "fs" | "publish" | "template" | "register" | "skill";
662
+ path?: string | undefined;
663
+ cid?: string | undefined;
664
+ name?: string | undefined;
665
+ source?: string | undefined;
666
+ expect?: string | undefined;
667
+ replace?: boolean | undefined;
668
+ snapshot?: boolean | undefined;
669
+ wrapArtifact?: boolean | undefined;
670
+ validator?: "template" | "app" | "bundle" | undefined;
671
+ schema?: string | undefined;
672
+ app?: string | undefined;
673
+ argv?: string[] | undefined;
674
+ skill?: string | undefined;
675
+ global?: boolean | undefined;
676
+ types?: string[] | undefined;
677
+ },
678
+ options?: DaemonRequestOptions,
679
+ ) =>
680
+ this.request<SetSwarmFsPathResult>(
681
+ "POST",
682
+ "/v1/swarms/fs/set",
683
+ params,
684
+ options,
685
+ ),
686
+
687
+ fsRm: (
688
+ params: {
689
+ swarm: string;
690
+ kind?: "fs" | "template" | "register" | "skill";
691
+ path?: string | undefined;
692
+ name?: string | undefined;
693
+ expect?: string | undefined;
694
+ schema?: string | undefined;
695
+ globalName?: string | undefined;
696
+ types?: string[] | undefined;
697
+ },
698
+ options?: DaemonRequestOptions,
699
+ ) =>
700
+ this.request<RemoveSwarmFsPathResult>(
701
+ "POST",
702
+ "/v1/swarms/fs/rm",
703
+ params,
704
+ options,
705
+ ),
706
+
707
+ search: (
708
+ params: {
709
+ swarm?: string | undefined;
710
+ swarms?: string[] | undefined;
711
+ q: string;
712
+ prefix?: string | undefined;
713
+ kind?: "all" | "bundle" | "dir" | "file" | undefined;
714
+ schemaCid?: string | undefined;
715
+ limit?: number | string | undefined;
716
+ offset?: number | string | undefined;
717
+ refresh?: boolean | undefined;
718
+ },
719
+ options?: DaemonRequestOptions,
720
+ ) => this.request("POST", "/v1/swarms/search", params, options),
721
+
722
+ members: (
723
+ params: { swarm: string; refresh?: boolean | undefined },
724
+ options?: DaemonRequestOptions,
725
+ ) => this.request("POST", "/v1/swarms/members", params, options),
726
+
727
+ status: (
728
+ params: { swarm: string; refresh?: boolean | undefined },
729
+ options?: DaemonRequestOptions,
730
+ ) => this.request("POST", "/v1/swarms/status", params, options),
731
+
732
+ update: (
733
+ params: {
734
+ swarm: string;
735
+ name?: string | undefined;
736
+ description?: string | undefined;
737
+ },
738
+ options?: DaemonRequestOptions,
739
+ ) => this.request("POST", "/v1/swarms/update", params, options),
740
+
741
+ replicate: (
742
+ params: { swarm: string; pivot?: string | undefined },
743
+ options?: DaemonRequestOptions,
744
+ ) => this.request("POST", "/v1/swarms/replicate", params, options),
745
+
746
+ governance: (
747
+ action:
748
+ | "create"
749
+ | "request"
750
+ | "approve"
751
+ | "pivot-grant"
752
+ | "export"
753
+ | "exclude"
754
+ | "resume"
755
+ | "profile",
756
+ params: Record<string, unknown>,
757
+ options?: DaemonRequestOptions,
758
+ ) =>
759
+ this.request(
760
+ "POST",
761
+ `/v1/swarms/governance/${encodeURIComponent(action)}`,
762
+ params,
763
+ options,
764
+ ),
765
+ };
766
+
767
+ // ---- 3. /v1/runs/* ----
768
+
769
+ readonly runs = {
770
+ prepare: (
771
+ params: {
772
+ origin: "open" | "exec";
773
+ target?: string | undefined;
774
+ appCid?: string | undefined;
775
+ argv?: string[] | undefined;
776
+ swarm?: string | undefined;
777
+ history?: boolean | undefined;
778
+ retain?: boolean | undefined;
779
+ log?: boolean | undefined;
780
+ raw?: boolean | undefined;
781
+ refresh?: boolean | undefined;
782
+ inputSchema?: string | undefined;
783
+ },
784
+ options?: DaemonRequestOptions,
785
+ ) => this.request<PreparedRun>("POST", "/v1/runs/prepare", params, options),
786
+
787
+ ipc: async (
788
+ runId: string,
789
+ operation: string,
790
+ args?: unknown,
791
+ options?: DaemonRequestOptions,
792
+ ): Promise<unknown> => {
793
+ const response = await this.request<{ result: unknown }>(
794
+ "POST",
795
+ `/v1/runs/${encodeURIComponent(runId)}/ipc`,
796
+ { operation, args: encodeIpcValue(args) },
797
+ options,
798
+ );
799
+ return decodeIpcValue(response.result);
800
+ },
801
+
802
+ finish: (
803
+ runId: string,
804
+ params: {
805
+ code: number | null;
806
+ signal?: NodeJS.Signals | null;
807
+ logComplete?: boolean;
808
+ logFailure?: string | null;
809
+ fatalError?: string | null;
810
+ cancellation?: number;
811
+ },
812
+ options?: DaemonRequestOptions,
813
+ ) =>
814
+ this.request<{ exitCode: number; record: RunRecord }>(
815
+ "POST",
816
+ `/v1/runs/${encodeURIComponent(runId)}/finish`,
817
+ params,
818
+ options,
819
+ ),
820
+
821
+ cancel: (
822
+ runId: string,
823
+ params: { exitCode?: number; reason?: string } = {},
824
+ options?: DaemonRequestOptions,
825
+ ) =>
826
+ this.request<{ exitCode: number; record: RunRecord }>(
827
+ "POST",
828
+ `/v1/runs/${encodeURIComponent(runId)}/cancel`,
829
+ params,
830
+ options,
831
+ ),
832
+
833
+ list: (
834
+ params: {
835
+ app?: string;
836
+ status?: RunRecord["status"];
837
+ since?: string;
838
+ until?: string;
839
+ limit?: number;
840
+ before?: string;
841
+ } = {},
842
+ options?: DaemonRequestOptions,
843
+ ) =>
844
+ this.request<{
845
+ items: Omit<
846
+ RunRecord,
847
+ "origin" | "appExitCode" | "error" | "retention"
848
+ >[];
849
+ nextBefore: string | null;
850
+ shortNextBefore?: string | null;
851
+ pinNames?: Record<string, string>;
852
+ }>("POST", "/v1/runs/list", params, options),
853
+
854
+ show: (runId: string, options?: DaemonRequestOptions) =>
855
+ this.request<
856
+ RunRecord & { logs?: { stdout: string | null; stderr: string | null } }
857
+ >("GET", `/v1/runs/${encodeURIComponent(runId)}`, undefined, options),
858
+
859
+ remove: (
860
+ params: {
861
+ ids?: string[];
862
+ app?: string;
863
+ status?: RunRecord["status"];
864
+ since?: string;
865
+ until?: string;
866
+ dryRun?: boolean;
867
+ },
868
+ options?: DaemonRequestOptions,
869
+ ) =>
870
+ this.request<{
871
+ ids?: string[];
872
+ removed?: string[];
873
+ retentionClaimsReleased?: true;
874
+ garbageCollectionGuaranteed?: false;
875
+ }>("POST", "/v1/runs/remove", params, options),
876
+ };
877
+
878
+ // ---- 4. /v1/host/* ----
879
+
880
+ readonly host = {
881
+ getConfig: ((
882
+ key?: ConfigKey,
883
+ options?: DaemonRequestOptions & { includeSecrets?: boolean },
884
+ ) => {
885
+ const qs = new URLSearchParams();
886
+ if (key) qs.set("key", key);
887
+ if (options?.includeSecrets === false) qs.set("includeSecrets", "false");
888
+ const suffix = qs.size ? `?${qs.toString()}` : "";
889
+ return this.request(
890
+ "GET",
891
+ `/v1/host/config${suffix}`,
892
+ undefined,
893
+ options,
894
+ );
895
+ }) as {
896
+ (
897
+ key: ConfigKey,
898
+ options?: DaemonRequestOptions & { includeSecrets?: boolean },
899
+ ): Promise<ConfigItem>;
900
+ (
901
+ key?: undefined,
902
+ options?: DaemonRequestOptions & { includeSecrets?: boolean },
903
+ ): Promise<{
904
+ items: ConfigItem[];
905
+ saved?: Partial<Record<ConfigKey, ConfigValue>>;
906
+ legacyPinCount?: number;
907
+ legacyRegistrationCount?: number;
908
+ stateDir?: string;
909
+ }>;
910
+ },
911
+
912
+ setConfig: (
913
+ key: ConfigKey,
914
+ value: ConfigValue,
915
+ options?: DaemonRequestOptions & { fromString?: boolean },
916
+ ) =>
917
+ this.request<
918
+ ConfigItem & {
919
+ effectiveSource?: ConfigItem["source"];
920
+ effectiveValue?: ConfigValue;
921
+ }
922
+ >(
923
+ "PUT",
924
+ `/v1/host/config/${encodeURIComponent(key)}`,
925
+ {
926
+ value,
927
+ ...(options?.fromString !== undefined
928
+ ? { fromString: options.fromString }
929
+ : {}),
930
+ },
931
+ options,
932
+ ),
933
+
934
+ resetConfig: (
935
+ key: ConfigKey | "store.rpc",
936
+ options?: DaemonRequestOptions,
937
+ ) =>
938
+ this.request<ConfigItem & { legacyReset?: boolean }>(
939
+ "DELETE",
940
+ `/v1/host/config/${encodeURIComponent(key)}`,
941
+ undefined,
942
+ options,
943
+ ),
944
+
945
+ syncSkills: (
946
+ params: {
947
+ swarm: string;
948
+ names?: string[] | undefined;
949
+ agents?: string[] | undefined;
950
+ overrideExisting?: boolean | undefined;
951
+ dryRun?: boolean | undefined;
952
+ yes?: boolean | undefined;
953
+ refresh?: boolean | undefined;
954
+ quietPreview?: boolean | undefined;
955
+ daemonSync?: boolean | undefined;
956
+ },
957
+ options?: DaemonRequestOptions,
958
+ ) => this.request("POST", "/v1/host/skills/sync", params, options),
959
+ };
960
+
961
+ // ---- 5. /v1/daemon/* ----
962
+
963
+ readonly daemon = {
964
+ shutdown: async (options?: DaemonRequestOptions): Promise<{ ok: true }> => {
965
+ const result = await this.request<{ ok: true }>(
966
+ "POST",
967
+ "/v1/daemon/shutdown",
968
+ {},
969
+ options,
970
+ );
971
+ this.invalidateEndpoint();
972
+ return result;
973
+ },
974
+ };
975
+ }