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

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 (134) hide show
  1. package/dist/admin/admin-agents.controller.d.ts +3 -5
  2. package/dist/admin/admin-agents.controller.js +1 -1
  3. package/dist/admin/admin-connectors.controller.d.ts +3 -5
  4. package/dist/admin/admin-connectors.controller.js +1 -1
  5. package/dist/admin/admin-items.schemas.d.ts +6 -6
  6. package/dist/admin/admin-items.schemas.js +5 -9
  7. package/dist/admin/admin.controller.d.ts +18 -12
  8. package/dist/admin/admin.controller.js +29 -15
  9. package/dist/admin/admin.schemas.d.ts +12 -3
  10. package/dist/admin/admin.schemas.js +17 -6
  11. package/dist/agents/admin-agents.d.ts +30 -11
  12. package/dist/agents/admin-agents.js +51 -16
  13. package/dist/automations/automations.controller.d.ts +9 -5
  14. package/dist/automations/automations.controller.js +21 -4
  15. package/dist/automations/automations.schemas.d.ts +19 -0
  16. package/dist/automations/automations.schemas.js +9 -0
  17. package/dist/automations/automations.service.d.ts +25 -8
  18. package/dist/automations/automations.service.js +40 -34
  19. package/dist/automations/store.d.ts +17 -0
  20. package/dist/automations/store.js +35 -0
  21. package/dist/catalog/admin-catalog.controller.d.ts +64 -2
  22. package/dist/catalog/admin-catalog.controller.js +17 -0
  23. package/dist/catalog/cli.js +2 -2
  24. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  25. package/dist/catalog/marketplace-fetch.js +7 -2
  26. package/dist/catalog/marketplaces.service.d.ts +1 -1
  27. package/dist/catalog/plugin-package.js +2 -1
  28. package/dist/client/client-access.service.js +29 -1
  29. package/dist/config/schema.d.ts +9 -0
  30. package/dist/config/schema.js +26 -0
  31. package/dist/ctx/create-ctx.d.ts +2 -19
  32. package/dist/ctx/create-ctx.js +3 -93
  33. package/dist/ctx/durable-relay.d.ts +2 -5
  34. package/dist/ctx/durable-relay.js +56 -29
  35. package/dist/db/extension-handoff-schema.js +5 -0
  36. package/dist/db/kernel-schema.d.ts +74 -0
  37. package/dist/erasure/account-batches.js +2 -0
  38. package/dist/erasure/account-residual.js +1 -0
  39. package/dist/erasure/org-catalog.js +8 -3
  40. package/dist/erasure/org-rules.js +1 -0
  41. package/dist/errors.d.ts +1 -1
  42. package/dist/errors.js +2 -2
  43. package/dist/evals/evals.schemas.d.ts +15 -5
  44. package/dist/evals/evals.schemas.js +17 -10
  45. package/dist/evals/runs.controller.d.ts +4 -12
  46. package/dist/evals/runs.controller.js +14 -11
  47. package/dist/evals/runs.service.d.ts +29 -25
  48. package/dist/evals/runs.service.js +73 -61
  49. package/dist/evals/trajectory.controller.d.ts +10 -6
  50. package/dist/evals/trajectory.controller.js +11 -4
  51. package/dist/evals/trajectory.service.d.ts +17 -9
  52. package/dist/evals/trajectory.service.js +52 -35
  53. package/dist/extensions/admin-ops.js +4 -3
  54. package/dist/extensions/blobs.d.ts +2 -0
  55. package/dist/extensions/blobs.js +11 -0
  56. package/dist/extensions/enabled.d.ts +5 -0
  57. package/dist/extensions/grant-epoch.d.ts +108 -0
  58. package/dist/extensions/grant-epoch.js +214 -0
  59. package/dist/extensions/host.d.ts +30 -10
  60. package/dist/extensions/host.js +162 -43
  61. package/dist/extensions/instance.d.ts +3 -3
  62. package/dist/extensions/instance.js +1 -1
  63. package/dist/extensions/isolated/authorization.d.ts +54 -2
  64. package/dist/extensions/isolated/authorization.js +148 -35
  65. package/dist/extensions/isolated/child-session.js +0 -1
  66. package/dist/extensions/isolated/revision.js +1 -1
  67. package/dist/extensions/isolated/tier.d.ts +14 -0
  68. package/dist/extensions/isolated/tier.js +27 -0
  69. package/dist/extensions/package-digest.job.d.ts +34 -0
  70. package/dist/extensions/package-digest.job.js +121 -0
  71. package/dist/extensions/package.js +10 -6
  72. package/dist/extensions/permission-set.d.ts +14 -78
  73. package/dist/extensions/permission-set.js +17 -143
  74. package/dist/extensions/permission-view.d.ts +13 -1
  75. package/dist/extensions/permission-view.js +20 -0
  76. package/dist/extensions/publisher-proof.job.d.ts +39 -0
  77. package/dist/extensions/publisher-proof.job.js +160 -0
  78. package/dist/extensions/registry.js +4 -1
  79. package/dist/extensions/resolve.d.ts +7 -8
  80. package/dist/extensions/resolve.js +7 -8
  81. package/dist/extensions/revision-approvals.d.ts +167 -0
  82. package/dist/extensions/revision-approvals.js +353 -0
  83. package/dist/extensions/revision-grants.d.ts +197 -0
  84. package/dist/extensions/revision-grants.js +584 -0
  85. package/dist/extensions/state.module.js +12 -1
  86. package/dist/identity/accounts.d.ts +10 -4
  87. package/dist/identity/accounts.js +18 -5
  88. package/dist/infra/database/extension-effect-key-lock.js +7 -0
  89. package/dist/infra/paging/paged-read.d.ts +34 -4
  90. package/dist/infra/paging/paged-read.js +38 -1
  91. package/dist/orgs/invitations.controller.d.ts +4 -7
  92. package/dist/orgs/invitations.controller.js +8 -5
  93. package/dist/orgs/invitations.service.d.ts +17 -3
  94. package/dist/orgs/invitations.service.js +35 -13
  95. package/dist/orgs/members.service.d.ts +35 -0
  96. package/dist/orgs/members.service.js +52 -3
  97. package/dist/orgs/orgs.controller.d.ts +11 -4
  98. package/dist/orgs/orgs.controller.js +25 -5
  99. package/dist/orgs/orgs.schemas.d.ts +14 -0
  100. package/dist/orgs/orgs.schemas.js +19 -2
  101. package/dist/orgs/orgs.service.d.ts +21 -1
  102. package/dist/orgs/orgs.service.js +40 -1
  103. package/dist/orgs/security-settings.service.d.ts +14 -6
  104. package/dist/orgs/security-settings.service.js +18 -13
  105. package/dist/orgs/settings.controller.d.ts +7 -4
  106. package/dist/packages/official-publisher.d.ts +5 -0
  107. package/dist/packages/official-publisher.js +24 -3
  108. package/dist/packages/provenance.d.ts +6 -0
  109. package/dist/packages/provenance.js +26 -9
  110. package/dist/platform/exclusions.js +15 -0
  111. package/dist/platform/ops/accounts.ops.js +7 -16
  112. package/dist/platform/ops/admin-items.ops.js +8 -8
  113. package/dist/platform/ops/automations.ops.js +6 -4
  114. package/dist/platform/ops/evals.ops.js +30 -15
  115. package/dist/platform/ops/org-settings.ops.js +2 -2
  116. package/dist/platform/ops/orgs.ops.js +44 -27
  117. package/dist/roles/worker.module.js +6 -0
  118. package/dist/runtime/step-log.d.ts +1 -1
  119. package/dist/runtime/step-log.js +5 -4
  120. package/dist/setup/kernel-checks.d.ts +3 -3
  121. package/dist/setup/kernel-checks.js +4 -4
  122. package/dist/setup/setup-check-registry.d.ts +16 -5
  123. package/dist/setup/setup-check-registry.js +11 -3
  124. package/dist/setup/setup-checks.service.d.ts +1 -2
  125. package/dist/setup/setup-checks.service.js +7 -6
  126. package/dist/tools/admin-connectors.d.ts +10 -8
  127. package/dist/tools/admin-connectors.js +12 -10
  128. package/dist/tools/builtins/automations.d.ts +1 -1
  129. package/dist/tools/builtins/automations.js +1 -1
  130. package/package.json +3 -3
  131. package/src/migrations/0234_extension_grant_epoch.sql +141 -0
  132. package/src/migrations/0235_extension_revision_grants.sql +166 -0
  133. package/src/migrations/0236_paged_table_idx.sql +33 -0
  134. package/src/migrations/0237_extension_handoff_health.sql +18 -0
@@ -17,6 +17,7 @@ import { peopleOfEvents } from "../conversations/event-people.js";
17
17
  import { ApiError } from "../errors.js";
18
18
  import { audit } from "../identity/audit.js";
19
19
  import { KernelDb } from "../infra/database/kernel-db.js";
20
+ import { assertReadablePage, cappedCount, PAGED_NEWER_CAP, PAGED_TOTAL_CAP, pageOf, pageOffset, snapshotNow, } from "../infra/paging/paged-read.js";
20
21
  import { roleAtLeast } from "../orgs/roles.js";
21
22
  import { buildTrajectory } from "./trajectory.js";
22
23
  /** 运行的状态(`runs.status`),列表按最近一次运行的状态过滤用。 */
@@ -80,58 +81,72 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
80
81
  return roleAtLeast(role, "admin") || agent.owner_account_id === accountId;
81
82
  }
82
83
  /**
83
- * 列出可查看的对话(admin 看全部,其余只看自己负责的 agent),按 (updated_at, id) 倒序;`kind` 缺省为 `chat`。
84
- * `before` 是上一页的 `next`(对话 id):从该对话当前的 (updated_at, id) 之后继续。
84
+ * One page of the conversations the account may view (an org admin all of them, anyone else
85
+ * those of the agents they own), last active first (`(updated_at, id)` descending), by page
86
+ * number on a snapshot (table pagination spec §2.3); `kind` defaults to `chat`.
87
+ *
88
+ * Conversations move up as they are used, so the snapshot is a point in time, not a row: `asOf`
89
+ * is the database time of the first read (ISO 8601 with microseconds), and a page lists only
90
+ * conversations last updated at or before it. A conversation used after the snapshot leaves the
91
+ * snapshot (it shifts later rows by one) and counts in `newer` until a new snapshot is read.
92
+ * Known caveat (accepted, as the audit log's): a write whose transaction started before the
93
+ * snapshot and commits after it may carry an `updated_at` at or before `asOf` and appear inside
94
+ * the snapshot.
85
95
  */
86
96
  async list(orgId, accountId, q) {
97
+ assertReadablePage(q.page, q.size);
98
+ const asOf = q.asOf ?? (await snapshotNow(this.db.db));
99
+ const empty = {
100
+ ...pageOf([], q, { count: 0, capped: false }),
101
+ asOf,
102
+ newer: 0,
103
+ };
87
104
  const role = await this.role(orgId, accountId);
88
105
  if (!TrajectoryService_1.isMember(role))
89
- return { items: [], next: null };
106
+ return empty;
90
107
  const admin = roleAtLeast(role, "admin");
91
- // 评测对话只给组织管理员(Ruling S1-c)
108
+ // eval conversations are for org admins only (Ruling S1-c)
92
109
  if (q.kind === "eval" && !admin)
93
- return { items: [], next: null };
94
- let query = this.db
110
+ return empty;
111
+ // the count, the rows and `newer` share these joins (an agent without its current version
112
+ // row is in none of them)
113
+ let matching = this.db
95
114
  .selectFrom("conversations as c")
96
115
  .innerJoin("agents as a", "a.id", "c.agent_id")
97
116
  .innerJoin("agent_versions as v", (j) => j.onRef("v.agent_id", "=", "a.id").onRef("v.version", "=", "a.current_version"))
98
- .select([
99
- "c.id",
100
- "c.agent_id",
101
- "c.account_id",
102
- "c.title",
103
- "c.updated_at",
104
- sql `v.definition ->> 'name'`.as("agent_name"),
105
- ])
106
117
  .where("c.org_id", "=", orgId)
107
118
  .where("c.kind", "=", q.kind ?? "chat")
108
119
  .where("a.org_id", "=", orgId)
109
- .where("a.deleted_at", "is", null)
110
- .orderBy("c.updated_at", "desc")
111
- .orderBy("c.id", "desc")
112
- .limit(q.limit + 1);
120
+ .where("a.deleted_at", "is", null);
113
121
  if (!admin)
114
- query = query.where("a.owner_account_id", "=", accountId);
122
+ matching = matching.where("a.owner_account_id", "=", accountId);
115
123
  if (q.agentId !== undefined)
116
- query = query.where("c.agent_id", "=", q.agentId);
124
+ matching = matching.where("c.agent_id", "=", q.agentId);
117
125
  if (q.status !== undefined) {
118
126
  const status = q.status;
119
- // 与下面取 lastRun 的排序一致:最近一次运行 = created_at、id 最大的一条
120
- query = query.where((eb) => sql `(
127
+ // the latest run as below (lastRun): the one with the largest created_at, then id
128
+ matching = matching.where((eb) => sql `(
121
129
  SELECT r.status FROM capybara.runs r WHERE r.conversation_id = ${eb.ref("c.id")}
122
130
  ORDER BY r.created_at DESC, r.id DESC LIMIT 1
123
131
  ) = ${status}`);
124
132
  }
125
- if (q.before !== undefined) {
126
- const before = q.before;
127
- query = query.where((eb) => sql `(${eb.ref("c.updated_at")}, ${eb.ref("c.id")}) < (
128
- SELECT x.updated_at, x.id FROM capybara.conversations x
129
- WHERE x.id = ${before} AND x.org_id = ${orgId}
130
- )`);
131
- }
132
- const rows = await query.execute();
133
- const page = rows.slice(0, q.limit);
134
- const ids = page.map((r) => r.id);
133
+ const snapshot = matching.where(sql `c.updated_at <= ${asOf}::timestamptz`);
134
+ const counted = await cappedCount(this.db.db, snapshot, PAGED_TOTAL_CAP);
135
+ const rows = await snapshot
136
+ .select([
137
+ "c.id",
138
+ "c.agent_id",
139
+ "c.account_id",
140
+ "c.title",
141
+ "c.updated_at",
142
+ sql `v.definition ->> 'name'`.as("agent_name"),
143
+ ])
144
+ .orderBy("c.updated_at", "desc")
145
+ .orderBy("c.id", "desc")
146
+ .offset(pageOffset(q.page, q.size))
147
+ .limit(q.size)
148
+ .execute();
149
+ const ids = rows.map((r) => r.id);
135
150
  const lastRuns = ids.length === 0
136
151
  ? []
137
152
  : await this.db
@@ -144,7 +159,7 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
144
159
  .orderBy("id", "desc")
145
160
  .execute();
146
161
  const byConv = new Map(lastRuns.map((r) => [r.conversation_id, r]));
147
- const items = page.map((r) => {
162
+ const items = rows.map((r) => {
148
163
  const run = byConv.get(r.id);
149
164
  return {
150
165
  conversationId: r.id,
@@ -163,8 +178,10 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
163
178
  },
164
179
  };
165
180
  });
166
- const next = rows.length > q.limit ? (page.at(-1)?.id ?? null) : null;
167
- return { items, next };
181
+ const newer = q.asOf === undefined
182
+ ? { count: 0 }
183
+ : await cappedCount(this.db.db, matching.where(sql `c.updated_at > ${asOf}::timestamptz`), PAGED_NEWER_CAP);
184
+ return { ...pageOf(items, q, counted), asOf, newer: newer.count };
168
185
  }
169
186
  /**
170
187
  * 一个对话的轨迹;无权或不存在 → `trajectory.not_found`。成功时(含窗口为空)写审计 `trajectory.viewed`。
@@ -7,7 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { SDK_VERSION } from "@capybara-hq/plugin-sdk";
10
+ import { extensionPointRefs, SDK_VERSION, staticPermissionDeclarations, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import semver from "semver";
@@ -335,7 +335,8 @@ let ExtensionAdminOps = class ExtensionAdminOps {
335
335
  if (sourceIntent)
336
336
  await restoreSourceIntent(db, name, sourceIntent, actor);
337
337
  if (leftDisabled !== undefined ||
338
- target.section.manifest.permissions?.deviceAccess?.siteAccess !== true) {
338
+ staticPermissionDeclarations(target.section.manifest).permissions.deviceAccess?.siteAccess !==
339
+ true) {
339
340
  await revokeSiteGrantsOfExtensionEverywhere(db, name);
340
341
  }
341
342
  await this.audit(actor, actorTokenId, "extension.installed", name, pkg.version, sha256, {
@@ -681,7 +682,7 @@ const notFound = (name) => new ApiError("extension.not_found", `Extension ${name
681
682
  const isDowngrade = (to, from) => semver.valid(to) !== null && semver.valid(from) !== null && semver.lt(to, from);
682
683
  /** The extension points a stored package's reviewed manifest provides. */
683
684
  function providesOf(section) {
684
- return section?.manifest?.provides ?? [];
685
+ return extensionPointRefs(section?.manifest?.provides ?? []);
685
686
  }
686
687
  /** The audit detail of an owner's operation. */
687
688
  function ownerDetail(owner) {
@@ -25,6 +25,8 @@ export declare class ExtensionBlobIntegrityError extends Error {
25
25
  }
26
26
  /** 对象存储里的键(相对 `deployment/`)。 */
27
27
  export declare const blobKey: (sha256: string) => string;
28
+ /** The lowercase hex sha512 of a package archive: the digest revision grants are keyed by. */
29
+ export declare const packageSha512: (bytes: Uint8Array) => string;
28
30
  export interface ExtensionBlobSource {
29
31
  source: "npm" | "file" | "catalog" | "bootstrap";
30
32
  ref: string;
@@ -41,6 +41,8 @@ export class ExtensionBlobIntegrityError extends Error {
41
41
  }
42
42
  /** 对象存储里的键(相对 `deployment/`)。 */
43
43
  export const blobKey = (sha256) => `plugins/blobs/${sha256}.tgz`;
44
+ /** The lowercase hex sha512 of a package archive: the digest revision grants are keyed by. */
45
+ export const packageSha512 = (bytes) => createHash("sha512").update(bytes).digest("hex");
44
46
  const SHA256_RE = /^[0-9a-f]{64}$/;
45
47
  /** How many packages {@link ExtensionBlobs.remember} keeps; the oldest is dropped beyond it. */
46
48
  const REMEMBERED_MAX = 8;
@@ -120,6 +122,13 @@ let ExtensionBlobs = class ExtensionBlobs {
120
122
  // The row is there: bytes that went missing (an object deleted, a database cleared) are
121
123
  // restored where the row says, and so are the client build's files and row
122
124
  await this.repair(p.sha256, existing.blob_store, bytes);
125
+ // a row stored before 0235 gets its sha512 now that the bytes are at hand
126
+ await this.db
127
+ .updateTable("extension_packages")
128
+ .set({ sha512: packageSha512(bytes) })
129
+ .where("sha256", "=", p.sha256)
130
+ .where("sha512", "is", null)
131
+ .execute();
123
132
  if (client !== undefined) {
124
133
  await this.clientBuilds.extract(p.sha256, plugin, client.files, client.section);
125
134
  }
@@ -163,6 +172,8 @@ let ExtensionBlobs = class ExtensionBlobs {
163
172
  source_ref: src.ref,
164
173
  uploaded_by: src.actor,
165
174
  display_name: p.displayName === undefined ? null : JSON.stringify(p.displayName),
175
+ // the revision identity grants bind to (plan task 1.2b)
176
+ sha512: packageSha512(bytes),
166
177
  })
167
178
  .onConflict((oc) => oc.column("sha256").doNothing())
168
179
  .returning("sha256")
@@ -106,6 +106,7 @@ export declare function extensionOrgCountsQuery(db: KernelSchemaDb, names: reado
106
106
  eval_results: import("../db/kernel-schema.js").EvalResultsTable;
107
107
  eval_runs: import("../db/kernel-schema.js").EvalRunsTable;
108
108
  eval_sets: import("../db/kernel-schema.js").EvalSetsTable;
109
+ extension_admission_refusals: import("../db/kernel-schema.js").ExtensionAdmissionRefusalsTable;
109
110
  extension_blobs: import("../db/kernel-schema.js").ExtensionBlobsTable;
110
111
  extension_catalog_sources: import("../db/kernel-schema.js").ExtensionCatalogSourcesTable;
111
112
  extension_client_builds: import("../db/kernel-schema.js").ExtensionClientBuildsTable;
@@ -113,6 +114,8 @@ export declare function extensionOrgCountsQuery(db: KernelSchemaDb, names: reado
113
114
  extension_deployment_configs: import("../db/kernel-schema.js").ExtensionDeploymentConfigsTable;
114
115
  extension_effect_cancellations: import("../db/kernel-schema.js").ExtensionEffectCancellationsTable;
115
116
  extension_effect_receipts: import("../db/kernel-schema.js").ExtensionEffectReceiptsTable;
117
+ extension_grant_epoch: import("../db/kernel-schema.js").ExtensionGrantEpochTable;
118
+ extension_handoff_tables: import("../db/kernel-schema.js").ExtensionHandoffTablesTable;
116
119
  extension_installs: import("../db/kernel-schema.js").ExtensionInstallsTable;
117
120
  extension_name_owners: import("../db/kernel-schema.js").ExtensionNameOwnersTable;
118
121
  extension_org_configs: import("../db/kernel-schema.js").ExtensionOrgConfigsTable;
@@ -120,6 +123,8 @@ export declare function extensionOrgCountsQuery(db: KernelSchemaDb, names: reado
120
123
  extension_packages: import("../db/kernel-schema.js").ExtensionPackagesTable;
121
124
  extension_permission_snapshots: import("../db/kernel-schema.js").ExtensionPermissionSnapshotsTable;
122
125
  extension_replica_status: import("../db/kernel-schema.js").ExtensionReplicaStatusTable;
126
+ extension_revision_grant_orgs: import("../db/kernel-schema.js").ExtensionRevisionGrantOrgsTable;
127
+ extension_revision_grants: import("../db/kernel-schema.js").ExtensionRevisionGrantsTable;
123
128
  file_previewers: import("../db/kernel-schema.js").FilePreviewersTable;
124
129
  file_shares: import("../db/kernel-schema.js").FileSharesTable;
125
130
  files: import("../db/kernel-schema.js").FilesTable;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The deployment grant epoch as one replica sees it (isolation capacity spec 2026-12-04,
3
+ * "Required change: grant epoch").
4
+ *
5
+ * PostgreSQL advances `extension_grant_epoch.epoch` in the transaction of every committed change to
6
+ * a table the isolated grant check reads (migration 0234). Each replica polls it once per second.
7
+ * A changed epoch makes every cached grant stale; a replica that cannot read the epoch stops
8
+ * trusting its cache after `maxAgeMs` and fences in-flight isolated work at the fence deadline.
9
+ *
10
+ * The user-visible bound is {@link REVOCATION_BOUND_MS} (5 s). The kernel acts by
11
+ * {@link FENCE_DEADLINE_MS} (4 s) so that timer delay and event-loop lag under load
12
+ * ({@link FENCE_SLACK_MS}, 1 s) never push a refusal past the bound. For a revocation that commits
13
+ * after the start `t` of the last read that saw the old epoch (that read's snapshot predates the
14
+ * commit):
15
+ * - admissions: a cached grant is trusted only until `t + maxAgeMs` (3 s by default);
16
+ * - in-flight work: when a later read sees the change, work not revalidated at the new epoch is
17
+ * fenced at `t + 4 s` ({@link GrantEpochOptions.onSettleDeadline}), at once if that time has
18
+ * passed, however slow the reads in between were;
19
+ * - no successful read: the expiry timer fences everything at `t + 4 s` as well.
20
+ *
21
+ * Why a plain per-replica timer and not `@LockedInterval`: a locked interval runs once per tick
22
+ * across all replicas, on a worker, but the epoch guards each replica's own in-memory cache, so
23
+ * every replica (api, worker and gateway alike) must read it itself. The read is a one-row
24
+ * primary-key lookup and writes nothing, so a timer per replica carries no cross-replica state;
25
+ * the source of truth stays in PostgreSQL. It runs only after an isolated grant was requested on
26
+ * this replica and stops when the extension host closes.
27
+ */
28
+ /** #1373: stale kernel admission or broker access ends at most 5 s after a revocation commits. */
29
+ export declare const REVOCATION_BOUND_MS = 5000;
30
+ /** Room left under the bound for timer delay and event-loop lag on a loaded replica. */
31
+ export declare const FENCE_SLACK_MS = 1000;
32
+ /** When the kernel fences, counted from the last read that saw the old epoch. */
33
+ export declare const FENCE_DEADLINE_MS: number;
34
+ export declare const GRANT_EPOCH_POLL_MS = 1000;
35
+ /** How long one epoch read may take: what remains of the trusted age after a poll interval. */
36
+ export declare function grantEpochReadTimeoutMs(maxAgeMs: number, pollMs?: number): number;
37
+ /**
38
+ * The epoch read on its own one-connection pool, opened at the first read. A blocked read (a lock
39
+ * on the epoch row, a saturated server) is cut off on both sides at the read timeout:
40
+ * `statement_timeout` and `lock_timeout` end it in PostgreSQL and `query_timeout` in the client,
41
+ * so it never holds a kernel pool connection or piles up connections of its own. The row has no
42
+ * org_id: deployment state, outside RLS and org scope.
43
+ */
44
+ export declare function grantEpochReader(opts: {
45
+ url: string;
46
+ readTimeoutMs: number;
47
+ connectTimeoutMs?: number | undefined;
48
+ onError: (err: Error) => void;
49
+ }): {
50
+ read: () => Promise<string>;
51
+ close: () => Promise<void>;
52
+ };
53
+ export interface GrantEpochOptions {
54
+ /** Reads the current epoch; rejects when PostgreSQL cannot be reached. */
55
+ read: () => Promise<string>;
56
+ /** How long a successful read is trusted (`extensionHost.capacity.grantEpochMaxAgeMs`). */
57
+ maxAgeMs: number;
58
+ /** Called after a read that observed a different epoch than the previous successful read. */
59
+ onChange: (epoch: string) => void;
60
+ /**
61
+ * Called after a change was observed, at {@link FENCE_DEADLINE_MS} counted from the start of the
62
+ * last read that saw the old epoch: in-flight work not revalidated at the new epoch must be fenced.
63
+ */
64
+ onSettleDeadline: () => void;
65
+ /** Called once when no read has succeeded for {@link FENCE_DEADLINE_MS}. */
66
+ onExpired: () => void;
67
+ onFault?: (err: unknown) => void;
68
+ pollMs?: number;
69
+ now?: () => number;
70
+ }
71
+ export declare class GrantEpoch {
72
+ private readonly options;
73
+ private epoch;
74
+ /** Start time of the last successful read: the snapshot it saw is at least this old. */
75
+ private readAt;
76
+ private reading;
77
+ private pollTimer;
78
+ private expiryTimer;
79
+ private readonly settleTimers;
80
+ private running;
81
+ private readonly now;
82
+ private readonly pollMs;
83
+ private readonly readTimeoutMs;
84
+ /**
85
+ * Timers run in the context the epoch was built in (the host's construction), never in the
86
+ * context of the call that first started polling (its org scope or request log context).
87
+ */
88
+ private readonly inOwnContext;
89
+ constructor(options: GrantEpochOptions);
90
+ /** Starts polling on this replica; idempotent. */
91
+ start(): void;
92
+ stop(): void;
93
+ /** The epoch when the last successful read is younger than `maxAgeMs`, otherwise undefined. */
94
+ fresh(): string | undefined;
95
+ /** The fresh epoch, reading PostgreSQL first when needed; undefined when that read fails. */
96
+ ensureFresh(): Promise<string | undefined>;
97
+ /** One read at a time; concurrent callers share it. It settles within the read timeout. */
98
+ refresh(): Promise<string | undefined>;
99
+ private readOnce;
100
+ private withTimeout;
101
+ /** Fence everything at the revocation bound unless a later read succeeds first. */
102
+ private armExpiry;
103
+ /** `oldEpochReadAt`: start of the last read that saw the old epoch, before the commit. */
104
+ private armSettleDeadline;
105
+ /** Polls on a fixed cadence; a slow read never delays the next tick (reads are coalesced). */
106
+ private poll;
107
+ private timer;
108
+ }
@@ -0,0 +1,214 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import pg from "pg";
3
+ import { KERNEL_APPLICATION_NAME } from "../db/pool.js";
4
+ /**
5
+ * The deployment grant epoch as one replica sees it (isolation capacity spec 2026-12-04,
6
+ * "Required change: grant epoch").
7
+ *
8
+ * PostgreSQL advances `extension_grant_epoch.epoch` in the transaction of every committed change to
9
+ * a table the isolated grant check reads (migration 0234). Each replica polls it once per second.
10
+ * A changed epoch makes every cached grant stale; a replica that cannot read the epoch stops
11
+ * trusting its cache after `maxAgeMs` and fences in-flight isolated work at the fence deadline.
12
+ *
13
+ * The user-visible bound is {@link REVOCATION_BOUND_MS} (5 s). The kernel acts by
14
+ * {@link FENCE_DEADLINE_MS} (4 s) so that timer delay and event-loop lag under load
15
+ * ({@link FENCE_SLACK_MS}, 1 s) never push a refusal past the bound. For a revocation that commits
16
+ * after the start `t` of the last read that saw the old epoch (that read's snapshot predates the
17
+ * commit):
18
+ * - admissions: a cached grant is trusted only until `t + maxAgeMs` (3 s by default);
19
+ * - in-flight work: when a later read sees the change, work not revalidated at the new epoch is
20
+ * fenced at `t + 4 s` ({@link GrantEpochOptions.onSettleDeadline}), at once if that time has
21
+ * passed, however slow the reads in between were;
22
+ * - no successful read: the expiry timer fences everything at `t + 4 s` as well.
23
+ *
24
+ * Why a plain per-replica timer and not `@LockedInterval`: a locked interval runs once per tick
25
+ * across all replicas, on a worker, but the epoch guards each replica's own in-memory cache, so
26
+ * every replica (api, worker and gateway alike) must read it itself. The read is a one-row
27
+ * primary-key lookup and writes nothing, so a timer per replica carries no cross-replica state;
28
+ * the source of truth stays in PostgreSQL. It runs only after an isolated grant was requested on
29
+ * this replica and stops when the extension host closes.
30
+ */
31
+ /** #1373: stale kernel admission or broker access ends at most 5 s after a revocation commits. */
32
+ export const REVOCATION_BOUND_MS = 5_000;
33
+ /** Room left under the bound for timer delay and event-loop lag on a loaded replica. */
34
+ export const FENCE_SLACK_MS = 1_000;
35
+ /** When the kernel fences, counted from the last read that saw the old epoch. */
36
+ export const FENCE_DEADLINE_MS = REVOCATION_BOUND_MS - FENCE_SLACK_MS;
37
+ export const GRANT_EPOCH_POLL_MS = 1_000;
38
+ /** How long one epoch read may take: what remains of the trusted age after a poll interval. */
39
+ export function grantEpochReadTimeoutMs(maxAgeMs, pollMs = GRANT_EPOCH_POLL_MS) {
40
+ return maxAgeMs - pollMs;
41
+ }
42
+ /**
43
+ * The epoch read on its own one-connection pool, opened at the first read. A blocked read (a lock
44
+ * on the epoch row, a saturated server) is cut off on both sides at the read timeout:
45
+ * `statement_timeout` and `lock_timeout` end it in PostgreSQL and `query_timeout` in the client,
46
+ * so it never holds a kernel pool connection or piles up connections of its own. The row has no
47
+ * org_id: deployment state, outside RLS and org scope.
48
+ */
49
+ export function grantEpochReader(opts) {
50
+ let pool;
51
+ let closed = false;
52
+ const connectTimeoutMs = Math.min(opts.connectTimeoutMs ?? opts.readTimeoutMs, opts.readTimeoutMs);
53
+ return {
54
+ read: async () => {
55
+ if (closed)
56
+ throw new Error("The grant epoch reader is closed");
57
+ pool ??= (() => {
58
+ const created = new pg.Pool({
59
+ connectionString: opts.url,
60
+ max: 1,
61
+ application_name: `${KERNEL_APPLICATION_NAME}-grant-epoch`,
62
+ connectionTimeoutMillis: connectTimeoutMs,
63
+ statement_timeout: opts.readTimeoutMs,
64
+ lock_timeout: opts.readTimeoutMs,
65
+ query_timeout: opts.readTimeoutMs,
66
+ keepAlive: true,
67
+ });
68
+ created.on("error", opts.onError);
69
+ created.on("connect", (client) => client.on("error", opts.onError));
70
+ return created;
71
+ })();
72
+ const { rows } = await pool.query("SELECT epoch::text AS epoch FROM capybara.extension_grant_epoch WHERE id = 1");
73
+ const epoch = rows[0]?.epoch;
74
+ if (epoch === undefined)
75
+ throw new Error("The grant epoch row is missing");
76
+ return epoch;
77
+ },
78
+ close: async () => {
79
+ closed = true;
80
+ const closing = pool;
81
+ pool = undefined;
82
+ await closing?.end();
83
+ },
84
+ };
85
+ }
86
+ class EpochReadTimeout extends Error {
87
+ constructor() {
88
+ super("Reading the grant epoch timed out");
89
+ }
90
+ }
91
+ export class GrantEpoch {
92
+ options;
93
+ epoch;
94
+ /** Start time of the last successful read: the snapshot it saw is at least this old. */
95
+ readAt = Number.NEGATIVE_INFINITY;
96
+ reading;
97
+ pollTimer;
98
+ expiryTimer;
99
+ settleTimers = new Set();
100
+ running = false;
101
+ now;
102
+ pollMs;
103
+ readTimeoutMs;
104
+ /**
105
+ * Timers run in the context the epoch was built in (the host's construction), never in the
106
+ * context of the call that first started polling (its org scope or request log context).
107
+ */
108
+ inOwnContext = AsyncLocalStorage.snapshot();
109
+ constructor(options) {
110
+ this.options = options;
111
+ this.now = options.now ?? (() => performance.now());
112
+ this.pollMs = options.pollMs ?? GRANT_EPOCH_POLL_MS;
113
+ if (options.maxAgeMs <= this.pollMs || options.maxAgeMs >= FENCE_DEADLINE_MS) {
114
+ throw new RangeError("The grant epoch age must exceed the poll interval and stay below the 4 s fence deadline");
115
+ }
116
+ this.readTimeoutMs = grantEpochReadTimeoutMs(options.maxAgeMs, this.pollMs);
117
+ }
118
+ /** Starts polling on this replica; idempotent. */
119
+ start() {
120
+ if (this.running)
121
+ return;
122
+ this.running = true;
123
+ this.poll();
124
+ }
125
+ stop() {
126
+ this.running = false;
127
+ clearTimeout(this.pollTimer);
128
+ clearTimeout(this.expiryTimer);
129
+ for (const timer of this.settleTimers)
130
+ clearTimeout(timer);
131
+ this.settleTimers.clear();
132
+ this.pollTimer = undefined;
133
+ this.expiryTimer = undefined;
134
+ }
135
+ /** The epoch when the last successful read is younger than `maxAgeMs`, otherwise undefined. */
136
+ fresh() {
137
+ return this.now() - this.readAt < this.options.maxAgeMs ? this.epoch : undefined;
138
+ }
139
+ /** The fresh epoch, reading PostgreSQL first when needed; undefined when that read fails. */
140
+ async ensureFresh() {
141
+ return this.fresh() ?? (await this.refresh());
142
+ }
143
+ /** One read at a time; concurrent callers share it. It settles within the read timeout. */
144
+ refresh() {
145
+ this.reading ??= this.readOnce().finally(() => {
146
+ this.reading = undefined;
147
+ });
148
+ return this.reading;
149
+ }
150
+ async readOnce() {
151
+ const startedAt = this.now();
152
+ let epoch;
153
+ try {
154
+ epoch = await this.withTimeout(this.options.read());
155
+ }
156
+ catch (err) {
157
+ this.options.onFault?.(err);
158
+ return undefined;
159
+ }
160
+ const previous = this.epoch;
161
+ const previousReadAt = this.readAt;
162
+ this.epoch = epoch;
163
+ if (startedAt > this.readAt) {
164
+ this.readAt = startedAt;
165
+ this.armExpiry();
166
+ }
167
+ if (previous !== undefined && previous !== epoch) {
168
+ this.options.onChange(epoch);
169
+ this.armSettleDeadline(previousReadAt);
170
+ }
171
+ return this.fresh();
172
+ }
173
+ withTimeout(read) {
174
+ let timer;
175
+ const timeout = new Promise((_resolve, reject) => {
176
+ timer = this.timer(() => reject(new EpochReadTimeout()), this.readTimeoutMs);
177
+ });
178
+ return Promise.race([read, timeout]).finally(() => clearTimeout(timer));
179
+ }
180
+ /** Fence everything at the revocation bound unless a later read succeeds first. */
181
+ armExpiry() {
182
+ if (!this.running)
183
+ return;
184
+ clearTimeout(this.expiryTimer);
185
+ const delay = Math.max(0, this.readAt + FENCE_DEADLINE_MS - this.now());
186
+ this.expiryTimer = this.timer(() => {
187
+ this.expiryTimer = undefined;
188
+ this.options.onExpired();
189
+ }, delay);
190
+ }
191
+ /** `oldEpochReadAt`: start of the last read that saw the old epoch, before the commit. */
192
+ armSettleDeadline(oldEpochReadAt) {
193
+ if (!this.running)
194
+ return;
195
+ const delay = Math.max(0, oldEpochReadAt + FENCE_DEADLINE_MS - this.now());
196
+ const timer = this.timer(() => {
197
+ this.settleTimers.delete(timer);
198
+ this.options.onSettleDeadline();
199
+ }, delay);
200
+ this.settleTimers.add(timer);
201
+ }
202
+ /** Polls on a fixed cadence; a slow read never delays the next tick (reads are coalesced). */
203
+ poll() {
204
+ if (!this.running)
205
+ return;
206
+ this.pollTimer = this.timer(() => this.poll(), this.pollMs);
207
+ void this.refresh();
208
+ }
209
+ timer(run, delay) {
210
+ const timer = setTimeout(() => this.inOwnContext(run), delay);
211
+ timer.unref?.();
212
+ return timer;
213
+ }
214
+ }
@@ -3,7 +3,7 @@ import type { Redis } from "ioredis";
3
3
  import type { core } from "zod";
4
4
  import type { KernelAppOptions } from "../app.js";
5
5
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
6
- import type { KernelConfig } from "../config/schema.js";
6
+ import { type KernelConfig } from "../config/schema.js";
7
7
  import type { ExternalConversationsBackend } from "../conversations/external/external-conversations.service.js";
8
8
  import { EXTERNAL_CONVERSATIONS_BACKEND } from "../conversations/external/token.js";
9
9
  import type { BusSubscriber } from "../ctx/bus.js";
@@ -39,9 +39,10 @@ import type { InflightTracker } from "./inflight.js";
39
39
  import { type DesiredExtension, ExtensionInstalls } from "./installs.js";
40
40
  import { type ExtensionInstance } from "./instance.js";
41
41
  import { type IsolatedRevocation } from "./isolated/authorization.js";
42
- import type { ExtensionTier } from "./isolated/tier.js";
42
+ import { type ExtensionTier } from "./isolated/tier.js";
43
43
  import { type PermissionSet } from "./permission-set.js";
44
44
  import { type ExtensionPointEntry, ExtensionRegistry } from "./registry.js";
45
+ import { ExtensionRevisionApprovals } from "./revision-approvals.js";
45
46
  import { type ExtensionSource, ReplicaStatusStore } from "./sources.js";
46
47
  export { deploymentConfigHash };
47
48
  /**
@@ -162,6 +163,11 @@ export declare class ExtensionHost {
162
163
  */
163
164
  private readonly modules?;
164
165
  private readonly dbIdentity;
166
+ /**
167
+ * Shadow revision approvals (plan task 1.2b): reported at start, never refusing. Absent in a
168
+ * hand-built host, which then reports nothing.
169
+ */
170
+ private readonly revisionApprovals?;
165
171
  /**
166
172
  * Only resolves extensions and runs migrations in dependency order: no deployment config check, no
167
173
  * setup, no Redis (for `capybara migrate`). Like `load()` it checks secret markers first
@@ -210,6 +216,9 @@ export declare class ExtensionHost {
210
216
  private readonly isolatedAuthority;
211
217
  private readonly isolatedLanes;
212
218
  private readonly isolatedGrants;
219
+ /** This replica's view of the deployment grant epoch; polls only once an isolated grant was issued. */
220
+ private readonly grantEpoch;
221
+ private readonly epochReader;
213
222
  private readonly executionTier;
214
223
  private policyExpected;
215
224
  /**
@@ -364,7 +373,12 @@ export declare class ExtensionHost {
364
373
  }): ExternalConversationsBackend;
365
374
  } | undefined,
366
375
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
367
- netSeams?: ExtensionNetSeams, dbIdentity?: ExtensionDbIdentity);
376
+ netSeams?: ExtensionNetSeams, dbIdentity?: ExtensionDbIdentity,
377
+ /**
378
+ * Shadow revision approvals (plan task 1.2b): reported at start, never refusing. Absent in a
379
+ * hand-built host, which then reports nothing.
380
+ */
381
+ revisionApprovals?: Pick<ExtensionRevisionApprovals, "startGate"> | undefined);
368
382
  /** The startup config's `extensionConfig` (file / Nacos merged with env). */
369
383
  private get extensionConfig();
370
384
  /** `extensionPermissions.autoApprove` (development and trials only; see `planApprovals`). */
@@ -421,6 +435,18 @@ export declare class ExtensionHost {
421
435
  * `plugin host closed during load` at the next checkpoint.
422
436
  */
423
437
  load(plan: string[] | ExtensionLoadPlan): Promise<void>;
438
+ /** The last shadow report logged by this replica (a log de-duplication, not state). */
439
+ private lastShadowReport;
440
+ /**
441
+ * Shadow mode (plan task 1.2b, rollout fence until 1.5a): what the enforcing start gate would
442
+ * decide from revision grants, reported in the log after the start and after each install
443
+ * convergence, when it changes. The legacy snapshots govern; this never refuses, never blocks
444
+ * the start (it runs after it, reading packages in the background) and its failures only warn.
445
+ * An info line, not a warning: until the first reviews (plan tasks 1.3a and 1.3c) every install
446
+ * is listed. Config-declared extensions have no stored package digest and are left to the
447
+ * bootstrap review (1.3c) and the cutover preflight (1.5a).
448
+ */
449
+ private reportShadowStartGate;
424
450
  /**
425
451
  * Records each config-declared extension's display name from its plugin directory's plugin.json
426
452
  * (spec §2.2); an invalid plugin.json only warns (no display name).
@@ -480,6 +506,7 @@ export declare class ExtensionHost {
480
506
  /**
481
507
  * 安装记录加载失败的 error 日志:每个周期都会重试,同一个包、同一个原因只记一次(状态行每次照写)。
482
508
  */
509
+ private reportAdmissionRefusal;
483
510
  private logFailure;
484
511
  /** 记下(替换同名的)待定插件,供 {@link pending} 列出。 */
485
512
  private notePending;
@@ -581,13 +608,6 @@ export declare class ExtensionHost {
581
608
  * takes effect quickly.
582
609
  */
583
610
  enabledPlugins(orgId: string): Promise<Set<string>>;
584
- /**
585
- * The access behind an extension's `ctx.extensionPoints`: only active instances in the registry
586
- * (dependencies load in topological order, so the depended-on are ready first); org enablement is
587
- * read from PostgreSQL every time, not cached. Resolved live on every call: once a
588
- * provider is revoked it is no longer returned.
589
- */
590
- private readonly extensionPointAccess;
591
611
  private get loadDeps();
592
612
  /**
593
613
  * Build a new generation. Track its context during setup so shutdown can close it immediately.