@ipab/cli 0.1.0-rc.7 → 0.1.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +70 -30
  2. package/dist/app-authoring.d.ts.map +1 -1
  3. package/dist/app-authoring.js +2 -44
  4. package/dist/app-authoring.js.map +1 -1
  5. package/dist/app-prebuild.d.ts +18 -0
  6. package/dist/app-prebuild.d.ts.map +1 -1
  7. package/dist/app-prebuild.js +46 -0
  8. package/dist/app-prebuild.js.map +1 -1
  9. package/dist/builtins/skill.ipab.car +0 -0
  10. package/dist/bundled-skills.d.ts +14 -0
  11. package/dist/bundled-skills.d.ts.map +1 -0
  12. package/dist/bundled-skills.js +34 -0
  13. package/dist/bundled-skills.js.map +1 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +309 -157
  16. package/dist/cli.js.map +1 -1
  17. package/dist/config.d.ts +1 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +9 -4
  20. package/dist/config.js.map +1 -1
  21. package/dist/context.d.ts +4 -0
  22. package/dist/context.d.ts.map +1 -1
  23. package/dist/context.js +11 -2
  24. package/dist/context.js.map +1 -1
  25. package/dist/daemon.d.ts +4 -0
  26. package/dist/daemon.d.ts.map +1 -0
  27. package/dist/daemon.js +200 -0
  28. package/dist/daemon.js.map +1 -0
  29. package/dist/doctor.d.ts +2 -0
  30. package/dist/doctor.d.ts.map +1 -1
  31. package/dist/doctor.js +18 -4
  32. package/dist/doctor.js.map +1 -1
  33. package/dist/errors.d.ts +1 -8
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +1 -20
  36. package/dist/errors.js.map +1 -1
  37. package/dist/host-error.d.ts +9 -0
  38. package/dist/host-error.d.ts.map +1 -0
  39. package/dist/host-error.js +21 -0
  40. package/dist/host-error.js.map +1 -0
  41. package/dist/ipc.d.ts.map +1 -1
  42. package/dist/ipc.js +17 -0
  43. package/dist/ipc.js.map +1 -1
  44. package/dist/kubo-install.js +1 -1
  45. package/dist/kubo-install.js.map +1 -1
  46. package/dist/kubo-peers.d.ts.map +1 -1
  47. package/dist/kubo-peers.js +2 -1
  48. package/dist/kubo-peers.js.map +1 -1
  49. package/dist/kubo-topology.d.ts +19 -0
  50. package/dist/kubo-topology.d.ts.map +1 -0
  51. package/dist/kubo-topology.js +105 -0
  52. package/dist/kubo-topology.js.map +1 -0
  53. package/dist/kubo.d.ts +10 -0
  54. package/dist/kubo.d.ts.map +1 -1
  55. package/dist/kubo.js +96 -15
  56. package/dist/kubo.js.map +1 -1
  57. package/dist/skill-source.d.ts +4 -0
  58. package/dist/skill-source.d.ts.map +1 -1
  59. package/dist/skill-source.js +14 -2
  60. package/dist/skill-source.js.map +1 -1
  61. package/dist/skills.d.ts +18 -1
  62. package/dist/skills.d.ts.map +1 -1
  63. package/dist/skills.js +137 -39
  64. package/dist/skills.js.map +1 -1
  65. package/dist/space-path.d.ts +3 -0
  66. package/dist/space-path.d.ts.map +1 -0
  67. package/dist/space-path.js +17 -0
  68. package/dist/space-path.js.map +1 -0
  69. package/dist/space.d.ts +1 -2
  70. package/dist/space.d.ts.map +1 -1
  71. package/dist/space.js +2 -15
  72. package/dist/space.js.map +1 -1
  73. package/dist/state-storage.js +1 -1
  74. package/dist/state-storage.js.map +1 -1
  75. package/dist/state.d.ts +2 -0
  76. package/dist/state.d.ts.map +1 -1
  77. package/dist/state.js +31 -12
  78. package/dist/state.js.map +1 -1
  79. package/dist/swarm-files.d.ts +1 -1
  80. package/dist/swarm-files.d.ts.map +1 -1
  81. package/dist/swarm-files.js +10 -4
  82. package/dist/swarm-files.js.map +1 -1
  83. package/dist/swarm-meta.d.ts +1 -4
  84. package/dist/swarm-meta.d.ts.map +1 -1
  85. package/dist/swarm-meta.js +3 -34
  86. package/dist/swarm-meta.js.map +1 -1
  87. package/dist/swarm-observations.d.ts +40 -0
  88. package/dist/swarm-observations.d.ts.map +1 -0
  89. package/dist/swarm-observations.js +262 -0
  90. package/dist/swarm-observations.js.map +1 -0
  91. package/dist/swarm.d.ts +121 -6
  92. package/dist/swarm.d.ts.map +1 -1
  93. package/dist/swarm.js +672 -81
  94. package/dist/swarm.js.map +1 -1
  95. package/package.json +4 -4
  96. package/src/app-authoring.ts +12 -53
  97. package/src/app-prebuild.ts +61 -0
  98. package/src/bundled-skills.ts +60 -0
  99. package/src/cli.ts +398 -195
  100. package/src/config.ts +12 -4
  101. package/src/context.ts +15 -2
  102. package/src/daemon.ts +237 -0
  103. package/src/doctor.ts +42 -5
  104. package/src/errors.ts +1 -25
  105. package/src/host-error.ts +26 -0
  106. package/src/ipc.ts +19 -0
  107. package/src/kubo-install.ts +1 -1
  108. package/src/kubo-peers.ts +2 -3
  109. package/src/kubo-topology.ts +135 -0
  110. package/src/kubo.ts +134 -25
  111. package/src/skill-source.ts +16 -2
  112. package/src/skills.ts +195 -53
  113. package/src/space-path.ts +30 -0
  114. package/src/space.ts +2 -28
  115. package/src/state-storage.ts +1 -1
  116. package/src/state.ts +37 -12
  117. package/src/swarm-files.ts +8 -3
  118. package/src/swarm-meta.ts +15 -34
  119. package/src/swarm-observations.ts +374 -0
  120. package/src/swarm.ts +953 -92
package/src/config.ts CHANGED
@@ -3,11 +3,12 @@ import { join, resolve } from "node:path";
3
3
  import { CID } from "multiformats/cid";
4
4
  import { readContentConfiguration } from "@ipab/ipfs-store/node";
5
5
  import type { StoreConfiguration } from "@ipab/ipfs-store";
6
- import { HostError, object, syntax } from "./errors.js";
6
+ import { HostError, object, syntax } from "./host-error.js";
7
7
 
8
8
  export type ConfigKey =
9
9
  | "swarm.default"
10
10
  | "swarm.listen"
11
+ | "swarm.pivot"
11
12
  | "swarm.cacheTtl"
12
13
  | "swarm.forceRefresh"
13
14
  | "store.gateway"
@@ -33,6 +34,7 @@ export interface ConfigItem {
33
34
  export const defaults: Record<ConfigKey, ConfigValue> = {
34
35
  "swarm.default": null,
35
36
  "swarm.listen": "lan",
37
+ "swarm.pivot": false,
36
38
  "swarm.cacheTtl": 300,
37
39
  "swarm.forceRefresh": false,
38
40
  "store.gateway": null,
@@ -45,6 +47,7 @@ export const defaults: Record<ConfigKey, ConfigValue> = {
45
47
  };
46
48
  const environments: Partial<Record<ConfigKey, string>> = {
47
49
  "swarm.listen": "IPAB_SWARM_LISTEN",
50
+ "swarm.pivot": "IPAB_SWARM_PIVOT",
48
51
  "swarm.cacheTtl": "IPAB_SWARM_CACHE_TTL",
49
52
  "swarm.forceRefresh": "IPAB_SWARM_FORCE_REFRESH",
50
53
  "store.gateway": "IPAB_STORE_GATEWAY",
@@ -127,10 +130,15 @@ export function parseValue(
127
130
  if (key.startsWith("swarm.") && value === "default")
128
131
  return key === "swarm.cacheTtl" ||
129
132
  key === "swarm.forceRefresh" ||
133
+ key === "swarm.pivot" ||
130
134
  key === "swarm.listen"
131
135
  ? defaults[key]
132
136
  : null;
133
- if (key === "history.enabled" || key === "swarm.forceRefresh") {
137
+ if (
138
+ key === "history.enabled" ||
139
+ key === "swarm.forceRefresh" ||
140
+ key === "swarm.pivot"
141
+ ) {
134
142
  if (value === "true") return true;
135
143
  if (value === "false") return false;
136
144
  }
@@ -177,9 +185,9 @@ export function parseValue(
177
185
  "swarm.cacheTtl requires an integer number of seconds from 0 to 86400.",
178
186
  );
179
187
  }
180
- if (key === "swarm.forceRefresh") {
188
+ if (key === "swarm.forceRefresh" || key === "swarm.pivot") {
181
189
  if (typeof value === "boolean") return value;
182
- syntax("swarm.forceRefresh requires true or false.");
190
+ syntax(`${key} requires true or false.`);
183
191
  }
184
192
  if (key === "swarm.listen") {
185
193
  if (value === "lan" || value === "loopback") return value;
package/src/context.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { HostError } from "./errors.js";
2
- import { CHUNK_BYTES, relativePath } from "./space.js";
1
+ import { HostError } from "./host-error.js";
2
+ import { CHUNK_BYTES, relativePath } from "./space-path.js";
3
3
 
4
4
  import type { BundleInspection } from "./context-types.js";
5
5
  export type { BundleInspection } from "./context-types.js";
@@ -27,6 +27,10 @@ export interface AppContext {
27
27
  reference: string,
28
28
  options?: { signal?: AbortSignal; swarm?: string },
29
29
  ): Promise<BundleInspection>;
30
+ readBlock(
31
+ cid: string,
32
+ options?: { signal?: AbortSignal; maxBytes?: number },
33
+ ): Promise<Uint8Array>;
30
34
  readFile(
31
35
  rootCid: string,
32
36
  path: string,
@@ -211,6 +215,15 @@ export function createContext(port: Port): {
211
215
  throw new HostError("Invalid Bundle inspection response.");
212
216
  return data as BundleInspection;
213
217
  },
218
+ async readBlock(cid, options = {}) {
219
+ const maxBytes = options.maxBytes ?? 65536;
220
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 65536)
221
+ throw new HostError("Block read limit must be 1..65536 bytes.");
222
+ const result = await rpc("readBlock", { cid, maxBytes }, options.signal);
223
+ if (!(result instanceof Uint8Array) || result.byteLength > maxBytes)
224
+ throw new HostError("Invalid bounded block response.");
225
+ return result;
226
+ },
214
227
  get appCid() {
215
228
  if (!appCid)
216
229
  throw new HostError("IPAB context identity is not initialized.");
package/src/daemon.ts ADDED
@@ -0,0 +1,237 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { open, unlink } from "node:fs/promises";
4
+ import { createServer } from "node:http";
5
+ import { join, resolve } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { nodeError } from "./authoring.js";
9
+ import { HostError, object } from "./errors.js";
10
+ import { protectedPath, secureNew } from "./identity.js";
11
+ import {
12
+ privateDirectory,
13
+ readPrivate,
14
+ withPrivateLock,
15
+ writePrivate,
16
+ } from "./swarm-files.js";
17
+
18
+ interface Endpoint {
19
+ pid: number;
20
+ port: number;
21
+ token: string;
22
+ swarm: string | null;
23
+ }
24
+
25
+ export async function daemonResponsive(
26
+ stateDir: string,
27
+ requireAll = false,
28
+ ): Promise<boolean> {
29
+ let raw: unknown;
30
+ try {
31
+ raw = await readPrivate<unknown>(
32
+ join(stateDir, "swarm-daemon"),
33
+ "endpoint.json",
34
+ );
35
+ } catch (cause) {
36
+ if (nodeError(cause, "ENOENT")) return false;
37
+ throw cause;
38
+ }
39
+ if (raw === undefined) return false;
40
+ const endpoint = object(raw, "daemon endpoint");
41
+ if (
42
+ !Number.isSafeInteger(endpoint.pid) ||
43
+ Number(endpoint.pid) < 1 ||
44
+ !Number.isSafeInteger(endpoint.port) ||
45
+ Number(endpoint.port) < 1 ||
46
+ Number(endpoint.port) > 65535 ||
47
+ typeof endpoint.token !== "string" ||
48
+ !/^[a-f0-9]{64}$/.test(endpoint.token) ||
49
+ (endpoint.swarm !== null && typeof endpoint.swarm !== "string")
50
+ )
51
+ throw new HostError(
52
+ "Invalid daemon endpoint; inspect the protected swarm-daemon/endpoint.json before retrying.",
53
+ );
54
+ try {
55
+ const response = await fetch(
56
+ `http://127.0.0.1:${Number(endpoint.port)}/health`,
57
+ {
58
+ headers: { authorization: `Bearer ${endpoint.token}` },
59
+ signal: AbortSignal.timeout(750),
60
+ redirect: "error",
61
+ },
62
+ );
63
+ if (!response.ok) return false;
64
+ const responsive =
65
+ (await response.text()) ===
66
+ JSON.stringify({
67
+ pid: endpoint.pid,
68
+ stateDir: resolve(stateDir),
69
+ swarm: endpoint.swarm,
70
+ });
71
+ if (responsive && requireAll && endpoint.swarm !== null)
72
+ throw new HostError(
73
+ "The existing foreground daemon manages only one Swarm. Stop it and run ipab daemon without --swarm, or retry this network command to start the all-Swarm background manager.",
74
+ );
75
+ return responsive;
76
+ } catch (cause) {
77
+ if (
78
+ cause instanceof TypeError ||
79
+ (cause instanceof Error &&
80
+ ["TimeoutError", "AbortError"].includes(cause.name))
81
+ )
82
+ return false;
83
+ throw cause;
84
+ }
85
+ }
86
+
87
+ // Called only after acquiring the daemon's lifetime lock, before network work.
88
+ export async function serveDaemon(
89
+ stateDir: string,
90
+ selected?: string,
91
+ ): Promise<() => Promise<void>> {
92
+ const directory = await privateDirectory(stateDir, "swarm-daemon");
93
+ const token = randomBytes(32).toString("hex");
94
+ const server = createServer((request, response) => {
95
+ if (
96
+ request.method !== "GET" ||
97
+ request.url !== "/health" ||
98
+ request.headers.authorization !== `Bearer ${token}`
99
+ ) {
100
+ response.writeHead(403).end();
101
+ return;
102
+ }
103
+ response.setHeader("content-type", "application/json");
104
+ response.end(
105
+ JSON.stringify({
106
+ pid: process.pid,
107
+ stateDir: resolve(stateDir),
108
+ swarm: selected ?? null,
109
+ }),
110
+ );
111
+ });
112
+ server.requestTimeout = 1000;
113
+ server.headersTimeout = 1000;
114
+ server.maxConnections = 16;
115
+ const close = () =>
116
+ new Promise<void>((accept, reject) => {
117
+ server.close((error) => {
118
+ if (error) reject(error);
119
+ else accept();
120
+ });
121
+ server.closeAllConnections();
122
+ });
123
+ try {
124
+ await new Promise<void>((accept, reject) => {
125
+ server.once("error", reject);
126
+ server.listen(0, "127.0.0.1", () => {
127
+ server.removeListener("error", reject);
128
+ accept();
129
+ });
130
+ });
131
+ const address = server.address();
132
+ if (!address || typeof address === "string")
133
+ throw new HostError(
134
+ "Daemon did not bind its loopback readiness endpoint.",
135
+ );
136
+ const endpoint: Endpoint = {
137
+ pid: process.pid,
138
+ port: address.port,
139
+ token,
140
+ swarm: selected ?? null,
141
+ };
142
+ await writePrivate(directory, "endpoint.json", endpoint);
143
+ } catch (cause) {
144
+ if (server.listening) await close();
145
+ throw cause;
146
+ }
147
+ return async () => {
148
+ try {
149
+ await unlink(join(directory, "endpoint.json"));
150
+ } finally {
151
+ await close();
152
+ }
153
+ };
154
+ }
155
+
156
+ export async function ensureDaemon(
157
+ stateDir: string,
158
+ env: NodeJS.ProcessEnv,
159
+ diagnostic?: (text: string) => void,
160
+ ): Promise<void> {
161
+ if (await daemonResponsive(stateDir, true)) return;
162
+ const directory = await privateDirectory(stateDir, "swarm-daemon");
163
+ const launch = await privateDirectory(directory, "launch");
164
+ await withPrivateLock(launch, async () => {
165
+ if (await daemonResponsive(stateDir, true)) return;
166
+ const logfile = join(directory, "daemon.log");
167
+ let log;
168
+ let created = false;
169
+ try {
170
+ log = await open(logfile, "ax", 0o600);
171
+ created = true;
172
+ } catch (cause) {
173
+ if (!nodeError(cause, "EEXIST")) throw cause;
174
+ await protectedPath(logfile);
175
+ log = await open(logfile, "a");
176
+ }
177
+ try {
178
+ if (created) await secureNew(logfile);
179
+ } catch (cause) {
180
+ await log.close();
181
+ throw cause;
182
+ }
183
+ const child = spawn(
184
+ process.execPath,
185
+ [
186
+ fileURLToPath(new URL("../dist/main.js", import.meta.url)),
187
+ "--state-dir",
188
+ resolve(stateDir),
189
+ "daemon",
190
+ ],
191
+ {
192
+ env,
193
+ cwd: fileURLToPath(new URL("..", import.meta.url)),
194
+ detached: true,
195
+ windowsHide: true,
196
+ shell: false,
197
+ stdio: ["ignore", log.fd, log.fd],
198
+ },
199
+ );
200
+ child.unref();
201
+ let failure: Error | undefined;
202
+ const onError = (error: Error) => {
203
+ failure = error;
204
+ };
205
+ const onExit = (code: number | null) => {
206
+ failure = new HostError(
207
+ `Daemon exited before readiness (exit ${code ?? "signal"}).`,
208
+ );
209
+ };
210
+ child.once("error", onError);
211
+ child.once("exit", onExit);
212
+ try {
213
+ const deadline = Date.now() + 15_000;
214
+ do {
215
+ if (await daemonResponsive(stateDir, true)) {
216
+ diagnostic?.(
217
+ `IPAB daemon is running in the background. Log: ${logfile}`,
218
+ );
219
+ return;
220
+ }
221
+ if (failure) throw failure;
222
+ await delay(100);
223
+ } while (Date.now() < deadline);
224
+ throw new HostError("Timed out waiting for daemon readiness.");
225
+ } catch (cause) {
226
+ if (child.pid && child.exitCode === null && child.signalCode === null)
227
+ child.kill();
228
+ throw new HostError(
229
+ `Could not start background IPAB daemon. Inspect ${logfile}. ${cause instanceof Error ? cause.message : String(cause)}`,
230
+ );
231
+ } finally {
232
+ child.removeListener("error", onError);
233
+ child.removeListener("exit", onExit);
234
+ await log.close();
235
+ }
236
+ });
237
+ }
package/src/doctor.ts CHANGED
@@ -43,7 +43,12 @@ import {
43
43
  type KuboArchive,
44
44
  type KuboRelease,
45
45
  } from "./kubo-release.js";
46
- import { HostError } from "./errors.js";
46
+ import { HostError, message } from "./errors.js";
47
+ import {
48
+ inspectBundledSkills,
49
+ installBundledSkills,
50
+ } from "./bundled-skills.js";
51
+ import type { SkillsPort } from "./skills.js";
47
52
  import { inspectLocalMembership } from "./swarm.js";
48
53
  import { nodeRecord } from "./kubo.js";
49
54
  import { readPrivate } from "./swarm-files.js";
@@ -70,6 +75,7 @@ export interface DoctorReport {
70
75
  }[];
71
76
  }
72
77
  export interface DoctorOptions extends InstallOptions {
78
+ skillsPort?: SkillsPort;
73
79
  fix?: boolean;
74
80
  yes?: boolean;
75
81
  tty: boolean;
@@ -193,7 +199,7 @@ function check(
193
199
  ): DoctorCheck {
194
200
  return {
195
201
  id,
196
- capability: id === "state" ? "base" : "swarm",
202
+ capability: id === "state" || id === "ipab-skill" ? "base" : "swarm",
197
203
  required: id === "state",
198
204
  status,
199
205
  message,
@@ -295,7 +301,7 @@ async function stateSnapshot(file: string, signal?: AbortSignal) {
295
301
  async function inspect(
296
302
  stateDir: string,
297
303
  env: NodeJS.ProcessEnv,
298
- options: InstallOptions,
304
+ options: InstallOptions & Pick<DoctorOptions, "skillsPort">,
299
305
  verificationFact?: KuboArchive,
300
306
  ): Promise<{
301
307
  report: DoctorReport;
@@ -680,6 +686,29 @@ async function inspect(
680
686
  `Latest verified compatible stable Kubo is ${release.version} (${KUBO_RANGE}); installed ${installed?.version ?? "none"}.`,
681
687
  ),
682
688
  );
689
+ try {
690
+ const skill = await inspectBundledSkills(options.skillsPort);
691
+ checks.push(
692
+ check(
693
+ "ipab-skill",
694
+ skill.status,
695
+ skill.message,
696
+ skill.repairable,
697
+ skill.guidance,
698
+ ),
699
+ );
700
+ } catch (cause) {
701
+ options.signal?.throwIfAborted();
702
+ checks.push(
703
+ check(
704
+ "ipab-skill",
705
+ "invalid",
706
+ `Could not inspect bundled IPAB Skill: ${message(cause)}`,
707
+ false,
708
+ "Inspect Agent directories and the protected Skills ledger; no Skill files were changed.",
709
+ ),
710
+ );
711
+ }
683
712
  report.ready = ready(report);
684
713
  options.signal?.throwIfAborted();
685
714
  return {
@@ -763,7 +792,9 @@ export async function doctorDevice(
763
792
  : `${kubo.status === "blocked" ? "Recover journaled installation using verified managed Kubo" : "Install verified managed Kubo"} ${release!.version}`
764
793
  : item.id === "identity"
765
794
  ? "Create missing protected HOME account identity"
766
- : "Create missing protected local state",
795
+ : item.id === "ipab-skill"
796
+ ? `Install/update bundled IPAB Skill: ${item.message}`
797
+ : "Create missing protected local state",
767
798
  }));
768
799
  if (!actions.length) {
769
800
  report.repairs = blockedRepairs;
@@ -833,6 +864,12 @@ export async function doctorDevice(
833
864
  )
834
865
  throw new Error("Kubo dependency is unavailable.");
835
866
  await accountIdentity(env, true, true);
867
+ } else if (action.id === "ipab-skill") {
868
+ await installBundledSkills(
869
+ env,
870
+ (text) => options.diagnostic?.(text),
871
+ options.skillsPort,
872
+ );
836
873
  } else if (action.id === "kubo" && verification)
837
874
  await verifyExistingKuboArchive(stateDir, verification, {
838
875
  ...options,
@@ -848,7 +885,7 @@ export async function doctorDevice(
848
885
  } catch (cause) {
849
886
  options.signal?.throwIfAborted();
850
887
  options.diagnostic?.(
851
- `Repair failed: ${action.action}. ${cause instanceof HostError && cause.code === "KUBO_SETUP_FAILED" ? cause.message : "Existing resources were not replaced; inspect the protected installation/cache and retry."}`,
888
+ `Repair failed: ${action.action}. ${message(cause)} Existing resources were not replaced; inspect the protected installation/cache and retry.`,
852
889
  );
853
890
  repairs.push({ ...action, status: "failed" });
854
891
  if (action.id === "kubo" || action.id === "kubo-update")
package/src/errors.ts CHANGED
@@ -1,23 +1,4 @@
1
- export class HostError extends Error {
2
- constructor(
3
- message: string,
4
- readonly exitCode = 1,
5
- readonly code = "OPERATION_FAILED",
6
- readonly phase = "state",
7
- ) {
8
- super(message);
9
- this.name = "HostError";
10
- }
11
- }
12
-
13
- export function syntax(message: string): never {
14
- throw new HostError(
15
- `${message} Run ipab --help.`,
16
- 2,
17
- "INVALID_ARGUMENT",
18
- "arguments",
19
- );
20
- }
1
+ export { HostError, object, syntax } from "./host-error.js";
21
2
 
22
3
  export function message(error: unknown): string {
23
4
  let text =
@@ -38,9 +19,4 @@ export function message(error: unknown): string {
38
19
  });
39
20
  }
40
21
 
41
- export function object(value: unknown, label: string): Record<string, unknown> {
42
- if (!value || typeof value !== "object" || Array.isArray(value))
43
- throw new HostError(`Invalid ${label}.`);
44
- return value as Record<string, unknown>;
45
- }
46
22
  import { ContentBundleError } from "@ipab/bundle";
@@ -0,0 +1,26 @@
1
+ export class HostError extends Error {
2
+ constructor(
3
+ message: string,
4
+ readonly exitCode = 1,
5
+ readonly code = "OPERATION_FAILED",
6
+ readonly phase = "state",
7
+ ) {
8
+ super(message);
9
+ this.name = "HostError";
10
+ }
11
+ }
12
+
13
+ export function syntax(message: string): never {
14
+ throw new HostError(
15
+ `${message} Run ipab --help.`,
16
+ 2,
17
+ "INVALID_ARGUMENT",
18
+ "arguments",
19
+ );
20
+ }
21
+
22
+ export function object(value: unknown, label: string): Record<string, unknown> {
23
+ if (!value || typeof value !== "object" || Array.isArray(value))
24
+ throw new HostError(`Invalid ${label}.`);
25
+ return value as Record<string, unknown>;
26
+ }
package/src/ipc.ts CHANGED
@@ -171,6 +171,25 @@ export class ContextServer {
171
171
  ): Promise<unknown> {
172
172
  signal.throwIfAborted();
173
173
  if (operation === "identity") return this.appCid;
174
+ if (operation === "readBlock") {
175
+ const data = object(args, "block read request");
176
+ if (
177
+ typeof data.cid !== "string" ||
178
+ typeof data.maxBytes !== "number" ||
179
+ !Number.isSafeInteger(data.maxBytes) ||
180
+ data.maxBytes < 1 ||
181
+ data.maxBytes > 65536
182
+ )
183
+ throw new HostError("Block read limit must be 1..65536 bytes.");
184
+ const cid = CID.parse(data.cid);
185
+ if (cid.toV1().toString() !== data.cid)
186
+ throw new HostError("Block reads require an exact canonical CID.");
187
+ const bytes = await this.store.block.get(data.cid, { signal });
188
+ signal.throwIfAborted();
189
+ if (bytes.byteLength > data.maxBytes)
190
+ throw new HostError("Block exceeds the requested read limit.");
191
+ return bytes;
192
+ }
174
193
  if (operation === "deriveBundle") {
175
194
  const data = object(args, "Bundle derivation request");
176
195
  if (typeof data.inputCid !== "string")
@@ -847,7 +847,7 @@ export async function kuboBinary(
847
847
  [
848
848
  "id",
849
849
  "swarm connect",
850
- "swarm peering ls",
850
+ "diag datastore put",
851
851
  "dag import",
852
852
  "dag export",
853
853
  "pin add",
package/src/kubo-peers.ts CHANGED
@@ -22,9 +22,8 @@ export function advertisedIps(
22
22
  if (
23
23
  !item.internal &&
24
24
  item.family === "IPv4" &&
25
- /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(
26
- item.address,
27
- )
25
+ !/^(?:0\.|127\.|169\.254\.)/.test(item.address) &&
26
+ Number(item.address.split(".")[0]) < 224
28
27
  )
29
28
  ips.add(item.address);
30
29
  }
@@ -0,0 +1,135 @@
1
+ import { object } from "./errors.js";
2
+ import type { PeeringPeer } from "./kubo-peering.js";
3
+
4
+ export function topologyConfig(
5
+ config: Record<string, unknown>,
6
+ pivot: boolean,
7
+ peers: readonly PeeringPeer[],
8
+ loopback: boolean,
9
+ ): Record<string, unknown> {
10
+ const swarm = object(config.Swarm, "Kubo Swarm configuration");
11
+ const addresses = peers
12
+ .flatMap(({ ID, Addrs }) => Addrs.map((address) => `${address}/p2p/${ID}`))
13
+ .sort();
14
+ return {
15
+ ...config,
16
+ Bootstrap: addresses,
17
+ Peering: { Peers: [] },
18
+ AutoConf: { Enabled: false },
19
+ AutoTLS: { Enabled: false },
20
+ AutoNAT: { ServiceMode: "disabled" },
21
+ Ipns: {
22
+ ...object(config.Ipns ?? {}, "Kubo IPNS configuration"),
23
+ DelegatedPublishers: [],
24
+ },
25
+ Routing: {
26
+ Type: pivot ? "dhtserver" : "dhtclient",
27
+ DelegatedRouters: [],
28
+ LoopbackAddressesOnLanDHT: loopback,
29
+ },
30
+ Internal: {
31
+ ...object(config.Internal ?? {}, "Kubo Internal configuration"),
32
+ // Private swarms cannot use public AutoNAT to activate their hop service.
33
+ // This is a role declaration, not a verified Internet reachability claim.
34
+ Libp2pForceReachability: pivot ? "public" : "private",
35
+ NonPublicAddrPublishing: true,
36
+ },
37
+ Discovery: { MDNS: { Enabled: false } },
38
+ Swarm: {
39
+ ...swarm,
40
+ EnableHolePunching: true,
41
+ RelayClient: {
42
+ Enabled: true,
43
+ // libp2p counts static entries before grouping candidates by PeerID.
44
+ // One entry per ID avoids a three-minute wait for duplicate candidates;
45
+ // Bootstrap supplies the complete address set to the same peerstore.
46
+ StaticRelays: peers
47
+ .flatMap(({ ID, Addrs }) =>
48
+ Addrs[0] ? [`${Addrs[0]}/p2p/${ID}`] : [],
49
+ )
50
+ .sort(),
51
+ },
52
+ RelayService: {
53
+ ...object(swarm.RelayService ?? {}, "Kubo relay service"),
54
+ Enabled: pivot,
55
+ },
56
+ },
57
+ };
58
+ }
59
+
60
+ export interface PivotCandidate {
61
+ addresses: string[];
62
+ failures: number;
63
+ retryAt: number;
64
+ probe: "success" | "failure" | "unknown";
65
+ probedAt: number | null;
66
+ error: string | null;
67
+ }
68
+
69
+ export class PivotCandidates {
70
+ private readonly candidates = new Map<string, PivotCandidate>();
71
+
72
+ reconcile(profiles: ReadonlyMap<string, readonly string[]>) {
73
+ for (const id of this.candidates.keys())
74
+ if (!profiles.has(id)) this.candidates.delete(id);
75
+ for (const [id, values] of profiles) {
76
+ const addresses = [...new Set(values)].sort();
77
+ const current = this.candidates.get(id);
78
+ if (JSON.stringify(current?.addresses) !== JSON.stringify(addresses))
79
+ this.candidates.set(id, {
80
+ addresses,
81
+ failures: 0,
82
+ retryAt: 0,
83
+ probe: "unknown",
84
+ probedAt: null,
85
+ error: null,
86
+ });
87
+ }
88
+ }
89
+
90
+ known(id: string): readonly string[] | undefined {
91
+ return this.candidates.get(id)?.addresses;
92
+ }
93
+
94
+ observations(): Map<string, PivotCandidate> {
95
+ return new Map(
96
+ [...this.candidates].map(([id, value]) => [
97
+ id,
98
+ { ...value, addresses: [...value.addresses] },
99
+ ]),
100
+ );
101
+ }
102
+
103
+ active(now = Date.now()): Map<string, readonly string[]> {
104
+ return new Map(
105
+ [...this.candidates]
106
+ .filter(([, value]) => value.addresses.length && value.retryAt <= now)
107
+ .map(([id, value]) => [id, value.addresses]),
108
+ );
109
+ }
110
+
111
+ result(
112
+ id: string,
113
+ healthy: boolean,
114
+ now = Date.now(),
115
+ random = Math.random(),
116
+ error: string | null = null,
117
+ ) {
118
+ const candidate = this.candidates.get(id);
119
+ if (!candidate) return;
120
+ candidate.probe = healthy ? "success" : "failure";
121
+ candidate.probedAt = now;
122
+ candidate.error = error;
123
+ if (healthy) {
124
+ candidate.failures = 0;
125
+ candidate.retryAt = 0;
126
+ } else {
127
+ candidate.failures++;
128
+ if (candidate.failures >= 3)
129
+ candidate.retryAt =
130
+ now +
131
+ Math.min(900_000, 60_000 * 2 ** Math.min(candidate.failures - 3, 4)) *
132
+ (0.8 + random * 0.4);
133
+ }
134
+ }
135
+ }