@capybara-hq/kernel 0.1.0-rc.146 → 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 (168) 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 +2 -0
  34. package/dist/catalog/provenance.js +5 -1
  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/net.d.ts +5 -1
  45. package/dist/ctx/net.js +62 -12
  46. package/dist/db/kernel-schema.d.ts +31 -0
  47. package/dist/db/migrator.js +0 -36
  48. package/dist/dial-in/routes.js +1 -1
  49. package/dist/erasure/org-batches.js +1 -6
  50. package/dist/erasure/org-catalog.js +6 -2
  51. package/dist/erasure/org-rules.js +1 -0
  52. package/dist/erasure/org-worker.js +0 -13
  53. package/dist/errors.d.ts +6 -0
  54. package/dist/errors.js +6 -0
  55. package/dist/extensions/admin-ops.d.ts +14 -1
  56. package/dist/extensions/admin-ops.js +30 -3
  57. package/dist/extensions/admin-view.d.ts +21 -1
  58. package/dist/extensions/admin-view.js +43 -0
  59. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  60. package/dist/extensions/bootstrap-packages.js +1 -1
  61. package/dist/extensions/bootstrap-review.d.ts +251 -0
  62. package/dist/extensions/bootstrap-review.js +676 -0
  63. package/dist/extensions/bootstrap.d.ts +21 -1
  64. package/dist/extensions/bootstrap.js +72 -2
  65. package/dist/extensions/cli.d.ts +6 -0
  66. package/dist/extensions/cli.js +4 -0
  67. package/dist/extensions/enabled.d.ts +3 -0
  68. package/dist/extensions/extensions.module.js +9 -0
  69. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  70. package/dist/extensions/full-access-disclosure.js +57 -0
  71. package/dist/extensions/grant-epoch.d.ts +5 -0
  72. package/dist/extensions/grant-epoch.js +9 -0
  73. package/dist/extensions/host.d.ts +71 -2
  74. package/dist/extensions/host.js +293 -27
  75. package/dist/extensions/installs.d.ts +18 -0
  76. package/dist/extensions/installs.js +28 -0
  77. package/dist/extensions/isolated/admission.d.ts +17 -2
  78. package/dist/extensions/isolated/admission.js +15 -7
  79. package/dist/extensions/isolated/authorization.d.ts +8 -2
  80. package/dist/extensions/isolated/authorization.js +11 -3
  81. package/dist/extensions/isolated/broker.d.ts +3 -0
  82. package/dist/extensions/isolated/broker.js +50 -14
  83. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  84. package/dist/extensions/isolated/configured-package.js +2 -0
  85. package/dist/extensions/isolated/lanes.d.ts +44 -3
  86. package/dist/extensions/isolated/lanes.js +263 -80
  87. package/dist/extensions/isolated/metrics.d.ts +146 -0
  88. package/dist/extensions/isolated/metrics.js +304 -0
  89. package/dist/extensions/isolated/revision.d.ts +7 -1
  90. package/dist/extensions/isolated/revision.js +26 -5
  91. package/dist/extensions/isolated/rpc.d.ts +5 -0
  92. package/dist/extensions/isolated/rpc.js +7 -2
  93. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  94. package/dist/extensions/isolated/sandbox.js +50 -0
  95. package/dist/extensions/isolated/status.d.ts +79 -0
  96. package/dist/extensions/isolated/status.js +216 -0
  97. package/dist/extensions/isolated/tier.d.ts +127 -2
  98. package/dist/extensions/isolated/tier.js +266 -7
  99. package/dist/extensions/isolated/usage.d.ts +134 -0
  100. package/dist/extensions/isolated/usage.js +322 -0
  101. package/dist/extensions/lifecycle.d.ts +42 -2
  102. package/dist/extensions/lifecycle.js +100 -4
  103. package/dist/extensions/org-config.js +11 -0
  104. package/dist/extensions/package.d.ts +14 -0
  105. package/dist/extensions/package.js +23 -0
  106. package/dist/extensions/permissions.controller.d.ts +35 -0
  107. package/dist/extensions/permissions.controller.js +98 -0
  108. package/dist/extensions/permissions.schemas.d.ts +288 -0
  109. package/dist/extensions/permissions.schemas.js +96 -0
  110. package/dist/extensions/permissions.service.d.ts +116 -0
  111. package/dist/extensions/permissions.service.js +428 -0
  112. package/dist/extensions/realm-retirement.d.ts +65 -0
  113. package/dist/extensions/realm-retirement.js +150 -0
  114. package/dist/extensions/revision-approvals.d.ts +58 -3
  115. package/dist/extensions/revision-approvals.js +135 -14
  116. package/dist/extensions/revision-review.d.ts +144 -0
  117. package/dist/extensions/revision-review.js +297 -0
  118. package/dist/extensions/revocation.js +3 -0
  119. package/dist/extensions/state.module.js +12 -0
  120. package/dist/git/run-end.d.ts +35 -7
  121. package/dist/git/run-end.js +87 -38
  122. package/dist/http/api.module.js +2 -0
  123. package/dist/identity/audit.d.ts +2 -1
  124. package/dist/identity/audit.js +4 -17
  125. package/dist/index.d.ts +4 -0
  126. package/dist/index.js +4 -0
  127. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  128. package/dist/infra/config/kernel-config.service.js +21 -0
  129. package/dist/infra/outbox/registry.d.ts +13 -0
  130. package/dist/infra/outbox/registry.js +8 -0
  131. package/dist/lifecycle/kernel-lifecycle.d.ts +25 -1
  132. package/dist/lifecycle/kernel-lifecycle.js +73 -18
  133. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  134. package/dist/net/private-endpoint-preflight.js +417 -0
  135. package/dist/net/private-endpoints.d.ts +68 -0
  136. package/dist/net/private-endpoints.js +164 -0
  137. package/dist/net/public-address.d.ts +14 -0
  138. package/dist/net/public-address.js +15 -1
  139. package/dist/net/safe-fetch.d.ts +2 -1
  140. package/dist/net/safe-fetch.js +10 -3
  141. package/dist/overrides.d.ts +4 -0
  142. package/dist/overrides.js +2 -0
  143. package/dist/packages/official-publisher.d.ts +26 -1
  144. package/dist/packages/official-publisher.js +48 -1
  145. package/dist/packages/provenance.d.ts +11 -0
  146. package/dist/packages/provenance.js +24 -0
  147. package/dist/platform/exclusions.js +4 -4
  148. package/dist/platform/ops/automations.ops.js +1 -1
  149. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  150. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  151. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  152. package/dist/platform/platform-ops.module.d.ts +2 -1
  153. package/dist/platform/platform-ops.module.js +2 -0
  154. package/dist/platform/route-schemas.js +2 -0
  155. package/dist/retention/purge-batch.js +10 -14
  156. package/dist/runtime/maintenance.d.ts +4 -2
  157. package/dist/runtime/maintenance.js +16 -3
  158. package/dist/runtime/run-finish.d.ts +3 -3
  159. package/dist/runtime/run-finish.js +7 -3
  160. package/dist/sandbox/permission-availability.d.ts +17 -2
  161. package/dist/sandbox/permission-availability.js +22 -1
  162. package/dist/sandbox/permission-facts.js +7 -1
  163. package/dist/tools/builtins/sandbox/common.js +2 -0
  164. package/dist/tools/pipeline.d.ts +2 -1
  165. package/dist/tools/pipeline.js +7 -2
  166. package/package.json +4 -3
  167. package/src/migrations/0238_extension_usage.sql +40 -0
  168. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -16,8 +16,8 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { ModuleRef } from "@nestjs/core";
17
17
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
18
18
  import { officialPublisherProofMode } from "../catalog/publisher-policy.js";
19
+ import { resolveCapacity } from "../config/capacity-presets.js";
19
20
  import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
20
- import { EXTENSION_CAPACITY_DEFAULTS } from "../config/schema.js";
21
21
  import { EXTERNAL_CONVERSATIONS_BACKEND } from "../conversations/external/token.js";
22
22
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
23
23
  import { ExtensionEffects } from "../ctx/durable-effects.service.js";
@@ -35,7 +35,7 @@ import { INBOX_ITEMS_BACKEND } from "../inbox/token.js";
35
35
  import { waitWithin } from "../infra/close-within.js";
36
36
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
37
37
  import { KernelDb } from "../infra/database/kernel-db.js";
38
- import { withOrgScope } from "../infra/database/org-scope.js";
38
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
39
39
  import { LockService } from "../infra/lock/lock.service.js";
40
40
  import { KERNEL_LOGGER, KEYRING, REDIS, REDIS_SUBSCRIBER } from "../infra/tokens.js";
41
41
  import { KERNEL_APP_OPTIONS, KERNEL_FIXTURE_TRUST, } from "../lifecycle/tokens.js";
@@ -57,13 +57,15 @@ import { GrantEpoch, grantEpochReader, grantEpochReadTimeoutMs } from "./grant-e
57
57
  import { HookRegistry } from "./hooks.js";
58
58
  import { ExtensionInstalls } from "./installs.js";
59
59
  import { ImportTracker, importExtensionModule, ManifestMismatchError, matchesSection, setupInstance, warnUpgrades, } from "./instance.js";
60
- import { assertIsolatedSection, isolatedDeploymentSchema } from "./isolated/admission.js";
60
+ import { assertIsolatedSection, isolatedDeploymentSchema, } from "./isolated/admission.js";
61
61
  import { IsolatedInvocationGrants, readIsolatedGrant, } from "./isolated/authorization.js";
62
62
  import { readConfiguredExtensionPackage, stageConfiguredExtensionPackage, } from "./isolated/configured-package.js";
63
63
  import { IsolatedExtensionQuota } from "./isolated/lanes.js";
64
+ import { IsolationObserver, OrgLabels, observeGrantEpochLag } from "./isolated/metrics.js";
64
65
  import { isolatedRevision } from "./isolated/revision.js";
65
- import { sweepExtensionSandboxOrphans } from "./isolated/sandbox.js";
66
- import { publisherProofMissing, publisherProofRefusal, } from "./isolated/tier.js";
66
+ import { probeExtensionSandboxChecks, sweepExtensionSandboxOrphans, } from "./isolated/sandbox.js";
67
+ import { GrantReadError, isolatedSectionGrant, keepsServingAdmission, publisherProofMissing, publisherProofRefusal, shadowExecutionOf, } from "./isolated/tier.js";
68
+ import { ExtensionUsageCounters, ExtensionUsageFlusher } from "./isolated/usage.js";
67
69
  import { parseLoadGate } from "./org-levels.js";
68
70
  import { declaredDisplayName, permissionSetOfSection, readMigrationSql } from "./package.js";
69
71
  import { blockingKeys, computePermissionSet, SETUP_CHECK_KEY_PREFIX, UI_VIEW_KEY_PREFIX, } from "./permission-set.js";
@@ -258,6 +260,11 @@ export function assertSecretsReachable(manifest) {
258
260
  }
259
261
  /** 按模块解析的插件(配置声明)的迁移目录:清单 `migrations` 相对模块所在目录。 */
260
262
  const migrationsDirOf = (m, dir) => m.migrations ? resolvePath(dir, m.migrations) : undefined;
263
+ /**
264
+ * A pending status reason: the revision's grant could not be read (plan task 1.3b). It is retried
265
+ * at the next convergence; a serving revision keeps its tier instead.
266
+ */
267
+ export const GRANT_UNAVAILABLE = "grant_unavailable";
261
268
  /**
262
269
  * 由审阅过的静态清单拼出解析依赖、判定权限闸门用的清单(没有 setup 与配置 schema,不能用来加载)。
263
270
  * 闸门放行后导入的真实模块必须与静态清单一致({@link matchesSection}),两者在依赖解析上等价。
@@ -422,6 +429,13 @@ let ExtensionHost = class ExtensionHost {
422
429
  */
423
430
  grantEpoch;
424
431
  epochReader;
432
+ /** Which orgs get their own label on the isolation metrics (the largest few). */
433
+ orgLabels;
434
+ /** This replica's isolated usage increments, flushed every 10 s once isolated work started. */
435
+ usageCounters = new ExtensionUsageCounters();
436
+ usageFlusher;
437
+ unobserveEpochLag;
438
+ capacityCache;
425
439
  executionTier = new Map();
426
440
  policyExpected = new Map();
427
441
  /**
@@ -582,8 +596,7 @@ let ExtensionHost = class ExtensionHost {
582
596
  config: () => ({ hooks: { timeoutMs: this.config.get().hooks.timeoutMs } }),
583
597
  log,
584
598
  });
585
- // Hand-built configs (tests, embedders) may leave the capacity object out.
586
- const capacity = { ...EXTENSION_CAPACITY_DEFAULTS, ...c.extensionHost.capacity };
599
+ const capacity = this.capacity();
587
600
  this.epochReader = grantEpochReader({
588
601
  url: c.db.url,
589
602
  readTimeoutMs: grantEpochReadTimeoutMs(capacity.grantEpochMaxAgeMs),
@@ -612,7 +625,7 @@ let ExtensionHost = class ExtensionHost {
612
625
  },
613
626
  onFault: (err) => this.log.warn("reading the extension grant epoch failed", { err }),
614
627
  });
615
- this.isolatedGrants = new IsolatedInvocationGrants(this.grantEpoch, capacity.grantCacheEntries);
628
+ this.isolatedGrants = new IsolatedInvocationGrants(this.grantEpoch, capacity.grantCacheEntries, () => performance.now(), capacity.grantFullRevalidationMs);
616
629
  const grantReads = kernelDb(kdb.pool);
617
630
  this.revisionLeases = new RevisionLeases({
618
631
  epochs: this.grantEpoch,
@@ -645,6 +658,36 @@ let ExtensionHost = class ExtensionHost {
645
658
  }),
646
659
  }),
647
660
  });
661
+ this.unobserveEpochLag = observeGrantEpochLag(() => this.grantEpoch.lagSeconds());
662
+ this.orgLabels = new OrgLabels({
663
+ limits: () => ({
664
+ minMembers: this.config.get().metrics?.orgLabelMinMembers ?? 1_000,
665
+ maxOrgs: this.config.get().metrics?.orgLabelMaxOrgs ?? 20,
666
+ }),
667
+ read: (minMembers, maxOrgs) => asPlatform("pick the org labels of the isolation metrics", async () => {
668
+ const rows = await kernelDb(this.deps.db)
669
+ .selectFrom("memberships")
670
+ .innerJoin("orgs", "orgs.id", "memberships.org_id")
671
+ .where("orgs.deleted_at", "is", null)
672
+ // Guests are not members for sizing: they do not make an org large.
673
+ .where("memberships.role", "!=", "guest")
674
+ .select(["memberships.org_id as orgId", (eb) => eb.fn.countAll().as("members")])
675
+ .groupBy("memberships.org_id")
676
+ .having((eb) => eb.fn.countAll(), ">=", minMembers)
677
+ .orderBy("members", "desc")
678
+ .orderBy("memberships.org_id")
679
+ .limit(maxOrgs)
680
+ .execute();
681
+ return rows.map((row) => ({ orgId: row.orgId, members: Number(row.members) }));
682
+ }),
683
+ onError: (err) => this.log.warn("reading the isolation metrics org labels failed", { err }),
684
+ });
685
+ this.usageFlusher = new ExtensionUsageFlusher({
686
+ db: kdb.pool,
687
+ counters: this.usageCounters,
688
+ onError: (err) => this.log.warn("flushing isolated extension usage failed", { err }),
689
+ onDropped: (detail) => this.log.warn("isolated extension usage increments were dropped", detail),
690
+ });
648
691
  this.deps = {
649
692
  db: kdb.pool,
650
693
  dbUrl: c.db.url,
@@ -821,6 +864,8 @@ let ExtensionHost = class ExtensionHost {
821
864
  await sweepExtensionSandboxOrphans(isolation.engineUrl).catch(() => {
822
865
  this.log.error("Could not sweep exited isolated extension sandboxes");
823
866
  });
867
+ // off the startup path: the probe can take up to the Engine deadline
868
+ void this.probeIsolation();
824
869
  }
825
870
  const entries = await importEntries(p.config ?? [], this.resolveFrom, this.options[KERNEL_FIXTURE_TRUST] !== undefined, this.config.get().packages.maxBytes, this.config.get().extensionHost.dir);
826
871
  for (const { manifest, isolated } of entries) {
@@ -909,6 +954,110 @@ let ExtensionHost = class ExtensionHost {
909
954
  });
910
955
  }
911
956
  }
957
+ /**
958
+ * This replica's isolation supervisor as last observed (plan task 1.3b): `not_configured`
959
+ * without `extensionHost.isolation`; otherwise `available` only after the Engine answered
960
+ * ({@link probeIsolation}), `failing` when it did not. Configuration alone is never readiness.
961
+ */
962
+ isolationState;
963
+ hostIsolation() {
964
+ if (!this.config.get().extensionHost.isolation)
965
+ return "not_configured";
966
+ return this.isolationState ?? "failing";
967
+ }
968
+ /**
969
+ * Probes the isolation supervisor with the same read-only Engine and image checks a sandbox start
970
+ * runs (Linux, cgroup v2, the mandatory security options, the local runtime image): the positive
971
+ * readiness signal host-reason retirement waits for. Called at load and on each periodic
972
+ * convergence, so the reported state may lag a failure by one period (reporting only: a sandbox
973
+ * start runs the checks again and fails closed).
974
+ */
975
+ async probeIsolation() {
976
+ const isolation = this.config.get().extensionHost.isolation;
977
+ if (!isolation) {
978
+ this.isolationState = undefined;
979
+ this.lastProbe = undefined;
980
+ return "not_configured";
981
+ }
982
+ const result = await probeExtensionSandboxChecks(isolation);
983
+ this.lastProbe = { result, at: new Date() };
984
+ this.isolationState = result.ok ? "available" : "failing";
985
+ return this.isolationState;
986
+ }
987
+ /** The last probe with its named checks (plan task 1.4j), undefined before any or unconfigured. */
988
+ lastProbe;
989
+ /**
990
+ * What this replica records for the isolation status projection (`ReplicaIsolationStore`): its
991
+ * last probe and the shadow placements of its last convergence.
992
+ */
993
+ isolationRecord() {
994
+ return { probe: this.lastProbe, shadow: this.executions };
995
+ }
996
+ /**
997
+ * The newest grant of each install's revision, or undefined when the read failed: a revision
998
+ * already serving then keeps its admission (a read error is never a refusal), and any other
999
+ * revision is admitted as without a grant (today's admission).
1000
+ */
1001
+ async grantSurfaces(desired) {
1002
+ try {
1003
+ return await readGrantSurfacesBySha256(kernelDb(this.deps.db), desired.map((d) => d.sha256));
1004
+ }
1005
+ catch (err) {
1006
+ this.log.warn("reading extension revision grants for admission failed", { err });
1007
+ return undefined;
1008
+ }
1009
+ }
1010
+ /** The last shadow execution report logged by this replica (log de-duplication, not state). */
1011
+ lastExecutionReport;
1012
+ /** The shadow execution decisions of the last convergence on this replica (for the inventory). */
1013
+ executions = [];
1014
+ /** This replica's shadow execution decisions of the installs it last converged. */
1015
+ shadowExecutions() {
1016
+ return this.executions;
1017
+ }
1018
+ /**
1019
+ * Shadow mode (plan task 1.3b, rollout fence until 1.5a): where each admitted install would run
1020
+ * under the execution-realm decision and whether its grant covers the forcing keys, including
1021
+ * the kernel's `host.no-isolation` on a host without isolation. Logged when it changes; never
1022
+ * refuses or moves a revision: the legacy tier governs.
1023
+ */
1024
+ reportShadowExecution(desired, tiers, grants) {
1025
+ try {
1026
+ const host = this.hostIsolation();
1027
+ const executions = [];
1028
+ for (const d of desired) {
1029
+ const tier = tiers.get(d.name);
1030
+ if (tier === undefined || tier === "refused")
1031
+ continue;
1032
+ executions.push(shadowExecutionOf(d, tier, host, grants.get(d.sha256)));
1033
+ }
1034
+ this.executions = executions;
1035
+ const notable = executions.filter((e) => e.diverges || e.hostReasonRetired || e.retireHostReason);
1036
+ const report = notable.map((e) => ({
1037
+ plugin: `${e.plugin}@${e.version}`,
1038
+ legacy: e.legacy,
1039
+ would: e.would,
1040
+ uncovered: e.uncovered,
1041
+ ...(e.hostReasonRetired && {
1042
+ hostReasonRetired: "host.no-isolation was retired when isolation was available; it is not restored, the revision needs a new review",
1043
+ }),
1044
+ ...(e.retireHostReason && { retireHostReason: true }),
1045
+ }));
1046
+ const digest = JSON.stringify({ host, report });
1047
+ if (digest === this.lastExecutionReport)
1048
+ return;
1049
+ this.lastExecutionReport = digest;
1050
+ if (report.length > 0) {
1051
+ this.log.info("shadow execution realms: the enforcing cutover would place these differently", {
1052
+ host,
1053
+ revisions: report,
1054
+ });
1055
+ }
1056
+ }
1057
+ catch (err) {
1058
+ this.log.warn("shadow execution decisions failed", { err });
1059
+ }
1060
+ }
912
1061
  /** The last shadow report logged by this replica (a log de-duplication, not state). */
913
1062
  lastShadowReport;
914
1063
  /**
@@ -1051,11 +1200,44 @@ let ExtensionHost = class ExtensionHost {
1051
1200
  }
1052
1201
  tierOf(loader, revision, verifyBytes) {
1053
1202
  const fixtures = this.options[KERNEL_FIXTURE_TRUST];
1203
+ // Shadow mode (plan task 1.3b, until 1.5a): a pin-only revision is placed by its grant at
1204
+ // admission only. While its generation serves, a grant change (a retired host reason, a
1205
+ // revoked realm or grant) moves or refuses nothing; 1.3e's afterRevocation does that once
1206
+ // enforcing. Its bytes were verified at admission and a package sha256 never changes.
1207
+ const serving = this.servingTier(revision);
1208
+ // An extra-manifest pin placed by its grant (#1371) likewise keeps its serving tier
1209
+ const cause = publisherProofMissing(revision)
1210
+ ? "pin_only_grant"
1211
+ : revision.source === "bootstrap"
1212
+ ? "extra_pin_grant"
1213
+ : undefined;
1214
+ if (cause !== undefined &&
1215
+ keepsServingAdmission({ serving, enforced: this.revisionLeases.enforced, cause })) {
1216
+ return Promise.resolve(serving);
1217
+ }
1054
1218
  const tier = fixtures === true || fixtures?.installDigests.includes(revision.sha256)
1055
1219
  ? Promise.resolve("trusted")
1056
1220
  : (loader.tier?.(revision, verifyBytes) ?? Promise.resolve("isolated"));
1057
1221
  return tier.then((t) => (t === "refused" ? t : this.afterRevocation(revision, t)));
1058
1222
  }
1223
+ /**
1224
+ * What the isolated admission of an instance start takes from its grant. In shadow mode the
1225
+ * activation's decision (a reload reuses it; a grant change is reported, not enforced); once
1226
+ * enforcing (task 1.5a) the grant is read again, so a reload follows a revoked browser realm.
1227
+ */
1228
+ async isolatedGrantFor(spec) {
1229
+ const isolated = spec.isolated;
1230
+ if (!isolated || !this.revisionLeases.enforced || !spec.sha256)
1231
+ return isolated?.grant;
1232
+ const grant = await readGrantSurfaceBySha256(kernelDb(this.deps.db), spec.sha256);
1233
+ return isolatedSectionGrant({ name: spec.manifest.name, version: spec.manifest.version, section: isolated.section }, grant);
1234
+ }
1235
+ /** The tier this replica serves the exact revision in, or undefined when it does not serve it. */
1236
+ servingTier(revision) {
1237
+ return this.registry.current(revision.name)?.sha256 === revision.sha256
1238
+ ? this.executionTier.get(revision.name)
1239
+ : undefined;
1240
+ }
1059
1241
  /**
1060
1242
  * The tier after a revocation (plan task 1.3e; enforced from task 1.5a, until then the leases
1061
1243
  * only report it). A revision whose whole grant is revoked waits for a new review. A trusted
@@ -1076,7 +1258,7 @@ let ExtensionHost = class ExtensionHost {
1076
1258
  return tier;
1077
1259
  if (realmAfterRevocation(grant, "server") === "isolated") {
1078
1260
  try {
1079
- assertIsolatedSection(revision.section);
1261
+ assertIsolatedSection(revision.section, isolatedSectionGrant(revision, grant));
1080
1262
  return "isolated";
1081
1263
  }
1082
1264
  catch {
@@ -1108,6 +1290,9 @@ let ExtensionHost = class ExtensionHost {
1108
1290
  let proofMode;
1109
1291
  /** Revisions a revocation sends back to review: pending, not failed (plan task 1.3e). */
1110
1292
  const awaitingReview = new Map();
1293
+ /** Revisions whose grant could not be read: they wait for the next convergence. */
1294
+ const grantUnavailable = new Set();
1295
+ const grantsBySha = await this.grantSurfaces(electAmong);
1111
1296
  for (const d of electAmong) {
1112
1297
  if (declared.has(d.name))
1113
1298
  continue;
@@ -1125,17 +1310,42 @@ let ExtensionHost = class ExtensionHost {
1125
1310
  }
1126
1311
  continue;
1127
1312
  }
1128
- if (tier === "isolated")
1129
- assertIsolatedSection(d.section);
1313
+ // A serving revision keeps its isolated admission when the grant read failed (a read
1314
+ // error is no refusal) and, in shadow mode, when its grant changed (the browser realm
1315
+ // revoked): reported now, enforced from task 1.5a.
1316
+ const serving = this.servingTier(d);
1317
+ const keep = serving === tier &&
1318
+ keepsServingAdmission({
1319
+ serving,
1320
+ tier,
1321
+ enforced: this.revisionLeases.enforced,
1322
+ cause: grantsBySha === undefined ? "grant_read_failed" : "browser_grant",
1323
+ });
1324
+ if (tier === "isolated" && !keep) {
1325
+ assertIsolatedSection(d.section, isolatedSectionGrant(d, grantsBySha?.get(d.sha256)));
1326
+ }
1130
1327
  tiers.set(d.name, tier);
1131
1328
  }
1132
1329
  catch (error) {
1133
- if (error instanceof RevocationPendingError)
1330
+ const serving = this.servingTier(d);
1331
+ const keep = error instanceof GrantReadError &&
1332
+ keepsServingAdmission({
1333
+ serving,
1334
+ enforced: this.revisionLeases.enforced,
1335
+ cause: "grant_read_failed",
1336
+ });
1337
+ if (keep)
1338
+ tiers.set(d.name, serving);
1339
+ else if (error instanceof GrantReadError)
1340
+ grantUnavailable.add(d.name);
1341
+ else if (error instanceof RevocationPendingError)
1134
1342
  awaitingReview.set(d.name, error.message);
1135
1343
  else
1136
1344
  rejected.set(d.name, errMsg(error));
1137
1345
  }
1138
1346
  }
1347
+ if (grantsBySha)
1348
+ this.reportShadowExecution(electAmong, tiers, grantsBySha);
1139
1349
  // Single-provider election: of the enabled install records providing one single-provider
1140
1350
  // extension point, only the earliest enabled is loaded (desired() order: enabled_at, install
1141
1351
  // time, name). Decided from PG alone, never from what loaded here, so every replica and every
@@ -1195,6 +1405,19 @@ let ExtensionHost = class ExtensionHost {
1195
1405
  detail: null,
1196
1406
  });
1197
1407
  }
1408
+ for (const d of desired) {
1409
+ if (!grantUnavailable.has(d.name))
1410
+ continue;
1411
+ await this.writeStatus({
1412
+ plugin: d.name,
1413
+ version: d.version,
1414
+ sha256: d.sha256,
1415
+ source: "install",
1416
+ state: "pending",
1417
+ reason: GRANT_UNAVAILABLE,
1418
+ detail: "The revision's grant could not be read; retried at the next convergence",
1419
+ });
1420
+ }
1198
1421
  for (const d of desired) {
1199
1422
  const waiting = awaitingReview.get(d.name);
1200
1423
  if (waiting === undefined)
@@ -1239,16 +1462,29 @@ let ExtensionHost = class ExtensionHost {
1239
1462
  else if (current?.sha256 === d.sha256) {
1240
1463
  continue;
1241
1464
  }
1242
- if (tier === "trusted") {
1465
+ // a pin-only revision (no publisher proof) is verified whatever tier its grant gives it
1466
+ if (tier === "trusted" || publisherProofMissing(d)) {
1243
1467
  let verified = "refused";
1244
1468
  try {
1245
1469
  verified = await this.tierOf(loader, d, true);
1246
1470
  }
1247
- catch {
1471
+ catch (error) {
1472
+ if (error instanceof GrantReadError) {
1473
+ await this.writeStatus({
1474
+ plugin: d.name,
1475
+ version: d.version,
1476
+ sha256: d.sha256,
1477
+ source: "install",
1478
+ state: "pending",
1479
+ reason: GRANT_UNAVAILABLE,
1480
+ detail: "The revision's grant could not be read; retried at the next convergence",
1481
+ });
1482
+ continue;
1483
+ }
1248
1484
  // The refusal below reports the failed integrity check without logging verifier internals.
1249
1485
  }
1250
- if (verified !== "trusted") {
1251
- const detail = "The trusted extension package did not match its verified integrity";
1486
+ if (verified !== tier) {
1487
+ const detail = "The extension package did not match its verified integrity";
1252
1488
  await this.reportAdmissionRefusal(d.name, d.sha256, detail, "Check publisher verification and reimport the verified package.");
1253
1489
  await this.writeStatus({
1254
1490
  plugin: d.name,
@@ -1266,7 +1502,9 @@ let ExtensionHost = class ExtensionHost {
1266
1502
  if (c)
1267
1503
  candidates.push(c);
1268
1504
  }
1269
- // 与生效的插件一起解析依赖:被替换的旧实例在新的被接受之前仍算提供方;解析不过的反复重试直到没有新的能加进来
1505
+ // Resolve dependencies together with the serving extensions: a replaced old instance still
1506
+ // counts as a provider until its replacement is accepted; candidates that fail to resolve are
1507
+ // retried until no new one can be added
1270
1508
  const accepted = [];
1271
1509
  const base = () => {
1272
1510
  const replaced = new Set(accepted.map((a) => a.d.name));
@@ -1356,7 +1594,13 @@ let ExtensionHost = class ExtensionHost {
1356
1594
  const isolated = tiers.get(m.name) === "isolated";
1357
1595
  const a = {
1358
1596
  manifest: c.manifest,
1359
- ...(isolated && { isolated: { root: c.root, section: c.d.section } }),
1597
+ ...(isolated && {
1598
+ isolated: {
1599
+ root: c.root,
1600
+ section: c.d.section,
1601
+ grant: isolatedSectionGrant(c.d, grantsBySha?.get(c.d.sha256)),
1602
+ },
1603
+ }),
1360
1604
  source: "install",
1361
1605
  optionalBootstrap: c.d.source === "bootstrap" && !c.d.required,
1362
1606
  sha256: c.d.sha256,
@@ -1747,7 +1991,7 @@ let ExtensionHost = class ExtensionHost {
1747
1991
  }
1748
1992
  if (a.isolated && decision.action !== "pending") {
1749
1993
  try {
1750
- assertIsolatedSection(a.isolated.section);
1994
+ assertIsolatedSection(a.isolated.section, a.isolated.grant);
1751
1995
  manifest = isolatedManifestOf(a.isolated.section);
1752
1996
  }
1753
1997
  catch (error) {
@@ -2254,9 +2498,12 @@ let ExtensionHost = class ExtensionHost {
2254
2498
  throw new Error("The isolated extension supervisor is not configured");
2255
2499
  let quota = this.quota.get(name);
2256
2500
  if (!quota) {
2257
- quota = new IsolatedExtensionQuota();
2501
+ quota = new IsolatedExtensionQuota(() => this.capacity());
2258
2502
  this.quota.set(name, quota);
2259
2503
  }
2504
+ this.usageFlusher.start();
2505
+ const revision = spec.sha256 ?? spec.entryUrl;
2506
+ const observer = new IsolationObserver(name, revision, this.orgLabels.label, this.usageCounters);
2260
2507
  const modules = this.modules;
2261
2508
  const db = kernelDb(this.deps.db);
2262
2509
  const current = () => active !== undefined &&
@@ -2280,8 +2527,10 @@ let ExtensionHost = class ExtensionHost {
2280
2527
  const declared = spec.manifest.permissions?.network ?? [];
2281
2528
  manifest = await isolatedRevision({
2282
2529
  manifest,
2283
- revision: spec.sha256 ?? spec.entryUrl,
2530
+ revision,
2531
+ observer,
2284
2532
  section: spec.isolated.section,
2533
+ grant: await this.isolatedGrantFor(spec),
2285
2534
  identity,
2286
2535
  sandbox: {
2287
2536
  engineUrl: isolation.engineUrl,
@@ -2296,13 +2545,15 @@ let ExtensionHost = class ExtensionHost {
2296
2545
  onLanes: (value) => {
2297
2546
  lanes = value;
2298
2547
  },
2299
- onCrash: (retryAfterMs) => {
2300
- this.log.warn("Isolated extension sandbox exited unexpectedly", {
2301
- plugin: name,
2302
- retryAfterMs,
2303
- });
2548
+ onCrash: (retryAfterMs, cause) => {
2549
+ const exited = cause === "exited";
2550
+ this.log.warn(exited
2551
+ ? "Isolated extension sandbox exited unexpectedly"
2552
+ : "Isolated extension sandbox failed to start", { plugin: name, retryAfterMs });
2304
2553
  void this.status
2305
- .note(name, `Isolated sandbox crashed. Retry is delayed by ${retryAfterMs} ms.`)
2554
+ .note(name, exited
2555
+ ? `Isolated sandbox crashed. Retry is delayed by ${retryAfterMs} ms.`
2556
+ : `Isolated sandbox failed to start. Retry is delayed by ${retryAfterMs} ms.`)
2306
2557
  .catch(() => { });
2307
2558
  },
2308
2559
  cleanupFault: () => {
@@ -3015,6 +3266,7 @@ let ExtensionHost = class ExtensionHost {
3015
3266
  async close(opts = {}) {
3016
3267
  this.closed = true;
3017
3268
  this.grantEpoch.stop();
3269
+ this.unobserveEpochLag();
3018
3270
  await this.epochReader
3019
3271
  .close()
3020
3272
  .catch((err) => this.log.warn("closing the grant epoch connection failed", { err }));
@@ -3050,6 +3302,20 @@ let ExtensionHost = class ExtensionHost {
3050
3302
  this.log.error("plugin close failed", { plugin: inst.name, err: e });
3051
3303
  }
3052
3304
  }
3305
+ // Every isolated call has ended: book and flush this replica's last usage increments.
3306
+ await this.usageFlusher.stop();
3307
+ }
3308
+ /**
3309
+ * The resolved `extensionHost.capacity` (preset plus explicit fields), read at every isolated
3310
+ * admission and lane start so hot fields apply at once. Invalid fields fell back to the preset
3311
+ * when the config was parsed; the config service logs them.
3312
+ */
3313
+ capacity() {
3314
+ const from = this.config.get().extensionHost?.capacity;
3315
+ if (this.capacityCache?.from !== from || this.capacityCache === undefined) {
3316
+ this.capacityCache = { from, limits: resolveCapacity(from) };
3317
+ }
3318
+ return this.capacityCache.limits;
3053
3319
  }
3054
3320
  };
3055
3321
  ExtensionHost = __decorate([
@@ -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 = {
@@ -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. */
@@ -13,4 +13,19 @@ export declare function assertIsolatedToolSchema(input: unknown): void;
13
13
  * fields at all). The execution decision reads it as `configSchemaIsolatable`.
14
14
  */
15
15
  export declare function deploymentConfigIsolatable(section: PluginExtensionSection): boolean;
16
- export declare function assertIsolatedSection(section: PluginExtensionSection): void;
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({
@@ -198,16 +199,23 @@ export function deploymentConfigIsolatable(section) {
198
199
  return false;
199
200
  }
200
201
  }
201
- export function assertIsolatedSection(section) {
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 = {}) {
202
209
  const { manifest, client } = section;
203
210
  const permissions = manifest.permissions;
204
- if (client !== undefined ||
205
- permissions?.client ||
211
+ const isolatedPoint = (point) => ISOLATED_EXTENSION_POINTS.includes(point);
212
+ const inPage = grant.browserFullAccess === true;
213
+ if ((!inPage && (client !== undefined || permissions?.client)) ||
206
214
  permissions?.secrets ||
207
- manifest.provides.some((point) => point !== "trigger-source@1") ||
208
- (manifest.requires ?? []).some((point) => point !== "trigger-source@1") ||
209
- (manifest.optional ?? []).some((point) => point !== "trigger-source@1") ||
210
- 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")) ||
211
219
  permissions?.http ||
212
220
  permissions?.dialIn ||
213
221
  permissions?.deviceAccess ||