@capybara-hq/kernel 0.1.0-rc.73 → 0.1.0-rc.75

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 (85) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/catalog/admin-catalog.schemas.d.ts +3 -1
  3. package/dist/catalog/admin-catalog.schemas.js +6 -2
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/org-catalog.schemas.d.ts +3 -1
  6. package/dist/catalog/org-catalog.schemas.js +3 -1
  7. package/dist/catalog/plugin-package.js +7 -5
  8. package/dist/catalog/reserved-names.js +3 -9
  9. package/dist/channels/actions.js +4 -0
  10. package/dist/channels/cards.d.ts +10 -7
  11. package/dist/channels/cards.js +23 -12
  12. package/dist/channels/phrases.d.ts +24 -2
  13. package/dist/channels/phrases.js +12 -2
  14. package/dist/ctx/secrets.d.ts +4 -2
  15. package/dist/ctx/secrets.js +19 -5
  16. package/dist/db/kernel-schema.d.ts +14 -0
  17. package/dist/devices/conversation-devices.d.ts +3 -2
  18. package/dist/devices/conversation-devices.js +9 -4
  19. package/dist/devices/device-projects.service.d.ts +22 -27
  20. package/dist/devices/device-projects.service.js +39 -44
  21. package/dist/devices/devices.controller.d.ts +3 -5
  22. package/dist/devices/devices.controller.js +4 -17
  23. package/dist/devices/devices.schemas.d.ts +1 -1
  24. package/dist/devices/devices.schemas.js +1 -1
  25. package/dist/devices/devices.service.d.ts +75 -52
  26. package/dist/devices/devices.service.js +166 -95
  27. package/dist/devices/project-rules.d.ts +6 -8
  28. package/dist/devices/project-rules.js +5 -11
  29. package/dist/dial-in/auth.service.js +1 -1
  30. package/dist/dial-in/machines.d.ts +4 -15
  31. package/dist/dial-in/machines.js +4 -59
  32. package/dist/errors.d.ts +8 -3
  33. package/dist/errors.js +8 -3
  34. package/dist/extensions/admin-ops.js +2 -1
  35. package/dist/extensions/bootstrap-extra.d.ts +11 -1
  36. package/dist/extensions/bootstrap-extra.js +21 -1
  37. package/dist/extensions/bootstrap-manifest.d.ts +14 -0
  38. package/dist/extensions/bootstrap-manifest.js +23 -0
  39. package/dist/extensions/bootstrap-packages.d.ts +87 -0
  40. package/dist/extensions/bootstrap-packages.js +263 -0
  41. package/dist/extensions/bootstrap.d.ts +27 -71
  42. package/dist/extensions/bootstrap.js +85 -329
  43. package/dist/extensions/guide-places.d.ts +9 -0
  44. package/dist/extensions/guide-places.js +32 -22
  45. package/dist/extensions/plugin-guides.d.ts +20 -2
  46. package/dist/extensions/plugin-guides.js +39 -14
  47. package/dist/http/meta.controller.d.ts +0 -1
  48. package/dist/http/meta.controller.js +2 -6
  49. package/dist/identity/sso-paths.d.ts +7 -0
  50. package/dist/identity/sso-paths.js +13 -0
  51. package/dist/identity/sso.js +3 -2
  52. package/dist/index.d.ts +3 -1
  53. package/dist/index.js +3 -1
  54. package/dist/lifecycle/kernel-lifecycle.js +2 -2
  55. package/dist/platform/exclusions.js +2 -7
  56. package/dist/platform/ops/devices.ops.js +11 -7
  57. package/dist/platform/ops/setup.ops.js +1 -1
  58. package/dist/runtime/project/knowledge.service.js +6 -5
  59. package/dist/sandbox/device-sandbox.d.ts +27 -2
  60. package/dist/sandbox/device-sandbox.js +42 -5
  61. package/dist/sandbox/modes.d.ts +16 -4
  62. package/dist/sandbox/modes.js +12 -0
  63. package/dist/sandbox/operation-authority.js +3 -1
  64. package/dist/sandbox/permission-authority-lock.d.ts +6 -0
  65. package/dist/sandbox/permission-authority-lock.js +14 -0
  66. package/dist/sandbox/permission-facts.d.ts +16 -2
  67. package/dist/sandbox/permission-facts.js +20 -5
  68. package/dist/sandbox/review/permission-candidate.d.ts +12 -7
  69. package/dist/sandbox/review/permission-candidate.js +28 -7
  70. package/dist/sandbox/sandbox.service.d.ts +18 -11
  71. package/dist/sandbox/sandbox.service.js +51 -24
  72. package/dist/setup/setup-guides.service.d.ts +3 -4
  73. package/dist/setup/setup-guides.service.js +2 -5
  74. package/dist/shares/sweep.job.d.ts +2 -0
  75. package/dist/shares/sweep.job.js +3 -1
  76. package/dist/tools/approvals.service.d.ts +31 -11
  77. package/dist/tools/approvals.service.js +55 -19
  78. package/dist/tools/builtins/sandbox/common.d.ts +2 -2
  79. package/dist/tools/builtins/sandbox/common.js +2 -2
  80. package/dist/tools/network-asks.d.ts +103 -20
  81. package/dist/tools/network-asks.js +133 -18
  82. package/dist/tools/pipeline.d.ts +5 -0
  83. package/dist/tools/pipeline.js +15 -8
  84. package/package.json +3 -3
  85. package/src/migrations/0178_bootstrap_run_extra.sql +17 -0
@@ -11,7 +11,6 @@ import { randomBytes } from "node:crypto";
11
11
  import { isDeviceBootId } from "@capybara-hq/plugin-sdk/device-protocol";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
- import { audit } from "../identity/audit.js";
15
14
  import { sha256Hex } from "../identity/hash.js";
16
15
  import { afterCommit } from "../infra/database/after-commit.js";
17
16
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -19,8 +18,6 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
19
18
  import { Transactional } from "../infra/database/transactional.decorator.js";
20
19
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
21
20
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
22
- import { DeviceProviders, servesDialIn } from "../sandbox/providers.js";
23
- import { deviceNotFound } from "../sandbox/sandbox.service.js";
24
21
  import { deviceRevokedTopic } from "./keys.js";
25
22
  import { DialInRelay } from "./relay.js";
26
23
  /** The machine credential's prefix (`cap_dev_` plus 32 random bytes, base64url). */
@@ -44,15 +41,13 @@ let DialInMachines = class DialInMachines {
44
41
  bus;
45
42
  log;
46
43
  ceilings;
47
- providers;
48
- constructor(db, txHost, relay, bus, log, ceilings, providers) {
44
+ constructor(db, txHost, relay, bus, log, ceilings) {
49
45
  this.db = db;
50
46
  this.txHost = txHost;
51
47
  this.relay = relay;
52
48
  this.bus = bus;
53
49
  this.log = log;
54
50
  this.ceilings = ceilings;
55
- this.providers = providers;
56
51
  }
57
52
  /**
58
53
  * A new machine for the device and its credential (returned once). Revokes the
@@ -196,47 +191,11 @@ let DialInMachines = class DialInMachines {
196
191
  ]))
197
192
  .execute();
198
193
  }
199
- /**
200
- * Disconnects the machine of one of the person's own live dial-in devices, whatever its
201
- * provider (`DELETE /orgs/:orgId/devices/:id/machine`): revokes it and audits
202
- * `device.machine_revoked`. Anyone else's device, a cloud one or a missing one →
203
- * `device.not_found`; no machine connected is a no-op.
204
- */
205
- async revoke(orgId, accountId, deviceId, actorTokenId) {
206
- const env = await this.db
207
- .selectFrom("devices")
208
- .select(["id", "provider"])
209
- .where("id", "=", deviceId)
210
- .where("org_id", "=", orgId)
211
- .where("owner_kind", "=", "personal")
212
- .where("owner_account_id", "=", accountId)
213
- .where("deleted_at", "is", null)
214
- .forNoKeyUpdate()
215
- .executeTakeFirst();
216
- if (!env)
217
- throw deviceNotFound();
218
- // a dial-in device: its provider serves the dial-in channel, or a machine signed in to it
219
- // (its provider may be unloaded here, and the person disconnects anyway)
220
- const p = this.providers.forDevice(env.provider);
221
- if (!(p !== undefined && servesDialIn(p)) && !(await this.everSignedIn(deviceId)))
222
- throw deviceNotFound();
223
- const machineId = await this.revokeActive(deviceId, "revoked");
224
- if (machineId === null)
225
- return;
226
- await audit(this.db.db, {
227
- actorAccountId: accountId,
228
- ...(actorTokenId !== undefined && { actorTokenId }),
229
- orgId,
230
- action: "device.machine_revoked",
231
- target: deviceId,
232
- detail: { machineId },
233
- });
234
- }
235
194
  /**
236
195
  * Revokes the device's active machine, if any, in the caller's transaction, and after the
237
196
  * commit tells it to stop (not when `replaced`) and closes its connection for `reason`. Returns
238
- * the revoked machine's id. Used by {@link issue} (`replaced`), {@link revoke} (`revoked`) and
239
- * the device's deletion (`deleted`).
197
+ * the revoked machine's id. Used by {@link issue} (`replaced`) and the device's deletion
198
+ * (`deleted`).
240
199
  */
241
200
  async revokeActive(deviceId, reason) {
242
201
  const device = await this.db
@@ -286,16 +245,6 @@ let DialInMachines = class DialInMachines {
286
245
  afterCommit(() => this.disconnect(deviceId, machineId, "revoked", { stop: false }));
287
246
  return true;
288
247
  }
289
- /** Whether a machine ever signed in to the device (revoked or not). */
290
- async everSignedIn(deviceId) {
291
- const row = await this.db
292
- .selectFrom("device_machines")
293
- .select("id")
294
- .where("device_id", "=", deviceId)
295
- .limit(1)
296
- .executeTakeFirst();
297
- return row !== undefined;
298
- }
299
248
  /** The device's active machine, or null. */
300
249
  async activeFor(deviceId) {
301
250
  const r = await this.db
@@ -357,9 +306,6 @@ __decorate([
357
306
  __decorate([
358
307
  Transactional()
359
308
  ], DialInMachines.prototype, "recordConnect", null);
360
- __decorate([
361
- Transactional()
362
- ], DialInMachines.prototype, "revoke", null);
363
309
  __decorate([
364
310
  Transactional()
365
311
  ], DialInMachines.prototype, "revokeActive", null);
@@ -373,8 +319,7 @@ DialInMachines = __decorate([
373
319
  __param(2, Inject(DialInRelay)),
374
320
  __param(3, Inject(KERNEL_BUS)),
375
321
  __param(4, Inject(KERNEL_LOGGER)),
376
- __param(5, Inject(PermissionCeilingWrites)),
377
- __param(6, Inject(DeviceProviders))
322
+ __param(5, Inject(PermissionCeilingWrites))
378
323
  ], DialInMachines);
379
324
  export { DialInMachines };
380
325
  /** Two machine rows (or a login) name the same machine: same name, OS and arch. */
package/dist/errors.d.ts CHANGED
@@ -455,6 +455,11 @@ export declare const ERROR_CODES: {
455
455
  * message lists the providers on in the org.
456
456
  */
457
457
  readonly "device.provider_required": 400;
458
+ /**
459
+ * A new device is created on a dial-in provider (or the default is one): its devices are made
460
+ * by the machine signing in, following the provider's guide in the new-device dialog.
461
+ */
462
+ readonly "device.provider_dial_in": 409;
458
463
  /** The person already has a live device with this name (case-insensitive). */
459
464
  readonly "device.name_taken": 409;
460
465
  /** The person already has `devices.maxPersonal` live personal devices. */
@@ -505,8 +510,8 @@ export declare const ERROR_CODES: {
505
510
  /** The device has no project with this name. */
506
511
  readonly "device.project_not_found": 404;
507
512
  /**
508
- * The project's path is outside what the device may read in its current mode (sandbox mode and
509
- * cloud devices: the workspace; project root §4.2).
513
+ * The project's path is outside what the device lets a project reach: its browse scope refused
514
+ * it (no reason given), or the resolved path is not one a device can hold.
510
515
  */
511
516
  readonly "device.project_outside_mode": 422;
512
517
  /**
@@ -516,7 +521,7 @@ export declare const ERROR_CODES: {
516
521
  readonly "device.project_path_too_broad": 422;
517
522
  /** The project's directory does not exist on the device. */
518
523
  readonly "device.project_path_missing": 422;
519
- /** The project's path is a file, cannot be read, or the device refused it in its current mode. */
524
+ /** The project's path is a file or a directory the device cannot read. */
520
525
  readonly "device.project_path_unreadable": 422;
521
526
  /** The device provider refused the project's directory (its reason is the message and details). */
522
527
  readonly "device.project_refused": 422;
package/dist/errors.js CHANGED
@@ -455,6 +455,11 @@ export const ERROR_CODES = {
455
455
  * message lists the providers on in the org.
456
456
  */
457
457
  "device.provider_required": 400,
458
+ /**
459
+ * A new device is created on a dial-in provider (or the default is one): its devices are made
460
+ * by the machine signing in, following the provider's guide in the new-device dialog.
461
+ */
462
+ "device.provider_dial_in": 409,
458
463
  /** The person already has a live device with this name (case-insensitive). */
459
464
  "device.name_taken": 409,
460
465
  /** The person already has `devices.maxPersonal` live personal devices. */
@@ -505,8 +510,8 @@ export const ERROR_CODES = {
505
510
  /** The device has no project with this name. */
506
511
  "device.project_not_found": 404,
507
512
  /**
508
- * The project's path is outside what the device may read in its current mode (sandbox mode and
509
- * cloud devices: the workspace; project root §4.2).
513
+ * The project's path is outside what the device lets a project reach: its browse scope refused
514
+ * it (no reason given), or the resolved path is not one a device can hold.
510
515
  */
511
516
  "device.project_outside_mode": 422,
512
517
  /**
@@ -516,7 +521,7 @@ export const ERROR_CODES = {
516
521
  "device.project_path_too_broad": 422,
517
522
  /** The project's directory does not exist on the device. */
518
523
  "device.project_path_missing": 422,
519
- /** The project's path is a file, cannot be read, or the device refused it in its current mode. */
524
+ /** The project's path is a file or a directory the device cannot read. */
520
525
  "device.project_path_unreadable": 422,
521
526
  /** The device provider refused the project's directory (its reason is the message and details). */
522
527
  "device.project_refused": 422,
@@ -11,6 +11,7 @@ import { SDK_VERSION } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import semver from "semver";
14
+ import { itemRemovedError } from "../catalog/ownership.js";
14
15
  import { oweDeployedExtensionSync } from "../catalog/scope-jobs.js";
15
16
  import { pluginSchemaName } from "../ctx/create-ctx.js";
16
17
  import { ApiError } from "../errors.js";
@@ -180,7 +181,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
180
181
  .executeTakeFirst();
181
182
  // The lock waits out a removal holding the row; the row read then is the removed one
182
183
  if (opts.liveItem && (item === undefined || item.deleted_at !== null)) {
183
- throw new ApiError("catalog.item_removed", `${name} was removed while its confirmation was running; nothing of it stays installed`);
184
+ throw itemRemovedError(name);
184
185
  }
185
186
  }
186
187
  const row = await this.lockRow(name);
@@ -18,7 +18,9 @@ export type MergedBootstrapManifest = Omit<BootstrapManifest, "plugins"> & {
18
18
  };
19
19
  /**
20
20
  * What an extra manifest left in the deployment: the config-managed marketplaces and the entries
21
- * the last completed bootstrap run took from an extra manifest (flagged `extra` in its results).
21
+ * an extra manifest contributed to the latest bootstrap run: the run that started writing and has
22
+ * not completed (`bootstrap_run_started`, ruling R19) when there is one, else the last completed
23
+ * run (flagged `extra` in its results, R17).
22
24
  * A process without an extra manifest that finds any is configured differently from the ones that
23
25
  * wrote them ({@link missingExtraManifestMessage}).
24
26
  */
@@ -40,6 +42,14 @@ export type LoadedBootstrapManifest = MergedBootstrapManifest;
40
42
  export declare function readBootstrapExtraManifest(file: string): Promise<BootstrapExtraManifest>;
41
43
  /** Built-in entries first, then the extra ones; a name in both is `bootstrap.extra_conflict`. */
42
44
  export declare function mergeBootstrapManifests(builtin: BootstrapManifest, extra: BootstrapExtraManifest | undefined): MergedBootstrapManifest;
45
+ /**
46
+ * sha256 (hex) of the extra manifest's part of a merged manifest: its entries (as merged), its
47
+ * marketplaces and its default theme; null without an extra manifest. A recorded run counts as done
48
+ * only while the latest completed run has the same extra part (ruling R18), so a distribution
49
+ * removed (an empty extra manifest) and added back runs again, while a replica on another
50
+ * built-in manifest with the same extra manifest (a rolling upgrade) does not.
51
+ */
52
+ export declare function bootstrapExtraSha256(manifest: MergedBootstrapManifest): string | null;
43
53
  /** Loads the built-in manifest (a given one, else the file) and merges the extra file into it. */
44
54
  export declare function loadBootstrapManifest(o: {
45
55
  manifestFile?: string;
@@ -1,8 +1,10 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { readFile } from "node:fs/promises";
2
3
  import { parseBootstrapExtraManifest, } from "@capybara-hq/plugin-sdk";
3
4
  import { marketplaceForm } from "../catalog/marketplaces.service.js";
4
5
  import { ApiError } from "../errors.js";
5
- import { BOOTSTRAP_MANIFEST_FILE, errMsg, readBootstrapManifest } from "./bootstrap.js";
6
+ import { BOOTSTRAP_MANIFEST_FILE, readBootstrapManifest } from "./bootstrap-manifest.js";
7
+ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
6
8
  /** Whether `t` names anything: then a process without an extra manifest must not sync or run. */
7
9
  export const hasExtraManifestTraces = (t) => t.marketplaces.length > 0 || t.plugins.length > 0;
8
10
  /** Reads and parses an extra manifest; every problem (also a missing file) is `bootstrap.extra_invalid`. */
@@ -57,6 +59,24 @@ export function mergeBootstrapManifests(builtin, extra) {
57
59
  },
58
60
  };
59
61
  }
62
+ /**
63
+ * sha256 (hex) of the extra manifest's part of a merged manifest: its entries (as merged), its
64
+ * marketplaces and its default theme; null without an extra manifest. A recorded run counts as done
65
+ * only while the latest completed run has the same extra part (ruling R18), so a distribution
66
+ * removed (an empty extra manifest) and added back runs again, while a replica on another
67
+ * built-in manifest with the same extra manifest (a rolling upgrade) does not.
68
+ */
69
+ export function bootstrapExtraSha256(manifest) {
70
+ if (manifest.extra === undefined)
71
+ return null;
72
+ const names = new Set(manifest.extra.plugins);
73
+ const part = {
74
+ plugins: manifest.plugins.filter((p) => names.has(p.name)),
75
+ marketplaces: manifest.extra.marketplaces,
76
+ ...(manifest.extra.defaultTheme !== undefined && { defaultTheme: manifest.extra.defaultTheme }),
77
+ };
78
+ return createHash("sha256").update(JSON.stringify(part)).digest("hex");
79
+ }
60
80
  /** Loads the built-in manifest (a given one, else the file) and merges the extra file into it. */
61
81
  export async function loadBootstrapManifest(o) {
62
82
  const builtin = o.builtin ?? (await readBootstrapManifest(o.manifestFile ?? BOOTSTRAP_MANIFEST_FILE));
@@ -0,0 +1,14 @@
1
+ import { type BootstrapManifest } from "@capybara-hq/plugin-sdk";
2
+ /**
3
+ * The built-in bootstrap manifest: where it ships, how it is read and its run identity (spec
4
+ * 2026-11-20-bootstrap-extra-manifest §3). Shared by the kernel start and `capybara bootstrap`;
5
+ * merging an extra manifest into it is `bootstrap-extra.ts`.
6
+ */
7
+ /** The bootstrap manifest that ships with the kernel package. */
8
+ export declare const BOOTSTRAP_MANIFEST_FILE: string;
9
+ /** sha256 (hex) of a manifest: of its JSON text as parsed (key order kept). */
10
+ export declare function bootstrapManifestSha256(manifest: Omit<BootstrapManifest, "plugins"> & {
11
+ plugins: readonly object[];
12
+ }): string;
13
+ /** Reads and parses a bootstrap manifest file; an invalid one throws with its problems. */
14
+ export declare function readBootstrapManifest(file?: string): Promise<BootstrapManifest>;
@@ -0,0 +1,23 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { fileURLToPath } from "node:url";
4
+ import { parseBootstrapManifest } from "@capybara-hq/plugin-sdk";
5
+ /**
6
+ * The built-in bootstrap manifest: where it ships, how it is read and its run identity (spec
7
+ * 2026-11-20-bootstrap-extra-manifest §3). Shared by the kernel start and `capybara bootstrap`;
8
+ * merging an extra manifest into it is `bootstrap-extra.ts`.
9
+ */
10
+ /** The bootstrap manifest that ships with the kernel package. */
11
+ export const BOOTSTRAP_MANIFEST_FILE = fileURLToPath(new URL("../../bootstrap.json", import.meta.url));
12
+ /** sha256 (hex) of a manifest: of its JSON text as parsed (key order kept). */
13
+ export function bootstrapManifestSha256(manifest) {
14
+ return createHash("sha256").update(JSON.stringify(manifest)).digest("hex");
15
+ }
16
+ /** Reads and parses a bootstrap manifest file; an invalid one throws with its problems. */
17
+ export async function readBootstrapManifest(file = BOOTSTRAP_MANIFEST_FILE) {
18
+ const parsed = parseBootstrapManifest(JSON.parse(await readFile(file, "utf8")));
19
+ if ("errors" in parsed) {
20
+ throw new Error(`invalid bootstrap manifest ${file}: ${parsed.errors.join("; ")}`);
21
+ }
22
+ return parsed;
23
+ }
@@ -0,0 +1,87 @@
1
+ import { type BootstrapExtraMarketplace, type Logger } from "@capybara-hq/plugin-sdk";
2
+ import type { KernelConfig } from "../config/schema.js";
3
+ import { ApiError } from "../errors.js";
4
+ import { fetchNpmPackage } from "../packages/npm.js";
5
+ import type { BootstrapGitRunEntry, MergedBootstrapEntry, MergedBootstrapManifest } from "./bootstrap-extra.js";
6
+ /**
7
+ * Obtaining the packages of a bootstrap run (spec 2026-11-20-bootstrap-extra-manifest §3, §8): the
8
+ * offline directory, npm and git entries, each verified against its pinned sha512 before anything
9
+ * reads it. Shared by the bootstrap step and `capybara bootstrap`.
10
+ */
11
+ /** The sha512 integrity (`sha512-<base64>`) of a package's bytes. */
12
+ export declare const integrityOf: (bytes: Uint8Array) => string;
13
+ /** What {@link resolveBootstrapPackages} needs from the kernel config. */
14
+ export interface BootstrapResolveOptions {
15
+ /**
16
+ * The offline directory: every `*.tgz` directly in it is matched to the entries by sha512.
17
+ * Omitted or missing: no offline packages.
18
+ */
19
+ dir?: string;
20
+ config: Pick<KernelConfig, "packages" | "marketplaces" | "net">;
21
+ signal?: AbortSignal;
22
+ log?: Pick<Logger, "warn">;
23
+ /** The npm download (default {@link fetchNpmPackage}; tests replace it). */
24
+ fetch?: typeof fetchNpmPackage;
25
+ /**
26
+ * Entries whose package failing to be obtained is that entry's failure only: the error goes into
27
+ * `failed` (by entry name) and the other entries are still obtained. Every other entry's failure
28
+ * throws, so nothing is written.
29
+ */
30
+ soft?: (e: MergedBootstrapEntry) => boolean;
31
+ failed?: Map<string, ApiError>;
32
+ /**
33
+ * The credential of an extra-manifest marketplace (by name) for its git entries; default: the
34
+ * token `marketplaces.tokens[name]` (never the file or the secrets table) and the manifest's
35
+ * `username`. It is sent only to that marketplace URL's origin.
36
+ */
37
+ gitCredentials?: (marketplace: string) => {
38
+ token?: string;
39
+ username?: string;
40
+ };
41
+ /** Filled with the git tree oid of each git entry read from git (by entry name). */
42
+ gitTrees?: Map<string, string>;
43
+ }
44
+ /**
45
+ * The marketplace a git entry names, its URL expanded as the managed row's (`config:<name>`) is and
46
+ * checked as an admin-added one is (`bootstrap.extra_invalid` otherwise).
47
+ */
48
+ export declare function bootstrapGitMarketplace(manifest: Pick<MergedBootstrapManifest, "extra">, e: BootstrapGitRunEntry, config: Pick<KernelConfig, "marketplaces">): BootstrapExtraMarketplace;
49
+ /**
50
+ * Obtains every entry's tgz, checked against its pinned sha512: from the offline directory when a
51
+ * file there has that sha512, else (a `source: "npm"` entry) downloaded from the npm registry and
52
+ * verified against the pin (the packument's `dist.integrity` is not consulted), else (a
53
+ * `source: "git"` entry) its marketplace's tree at the pinned commit, the files under `path`
54
+ * re-rooted and packed with `packPackageTgz` (the pin is defined on that pack), refused unless the
55
+ * pack's sha512 is the pin: nothing of an unverified tree is read, translated or imported. The
56
+ * marketplace's token and username go only to its URL's origin. Throws an {@link ApiError} naming
57
+ * the plugin for the first entry it cannot obtain (`bootstrap.missing_file`,
58
+ * `bootstrap.download_failed`, `bootstrap.git_read_failed`, `bootstrap.integrity_mismatch`), except
59
+ * for the `soft` entries (recorded in `failed`, left out of the result).
60
+ */
61
+ export declare function resolveBootstrapPackages(manifest: MergedBootstrapManifest, o: BootstrapResolveOptions): Promise<Map<string, Uint8Array>>;
62
+ /** What a git entry's tree is, as the bootstrap import reads it ({@link readBootstrapGitPlugin}). */
63
+ export interface BootstrapGitPlugin {
64
+ /** `capybara`: `.capybara-plugin/plugin.json`; `claude`: a Claude Code plugin; `skills`: skills only. */
65
+ kind: "capybara" | "claude" | "skills";
66
+ name: string;
67
+ version: string;
68
+ /** The plugin has an extension (only a `capybara` tree can). */
69
+ extension: boolean;
70
+ }
71
+ /**
72
+ * Name, version and kind of a git entry's tree, as the bootstrap import identifies it (spec
73
+ * 2026-11-20-bootstrap-extra-manifest §9, "As built" R20): a tree with `.capybara-plugin/plugin.json`
74
+ * by that file (the import's manifest parser); a Claude Code plugin (`.claude-plugin/plugin.json`,
75
+ * or its other markers) by the import's translation with the entry as fallback, so its version is
76
+ * the Claude manifest's, else the entry's; a skills-only tree named and versioned by the entry. The
77
+ * kernel's bootstrap step and `capybara-plugin bootstrap --write` both call it, so the version a pin
78
+ * records is the one the import checks. Only the identity is read here: the import still checks the
79
+ * whole tree. An unreadable identity throws `PluginPackageError` (`catalog.invalid_manifest`).
80
+ */
81
+ export declare function readBootstrapGitPlugin(files: ReadonlyMap<string, Uint8Array>, entry: {
82
+ name: string;
83
+ version: string;
84
+ }, o?: {
85
+ publisher?: string;
86
+ allowInsecureLoopback?: boolean;
87
+ }): BootstrapGitPlugin;
@@ -0,0 +1,263 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdir, readFile, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { PLUGIN_MANIFEST_FILE, parsePluginManifest, } from "@capybara-hq/plugin-sdk";
5
+ import { isClaudePluginTree, translateClaudePlugin } from "../catalog/claude/translate.js";
6
+ import { GitSourceError, normalGitPath, readGitTreeAndOids } from "../catalog/git-source.js";
7
+ import { marketplaceNetPolicy, marketplaceUrlProblem } from "../catalog/marketplace-fetch.js";
8
+ import { marketplaceForm } from "../catalog/marketplaces.service.js";
9
+ import { PluginPackageError, withoutRemovedManifestFields } from "../catalog/plugin-package.js";
10
+ import { ApiError } from "../errors.js";
11
+ import { fetchNpmPackage, IntegrityMismatchError, NpmFetchError, PackageTooLargeError, } from "../packages/npm.js";
12
+ import { packPackageTgz } from "../packages/tgz.js";
13
+ /**
14
+ * Obtaining the packages of a bootstrap run (spec 2026-11-20-bootstrap-extra-manifest §3, §8): the
15
+ * offline directory, npm and git entries, each verified against its pinned sha512 before anything
16
+ * reads it. Shared by the bootstrap step and `capybara bootstrap`.
17
+ */
18
+ /** The sha512 integrity (`sha512-<base64>`) of a package's bytes. */
19
+ export const integrityOf = (bytes) => `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
20
+ /**
21
+ * The marketplace a git entry names, its URL expanded as the managed row's (`config:<name>`) is and
22
+ * checked as an admin-added one is (`bootstrap.extra_invalid` otherwise).
23
+ */
24
+ export function bootstrapGitMarketplace(manifest, e, config) {
25
+ const m = manifest.extra?.marketplaces.find((x) => x.name === e.marketplace);
26
+ const invalid = (why) => new ApiError("bootstrap.extra_invalid", `Bootstrap plugin ${e.name} ${e.version}: marketplace ${e.marketplace} ${why}`);
27
+ if (m === undefined)
28
+ throw invalid("is not declared in the extra bootstrap manifest");
29
+ const { form, url } = marketplaceForm(m.url);
30
+ if (form !== "git")
31
+ throw invalid("is not a git repository");
32
+ const problem = marketplaceUrlProblem(url, config.marketplaces.allowInsecureLoopback);
33
+ if (problem !== null)
34
+ throw invalid(`has an unusable url: ${problem}`);
35
+ return { ...m, url };
36
+ }
37
+ /**
38
+ * Obtains every entry's tgz, checked against its pinned sha512: from the offline directory when a
39
+ * file there has that sha512, else (a `source: "npm"` entry) downloaded from the npm registry and
40
+ * verified against the pin (the packument's `dist.integrity` is not consulted), else (a
41
+ * `source: "git"` entry) its marketplace's tree at the pinned commit, the files under `path`
42
+ * re-rooted and packed with `packPackageTgz` (the pin is defined on that pack), refused unless the
43
+ * pack's sha512 is the pin: nothing of an unverified tree is read, translated or imported. The
44
+ * marketplace's token and username go only to its URL's origin. Throws an {@link ApiError} naming
45
+ * the plugin for the first entry it cannot obtain (`bootstrap.missing_file`,
46
+ * `bootstrap.download_failed`, `bootstrap.git_read_failed`, `bootstrap.integrity_mismatch`), except
47
+ * for the `soft` entries (recorded in `failed`, left out of the result).
48
+ */
49
+ export async function resolveBootstrapPackages(manifest, o) {
50
+ const out = new Map();
51
+ if (manifest.plugins.length === 0)
52
+ return out;
53
+ const { npmRegistry, npmToken, maxBytes } = o.config.packages;
54
+ const offline = o.dir !== undefined ? await scanOfflineDir(o.dir, maxBytes, o.log) : new Map();
55
+ const fetchPackage = o.fetch ?? fetchNpmPackage;
56
+ const signal = o.signal ?? new AbortController().signal;
57
+ const where = o.dir !== undefined ? o.dir : "the bootstrap directory (config bootstrap.dir)";
58
+ for (const e of manifest.plugins) {
59
+ signal.throwIfAborted();
60
+ try {
61
+ out.set(e.name, await obtain(e));
62
+ }
63
+ catch (err) {
64
+ if (signal.aborted || !(err instanceof ApiError) || o.soft?.(e) !== true)
65
+ throw err;
66
+ o.failed?.set(e.name, err);
67
+ }
68
+ }
69
+ return out;
70
+ async function obtain(e) {
71
+ const found = offline.get(e.integrity);
72
+ if (found !== undefined)
73
+ return found;
74
+ if (e.source === "git")
75
+ return obtainGit(e);
76
+ if (e.source === "workspace") {
77
+ throw new ApiError("bootstrap.missing_file", `Bootstrap plugin ${e.name} ${e.version}: no file in ${where} has its pinned sha512 (${e.integrity.slice(0, 19)}…), and a workspace entry cannot be downloaded; put its package tgz (pnpm pack-plugin ${e.path}) in that directory`);
78
+ }
79
+ const registry = registryOrigin(npmRegistry);
80
+ const offlineHint = `to install offline, put the package tgz (npm pack ${e.npm}@${e.version}, any file name) in ${where}`;
81
+ try {
82
+ const r = await fetchPackage({
83
+ registry: npmRegistry,
84
+ ...(npmToken !== undefined && { token: npmToken }),
85
+ maxBytes,
86
+ net: marketplaceNetPolicy(o.config),
87
+ }, e.npm, e.version, signal, { expectedIntegrity: e.integrity });
88
+ return r.bytes;
89
+ }
90
+ catch (err) {
91
+ if (signal.aborted)
92
+ throw err;
93
+ if (err instanceof IntegrityMismatchError) {
94
+ throw new ApiError("bootstrap.integrity_mismatch", `Bootstrap plugin ${e.name} ${e.version}: the package ${e.npm}@${e.version} downloaded from ${registry} does not match its pinned sha512 (expected ${e.integrity.slice(0, 19)}…, got ${err.actual.slice(0, 19)}…); refusing to install anything`);
95
+ }
96
+ const reason = err instanceof NpmFetchError || err instanceof PackageTooLargeError
97
+ ? err.message
98
+ : err instanceof Error
99
+ ? err.message
100
+ : String(err);
101
+ throw new ApiError("bootstrap.download_failed", `Bootstrap plugin ${e.name} ${e.version}: cannot download ${e.npm}@${e.version} from ${registry} (${reason}); ${offlineHint}, or set packages.npmRegistry to a reachable mirror`);
102
+ }
103
+ }
104
+ async function obtainGit(e) {
105
+ const m = bootstrapGitMarketplace(manifest, e, o.config);
106
+ const u = new URL(m.url);
107
+ const at = `${e.path} at ${e.commit.slice(0, 12)} of marketplace ${m.name} (${u.origin}${u.pathname})`;
108
+ const cred = (o.gitCredentials ?? defaultGitCredentials)(m.name);
109
+ const token = cred.token !== undefined && cred.token !== "" ? cred.token : undefined;
110
+ const dir = normalGitPath(e.path);
111
+ let read;
112
+ try {
113
+ read = await readGitTreeAndOids({ url: m.url, commit: e.commit, path: e.path }, {
114
+ net: marketplaceNetPolicy(o.config),
115
+ maxBytes,
116
+ signal,
117
+ ...(token !== undefined && {
118
+ token,
119
+ tokenOrigin: u.origin,
120
+ ...(cred.username !== undefined && cred.username !== "" && { username: cred.username }),
121
+ }),
122
+ trees: () => [dir],
123
+ });
124
+ }
125
+ catch (err) {
126
+ if (signal.aborted)
127
+ throw err;
128
+ // git-source messages never carry the token; redacted all the same, it is a credential
129
+ const reason = errMsg(err);
130
+ const redacted = token !== undefined ? reason.replaceAll(token, "***") : reason;
131
+ // A bootstrap entry pins a commit by its sha: a ref tip is not what it can change to
132
+ const message = err instanceof GitSourceError && err.refusedCommit !== undefined
133
+ ? `the host refused to send commit ${err.refusedCommit} by its sha. The commit must be fetchable by its sha (GitHub: always; GitLab, Gitea and other hosts: only when fetching unadvertised commits is allowed, e.g. git's uploadpack.allowReachableSHA1InWant or the host's equivalent), or pin the commit of a tag and keep the tag, or put its pack (capybara-plugin bootstrap --write --out <dir>) in the offline directory, ${where}`
134
+ : `${redacted}; to install offline, put its pack (capybara-plugin bootstrap --write) in ${where}`;
135
+ throw new ApiError("bootstrap.git_read_failed", `Bootstrap plugin ${e.name} ${e.version}: cannot read ${at}: ${message}`);
136
+ }
137
+ const pack = await packPackageTgz(read.files);
138
+ const actual = integrityOf(pack);
139
+ if (actual !== e.integrity) {
140
+ throw new ApiError("bootstrap.integrity_mismatch", `Bootstrap plugin ${e.name} ${e.version}: ${at} packs to another sha512 than its pin (expected ${e.integrity.slice(0, 19)}…, got ${actual.slice(0, 19)}…); refusing to install anything`);
141
+ }
142
+ const tree = read.trees.get(dir);
143
+ if (tree !== undefined)
144
+ o.gitTrees?.set(e.name, tree);
145
+ return pack;
146
+ }
147
+ function defaultGitCredentials(name) {
148
+ const tokens = o.config.marketplaces.tokens;
149
+ const username = manifest.extra?.marketplaces.find((x) => x.name === name)?.username;
150
+ return {
151
+ ...(Object.hasOwn(tokens, name) && { token: tokens[name] }),
152
+ ...(username !== undefined && { username }),
153
+ };
154
+ }
155
+ }
156
+ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
157
+ /** The registry's origin, for messages (never its credentials or path). */
158
+ function registryOrigin(registry) {
159
+ try {
160
+ return new URL(registry).origin;
161
+ }
162
+ catch {
163
+ return "the configured npm registry";
164
+ }
165
+ }
166
+ /**
167
+ * The `*.tgz` files directly in `dir` by their sha512 integrity. A missing directory is an empty
168
+ * one; a file larger than `maxBytes` is skipped with a warning.
169
+ */
170
+ async function scanOfflineDir(dir, maxBytes, log) {
171
+ const out = new Map();
172
+ let names;
173
+ try {
174
+ names = await readdir(dir);
175
+ }
176
+ catch (err) {
177
+ const code = err.code;
178
+ if (code === "ENOENT" || code === "ENOTDIR")
179
+ return out;
180
+ throw err;
181
+ }
182
+ for (const name of names.sort()) {
183
+ if (!name.endsWith(".tgz"))
184
+ continue;
185
+ const file = join(dir, name);
186
+ const st = await stat(file).catch(() => undefined);
187
+ if (!st?.isFile())
188
+ continue;
189
+ if (st.size > maxBytes) {
190
+ log?.warn("bootstrap: a file in the bootstrap directory exceeds packages.maxBytes; skipped", {
191
+ file,
192
+ size: st.size,
193
+ maxBytes,
194
+ });
195
+ continue;
196
+ }
197
+ const bytes = new Uint8Array(await readFile(file));
198
+ const integrity = integrityOf(bytes);
199
+ if (!out.has(integrity))
200
+ out.set(integrity, bytes);
201
+ }
202
+ return out;
203
+ }
204
+ /**
205
+ * Name, version and kind of a git entry's tree, as the bootstrap import identifies it (spec
206
+ * 2026-11-20-bootstrap-extra-manifest §9, "As built" R20): a tree with `.capybara-plugin/plugin.json`
207
+ * by that file (the import's manifest parser); a Claude Code plugin (`.claude-plugin/plugin.json`,
208
+ * or its other markers) by the import's translation with the entry as fallback, so its version is
209
+ * the Claude manifest's, else the entry's; a skills-only tree named and versioned by the entry. The
210
+ * kernel's bootstrap step and `capybara-plugin bootstrap --write` both call it, so the version a pin
211
+ * records is the one the import checks. Only the identity is read here: the import still checks the
212
+ * whole tree. An unreadable identity throws `PluginPackageError` (`catalog.invalid_manifest`).
213
+ */
214
+ export function readBootstrapGitPlugin(files, entry, o = {}) {
215
+ const own = files.get(PLUGIN_MANIFEST_FILE);
216
+ if (own !== undefined) {
217
+ const m = manifestOf(own, PLUGIN_MANIFEST_FILE);
218
+ return {
219
+ kind: "capybara",
220
+ name: m.name,
221
+ version: m.version,
222
+ extension: m.extension !== undefined,
223
+ };
224
+ }
225
+ if (isClaudePluginTree(files)) {
226
+ const t = translateClaudePlugin(files, {
227
+ fallbackName: entry.name,
228
+ fallbackVersion: entry.version,
229
+ fallbackPublisher: o.publisher ?? entry.name,
230
+ entryVersion: entry.version,
231
+ ...(o.allowInsecureLoopback !== undefined && {
232
+ allowInsecureLoopback: o.allowInsecureLoopback,
233
+ }),
234
+ });
235
+ const m = manifestOf(t.tree.get(PLUGIN_MANIFEST_FILE), `${PLUGIN_MANIFEST_FILE} (translated)`);
236
+ return { kind: "claude", name: m.name, version: m.version, extension: false };
237
+ }
238
+ if (![...files.keys()].some((p) => p.startsWith("skills/"))) {
239
+ throw new PluginPackageError("catalog.invalid_manifest", [
240
+ `${PLUGIN_MANIFEST_FILE} not found, and the tree is neither a Claude Code plugin nor a skills-only plugin (no skills/ directory)`,
241
+ ]);
242
+ }
243
+ return { kind: "skills", name: entry.name, version: entry.version, extension: false };
244
+ }
245
+ /** A plugin manifest's bytes parsed as the import parses them. */
246
+ function manifestOf(bytes, where) {
247
+ let text;
248
+ try {
249
+ text =
250
+ bytes !== undefined ? new TextDecoder("utf-8", { fatal: true }).decode(bytes) : undefined;
251
+ }
252
+ catch {
253
+ text = undefined;
254
+ }
255
+ if (text === undefined) {
256
+ throw new PluginPackageError("catalog.invalid_manifest", [`${where} is not valid UTF-8 text`]);
257
+ }
258
+ const parsed = parsePluginManifest(withoutRemovedManifestFields(text));
259
+ if ("errors" in parsed) {
260
+ throw new PluginPackageError("catalog.invalid_manifest", parsed.errors.map((e) => `${where}: ${e}`));
261
+ }
262
+ return parsed;
263
+ }