@capybara-hq/kernel 0.1.0-rc.62 → 0.1.0-rc.63

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.
@@ -0,0 +1,74 @@
1
+ import { type BootstrapEntry, type BootstrapExtraManifest, type BootstrapExtraMarketplace, type BootstrapGitEntry, type BootstrapManifest, type Logger } from "@capybara-hq/plugin-sdk";
2
+ /**
3
+ * The built-in bootstrap manifest merged with the extra one (spec 2026-11-20-bootstrap-extra-manifest
4
+ * §3): ONE manifest, built-in entries first, hashed as a whole by `bootstrapManifestSha256`. `extra`
5
+ * is absent without an extra manifest, so the object (and its sha256) is the built-in manifest's.
6
+ */
7
+ export type MergedBootstrapManifest = Omit<BootstrapManifest, "plugins"> & {
8
+ plugins: MergedBootstrapEntry[];
9
+ extra?: {
10
+ marketplaces: BootstrapExtraMarketplace[];
11
+ /** The names of the entries that came from the extra manifest (flagged `extra` in a run's results). */
12
+ plugins: string[];
13
+ defaultTheme?: {
14
+ plugin: string;
15
+ theme: string;
16
+ };
17
+ };
18
+ };
19
+ /**
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).
22
+ * A process without an extra manifest that finds any is configured differently from the ones that
23
+ * wrote them ({@link missingExtraManifestMessage}).
24
+ */
25
+ export interface ExtraManifestTraces {
26
+ marketplaces: string[];
27
+ plugins: string[];
28
+ }
29
+ /** Whether `t` names anything: then a process without an extra manifest must not sync or run. */
30
+ export declare const hasExtraManifestTraces: (t: ExtraManifestTraces) => boolean;
31
+ /** A git entry of the merged manifest: `required` defaults to false, as for an npm extra entry. */
32
+ export type BootstrapGitRunEntry = BootstrapGitEntry & {
33
+ required: boolean;
34
+ };
35
+ /** One entry of the merged manifest. */
36
+ export type MergedBootstrapEntry = BootstrapEntry | BootstrapGitRunEntry;
37
+ /** What the bootstrap step runs: the merged manifest. */
38
+ export type LoadedBootstrapManifest = MergedBootstrapManifest;
39
+ /** Reads and parses an extra manifest; every problem (also a missing file) is `bootstrap.extra_invalid`. */
40
+ export declare function readBootstrapExtraManifest(file: string): Promise<BootstrapExtraManifest>;
41
+ /** Built-in entries first, then the extra ones; a name in both is `bootstrap.extra_conflict`. */
42
+ export declare function mergeBootstrapManifests(builtin: BootstrapManifest, extra: BootstrapExtraManifest | undefined): MergedBootstrapManifest;
43
+ /** Loads the built-in manifest (a given one, else the file) and merges the extra file into it. */
44
+ export declare function loadBootstrapManifest(o: {
45
+ manifestFile?: string;
46
+ builtin?: BootstrapManifest;
47
+ extraManifest?: string;
48
+ }): Promise<LoadedBootstrapManifest>;
49
+ /**
50
+ * A process without an extra manifest found what one left (`t`): another service of the deployment
51
+ * runs with an extra manifest, or an earlier `capybara bootstrap` ran with one. Bootstrapping or
52
+ * syncing here would demote its marketplaces and strip the extra entries' `required` / `builtin`
53
+ * under the built-in manifest's sha, which the correctly configured services then take as done.
54
+ */
55
+ export declare function missingExtraManifestMessage(t: ExtraManifestTraces): string;
56
+ /**
57
+ * The bootstrap step refused under its lock: the manifest has no extra manifest while an extra
58
+ * manifest left traces (`traces`; rulings R16, R17). A replica that checked before another
59
+ * replica's sync committed gets here instead of stripping the extra entries' required / builtin.
60
+ * Nothing was written.
61
+ */
62
+ export declare class BootstrapExtraMismatchError extends Error {
63
+ readonly traces: ExtraManifestTraces;
64
+ constructor(traces: ExtraManifestTraces);
65
+ }
66
+ /**
67
+ * Runs `syncExtraFromConfig`: a deadlock or serialization failure is retried once; a failure that
68
+ * remains is logged and does not stop the start (another replica writes the same rows).
69
+ * A configuration error is not contention and is thrown. The marketplaces it demoted (their
70
+ * names left the extra manifest) are logged as a warning.
71
+ */
72
+ export declare function syncExtraMarketplaces(sync: (marketplaces: readonly BootstrapExtraMarketplace[] | undefined) => Promise<readonly string[]>,
73
+ /** The extra manifest's marketplaces; undefined: no extra manifest (nothing is demoted). */
74
+ marketplaces: readonly BootstrapExtraMarketplace[] | undefined, log: Pick<Logger, "warn">): Promise<void>;
@@ -0,0 +1,131 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { parseBootstrapExtraManifest, } from "@capybara-hq/plugin-sdk";
3
+ import { marketplaceForm } from "../catalog/marketplaces.service.js";
4
+ import { ApiError } from "../errors.js";
5
+ import { BOOTSTRAP_MANIFEST_FILE, errMsg, readBootstrapManifest } from "./bootstrap.js";
6
+ /** Whether `t` names anything: then a process without an extra manifest must not sync or run. */
7
+ export const hasExtraManifestTraces = (t) => t.marketplaces.length > 0 || t.plugins.length > 0;
8
+ /** Reads and parses an extra manifest; every problem (also a missing file) is `bootstrap.extra_invalid`. */
9
+ export async function readBootstrapExtraManifest(file) {
10
+ let json;
11
+ try {
12
+ json = JSON.parse(await readFile(file, "utf8"));
13
+ }
14
+ catch (e) {
15
+ throw new ApiError("bootstrap.extra_invalid", `Cannot read the extra bootstrap manifest ${file}: ${errMsg(e)}`);
16
+ }
17
+ const parsed = parseBootstrapExtraManifest(json);
18
+ if ("errors" in parsed) {
19
+ throw new ApiError("bootstrap.extra_invalid", `Invalid extra bootstrap manifest ${file}: ${parsed.errors.join("; ")}`);
20
+ }
21
+ checkGitMarketplaces(parsed.manifest, file);
22
+ return parsed.manifest;
23
+ }
24
+ /** A git entry reads its marketplace as a git repository, so that marketplace must be git form. */
25
+ function checkGitMarketplaces(extra, where) {
26
+ const used = new Set(extra.plugins.flatMap((e) => (e.source === "git" ? [e.marketplace] : [])));
27
+ for (const m of extra.marketplaces) {
28
+ if (used.has(m.name) && marketplaceForm(m.url).form !== "git") {
29
+ throw new ApiError("bootstrap.extra_invalid", `Invalid extra bootstrap manifest ${where}: marketplace ${m.name} serves git entries, so its url must be a git repository: an https URL ending in .git`);
30
+ }
31
+ }
32
+ }
33
+ /** Built-in entries first, then the extra ones; a name in both is `bootstrap.extra_conflict`. */
34
+ export function mergeBootstrapManifests(builtin, extra) {
35
+ if (extra === undefined)
36
+ return builtin;
37
+ checkGitMarketplaces(extra, "(extra manifest)");
38
+ const names = new Set(builtin.plugins.map((p) => p.name));
39
+ for (const e of extra.plugins) {
40
+ if (names.has(e.name)) {
41
+ throw new ApiError("bootstrap.extra_conflict", `The extra bootstrap manifest declares plugin ${e.name}, which the built-in bootstrap manifest already pins; an extra manifest never overrides a built-in pin`);
42
+ }
43
+ }
44
+ const plugins = [
45
+ ...builtin.plugins,
46
+ ...extra.plugins.map((e) => e.source === "git"
47
+ ? { ...e, required: e.required ?? false }
48
+ : { ...e, required: e.required ?? false }),
49
+ ];
50
+ return {
51
+ ...builtin,
52
+ plugins,
53
+ extra: {
54
+ marketplaces: extra.marketplaces,
55
+ plugins: extra.plugins.map((e) => e.name),
56
+ ...(extra.defaultTheme !== undefined && { defaultTheme: extra.defaultTheme }),
57
+ },
58
+ };
59
+ }
60
+ /** Loads the built-in manifest (a given one, else the file) and merges the extra file into it. */
61
+ export async function loadBootstrapManifest(o) {
62
+ const builtin = o.builtin ?? (await readBootstrapManifest(o.manifestFile ?? BOOTSTRAP_MANIFEST_FILE));
63
+ const extra = o.extraManifest !== undefined ? await readBootstrapExtraManifest(o.extraManifest) : undefined;
64
+ return mergeBootstrapManifests(builtin, extra);
65
+ }
66
+ /**
67
+ * A process without an extra manifest found what one left (`t`): another service of the deployment
68
+ * runs with an extra manifest, or an earlier `capybara bootstrap` ran with one. Bootstrapping or
69
+ * syncing here would demote its marketplaces and strip the extra entries' `required` / `builtin`
70
+ * under the built-in manifest's sha, which the correctly configured services then take as done.
71
+ */
72
+ export function missingExtraManifestMessage(t) {
73
+ const found = [
74
+ ...(t.marketplaces.length > 0
75
+ ? [`marketplaces an extra manifest manages (${t.marketplaces.join(", ")})`]
76
+ : []),
77
+ ...(t.plugins.length > 0
78
+ ? [`plugins the last bootstrap run took from an extra manifest (${t.plugins.join(", ")})`]
79
+ : []),
80
+ ].join(" and ");
81
+ return `this service has no extra bootstrap manifest (bootstrap.extraManifest, env CAPYBARA_BOOTSTRAP__EXTRA_MANIFEST), but the deployment has ${found}: every service (init, api, worker, gateway) must use the same extra manifest. To remove a distribution, point bootstrap.extraManifest at a file whose marketplaces and plugins lists are empty`;
82
+ }
83
+ /**
84
+ * The bootstrap step refused under its lock: the manifest has no extra manifest while an extra
85
+ * manifest left traces (`traces`; rulings R16, R17). A replica that checked before another
86
+ * replica's sync committed gets here instead of stripping the extra entries' required / builtin.
87
+ * Nothing was written.
88
+ */
89
+ export class BootstrapExtraMismatchError extends Error {
90
+ traces;
91
+ constructor(traces) {
92
+ super(missingExtraManifestMessage(traces));
93
+ this.traces = traces;
94
+ this.name = "BootstrapExtraMismatchError";
95
+ }
96
+ }
97
+ /** Postgres deadlock_detected / serialization_failure: replicas starting together may collide. */
98
+ const isContention = (e) => {
99
+ const codeOf = (x) => x?.code;
100
+ const code = codeOf(e) ?? codeOf(e?.cause);
101
+ return code === "40P01" || code === "40001";
102
+ };
103
+ /**
104
+ * Runs `syncExtraFromConfig`: a deadlock or serialization failure is retried once; a failure that
105
+ * remains is logged and does not stop the start (another replica writes the same rows).
106
+ * A configuration error is not contention and is thrown. The marketplaces it demoted (their
107
+ * names left the extra manifest) are logged as a warning.
108
+ */
109
+ export async function syncExtraMarketplaces(sync,
110
+ /** The extra manifest's marketplaces; undefined: no extra manifest (nothing is demoted). */
111
+ marketplaces, log) {
112
+ for (let attempt = 1;; attempt++) {
113
+ try {
114
+ const demoted = await sync(marketplaces);
115
+ if (demoted.length > 0) {
116
+ log.warn("marketplaces left the extra bootstrap manifest: they are now ordinary custom marketplaces (editable, no deployment token)", { marketplaces: demoted });
117
+ }
118
+ return;
119
+ }
120
+ catch (e) {
121
+ if (!isContention(e))
122
+ throw e;
123
+ if (attempt < 2)
124
+ continue;
125
+ log.warn("could not sync the marketplaces of the extra bootstrap manifest; continuing", {
126
+ error: errMsg(e),
127
+ });
128
+ return;
129
+ }
130
+ }
131
+ }
@@ -1,4 +1,4 @@
1
- import { type BootstrapEntry, type BootstrapManifest, type Logger } from "@capybara-hq/plugin-sdk";
1
+ import { type BootstrapExtraMarketplace, type BootstrapManifest, type Logger } from "@capybara-hq/plugin-sdk";
2
2
  import { type PluginImport } from "../catalog/plugin-import.js";
3
3
  import type { KernelConfig } from "../config/schema.js";
4
4
  import { ApiError } from "../errors.js";
@@ -9,6 +9,7 @@ import { LockService } from "../infra/lock/lock.service.js";
9
9
  import type { KernelLogger } from "../log.js";
10
10
  import { fetchNpmPackage } from "../packages/npm.js";
11
11
  import { ExtensionAdminOps } from "./admin-ops.js";
12
+ import { type BootstrapGitRunEntry, type ExtraManifestTraces, type MergedBootstrapEntry, type MergedBootstrapManifest } from "./bootstrap-extra.js";
12
13
  import { ExtensionInstalls } from "./installs.js";
13
14
  import { PluginApproveLock } from "./locks.js";
14
15
  import { ExtensionRegistry } from "./registry.js";
@@ -24,8 +25,11 @@ import type { SingleProviderNote } from "./single-provider.js";
24
25
  * ({@link resolveBootstrapPackages}): a `*.tgz` file of the optional offline directory whose
25
26
  * sha512 equals the entry's `integrity` (the file name does not matter), else the npm download
26
27
  * of a `source: "npm"` entry (`packages.npmRegistry` / `npmToken` / `maxBytes`, verified against
27
- * the pin only). A workspace entry without a matching file is `bootstrap.missing_file`, a failed
28
- * download `bootstrap.download_failed`, a download that differs from the pin
28
+ * the pin only), or the git read of a `source: "git"` entry of the extra manifest (its tree at the
29
+ * pinned commit, packed with `packPackageTgz` and verified against the pin before anything reads
30
+ * it; see {@link resolveBootstrapPackages}). A workspace entry without a matching file is
31
+ * `bootstrap.missing_file`, a failed download `bootstrap.download_failed` (a failed git read
32
+ * `bootstrap.git_read_failed`), a package that differs from the pin
29
33
  * `bootstrap.integrity_mismatch` (all name the plugin), and then nothing is written. Downloading
30
34
  * inside the lock means a fleet starting together downloads once.
31
35
  * - The whole run holds the Redis lock `lock:bootstrap` (`LockService`, decision R5 of the Nest
@@ -47,7 +51,10 @@ import type { SingleProviderNote } from "./single-provider.js";
47
51
  * declarative one imported again when its catalog item is gone).
48
52
  * - Per entry, by the installed state of its extension:
49
53
  * - not installed (and new, or required): imported into the catalog (source `bootstrap`, ref
50
- * `bootstrap:<name>@<version>`, like a marketplace import), installed, approved (snapshot
54
+ * `bootstrap:<name>@<version>`, like a marketplace import; a git entry is recorded as the
55
+ * managed marketplace `config:<marketplace>` it names, with the git location an admin import of
56
+ * that marketplace's `path` entry records, so later imports from it are the same source),
57
+ * installed, approved (snapshot
51
58
  * source `bootstrap`, audited `extension.permissions_approved` with `source: "bootstrap"`)
52
59
  * and enabled -> `installed`;
53
60
  * - installed from `bootstrap` at a lower version: upgraded the same way (core's release vouched
@@ -88,6 +95,12 @@ export interface BootstrapEntryResult {
88
95
  * a single-provider extension point it provides. (A required entry fails instead.)
89
96
  */
90
97
  leftDisabled?: SingleProviderNote;
98
+ /**
99
+ * The entry came from the extra manifest (absent otherwise, and in rows written before this
100
+ * flag): a later process without an extra manifest that finds it in the last run refuses to run
101
+ * (ruling R17).
102
+ */
103
+ extra?: true;
91
104
  }
92
105
  export interface BootstrapResult {
93
106
  /** sha256 (hex) of the manifest ({@link bootstrapManifestSha256}). */
@@ -122,7 +135,9 @@ export declare class BootstrapFailedError extends Error {
122
135
  get requiredFailed(): boolean;
123
136
  }
124
137
  /** sha256 (hex) of a manifest: of its JSON text as parsed (key order kept). */
125
- export declare function bootstrapManifestSha256(manifest: BootstrapManifest): string;
138
+ export declare function bootstrapManifestSha256(manifest: Omit<BootstrapManifest, "plugins"> & {
139
+ plugins: readonly object[];
140
+ }): string;
126
141
  /** Reads and parses a bootstrap manifest file; an invalid one throws with its problems. */
127
142
  export declare function readBootstrapManifest(file?: string): Promise<BootstrapManifest>;
128
143
  /** What {@link resolveBootstrapPackages} needs from the kernel config. */
@@ -142,18 +157,40 @@ export interface BootstrapResolveOptions {
142
157
  * `failed` (by entry name) and the other entries are still obtained. Every other entry's failure
143
158
  * throws, so nothing is written.
144
159
  */
145
- soft?: (e: BootstrapEntry) => boolean;
160
+ soft?: (e: MergedBootstrapEntry) => boolean;
146
161
  failed?: Map<string, ApiError>;
162
+ /**
163
+ * The credential of an extra-manifest marketplace (by name) for its git entries; default: the
164
+ * token `marketplaces.tokens[name]` (never the file or the secrets table) and the manifest's
165
+ * `username`. It is sent only to that marketplace URL's origin.
166
+ */
167
+ gitCredentials?: (marketplace: string) => {
168
+ token?: string;
169
+ username?: string;
170
+ };
171
+ /** Filled with the git tree oid of each git entry read from git (by entry name). */
172
+ gitTrees?: Map<string, string>;
147
173
  }
174
+ /**
175
+ * The marketplace a git entry names, its URL expanded as the managed row's (`config:<name>`) is and
176
+ * checked as an admin-added one is (`bootstrap.extra_invalid` otherwise).
177
+ */
178
+ export declare function bootstrapGitMarketplace(manifest: Pick<MergedBootstrapManifest, "extra">, e: BootstrapGitRunEntry, config: Pick<KernelConfig, "marketplaces">): BootstrapExtraMarketplace;
148
179
  /**
149
180
  * Obtains every entry's tgz, checked against its pinned sha512: from the offline directory when a
150
181
  * file there has that sha512, else (a `source: "npm"` entry) downloaded from the npm registry and
151
- * verified against the pin (the packument's `dist.integrity` is not consulted). Throws an
152
- * {@link ApiError} naming the plugin for the first entry it cannot obtain
153
- * (`bootstrap.missing_file`, `bootstrap.download_failed`, `bootstrap.integrity_mismatch`), except
182
+ * verified against the pin (the packument's `dist.integrity` is not consulted), else (a
183
+ * `source: "git"` entry) its marketplace's tree at the pinned commit, the files under `path`
184
+ * re-rooted and packed with `packPackageTgz` (the pin is defined on that pack), refused unless the
185
+ * pack's sha512 is the pin: nothing of an unverified tree is read, translated or imported. The
186
+ * marketplace's token and username go only to its URL's origin. Throws an {@link ApiError} naming
187
+ * the plugin for the first entry it cannot obtain (`bootstrap.missing_file`,
188
+ * `bootstrap.download_failed`, `bootstrap.git_read_failed`, `bootstrap.integrity_mismatch`), except
154
189
  * for the `soft` entries (recorded in `failed`, left out of the result).
155
190
  */
156
- export declare function resolveBootstrapPackages(manifest: BootstrapManifest, o: BootstrapResolveOptions): Promise<Map<string, Uint8Array>>;
191
+ export declare function resolveBootstrapPackages(manifest: MergedBootstrapManifest, o: BootstrapResolveOptions): Promise<Map<string, Uint8Array>>;
192
+ /** The message of a thrown value. */
193
+ export declare const errMsg: (e: unknown) => string;
157
194
  /** The lock around a whole run (`lock:bootstrap`). */
158
195
  export declare const BOOTSTRAP_LOCK_KEY = "bootstrap";
159
196
  /** Its lifetime without renewal; a run keeps it by renewal, a crashed holder's expires. */
@@ -161,7 +198,7 @@ export declare const BOOTSTRAP_LOCK_TTL_MS = 120000;
161
198
  /** Optional provider: the lock's lifetime (ms) instead of {@link BOOTSTRAP_LOCK_TTL_MS} (tests shorten it). */
162
199
  export declare const BOOTSTRAP_LOCK_TTL: unique symbol;
163
200
  /** What a run imports a declarative entry or an entry's catalog version with. */
164
- export type BootstrapImports = Pick<PluginImport, "prepare" | "confirm">;
201
+ export type BootstrapImports = Pick<PluginImport, "prepare" | "prepareGit" | "confirm">;
165
202
  export declare class BootstrapService {
166
203
  private readonly kdb;
167
204
  readonly txHost: TransactionHost;
@@ -192,15 +229,27 @@ export declare class BootstrapService {
192
229
  private config;
193
230
  /** Whether the bootstrap step completed for the manifest with this sha256. */
194
231
  isDone(manifestSha256: string): Promise<boolean>;
232
+ /**
233
+ * What an extra manifest left ({@link ExtraManifestTraces}): the config-managed marketplaces
234
+ * (`managed = 'config'`) and the entries the last completed run flagged `extra`. A process
235
+ * without an extra manifest that finds any is configured differently from the ones that wrote
236
+ * them (rulings R14, R17). An entry a built-in manifest dropped is never flagged, so it is no
237
+ * trace.
238
+ */
239
+ extraManifestTraces(): Promise<ExtraManifestTraces>;
195
240
  /**
196
241
  * Runs the bootstrap step (see the file header); when it is already done for this manifest
197
242
  * (also when another replica finished it while this one waited for the lock) returns the
198
243
  * recorded result without doing anything. `carry`: the results of an earlier, failed run in the
199
244
  * same start ({@link BootstrapFailedError.results}); an entry it installed, upgraded or imported
200
- * keeps that action instead of `kept` in this run's record.
245
+ * keeps that action instead of `kept` in this run's record. A manifest without an extra manifest
246
+ * while an extra manifest left traces ({@link extraManifestTraces}) throws
247
+ * {@link BootstrapExtraMismatchError}, checked under the lock before anything is obtained or
248
+ * written (ruling R16): the caller's own check may have run before another replica's sync
249
+ * committed. Every result of an entry from the extra manifest is flagged `extra` (R17).
201
250
  */
202
251
  run(o: {
203
- manifest: BootstrapManifest;
252
+ manifest: MergedBootstrapManifest;
204
253
  /** The offline directory (see {@link resolveBootstrapPackages}); omitted: npm only. */
205
254
  dir?: string;
206
255
  signal?: AbortSignal;
@@ -233,6 +282,8 @@ export declare class BootstrapService {
233
282
  * signal that also aborts when the lock is lost.
234
283
  */
235
284
  private locked;
285
+ /** The results of the last completed run (undefined before any run completed). */
286
+ private lastRunResults;
236
287
  /** The entry names the last completed run handled (undefined before any run completed). */
237
288
  private lastRunNames;
238
289
  private entry;
@@ -247,6 +298,19 @@ export declare class BootstrapService {
247
298
  * `plugin.name_taken`) is never touched.
248
299
  */
249
300
  private markBuiltin;
301
+ /**
302
+ * The files of a git entry's verified pack (exactly the tree read at its commit). A tree the tgz
303
+ * rules refuse is `catalog.invalid_manifest`.
304
+ */
305
+ private unpackGit;
306
+ /**
307
+ * Name, version and extension of a git entry's tree: from its `plugin.json`; a tree without one
308
+ * (a Claude Code or skills-only plugin, never an extension) is named by the entry, which its
309
+ * import's review is checked against ({@link prepareGitEntry}).
310
+ */
311
+ private gitPlugin;
312
+ /** Stages a git entry from its files as an admin git import would (translation included). */
313
+ private prepareGitEntry;
250
314
  /** A declarative plugin: catalog only. Returns false when that version is already imported. */
251
315
  private importOnly;
252
316
  /**