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

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 (76) 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 +36 -41
  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 +72 -52
  26. package/dist/devices/devices.service.js +158 -93
  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 +5 -4
  31. package/dist/dial-in/machines.js +5 -4
  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/identity/sso-paths.d.ts +7 -0
  48. package/dist/identity/sso-paths.js +13 -0
  49. package/dist/identity/sso.js +3 -2
  50. package/dist/index.d.ts +3 -1
  51. package/dist/index.js +3 -1
  52. package/dist/lifecycle/kernel-lifecycle.js +2 -2
  53. package/dist/platform/exclusions.js +2 -7
  54. package/dist/platform/ops/devices.ops.js +11 -7
  55. package/dist/platform/ops/setup.ops.js +1 -1
  56. package/dist/runtime/project/knowledge.service.js +6 -5
  57. package/dist/sandbox/device-sandbox.d.ts +11 -0
  58. package/dist/sandbox/device-sandbox.js +29 -0
  59. package/dist/sandbox/modes.d.ts +16 -4
  60. package/dist/sandbox/modes.js +12 -0
  61. package/dist/sandbox/permission-facts.d.ts +12 -2
  62. package/dist/sandbox/permission-facts.js +14 -4
  63. package/dist/sandbox/sandbox.service.d.ts +18 -11
  64. package/dist/sandbox/sandbox.service.js +51 -24
  65. package/dist/setup/setup-guides.service.d.ts +2 -2
  66. package/dist/setup/setup-guides.service.js +1 -1
  67. package/dist/tools/approvals.service.d.ts +31 -11
  68. package/dist/tools/approvals.service.js +55 -19
  69. package/dist/tools/builtins/sandbox/common.d.ts +2 -2
  70. package/dist/tools/builtins/sandbox/common.js +2 -2
  71. package/dist/tools/network-asks.d.ts +103 -20
  72. package/dist/tools/network-asks.js +133 -18
  73. package/dist/tools/pipeline.d.ts +5 -0
  74. package/dist/tools/pipeline.js +15 -8
  75. package/package.json +3 -3
  76. package/src/migrations/0178_bootstrap_run_extra.sql +17 -0
@@ -8,20 +8,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHash } from "node:crypto";
11
- import { readdir, readFile, stat } from "node:fs/promises";
12
- import { join } from "node:path";
13
- import { fileURLToPath } from "node:url";
14
- import { PLUGIN_MANIFEST_FILE, parseBootstrapManifest, SDK_VERSION, } from "@capybara-hq/plugin-sdk";
11
+ import { SDK_VERSION } from "@capybara-hq/plugin-sdk";
15
12
  import { Inject, Injectable, Optional } from "@nestjs/common";
16
13
  import { sql } from "kysely";
17
14
  import semver from "semver";
18
15
  import { marketplaceGitSource, repoOwner } from "../catalog/catalog.service.js";
19
- import { GitSourceError, normalGitPath, readGitTreeAndOids } from "../catalog/git-source.js";
20
- import { marketplaceNetPolicy, marketplaceUrlProblem } from "../catalog/marketplace-fetch.js";
21
- import { CONFIG_MARKETPLACE_PREFIX, marketplaceForm } from "../catalog/marketplaces.service.js";
16
+ import { CONFIG_MARKETPLACE_PREFIX } from "../catalog/marketplaces.service.js";
22
17
  import { otherNameOwner } from "../catalog/ownership.js";
23
18
  import { catalogPackageError, } from "../catalog/plugin-import.js";
24
- import { PluginPackageError, readPluginFiles, readPluginPackage, } from "../catalog/plugin-package.js";
19
+ import { PluginPackageError, readPluginPackage } from "../catalog/plugin-package.js";
25
20
  import { ApiError } from "../errors.js";
26
21
  import { audit } from "../identity/audit.js";
27
22
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -30,91 +25,17 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
30
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
31
26
  import { LockService } from "../infra/lock/lock.service.js";
32
27
  import { KERNEL_LOGGER } from "../infra/tokens.js";
33
- import { fetchNpmPackage, IntegrityMismatchError, NpmFetchError, PackageTooLargeError, } from "../packages/npm.js";
34
- import { PackageTgzError, packPackageTgz, unpackPackageTgz } from "../packages/tgz.js";
28
+ import { PackageTgzError, unpackPackageTgz } from "../packages/tgz.js";
35
29
  import { ExtensionAdminOps } from "./admin-ops.js";
36
30
  import { writeSnapshot } from "./approvals.js";
37
- import { BootstrapExtraMismatchError, hasExtraManifestTraces, } from "./bootstrap-extra.js";
31
+ import { BootstrapExtraMismatchError, bootstrapExtraSha256, hasExtraManifestTraces, } from "./bootstrap-extra.js";
32
+ import { bootstrapManifestSha256 } from "./bootstrap-manifest.js";
33
+ import { bootstrapGitMarketplace, integrityOf, readBootstrapGitPlugin, resolveBootstrapPackages, } from "./bootstrap-packages.js";
38
34
  import { ExtensionInstalls } from "./installs.js";
39
35
  import { PluginApproveLock } from "./locks.js";
40
36
  import { ExtensionPackageError, permissionSetOfPackage, readExtensionPackage } from "./package.js";
41
37
  import { diffPermissions } from "./permission-set.js";
42
38
  import { ExtensionRegistry } from "./registry.js";
43
- /**
44
- * The bootstrap step (package ecosystem spec §7, startup bootstrap spec): installs the plugins
45
- * pinned by the bootstrap manifest (`packages/kernel/bootstrap.json`). It replaced the builtin
46
- * extensions.
47
- *
48
- * - When the run is already done for the manifest nothing is read: no directory, no network, so a
49
- * restart of an installed deployment never needs npm.
50
- * - Otherwise, inside the lock and before anything is written, every entry's tgz is obtained
51
- * ({@link resolveBootstrapPackages}): a `*.tgz` file of the optional offline directory whose
52
- * sha512 equals the entry's `integrity` (the file name does not matter), else the npm download
53
- * of a `source: "npm"` entry (`packages.npmRegistry` / `npmToken` / `maxBytes`, verified against
54
- * the pin only), or the git read of a `source: "git"` entry of the extra manifest (its tree at the
55
- * pinned commit, packed with `packPackageTgz` and verified against the pin before anything reads
56
- * it; see {@link resolveBootstrapPackages}). A workspace entry without a matching file is
57
- * `bootstrap.missing_file`, a failed download `bootstrap.download_failed` (a failed git read
58
- * `bootstrap.git_read_failed`), a package that differs from the pin
59
- * `bootstrap.integrity_mismatch` (all name the plugin), and then nothing is written. Downloading
60
- * inside the lock means a fleet starting together downloads once.
61
- * - The whole run holds the Redis lock `lock:bootstrap` (`LockService`, decision R5 of the Nest
62
- * kernel spec: TTL {@link BOOTSTRAP_LOCK_TTL_MS}, renewed every third of it, so a run longer than the TTL keeps
63
- * it and a crashed holder's lock expires within it), taken by an unbounded wait that observes
64
- * the signal: when several replicas (or `capybara bootstrap` and a starting kernel) run it
65
- * together only one runs it; the others wait, then find it done. A lost lock (renewal failed
66
- * until expiry) aborts the run at its next step. "Done" is a `bootstrap_runs` row for the
67
- * manifest's sha256 (written with the audit `bootstrap.completed` only when every entry
68
- * succeeded; otherwise the next start runs it again, which is idempotent).
69
- * - Two passes per start: the first runs before the extensions load (no object store yet), the
70
- * second after them. A `builtin` entry (not required, but builtin in the catalog) is deferred by
71
- * the first pass (`deferBuiltin`: skipped, not a failure; the run is then not recorded and the
72
- * start runs the second pass), so it may ship skills and templates. A required entry is imported
73
- * by the first pass and must succeed; a builtin one that fails is logged like an optional one.
74
- * - An optional preinstall (neither required nor builtin) may carry `scope: "all"`: its catalog
75
- * item is created with that scope (on in every org, switchable) instead of `optional`. The
76
- * scope is read only when the item is first imported (a new version of a live item keeps the
77
- * item's scope), so a later change of `scope` in the manifest never rewrites it: the super
78
- * admin owns the scope after import.
79
- * - Only entries new to the manifest are installed (Ruling 5): an optional entry that the last
80
- * completed run already handled and that is not installed now (a super admin uninstalled
81
- * it) stays uninstalled -> `kept`. A required or builtin entry is always installed (a
82
- * declarative one imported again when its catalog item is gone).
83
- * - Per entry, by the installed state of its extension:
84
- * - not installed (and new, or required): imported into the catalog (source `bootstrap`, ref
85
- * `bootstrap:<name>@<version>`, like a marketplace import; a git entry is recorded as the
86
- * managed marketplace `config:<marketplace>` it names, with the git location an admin import of
87
- * that marketplace's `path` entry records, so later imports from it are the same source),
88
- * installed, approved (snapshot
89
- * source `bootstrap`, audited `extension.permissions_approved` with `source: "bootstrap"`)
90
- * and enabled -> `installed`;
91
- * - installed from `bootstrap` at a lower version: upgraded the same way (core's release vouched
92
- * for the version, so new permissions are pre-approved and audited), keeping the desired state
93
- * a super admin chose (a disabled optional plugin stays disabled) -> `upgraded`;
94
- * - installed at a higher version, or from another source (a super admin upgraded it), or
95
- * the name is config-declared (`declared`: config wins, no install record is created):
96
- * untouched, never downgraded -> `kept`;
97
- * - a declarative plugin (no extension): imported into the catalog only -> `imported` (`kept`
98
- * when that version is already there, or when the entry is not new).
99
- * Every extension entry gets `extension_installs.required` from the manifest, and a required one
100
- * is enabled on the deployment.
101
- * - Package bytes are content-addressed: when the very same tgz was ingested before with another
102
- * source (e.g. imported from a marketplace), its `extension_packages` row keeps that source and
103
- * so does the install record, which is then not a bootstrap install and never upgraded by a
104
- * later manifest (`kept`, like a plugin the admin installed).
105
- * - An install record still `required` whose entry left the manifest is not uninstalled; it only
106
- * loses `required` -> `required_cleared`.
107
- * A failed entry does not stop the others; the run then throws {@link BootstrapFailedError} naming
108
- * them. The packages are kept in PG (`blob_store = 'pg'`), so installing an extension never needs
109
- * the object store (object-store-s3 is itself a bootstrap plugin) and the directory and npm are
110
- * never needed again. A plugin's icons and setup guide files are kept in PG too (`catalog_files`),
111
- * so they never need it either; its skills, connector templates and agent templates do (an entry
112
- * shipping them fails while no object store runs; an optional one is retried after the extensions
113
- * loaded, and a plugin that must be builtin and ships them is a `builtin` entry, which only the
114
- * pass after the extensions load imports).
115
- */
116
- /** The bootstrap manifest that ships with the kernel package. */
117
- export const BOOTSTRAP_MANIFEST_FILE = fileURLToPath(new URL("../../bootstrap.json", import.meta.url));
118
39
  /**
119
40
  * Some entries failed or were deferred (the others were done); the run is not recorded as done.
120
41
  */
@@ -146,206 +67,8 @@ export class BootstrapFailedError extends Error {
146
67
  return this.failures.some((f) => f.required);
147
68
  }
148
69
  }
149
- /** sha256 (hex) of a manifest: of its JSON text as parsed (key order kept). */
150
- export function bootstrapManifestSha256(manifest) {
151
- return createHash("sha256").update(JSON.stringify(manifest)).digest("hex");
152
- }
153
- /** Reads and parses a bootstrap manifest file; an invalid one throws with its problems. */
154
- export async function readBootstrapManifest(file = BOOTSTRAP_MANIFEST_FILE) {
155
- const parsed = parseBootstrapManifest(JSON.parse(await readFile(file, "utf8")));
156
- if ("errors" in parsed) {
157
- throw new Error(`invalid bootstrap manifest ${file}: ${parsed.errors.join("; ")}`);
158
- }
159
- return parsed;
160
- }
161
- const integrityOf = (bytes) => `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
162
- /**
163
- * The marketplace a git entry names, its URL expanded as the managed row's (`config:<name>`) is and
164
- * checked as an admin-added one is (`bootstrap.extra_invalid` otherwise).
165
- */
166
- export function bootstrapGitMarketplace(manifest, e, config) {
167
- const m = manifest.extra?.marketplaces.find((x) => x.name === e.marketplace);
168
- const invalid = (why) => new ApiError("bootstrap.extra_invalid", `Bootstrap plugin ${e.name} ${e.version}: marketplace ${e.marketplace} ${why}`);
169
- if (m === undefined)
170
- throw invalid("is not declared in the extra bootstrap manifest");
171
- const { form, url } = marketplaceForm(m.url);
172
- if (form !== "git")
173
- throw invalid("is not a git repository");
174
- const problem = marketplaceUrlProblem(url, config.marketplaces.allowInsecureLoopback);
175
- if (problem !== null)
176
- throw invalid(`has an unusable url: ${problem}`);
177
- return { ...m, url };
178
- }
179
70
  /** The managed marketplace's id of an extra-manifest marketplace (the row the kernel start creates). */
180
71
  const managedMarketplaceId = (name) => `${CONFIG_MARKETPLACE_PREFIX}${name}`;
181
- /**
182
- * Obtains every entry's tgz, checked against its pinned sha512: from the offline directory when a
183
- * file there has that sha512, else (a `source: "npm"` entry) downloaded from the npm registry and
184
- * verified against the pin (the packument's `dist.integrity` is not consulted), else (a
185
- * `source: "git"` entry) its marketplace's tree at the pinned commit, the files under `path`
186
- * re-rooted and packed with `packPackageTgz` (the pin is defined on that pack), refused unless the
187
- * pack's sha512 is the pin: nothing of an unverified tree is read, translated or imported. The
188
- * marketplace's token and username go only to its URL's origin. Throws an {@link ApiError} naming
189
- * the plugin for the first entry it cannot obtain (`bootstrap.missing_file`,
190
- * `bootstrap.download_failed`, `bootstrap.git_read_failed`, `bootstrap.integrity_mismatch`), except
191
- * for the `soft` entries (recorded in `failed`, left out of the result).
192
- */
193
- export async function resolveBootstrapPackages(manifest, o) {
194
- const out = new Map();
195
- if (manifest.plugins.length === 0)
196
- return out;
197
- const { npmRegistry, npmToken, maxBytes } = o.config.packages;
198
- const offline = o.dir !== undefined ? await scanOfflineDir(o.dir, maxBytes, o.log) : new Map();
199
- const fetchPackage = o.fetch ?? fetchNpmPackage;
200
- const signal = o.signal ?? new AbortController().signal;
201
- const where = o.dir !== undefined ? o.dir : "the bootstrap directory (config bootstrap.dir)";
202
- for (const e of manifest.plugins) {
203
- signal.throwIfAborted();
204
- try {
205
- out.set(e.name, await obtain(e));
206
- }
207
- catch (err) {
208
- if (signal.aborted || !(err instanceof ApiError) || o.soft?.(e) !== true)
209
- throw err;
210
- o.failed?.set(e.name, err);
211
- }
212
- }
213
- return out;
214
- async function obtain(e) {
215
- const found = offline.get(e.integrity);
216
- if (found !== undefined)
217
- return found;
218
- if (e.source === "git")
219
- return obtainGit(e);
220
- if (e.source === "workspace") {
221
- 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`);
222
- }
223
- const registry = registryOrigin(npmRegistry);
224
- const offlineHint = `to install offline, put the package tgz (npm pack ${e.npm}@${e.version}, any file name) in ${where}`;
225
- try {
226
- const r = await fetchPackage({
227
- registry: npmRegistry,
228
- ...(npmToken !== undefined && { token: npmToken }),
229
- maxBytes,
230
- net: marketplaceNetPolicy(o.config),
231
- }, e.npm, e.version, signal, { expectedIntegrity: e.integrity });
232
- return r.bytes;
233
- }
234
- catch (err) {
235
- if (signal.aborted)
236
- throw err;
237
- if (err instanceof IntegrityMismatchError) {
238
- 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`);
239
- }
240
- const reason = err instanceof NpmFetchError || err instanceof PackageTooLargeError
241
- ? err.message
242
- : err instanceof Error
243
- ? err.message
244
- : String(err);
245
- 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`);
246
- }
247
- }
248
- async function obtainGit(e) {
249
- const m = bootstrapGitMarketplace(manifest, e, o.config);
250
- const u = new URL(m.url);
251
- const at = `${e.path} at ${e.commit.slice(0, 12)} of marketplace ${m.name} (${u.origin}${u.pathname})`;
252
- const cred = (o.gitCredentials ?? defaultGitCredentials)(m.name);
253
- const token = cred.token !== undefined && cred.token !== "" ? cred.token : undefined;
254
- const dir = normalGitPath(e.path);
255
- let read;
256
- try {
257
- read = await readGitTreeAndOids({ url: m.url, commit: e.commit, path: e.path }, {
258
- net: marketplaceNetPolicy(o.config),
259
- maxBytes,
260
- signal,
261
- ...(token !== undefined && {
262
- token,
263
- tokenOrigin: u.origin,
264
- ...(cred.username !== undefined && cred.username !== "" && { username: cred.username }),
265
- }),
266
- trees: () => [dir],
267
- });
268
- }
269
- catch (err) {
270
- if (signal.aborted)
271
- throw err;
272
- // git-source messages never carry the token; redacted all the same, it is a credential
273
- const reason = errMsg(err);
274
- const redacted = token !== undefined ? reason.replaceAll(token, "***") : reason;
275
- // A bootstrap entry pins a commit by its sha: a ref tip is not what it can change to
276
- const message = err instanceof GitSourceError && err.refusedCommit !== undefined
277
- ? `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}`
278
- : `${redacted}; to install offline, put its pack (capybara-plugin bootstrap --write) in ${where}`;
279
- throw new ApiError("bootstrap.git_read_failed", `Bootstrap plugin ${e.name} ${e.version}: cannot read ${at}: ${message}`);
280
- }
281
- const pack = await packPackageTgz(read.files);
282
- const actual = integrityOf(pack);
283
- if (actual !== e.integrity) {
284
- 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`);
285
- }
286
- const tree = read.trees.get(dir);
287
- if (tree !== undefined)
288
- o.gitTrees?.set(e.name, tree);
289
- return pack;
290
- }
291
- function defaultGitCredentials(name) {
292
- const tokens = o.config.marketplaces.tokens;
293
- const username = manifest.extra?.marketplaces.find((x) => x.name === name)?.username;
294
- return {
295
- ...(Object.hasOwn(tokens, name) && { token: tokens[name] }),
296
- ...(username !== undefined && { username }),
297
- };
298
- }
299
- }
300
- /** The message of a thrown value. */
301
- export const errMsg = (e) => (e instanceof Error ? e.message : String(e));
302
- /** The registry's origin, for messages (never its credentials or path). */
303
- function registryOrigin(registry) {
304
- try {
305
- return new URL(registry).origin;
306
- }
307
- catch {
308
- return "the configured npm registry";
309
- }
310
- }
311
- /**
312
- * The `*.tgz` files directly in `dir` by their sha512 integrity. A missing directory is an empty
313
- * one; a file larger than `maxBytes` is skipped with a warning.
314
- */
315
- async function scanOfflineDir(dir, maxBytes, log) {
316
- const out = new Map();
317
- let names;
318
- try {
319
- names = await readdir(dir);
320
- }
321
- catch (err) {
322
- const code = err.code;
323
- if (code === "ENOENT" || code === "ENOTDIR")
324
- return out;
325
- throw err;
326
- }
327
- for (const name of names.sort()) {
328
- if (!name.endsWith(".tgz"))
329
- continue;
330
- const file = join(dir, name);
331
- const st = await stat(file).catch(() => undefined);
332
- if (!st?.isFile())
333
- continue;
334
- if (st.size > maxBytes) {
335
- log?.warn("bootstrap: a file in the bootstrap directory exceeds packages.maxBytes; skipped", {
336
- file,
337
- size: st.size,
338
- maxBytes,
339
- });
340
- continue;
341
- }
342
- const bytes = new Uint8Array(await readFile(file));
343
- const integrity = integrityOf(bytes);
344
- if (!out.has(integrity))
345
- out.set(integrity, bytes);
346
- }
347
- return out;
348
- }
349
72
  /** The lock around a whole run (`lock:bootstrap`). */
350
73
  export const BOOTSTRAP_LOCK_KEY = "bootstrap";
351
74
  /** Its lifetime without renewal; a run keeps it by renewal, a crashed holder's expires. */
@@ -391,14 +114,35 @@ let BootstrapService = class BootstrapService {
391
114
  config() {
392
115
  return this.configService.get();
393
116
  }
394
- /** Whether the bootstrap step completed for the manifest with this sha256. */
395
- async isDone(manifestSha256) {
117
+ /**
118
+ * Whether the bootstrap step is done for this manifest: a completed run of its sha256 while the
119
+ * latest completed run has the same extra-manifest part (ruling R18).
120
+ */
121
+ async isDone(manifest) {
122
+ return (await this.recorded(manifest)) !== undefined;
123
+ }
124
+ /** The recorded result of the manifest's run when it counts as done ({@link isDone}). */
125
+ async recorded(manifest) {
126
+ const manifestSha256 = bootstrapManifestSha256(manifest);
396
127
  const row = await this.db
397
128
  .selectFrom("bootstrap_runs")
398
- .select("manifest_sha256")
129
+ .select("results")
399
130
  .where("manifest_sha256", "=", manifestSha256)
400
131
  .executeTakeFirst();
401
- return row !== undefined;
132
+ if (row === undefined)
133
+ return undefined;
134
+ const latest = await this.db
135
+ .selectFrom("bootstrap_runs")
136
+ .select(["manifest_sha256", "extra_sha256"])
137
+ .orderBy("completed_at", "desc")
138
+ .orderBy("manifest_sha256")
139
+ .limit(1)
140
+ .executeTakeFirstOrThrow();
141
+ if (latest.manifest_sha256 !== manifestSha256 &&
142
+ latest.extra_sha256 !== bootstrapExtraSha256(manifest)) {
143
+ return undefined;
144
+ }
145
+ return { manifestSha256, results: row.results };
402
146
  }
403
147
  /**
404
148
  * What an extra manifest left ({@link ExtraManifestTraces}): the config-managed marketplaces
@@ -414,14 +158,15 @@ let BootstrapService = class BootstrapService {
414
158
  .where("managed", "=", "config")
415
159
  .orderBy("name")
416
160
  .execute();
417
- const last = await this.lastRunResults();
418
- return {
419
- marketplaces: rows.map((r) => r.name),
420
- plugins: (last ?? [])
421
- .filter((r) => r.extra === true)
422
- .map((r) => r.name)
423
- .sort(),
424
- };
161
+ // A run that started writing and has not completed is the latest state (R19)
162
+ const started = await this.db
163
+ .selectFrom("bootstrap_run_started")
164
+ .select("extra_plugins")
165
+ .executeTakeFirst();
166
+ const plugins = started !== undefined
167
+ ? [...started.extra_plugins]
168
+ : ((await this.lastRunResults()) ?? []).filter((r) => r.extra === true).map((r) => r.name);
169
+ return { marketplaces: rows.map((r) => r.name), plugins: plugins.sort() };
425
170
  }
426
171
  /**
427
172
  * Runs the bootstrap step (see the file header); when it is already done for this manifest
@@ -436,21 +181,13 @@ let BootstrapService = class BootstrapService {
436
181
  */
437
182
  async run(o) {
438
183
  const manifestSha256 = bootstrapManifestSha256(o.manifest);
439
- const recorded = async () => {
440
- const done = await this.db
441
- .selectFrom("bootstrap_runs")
442
- .select("results")
443
- .where("manifest_sha256", "=", manifestSha256)
444
- .executeTakeFirst();
445
- return done && { manifestSha256, results: done.results };
446
- };
447
184
  // Done: no lock, no directory, no network
448
- const before = await recorded();
185
+ const before = await this.recorded(o.manifest);
449
186
  if (before)
450
187
  return before;
451
188
  return this.locked(o.signal, async (signal) => {
452
189
  // Another replica may have finished it while this one waited for the lock
453
- const done = await recorded();
190
+ const done = await this.recorded(o.manifest);
454
191
  if (done)
455
192
  return done;
456
193
  if (o.manifest.extra === undefined) {
@@ -490,6 +227,8 @@ let BootstrapService = class BootstrapService {
490
227
  });
491
228
  for (const [name, bytes] of obtained)
492
229
  files.set(name, bytes);
230
+ // Before the first write: a process without the extra manifest is refused from here on (R19)
231
+ await this.recordStarted(manifestSha256, o.manifest.extra?.plugins ?? []);
493
232
  const handled = await this.lastRunNames();
494
233
  const results = [];
495
234
  const failures = [];
@@ -533,7 +272,7 @@ let BootstrapService = class BootstrapService {
533
272
  throw new BootstrapFailedError(failures, results, deferred, files);
534
273
  }
535
274
  signal.throwIfAborted();
536
- await this.recordDone(manifestSha256, results);
275
+ await this.recordDone(manifestSha256, bootstrapExtraSha256(o.manifest), results);
537
276
  this.log.info("bootstrap completed", { manifestSha256, results });
538
277
  return { manifestSha256, results };
539
278
  });
@@ -555,16 +294,36 @@ let BootstrapService = class BootstrapService {
555
294
  ownerOrg: holder.name,
556
295
  });
557
296
  }
558
- /** The `bootstrap_runs` row and the `bootstrap.completed` audit, in one transaction. */
559
- async recordDone(manifestSha256, results) {
560
- await this.db
561
- .insertInto("bootstrap_runs")
562
- .values({
297
+ /** The run has started writing: the `bootstrap_run_started` row names its extra entries. */
298
+ async recordStarted(manifestSha256, extraPlugins) {
299
+ const values = {
563
300
  manifest_sha256: manifestSha256,
301
+ extra_plugins: JSON.stringify(extraPlugins),
302
+ started_at: sql `now()`,
303
+ };
304
+ await this.db
305
+ .insertInto("bootstrap_run_started")
306
+ .values(values)
307
+ .onConflict((oc) => oc.column("singleton").doUpdateSet(values))
308
+ .execute();
309
+ }
310
+ /**
311
+ * The `bootstrap_runs` row (again with the current time and results when the manifest ran before:
312
+ * it is then the latest completed run, R18), the `bootstrap.completed` audit and the end of the
313
+ * started run, in one transaction.
314
+ */
315
+ async recordDone(manifestSha256, extraSha256, results) {
316
+ const values = {
564
317
  completed_at: sql `now()`,
565
318
  results: JSON.stringify(results),
566
- })
319
+ extra_sha256: extraSha256,
320
+ };
321
+ await this.db
322
+ .insertInto("bootstrap_runs")
323
+ .values({ manifest_sha256: manifestSha256, ...values })
324
+ .onConflict((oc) => oc.column("manifest_sha256").doUpdateSet(values))
567
325
  .execute();
326
+ await this.db.deleteFrom("bootstrap_run_started").execute();
568
327
  await audit(this.db, {
569
328
  action: "bootstrap.completed",
570
329
  target: manifestSha256,
@@ -599,6 +358,7 @@ let BootstrapService = class BootstrapService {
599
358
  .selectFrom("bootstrap_runs")
600
359
  .select("results")
601
360
  .orderBy("completed_at", "desc")
361
+ .orderBy("manifest_sha256")
602
362
  .limit(1)
603
363
  .executeTakeFirst();
604
364
  return row?.results;
@@ -619,7 +379,7 @@ let BootstrapService = class BootstrapService {
619
379
  if (e.source === "git") {
620
380
  const m = bootstrapGitMarketplace(at.manifest, e, this.config());
621
381
  git = { files: await this.unpackGit(e, bytes), publisher: repoOwner(m.url) };
622
- plugin = this.gitPlugin(e, git.files);
382
+ plugin = this.gitPlugin(e, git);
623
383
  // The source an admin import of the managed marketplace's `path` entry records (same
624
384
  // arguments), so its later versions add to this item
625
385
  const where = marketplaceGitSource({
@@ -793,24 +553,17 @@ let BootstrapService = class BootstrapService {
793
553
  }
794
554
  }
795
555
  /**
796
- * Name, version and extension of a git entry's tree: from its `plugin.json`; a tree without one
797
- * (a Claude Code or skills-only plugin, never an extension) is named by the entry, which its
798
- * import's review is checked against ({@link prepareGitEntry}).
556
+ * Name, version and extension of a git entry's tree ({@link readBootstrapGitPlugin}, which
557
+ * `capybara-plugin bootstrap --write` pins with): its `plugin.json`, a Claude Code plugin's
558
+ * manifest or the entry; its import's review is checked against the entry again
559
+ * ({@link prepareGitEntry}).
799
560
  */
800
- gitPlugin(e, files) {
801
- if (!files.has(PLUGIN_MANIFEST_FILE)) {
802
- return { name: e.name, version: e.version, extension: false };
803
- }
561
+ gitPlugin(e, git) {
804
562
  try {
805
- const { manifest } = readPluginFiles(files, {
806
- hostSdkVersion: SDK_VERSION,
807
- requirePackageJson: false,
563
+ return readBootstrapGitPlugin(git.files, e, {
564
+ publisher: git.publisher,
565
+ allowInsecureLoopback: this.config().marketplaces.allowInsecureLoopback,
808
566
  });
809
- return {
810
- name: manifest.name,
811
- version: manifest.version,
812
- extension: manifest.extension !== undefined,
813
- };
814
567
  }
815
568
  catch (err) {
816
569
  throw err instanceof PluginPackageError ? catalogPackageError(err) : err;
@@ -982,6 +735,9 @@ let BootstrapService = class BootstrapService {
982
735
  return rows.map((r) => ({ name: r.name, action: "required_cleared", version: r.version }));
983
736
  }
984
737
  };
738
+ __decorate([
739
+ Transactional()
740
+ ], BootstrapService.prototype, "recordStarted", null);
985
741
  __decorate([
986
742
  Transactional()
987
743
  ], BootstrapService.prototype, "recordDone", null);
@@ -14,6 +14,8 @@ export type UnresolvedReason =
14
14
  | "webhook_base"
15
15
  /** No connector is made from the template yet. */
16
16
  | "no_connector"
17
+ /** The guide covers several templates and the rendering names none (no template, no connector). */
18
+ | "no_template"
17
19
  /** Rendered for the platform (the super admin's preview), not for an org. */
18
20
  | "no_org";
19
21
  /**
@@ -33,6 +35,8 @@ export interface GuideTargetQuery {
33
35
  connectionId?: string | undefined;
34
36
  name?: string | undefined;
35
37
  connectorId?: string | undefined;
38
+ /** connector-template: which of the guide's templates to render for (a guide covering several). */
39
+ templateId?: string | undefined;
36
40
  }
37
41
  /** What a place resolves for one rendering (the mode is the caller's: it picks it from these). */
38
42
  export interface PlaceResolution {
@@ -43,6 +47,11 @@ export interface PlaceResolution {
43
47
  target: GuideTarget | null;
44
48
  /** The target's stored mode (a channel connection's `inbound_mode`), null without one. */
45
49
  storedMode: string | null;
50
+ /**
51
+ * connector-template: the template rendered for (the connector's, the one asked for, or the
52
+ * guide's only one); null otherwise or when a guide covering several names none.
53
+ */
54
+ template: string | null;
46
55
  }
47
56
  /** Where the values come from. */
48
57
  export interface PlaceContext {