@capybara-hq/kernel 0.1.0-rc.145 → 0.1.0-rc.147

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 (185) hide show
  1. package/dist/admin/extensions.controller.d.ts +0 -11
  2. package/dist/admin/extensions.controller.js +0 -28
  3. package/dist/admin/health.service.d.ts +25 -1
  4. package/dist/admin/health.service.js +50 -18
  5. package/dist/audit/full-access.d.ts +78 -0
  6. package/dist/audit/full-access.js +283 -0
  7. package/dist/automations/automations.service.d.ts +1 -0
  8. package/dist/automations/automations.service.js +3 -1
  9. package/dist/automations/calendar.js +3 -1
  10. package/dist/automations/grant-rules.d.ts +2 -1
  11. package/dist/automations/grant-rules.js +8 -1
  12. package/dist/automations/unattended.d.ts +13 -1
  13. package/dist/automations/unattended.js +13 -1
  14. package/dist/catalog/admin-catalog.controller.d.ts +8 -0
  15. package/dist/catalog/admin-catalog.controller.js +8 -2
  16. package/dist/catalog/admin-catalog.schemas.d.ts +10 -0
  17. package/dist/catalog/admin-catalog.schemas.js +8 -1
  18. package/dist/catalog/catalog-content.d.ts +6 -0
  19. package/dist/catalog/catalog-scope.service.d.ts +22 -2
  20. package/dist/catalog/catalog-scope.service.js +27 -3
  21. package/dist/catalog/catalog.service.js +19 -2
  22. package/dist/catalog/marketplaces.service.d.ts +1 -1
  23. package/dist/catalog/org-catalog.service.d.ts +8 -1
  24. package/dist/catalog/org-catalog.service.js +36 -3
  25. package/dist/catalog/platform-components.js +3 -2
  26. package/dist/catalog/platform-import-update.d.ts +2 -0
  27. package/dist/catalog/platform-import-update.js +8 -1
  28. package/dist/catalog/plugin-connectors.d.ts +11 -0
  29. package/dist/catalog/plugin-connectors.js +33 -0
  30. package/dist/catalog/plugin-import.d.ts +35 -15
  31. package/dist/catalog/plugin-import.js +110 -35
  32. package/dist/catalog/plugin-install.js +6 -0
  33. package/dist/catalog/provenance.d.ts +71 -0
  34. package/dist/catalog/provenance.js +112 -0
  35. package/dist/config/auto-approve.d.ts +16 -0
  36. package/dist/config/auto-approve.js +24 -0
  37. package/dist/config/capacity-presets.d.ts +243 -0
  38. package/dist/config/capacity-presets.js +195 -0
  39. package/dist/config/env.d.ts +2 -1
  40. package/dist/config/env.js +6 -1
  41. package/dist/config/load.js +15 -0
  42. package/dist/config/schema.d.ts +46 -9
  43. package/dist/config/schema.js +154 -30
  44. package/dist/ctx/create-ctx.d.ts +16 -0
  45. package/dist/ctx/create-ctx.js +269 -34
  46. package/dist/ctx/net.d.ts +5 -1
  47. package/dist/ctx/net.js +62 -12
  48. package/dist/db/kernel-schema.d.ts +31 -0
  49. package/dist/db/migrator.js +0 -36
  50. package/dist/dial-in/routes.js +1 -1
  51. package/dist/erasure/org-batches.js +1 -6
  52. package/dist/erasure/org-catalog.js +6 -2
  53. package/dist/erasure/org-rules.js +1 -0
  54. package/dist/erasure/org-worker.js +0 -13
  55. package/dist/errors.d.ts +6 -0
  56. package/dist/errors.js +6 -0
  57. package/dist/extensions/admin-ops.d.ts +14 -1
  58. package/dist/extensions/admin-ops.js +30 -3
  59. package/dist/extensions/admin-view.d.ts +21 -1
  60. package/dist/extensions/admin-view.js +43 -0
  61. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  62. package/dist/extensions/bootstrap-packages.js +1 -1
  63. package/dist/extensions/bootstrap-review.d.ts +251 -0
  64. package/dist/extensions/bootstrap-review.js +676 -0
  65. package/dist/extensions/bootstrap.d.ts +21 -1
  66. package/dist/extensions/bootstrap.js +72 -2
  67. package/dist/extensions/cli.d.ts +6 -0
  68. package/dist/extensions/cli.js +4 -0
  69. package/dist/extensions/enabled.d.ts +3 -0
  70. package/dist/extensions/execution-realm.d.ts +96 -0
  71. package/dist/extensions/execution-realm.js +141 -0
  72. package/dist/extensions/extensions.module.js +12 -0
  73. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  74. package/dist/extensions/full-access-disclosure.js +57 -0
  75. package/dist/extensions/grant-epoch.d.ts +9 -2
  76. package/dist/extensions/grant-epoch.js +13 -2
  77. package/dist/extensions/host.d.ts +96 -4
  78. package/dist/extensions/host.js +411 -33
  79. package/dist/extensions/installs.d.ts +18 -0
  80. package/dist/extensions/installs.js +28 -0
  81. package/dist/extensions/instance.d.ts +2 -0
  82. package/dist/extensions/instance.js +1 -0
  83. package/dist/extensions/isolated/admission.d.ts +23 -2
  84. package/dist/extensions/isolated/admission.js +32 -7
  85. package/dist/extensions/isolated/authorization.d.ts +8 -2
  86. package/dist/extensions/isolated/authorization.js +11 -3
  87. package/dist/extensions/isolated/broker.d.ts +3 -0
  88. package/dist/extensions/isolated/broker.js +50 -14
  89. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  90. package/dist/extensions/isolated/configured-package.js +2 -0
  91. package/dist/extensions/isolated/lanes.d.ts +44 -3
  92. package/dist/extensions/isolated/lanes.js +263 -80
  93. package/dist/extensions/isolated/metrics.d.ts +146 -0
  94. package/dist/extensions/isolated/metrics.js +304 -0
  95. package/dist/extensions/isolated/revision.d.ts +7 -1
  96. package/dist/extensions/isolated/revision.js +26 -5
  97. package/dist/extensions/isolated/rpc.d.ts +5 -0
  98. package/dist/extensions/isolated/rpc.js +7 -2
  99. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  100. package/dist/extensions/isolated/sandbox.js +50 -0
  101. package/dist/extensions/isolated/status.d.ts +79 -0
  102. package/dist/extensions/isolated/status.js +216 -0
  103. package/dist/extensions/isolated/tier.d.ts +127 -2
  104. package/dist/extensions/isolated/tier.js +266 -7
  105. package/dist/extensions/isolated/usage.d.ts +134 -0
  106. package/dist/extensions/isolated/usage.js +322 -0
  107. package/dist/extensions/ledger.d.ts +5 -0
  108. package/dist/extensions/ledger.js +16 -0
  109. package/dist/extensions/lifecycle.d.ts +42 -2
  110. package/dist/extensions/lifecycle.js +100 -4
  111. package/dist/extensions/org-config.js +11 -0
  112. package/dist/extensions/package.d.ts +14 -0
  113. package/dist/extensions/package.js +23 -0
  114. package/dist/extensions/permission-view.d.ts +2 -2
  115. package/dist/extensions/permissions.controller.d.ts +35 -0
  116. package/dist/extensions/permissions.controller.js +98 -0
  117. package/dist/extensions/permissions.schemas.d.ts +288 -0
  118. package/dist/extensions/permissions.schemas.js +96 -0
  119. package/dist/extensions/permissions.service.d.ts +116 -0
  120. package/dist/extensions/permissions.service.js +428 -0
  121. package/dist/extensions/realm-retirement.d.ts +65 -0
  122. package/dist/extensions/realm-retirement.js +150 -0
  123. package/dist/extensions/registry.d.ts +6 -0
  124. package/dist/extensions/registry.js +8 -0
  125. package/dist/extensions/review-hash.d.ts +114 -0
  126. package/dist/extensions/review-hash.js +145 -0
  127. package/dist/extensions/revision-approvals.d.ts +58 -3
  128. package/dist/extensions/revision-approvals.js +135 -14
  129. package/dist/extensions/revision-grants.d.ts +10 -0
  130. package/dist/extensions/revision-review.d.ts +144 -0
  131. package/dist/extensions/revision-review.js +297 -0
  132. package/dist/extensions/revocation-leases.d.ts +273 -0
  133. package/dist/extensions/revocation-leases.js +533 -0
  134. package/dist/extensions/revocation.d.ts +78 -0
  135. package/dist/extensions/revocation.js +205 -0
  136. package/dist/extensions/state.module.js +12 -0
  137. package/dist/git/run-end.d.ts +35 -7
  138. package/dist/git/run-end.js +87 -38
  139. package/dist/http/api.module.js +2 -0
  140. package/dist/identity/audit.d.ts +2 -1
  141. package/dist/identity/audit.js +4 -17
  142. package/dist/index.d.ts +10 -2
  143. package/dist/index.js +10 -2
  144. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  145. package/dist/infra/config/kernel-config.service.js +21 -0
  146. package/dist/infra/outbox/registry.d.ts +13 -0
  147. package/dist/infra/outbox/registry.js +8 -0
  148. package/dist/lifecycle/kernel-lifecycle.d.ts +27 -1
  149. package/dist/lifecycle/kernel-lifecycle.js +83 -22
  150. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  151. package/dist/net/private-endpoint-preflight.js +417 -0
  152. package/dist/net/private-endpoints.d.ts +68 -0
  153. package/dist/net/private-endpoints.js +164 -0
  154. package/dist/net/public-address.d.ts +14 -0
  155. package/dist/net/public-address.js +15 -1
  156. package/dist/net/safe-fetch.d.ts +2 -1
  157. package/dist/net/safe-fetch.js +10 -3
  158. package/dist/overrides.d.ts +9 -1
  159. package/dist/overrides.js +4 -0
  160. package/dist/packages/official-publisher.d.ts +65 -1
  161. package/dist/packages/official-publisher.js +171 -46
  162. package/dist/packages/provenance.d.ts +11 -0
  163. package/dist/packages/provenance.js +24 -0
  164. package/dist/platform/exclusions.js +4 -4
  165. package/dist/platform/ops/automations.ops.js +1 -1
  166. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  167. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  168. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  169. package/dist/platform/platform-ops.module.d.ts +2 -1
  170. package/dist/platform/platform-ops.module.js +2 -0
  171. package/dist/platform/route-schemas.js +2 -0
  172. package/dist/retention/purge-batch.js +10 -14
  173. package/dist/runtime/maintenance.d.ts +4 -2
  174. package/dist/runtime/maintenance.js +16 -3
  175. package/dist/runtime/run-finish.d.ts +3 -3
  176. package/dist/runtime/run-finish.js +7 -3
  177. package/dist/sandbox/permission-availability.d.ts +17 -2
  178. package/dist/sandbox/permission-availability.js +22 -1
  179. package/dist/sandbox/permission-facts.js +7 -1
  180. package/dist/tools/builtins/sandbox/common.js +2 -0
  181. package/dist/tools/pipeline.d.ts +2 -1
  182. package/dist/tools/pipeline.js +7 -2
  183. package/package.json +4 -3
  184. package/src/migrations/0238_extension_usage.sql +40 -0
  185. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -1,5 +1,6 @@
1
1
  import { type PluginExtensionSection } from "@capybara-hq/plugin-sdk";
2
2
  import type { core } from "zod";
3
+ import { type PublisherEvidence } from "../catalog/provenance.js";
3
4
  import type { Keyring } from "../ctx/secrets.js";
4
5
  import { SuperAdminLock } from "../identity/super-admin.js";
5
6
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -194,6 +195,23 @@ export declare class ExtensionInstalls {
194
195
  version: string;
195
196
  integrity?: string;
196
197
  }, signal?: AbortSignal): Promise<ProvenanceResult>;
198
+ /**
199
+ * One attestations fetch of an npm revision outside the official marketplace's policies: the
200
+ * review's display provenance (as {@link fetchProvenance}) and the publisher evidence, its
201
+ * attestations verified as any GitHub Actions publisher (`verified` with the normalized
202
+ * identity), else `none`. Never throws; the bytes were already checked against `integrity`.
203
+ */
204
+ npmEvidence(input: {
205
+ package: string;
206
+ version: string;
207
+ integrity: string;
208
+ }, signal?: AbortSignal): Promise<{
209
+ provenance: ProvenanceResult;
210
+ publisher: {
211
+ evidence: PublisherEvidence;
212
+ digest?: string;
213
+ };
214
+ }>;
197
215
  private fetchVerified;
198
216
  /**
199
217
  * Fetches from the configured npm registry (source `npm`, `ref` is `<package>@<version>`). Download
@@ -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 { marketplaceNetPolicy } from "../catalog/marketplace-fetch.js";
14
+ import { classifyPublisherEvidence } from "../catalog/provenance.js";
14
15
  import { configFields } from "../config/fields.js";
15
16
  import { ApiError } from "../errors.js";
16
17
  import { audit } from "../identity/audit.js";
@@ -21,6 +22,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
21
22
  import { Transactional } from "../infra/database/transactional.decorator.js";
22
23
  import { KEYRING } from "../infra/tokens.js";
23
24
  import { fetchNpmPackage, IntegrityMismatchError, NpmFetchError, PackageTooLargeError, } from "../packages/npm.js";
25
+ import { fetchAttestationEvidence } from "../packages/official-publisher.js";
24
26
  import { fetchProvenance, PROVENANCE_TIMEOUT_MS, } from "../packages/provenance.js";
25
27
  import { ExtensionApprovals } from "./approvals.js";
26
28
  import { ExtensionBlobs } from "./blobs.js";
@@ -253,6 +255,32 @@ let ExtensionInstalls = class ExtensionInstalls {
253
255
  const timeout = AbortSignal.timeout(PROVENANCE_TIMEOUT_MS);
254
256
  return fetchProvenance(cfg, input.package, input.version, signal ? AbortSignal.any([signal, timeout]) : timeout, input.integrity !== undefined ? { integrity: input.integrity } : {});
255
257
  }
258
+ /**
259
+ * One attestations fetch of an npm revision outside the official marketplace's policies: the
260
+ * review's display provenance (as {@link fetchProvenance}) and the publisher evidence, its
261
+ * attestations verified as any GitHub Actions publisher (`verified` with the normalized
262
+ * identity), else `none`. Never throws; the bytes were already checked against `integrity`.
263
+ */
264
+ async npmEvidence(input, signal) {
265
+ const c = this.config.get();
266
+ const cfg = {
267
+ registry: c.packages.npmRegistry,
268
+ maxBytes: c.packages.maxBytes,
269
+ net: marketplaceNetPolicy(c),
270
+ ...(c.packages.npmToken !== undefined && { token: c.packages.npmToken }),
271
+ };
272
+ const { provenance, attestation } = await fetchAttestationEvidence(cfg, { name: input.package, version: input.version, integrity: input.integrity }, signal);
273
+ const outcome = classifyPublisherEvidence({ integrity: "match", attestation });
274
+ if (outcome.outcome !== "accepted")
275
+ return { provenance, publisher: { evidence: { evidence: "none" } } };
276
+ return {
277
+ provenance,
278
+ publisher: {
279
+ evidence: outcome.publisher,
280
+ ...(outcome.evidenceDigest !== undefined && { digest: outcome.evidenceDigest }),
281
+ },
282
+ };
283
+ }
256
284
  async fetchVerified(input, signal, codes) {
257
285
  const c = this.config.get();
258
286
  const cfg = {
@@ -166,6 +166,8 @@ export declare function setupInstance(deps: LoadDeps, manifest: ExtensionManifes
166
166
  /** 已建好 ctx、setup 进行中时回调(宿主据此在 close() 时立即关闭它)。 */
167
167
  onCtx?: (ctx: KernelExtensionContext | undefined) => void;
168
168
  extensionDb?: ReturnType<typeof extensionDbPool>;
169
+ /** The instance runs in the kernel process (default); false for an isolated instance. */
170
+ inProcess?: boolean;
169
171
  }): Promise<ExtensionInstance>;
170
172
  /**
171
173
  * 加载一个插件实例:import → defineExtension → 有包内静态清单(`section`)时与 {@link staticManifestOf} 核对
@@ -311,6 +311,7 @@ export async function setupInstance(deps, manifest, input) {
311
311
  const ctx = createExtensionContext(deps.kernel, manifest, live, deps.objectStore, {
312
312
  sha256: input.sha256,
313
313
  ...(input.extensionDb && { db: input.extensionDb }),
314
+ ...(input.inProcess !== undefined && { inProcess: input.inProcess }),
314
315
  });
315
316
  input.onCtx?.(ctx);
316
317
  try {
@@ -1,4 +1,4 @@
1
- import type { PluginExtensionSection } from "@capybara-hq/plugin-sdk";
1
+ import { type PluginExtensionSection } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
  import type { OfficialNpmRevision } from "../../packages/official-publisher.js";
4
4
  /** The proof is a kernel-written record of verification at import or upgrade. */
@@ -7,4 +7,25 @@ export declare function isTrustedPublisherRevision(proof: unknown, expected: Off
7
7
  export declare function isolatedDeploymentSchema(input: unknown): z.ZodType;
8
8
  /** The kernel must never compile executable or unbounded schema features from a child. */
9
9
  export declare function assertIsolatedToolSchema(input: unknown): void;
10
- export declare function assertIsolatedSection(section: PluginExtensionSection): void;
10
+ /**
11
+ * Whether the section's deployment config fits the isolated tier: the same rule
12
+ * {@link assertIsolatedSection} applies (a declarative schema in the bounded subset, or no config
13
+ * fields at all). The execution decision reads it as `configSchemaIsolatable`.
14
+ */
15
+ export declare function deploymentConfigIsolatable(section: PluginExtensionSection): boolean;
16
+ /** What the isolated server admission takes from a revision's grant. */
17
+ export interface IsolatedSectionGrant {
18
+ /**
19
+ * The revision's live grant covers browser full access (`execution.full-access:browser`): its
20
+ * client entry, client permission and UI components run in the page beside the isolated server
21
+ * (plan task 1.3b; the one divergence the execution-realm parity test records).
22
+ */
23
+ browserFullAccess?: boolean;
24
+ }
25
+ /**
26
+ * Whether the server part of a section fits the isolated tier. The extension points come from the
27
+ * capability catalog's `ISOLATED_EXTENSION_POINTS` (marked per point on evidence, never by a codec
28
+ * landing). Client code is browser realm: it is admitted beside an isolated server only under a
29
+ * browser full-access grant, since the isolated client realm does not exist yet.
30
+ */
31
+ export declare function assertIsolatedSection(section: PluginExtensionSection, grant?: IsolatedSectionGrant): void;
@@ -1,3 +1,4 @@
1
+ import { extensionPointRefs, ISOLATED_EXTENSION_POINTS, } from "@capybara-hq/plugin-sdk";
1
2
  import { z } from "zod";
2
3
  import { unreachableSecrets } from "../../config/fields.js";
3
4
  const publisherProof = z.object({
@@ -181,16 +182,40 @@ export function assertIsolatedToolSchema(input) {
181
182
  throw new Error("Unsupported isolated extension tool schema");
182
183
  }
183
184
  }
184
- export function assertIsolatedSection(section) {
185
+ /**
186
+ * Whether the section's deployment config fits the isolated tier: the same rule
187
+ * {@link assertIsolatedSection} applies (a declarative schema in the bounded subset, or no config
188
+ * fields at all). The execution decision reads it as `configSchemaIsolatable`.
189
+ */
190
+ export function deploymentConfigIsolatable(section) {
191
+ const schema = section.configSchemas?.deployment;
192
+ if (schema === undefined)
193
+ return section.manifest.config.deployment.length === 0;
194
+ try {
195
+ isolatedDeploymentSchema(schema);
196
+ return true;
197
+ }
198
+ catch {
199
+ return false;
200
+ }
201
+ }
202
+ /**
203
+ * Whether the server part of a section fits the isolated tier. The extension points come from the
204
+ * capability catalog's `ISOLATED_EXTENSION_POINTS` (marked per point on evidence, never by a codec
205
+ * landing). Client code is browser realm: it is admitted beside an isolated server only under a
206
+ * browser full-access grant, since the isolated client realm does not exist yet.
207
+ */
208
+ export function assertIsolatedSection(section, grant = {}) {
185
209
  const { manifest, client } = section;
186
210
  const permissions = manifest.permissions;
187
- if (client !== undefined ||
188
- permissions?.client ||
211
+ const isolatedPoint = (point) => ISOLATED_EXTENSION_POINTS.includes(point);
212
+ const inPage = grant.browserFullAccess === true;
213
+ if ((!inPage && (client !== undefined || permissions?.client)) ||
189
214
  permissions?.secrets ||
190
- manifest.provides.some((point) => point !== "trigger-source@1") ||
191
- (manifest.requires ?? []).some((point) => point !== "trigger-source@1") ||
192
- (manifest.optional ?? []).some((point) => point !== "trigger-source@1") ||
193
- manifest.ui?.some((entry) => entry.kind !== "view") ||
215
+ !extensionPointRefs(manifest.provides).every(isolatedPoint) ||
216
+ !extensionPointRefs(manifest.requires ?? []).every(isolatedPoint) ||
217
+ !extensionPointRefs(manifest.optional ?? []).every(isolatedPoint) ||
218
+ manifest.ui?.some((entry) => entry.kind !== "view" && !(inPage && entry.kind === "component")) ||
194
219
  permissions?.http ||
195
220
  permissions?.dialIn ||
196
221
  permissions?.deviceAccess ||
@@ -10,6 +10,8 @@ export declare function readIsolatedGrant(db: KernelSchemaDb, grant: {
10
10
  export interface IsolatedInvocationGrant {
11
11
  signal: AbortSignal;
12
12
  release(): void;
13
+ /** Whether this admission checked the grant against PostgreSQL (a cold grant, for metrics). */
14
+ checked?: boolean;
13
15
  }
14
16
  export interface IsolatedRevocation {
15
17
  plugin?: string;
@@ -37,7 +39,10 @@ export interface GrantEpochView {
37
39
  fresh(): string | undefined;
38
40
  ensureFresh(): Promise<string | undefined>;
39
41
  }
40
- /** A grant checked at the current epoch is still rechecked after this long (backstop only). */
42
+ /**
43
+ * A grant checked at the current epoch is still rechecked after this long (backstop only): the
44
+ * default of `extensionHost.capacity.grantFullRevalidationMs`.
45
+ */
41
46
  export declare const GRANT_FULL_REVALIDATION_MS: number;
42
47
  /**
43
48
  * Replica-local cache of authority checked against deployment and org state.
@@ -51,12 +56,13 @@ export declare class IsolatedInvocationGrants {
51
56
  private readonly epochs;
52
57
  private readonly capacity;
53
58
  private readonly now;
59
+ private readonly fullRevalidationMs;
54
60
  private readonly instances;
55
61
  private readonly rechecks;
56
62
  /** Every cached grant across instances, least recently used first. */
57
63
  private readonly lru;
58
64
  private revalidating;
59
- constructor(epochs: GrantEpochView, capacity: number, now?: () => number);
65
+ constructor(epochs: GrantEpochView, capacity: number, now?: () => number, fullRevalidationMs?: number);
60
66
  issue({ plugin, orgId }: IsolatedRevocation, check: CachedGrant["check"], onRevoked: CachedGrant["onRevoked"] | undefined, instance: AbortSignal): Promise<IsolatedInvocationGrant | undefined>;
61
67
  revoke({ plugin, orgId }: IsolatedRevocation): void;
62
68
  /**
@@ -27,7 +27,10 @@ export async function readIsolatedGrant(db, grant) {
27
27
  const snapshot = await query.executeTakeFirst();
28
28
  return snapshotCovers(snapshot, permissions);
29
29
  }
30
- /** A grant checked at the current epoch is still rechecked after this long (backstop only). */
30
+ /**
31
+ * A grant checked at the current epoch is still rechecked after this long (backstop only): the
32
+ * default of `extensionHost.capacity.grantFullRevalidationMs`.
33
+ */
31
34
  export const GRANT_FULL_REVALIDATION_MS = 5 * 60_000;
32
35
  const REVALIDATION_BATCH = 8;
33
36
  const IN_FLIGHT_RECHECK_BATCH = 64;
@@ -43,15 +46,17 @@ export class IsolatedInvocationGrants {
43
46
  epochs;
44
47
  capacity;
45
48
  now;
49
+ fullRevalidationMs;
46
50
  instances = new Map();
47
51
  rechecks = new Map();
48
52
  /** Every cached grant across instances, least recently used first. */
49
53
  lru = new Map();
50
54
  revalidating;
51
- constructor(epochs, capacity, now = () => performance.now()) {
55
+ constructor(epochs, capacity, now = () => performance.now(), fullRevalidationMs = GRANT_FULL_REVALIDATION_MS) {
52
56
  this.epochs = epochs;
53
57
  this.capacity = capacity;
54
58
  this.now = now;
59
+ this.fullRevalidationMs = fullRevalidationMs;
55
60
  }
56
61
  async issue({ plugin, orgId }, check, onRevoked, instance) {
57
62
  if (instance.aborted)
@@ -99,6 +104,7 @@ export class IsolatedInvocationGrants {
99
104
  }
100
105
  this.lru.set(entry, { orgs, orgId, entry });
101
106
  entry.admitting += 1;
107
+ let checked = false;
102
108
  try {
103
109
  for (;;) {
104
110
  const epoch = this.epochs.fresh() ?? (await this.epochs.ensureFresh());
@@ -106,6 +112,7 @@ export class IsolatedInvocationGrants {
106
112
  return undefined;
107
113
  if (this.valid(entry, epoch))
108
114
  break;
115
+ checked = true;
109
116
  if (!(await this.validate(orgs, orgId, entry)))
110
117
  return undefined;
111
118
  }
@@ -116,6 +123,7 @@ export class IsolatedInvocationGrants {
116
123
  const call = new AbortController();
117
124
  entry.calls += 1;
118
125
  return {
126
+ checked,
119
127
  signal: AbortSignal.any([entry.abort.signal, call.signal]),
120
128
  release: () => {
121
129
  if (call.signal.aborted)
@@ -201,7 +209,7 @@ export class IsolatedInvocationGrants {
201
209
  valid(entry, epoch) {
202
210
  return (entry.pending === undefined &&
203
211
  entry.epoch === epoch &&
204
- this.now() - entry.checkedAt < GRANT_FULL_REVALIDATION_MS);
212
+ this.now() - entry.checkedAt < this.fullRevalidationMs);
205
213
  }
206
214
  evictIdle() {
207
215
  for (const { orgs, orgId, entry } of this.lru.values()) {
@@ -2,6 +2,7 @@ import type { KernelExtensionContext } from "../../ctx/create-ctx.js";
2
2
  import { type ExtensionEffects } from "../../ctx/durable-effects.service.js";
3
3
  import type { ExtensionEffectKeys } from "../../ctx/durable-keys.js";
4
4
  import type { BrokerCall } from "./lanes.js";
5
+ import type { IsolationObserver } from "./metrics.js";
5
6
  export interface BrokerOptions {
6
7
  ctx: KernelExtensionContext;
7
8
  plugin: string;
@@ -10,6 +11,8 @@ export interface BrokerOptions {
10
11
  current: () => boolean;
11
12
  network: (url: URL, orgId?: string) => Promise<boolean>;
12
13
  redactLog?: (message: string, config: unknown) => string;
14
+ /** Metrics (streams, frames) and usage counters (ctx.net bytes) of the revision. */
15
+ observer?: IsolationObserver | undefined;
13
16
  }
14
17
  /** The only route from an isolated process to kernel services. Authority comes from the live call. */
15
18
  export declare function createIsolatedBroker(options: BrokerOptions): BrokerCall;
@@ -44,9 +44,36 @@ const ACKNOWLEDGED_WRITES = new Set([
44
44
  "triggers.emit",
45
45
  "ui.invalidate",
46
46
  ]);
47
+ function callLabels(scope) {
48
+ return {
49
+ laneClass: scope.mode === "setupCheck" ? "control" : "standard",
50
+ mode: scope.mode,
51
+ role: scope.role ?? "none",
52
+ orgId: scope.orgId,
53
+ };
54
+ }
47
55
  class Handles {
56
+ observer;
48
57
  owners = new WeakMap();
49
- add(scope, value, close) {
58
+ constructor(observer) {
59
+ this.observer = observer;
60
+ }
61
+ /** `stream`: the kind of byte stream the handle is, for the open streams gauge. */
62
+ add(scope, value, release, stream) {
63
+ let close = release;
64
+ if (stream && this.observer) {
65
+ const observer = this.observer;
66
+ const labels = callLabels(scope);
67
+ let open = true;
68
+ observer.streamOpened(labels, stream);
69
+ close = () => {
70
+ if (open) {
71
+ open = false;
72
+ observer.streamClosed(labels, stream);
73
+ }
74
+ return release();
75
+ };
76
+ }
50
77
  let entries = this.owners.get(scope);
51
78
  if (!entries) {
52
79
  entries = new Map();
@@ -123,9 +150,10 @@ export function createIsolatedBroker(options) {
123
150
  const { ctx } = options;
124
151
  const loggedAt = new Map();
125
152
  let modelRequests = 0;
126
- const readers = new Handles();
153
+ const { observer } = options;
154
+ const readers = new Handles(observer);
127
155
  const leases = new Handles();
128
- const uploads = new Handles();
156
+ const uploads = new Handles(observer);
129
157
  const own = (org, supplied) => {
130
158
  if (org !== supplied)
131
159
  return refuse();
@@ -141,9 +169,9 @@ export function createIsolatedBroker(options) {
141
169
  return refuse();
142
170
  return Reflect.apply(method, api, args);
143
171
  };
144
- const openReader = (scope, body) => {
172
+ const openReader = (scope, body, kind) => {
145
173
  const reader = body.getReader();
146
- return readers.add(scope, { reader, reading: false }, () => reader.cancel());
174
+ return readers.add(scope, { reader, reading: false }, () => reader.cancel(), kind);
147
175
  };
148
176
  const modelResult = async (run, scope) => {
149
177
  if (modelRequests >= 2)
@@ -183,7 +211,7 @@ export function createIsolatedBroker(options) {
183
211
  finally {
184
212
  release();
185
213
  }
186
- }),
214
+ }, "models"),
187
215
  };
188
216
  }
189
217
  catch (error) {
@@ -197,6 +225,8 @@ export function createIsolatedBroker(options) {
197
225
  if (!(await options.network(url, org)) || !isCurrent(signal))
198
226
  return refuse();
199
227
  const init = requestInit.parse(initValue);
228
+ if (init.body !== undefined)
229
+ observer?.netBytesOut(org, Buffer.byteLength(init.body, "base64"));
200
230
  return ctx.net.fetch(url.href, {
201
231
  method: init.method,
202
232
  headers: init.headers,
@@ -315,7 +345,7 @@ export function createIsolatedBroker(options) {
315
345
  ...record(opts ?? {}),
316
346
  signal,
317
347
  });
318
- return found && { head: found.head, stream: openReader(scope, found.body) };
348
+ return found && { head: found.head, stream: openReader(scope, found.body, "storage") };
319
349
  },
320
350
  "storage.openPut": ([supplied, key, opts], org, scope, signal) => {
321
351
  own(org, supplied);
@@ -333,7 +363,7 @@ export function createIsolatedBroker(options) {
333
363
  signal,
334
364
  });
335
365
  void result.catch(() => { });
336
- return uploads.add(scope, { writer, result, writing: false }, () => writer.abort());
366
+ return uploads.add(scope, { writer, result, writing: false }, () => writer.abort(), "upload");
337
367
  },
338
368
  "storage.write": async ([id, chunk], _org, scope) => {
339
369
  const upload = uploads.get(scope, id);
@@ -343,6 +373,7 @@ export function createIsolatedBroker(options) {
343
373
  upload.writing = true;
344
374
  try {
345
375
  await upload.writer.write(chunk);
376
+ observer?.streamFrame(callLabels(scope), "upload");
346
377
  }
347
378
  finally {
348
379
  upload.writing = false;
@@ -369,7 +400,7 @@ export function createIsolatedBroker(options) {
369
400
  "lock.renew": ([id], _org, scope) => leases.get(scope, id).renew(),
370
401
  "lock.release": ([id], _org, scope) => leases.close(scope, id),
371
402
  };
372
- const read = async ([id], _org, scope) => {
403
+ const read = (kind) => async ([id], org, scope) => {
373
404
  const stream = readers.get(scope, id);
374
405
  if (stream.reading)
375
406
  return refuse();
@@ -385,16 +416,21 @@ export function createIsolatedBroker(options) {
385
416
  }
386
417
  const chunk = stream.remainder.subarray(0, CHUNK_BYTES);
387
418
  stream.remainder =
388
- stream.remainder.length > CHUNK_BYTES ? stream.remainder.subarray(CHUNK_BYTES) : undefined;
419
+ stream.remainder.length > CHUNK_BYTES
420
+ ? stream.remainder.subarray(CHUNK_BYTES)
421
+ : undefined;
422
+ observer?.streamFrame(callLabels(scope), kind);
423
+ if (kind === "net")
424
+ observer?.netBytesIn(org, chunk.length);
389
425
  return new RpcByteChunk({ done: false }, chunk);
390
426
  }
391
427
  finally {
392
428
  stream.reading = false;
393
429
  }
394
430
  };
395
- dispatch["net.read"] = read;
396
- dispatch["storage.read"] = read;
397
- dispatch["models.read"] = read;
431
+ dispatch["net.read"] = read("net");
432
+ dispatch["storage.read"] = read("storage");
433
+ dispatch["models.read"] = read("models");
398
434
  dispatch["models.close"] = ([id], _org, scope) => readers.close(scope, id);
399
435
  dispatch["net.close"] = ([id], _org, scope) => readers.close(scope, id);
400
436
  dispatch["storage.close"] = ([id], _org, scope) => readers.close(scope, id);
@@ -459,7 +495,7 @@ export function createIsolatedBroker(options) {
459
495
  status: response.status,
460
496
  statusText: response.statusText,
461
497
  headers: [...response.headers],
462
- ...(response.body && { stream: openReader(scope, response.body) }),
498
+ ...(response.body && { stream: openReader(scope, response.body, "net") }),
463
499
  };
464
500
  }
465
501
  // The scope was checked before dispatch. Reporting a completed write as refused can cause
@@ -3,6 +3,11 @@ export interface ConfiguredExtensionPackage {
3
3
  readonly archiveUrl: string;
4
4
  readonly review: ExtensionPackage;
5
5
  readonly maxBytes: number;
6
+ /**
7
+ * The lowercase hex sha512 of the captured archive: the digest its revision grants are keyed by
8
+ * (the bootstrap review and start gate resolve them, plan task 1.3c).
9
+ */
10
+ readonly sha512: string;
6
11
  /** A copy of the captured archive. Writes to the copy cannot change the reviewed package. */
7
12
  bytes(): Uint8Array;
8
13
  }
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { constants } from "node:fs";
2
3
  import { open } from "node:fs/promises";
3
4
  import { isAbsolute, resolve } from "node:path";
@@ -60,6 +61,7 @@ export async function readConfiguredExtensionPackage(specifier, resolveFrom, max
60
61
  archiveUrl: pathToFileURL(path).href,
61
62
  review,
62
63
  maxBytes,
64
+ sha512: createHash("sha512").update(bytes).digest("hex"),
63
65
  bytes: () => Uint8Array.from(bytes),
64
66
  });
65
67
  }
@@ -1,7 +1,13 @@
1
1
  import type { StaticExtensionManifest } from "@capybara-hq/plugin-sdk";
2
- import { type RpcBudget } from "./rpc.js";
2
+ import { type IsolatedCapacity } from "../../config/capacity-presets.js";
3
+ import type { IsolationObserver, RejectionReason } from "./metrics.js";
4
+ import { IsolatedRpcError, type RpcBudget } from "./rpc.js";
3
5
  import { type ExtensionSandboxOptions } from "./sandbox.js";
4
- export declare const MAX_ISOLATED_LANES = 4;
6
+ /**
7
+ * The limits below the `extensionHost.capacity` config (task 1.2c) are read from
8
+ * {@link IsolatedExtensionQuota.limits} at each admission and lane start; the `standard` preset is
9
+ * the set of constants this file had before.
10
+ */
5
11
  export type ServingRole = "api" | "worker" | "gateway";
6
12
  type InvocationMode = "org" | "deployment" | "setupCheck";
7
13
  export interface Invocation {
@@ -12,6 +18,10 @@ export interface Invocation {
12
18
  signal?: AbortSignal | undefined;
13
19
  toolCall?: unknown;
14
20
  cleanup?: Set<() => Promise<unknown> | undefined>;
21
+ /** `performance.now()` when the kernel took the call, for the call overhead metric. */
22
+ receivedAt?: number;
23
+ /** Whether the grant was checked against PostgreSQL for this call (a cold grant). */
24
+ grantChecked?: boolean;
15
25
  }
16
26
  export type BrokerCall = (method: string, args: unknown[], invocation: Invocation, signal: AbortSignal) => Promise<unknown>;
17
27
  export interface IsolatedLaneOptions {
@@ -30,8 +40,14 @@ export interface IsolatedLaneOptions {
30
40
  broker: BrokerCall;
31
41
  quota: IsolatedExtensionQuota;
32
42
  revision: string;
33
- onCrash?: ((retryAfterMs: number) => void) | undefined;
43
+ /**
44
+ * A lane failed: its sandbox exited unexpectedly (`exited`) or its start failed (`start_failed`).
45
+ * The revision backs off for `retryAfterMs`. A guard capacity refusal is not a failure.
46
+ */
47
+ onCrash?: ((retryAfterMs: number, cause: "exited" | "start_failed") => void) | undefined;
34
48
  cleanupFault: () => void;
49
+ /** Metrics and usage counters of this revision; absent in tests that do not measure. */
50
+ observer?: IsolationObserver | undefined;
35
51
  }
36
52
  type ProcessKind = "serving" | "control";
37
53
  interface ProcessIngress {
@@ -48,12 +64,25 @@ interface PendingRemoval {
48
64
  timer?: ReturnType<typeof setTimeout> | undefined;
49
65
  running: boolean;
50
66
  }
67
+ /** An `overloaded` refusal before the call reached a lane, with its reason for the metrics. */
68
+ export declare class IsolatedRejection extends IsolatedRpcError {
69
+ readonly reason: RejectionReason;
70
+ constructor(reason: RejectionReason);
71
+ }
51
72
  export declare class IsolatedExtensionQuota {
73
+ readonly limits: () => IsolatedCapacity;
52
74
  private readonly processes;
53
75
  private calls;
54
76
  private readonly services;
55
77
  private readonly preflights;
56
78
  private readonly starts;
79
+ /**
80
+ * `limits` is read at every admission and lane start (the hot capacity fields apply at once).
81
+ * Without it the quota uses the `standard` preset.
82
+ */
83
+ constructor(limits?: () => IsolatedCapacity);
84
+ private processLimit;
85
+ private startRate;
57
86
  private readonly retryTimers;
58
87
  private readonly available;
59
88
  private readonly removals;
@@ -65,6 +94,8 @@ export declare class IsolatedExtensionQuota {
65
94
  process(kind: ProcessKind): ProcessLease | undefined;
66
95
  call(): () => void;
67
96
  admitPreflight(orgId?: string, role?: ServingRole, setupCheck?: boolean): () => void;
97
+ /** Concurrent broker requests one lane may hold: each serving call can hold one. */
98
+ servicesPerLane(kind: ProcessKind, limits?: IsolatedCapacity): number;
68
99
  service(kind: ProcessKind): () => void;
69
100
  inBackoff(revision: string): boolean;
70
101
  crashed(revision: string): number;
@@ -83,7 +114,17 @@ export declare class IsolatedLanes {
83
114
  private draining?;
84
115
  private control?;
85
116
  private expected;
117
+ /** Lane keys whose serving lane exited unexpectedly: the next start there replaces a crash. */
118
+ private readonly crashedKeys;
86
119
  constructor(options: IsolatedLaneOptions);
120
+ private get limits();
121
+ /** The serving and control lanes as the gauges see them. */
122
+ private snapshot;
123
+ private servingLabels;
124
+ private reject;
125
+ /** Books the busy time of a lane whose calls just ended, or of every busy lane at a flush. */
126
+ private bookBusy;
127
+ private checkpointBusy;
87
128
  register(): Promise<unknown>;
88
129
  invoke(callback: string, args: readonly unknown[], scope: Invocation): Promise<unknown>;
89
130
  private admit;