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

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 (122) 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 +10 -8
  12. package/dist/agents/admin-agents.js +13 -9
  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/marketplaces.service.d.ts +1 -1
  25. package/dist/catalog/plugin-package.js +2 -1
  26. package/dist/client/client-access.service.js +29 -1
  27. package/dist/config/schema.d.ts +9 -0
  28. package/dist/config/schema.js +26 -0
  29. package/dist/ctx/create-ctx.d.ts +2 -19
  30. package/dist/ctx/create-ctx.js +3 -93
  31. package/dist/ctx/durable-relay.d.ts +2 -5
  32. package/dist/ctx/durable-relay.js +56 -29
  33. package/dist/db/extension-handoff-schema.js +5 -0
  34. package/dist/db/kernel-schema.d.ts +74 -0
  35. package/dist/erasure/account-batches.js +2 -0
  36. package/dist/erasure/account-residual.js +1 -0
  37. package/dist/erasure/org-catalog.js +8 -3
  38. package/dist/erasure/org-rules.js +1 -0
  39. package/dist/evals/evals.schemas.d.ts +15 -5
  40. package/dist/evals/evals.schemas.js +17 -10
  41. package/dist/evals/runs.controller.d.ts +4 -12
  42. package/dist/evals/runs.controller.js +14 -11
  43. package/dist/evals/runs.service.d.ts +29 -25
  44. package/dist/evals/runs.service.js +73 -61
  45. package/dist/evals/trajectory.controller.d.ts +10 -6
  46. package/dist/evals/trajectory.controller.js +11 -4
  47. package/dist/evals/trajectory.service.d.ts +17 -9
  48. package/dist/evals/trajectory.service.js +52 -35
  49. package/dist/extensions/admin-ops.js +4 -3
  50. package/dist/extensions/blobs.d.ts +2 -0
  51. package/dist/extensions/blobs.js +11 -0
  52. package/dist/extensions/enabled.d.ts +5 -0
  53. package/dist/extensions/grant-epoch.d.ts +108 -0
  54. package/dist/extensions/grant-epoch.js +214 -0
  55. package/dist/extensions/host.d.ts +29 -9
  56. package/dist/extensions/host.js +148 -42
  57. package/dist/extensions/instance.d.ts +3 -3
  58. package/dist/extensions/instance.js +1 -1
  59. package/dist/extensions/isolated/authorization.d.ts +54 -2
  60. package/dist/extensions/isolated/authorization.js +148 -35
  61. package/dist/extensions/isolated/child-session.js +0 -1
  62. package/dist/extensions/isolated/revision.js +1 -1
  63. package/dist/extensions/package-digest.job.d.ts +34 -0
  64. package/dist/extensions/package-digest.job.js +121 -0
  65. package/dist/extensions/package.js +10 -6
  66. package/dist/extensions/permission-set.d.ts +14 -78
  67. package/dist/extensions/permission-set.js +17 -143
  68. package/dist/extensions/permission-view.d.ts +13 -1
  69. package/dist/extensions/permission-view.js +20 -0
  70. package/dist/extensions/registry.js +4 -1
  71. package/dist/extensions/resolve.d.ts +7 -8
  72. package/dist/extensions/resolve.js +7 -8
  73. package/dist/extensions/revision-approvals.d.ts +167 -0
  74. package/dist/extensions/revision-approvals.js +353 -0
  75. package/dist/extensions/revision-grants.d.ts +197 -0
  76. package/dist/extensions/revision-grants.js +584 -0
  77. package/dist/extensions/state.module.js +12 -1
  78. package/dist/identity/accounts.d.ts +10 -4
  79. package/dist/identity/accounts.js +18 -5
  80. package/dist/infra/database/extension-effect-key-lock.js +7 -0
  81. package/dist/infra/paging/paged-read.d.ts +34 -4
  82. package/dist/infra/paging/paged-read.js +38 -1
  83. package/dist/orgs/invitations.controller.d.ts +4 -7
  84. package/dist/orgs/invitations.controller.js +8 -5
  85. package/dist/orgs/invitations.service.d.ts +17 -3
  86. package/dist/orgs/invitations.service.js +35 -13
  87. package/dist/orgs/members.service.d.ts +35 -0
  88. package/dist/orgs/members.service.js +52 -3
  89. package/dist/orgs/orgs.controller.d.ts +11 -4
  90. package/dist/orgs/orgs.controller.js +25 -5
  91. package/dist/orgs/orgs.schemas.d.ts +14 -0
  92. package/dist/orgs/orgs.schemas.js +19 -2
  93. package/dist/orgs/orgs.service.d.ts +21 -1
  94. package/dist/orgs/orgs.service.js +40 -1
  95. package/dist/orgs/security-settings.service.d.ts +14 -6
  96. package/dist/orgs/security-settings.service.js +18 -13
  97. package/dist/orgs/settings.controller.d.ts +7 -4
  98. package/dist/platform/exclusions.js +15 -0
  99. package/dist/platform/ops/accounts.ops.js +7 -16
  100. package/dist/platform/ops/admin-items.ops.js +7 -7
  101. package/dist/platform/ops/automations.ops.js +6 -4
  102. package/dist/platform/ops/evals.ops.js +30 -15
  103. package/dist/platform/ops/org-settings.ops.js +2 -2
  104. package/dist/platform/ops/orgs.ops.js +44 -27
  105. package/dist/roles/worker.module.js +3 -0
  106. package/dist/runtime/step-log.d.ts +1 -1
  107. package/dist/runtime/step-log.js +5 -4
  108. package/dist/setup/kernel-checks.d.ts +3 -3
  109. package/dist/setup/kernel-checks.js +4 -4
  110. package/dist/setup/setup-check-registry.d.ts +16 -5
  111. package/dist/setup/setup-check-registry.js +11 -3
  112. package/dist/setup/setup-checks.service.d.ts +1 -2
  113. package/dist/setup/setup-checks.service.js +7 -6
  114. package/dist/tools/admin-connectors.d.ts +10 -8
  115. package/dist/tools/admin-connectors.js +12 -10
  116. package/dist/tools/builtins/automations.d.ts +1 -1
  117. package/dist/tools/builtins/automations.js +1 -1
  118. package/package.json +3 -3
  119. package/src/migrations/0234_extension_grant_epoch.sql +141 -0
  120. package/src/migrations/0235_extension_revision_grants.sql +166 -0
  121. package/src/migrations/0236_paged_table_idx.sql +33 -0
  122. package/src/migrations/0237_extension_handoff_health.sql +18 -0
@@ -1,4 +1,4 @@
1
- import { CONVERSATION_TARGET_EXTENSION_POINT, CtxReadError, DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, InboxError, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
1
+ import { CONVERSATION_TARGET_EXTENSION_POINT, CtxReadError, DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, ExtensionPermissionError, FILE_PREVIEW_EXTENSION_POINT, InboxError, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
2
2
  import { conversationTopic } from "../conversations/event-log.js";
3
3
  import { checkExternalText } from "../conversations/external/external-calls.js";
4
4
  import { pluginSchemaName } from "../db/extension-db.js";
@@ -150,12 +150,6 @@ async function recordDenial(deps, plugin, item) {
150
150
  deps.log.warn("plugin permission denial audit failed", { plugin, item, err: e });
151
151
  }
152
152
  }
153
- /** 未注入能力访问时(单独构造 ctx 的测试等):没有任何提供方,组织启用照常查库。 */
154
- const noProviders = (deps) => ({
155
- providers: () => [],
156
- enabledPlugins: (orgId) => queryEnabledPlugins(deps.db, orgId),
157
- configOk: async () => true,
158
- });
159
153
  /**
160
154
  * An extension instance's deployment config (validated): `ctx.config` is a getter that reads it.
161
155
  * When a hot field changes the host replaces `value` (C10) and the extension's next read of
@@ -195,15 +189,13 @@ export class LiveConfig {
195
189
  * replicas; `ui.verifyEmbedToken` checks an embed token the kernel signed: `claims.plugin` must be
196
190
  * this extension, the extension still enabled in that org and the caller still an active member of
197
191
  * the org (org not deleted); returns the current role;
198
- * - `extensionPoints` only gives extension points declared in `requires` / `optional` that are not
199
- * brokered (through `extensionPointAccess`).
200
192
  * - `hooks.on` only during setup, only mount points declared in `permissions.hooks` and available
201
193
  * (`HOOKS_AVAILABLE`), `policy` only on `POLICY_HOOKS` declared in `permissions.policyHooks`; kept on the ctx (`registeredHooks`, read by
202
194
  * the host's `HookRegistry` from active instances only) and recorded in the ledger.
203
195
  * An undeclared access throws `ExtensionPermissionError` and audits `extension.permission_denied`
204
196
  * (once per extension and item).
205
197
  */
206
- export function createExtensionContext(deps, manifest, deploymentConfig, extensionPointAccess = noProviders(deps),
198
+ export function createExtensionContext(deps, manifest, deploymentConfig, objectStore = () => undefined,
207
199
  /** The package this instance was loaded from (null: not from an install record). */
208
200
  identity = { sha256: null }) {
209
201
  const name = manifest.name;
@@ -243,7 +235,7 @@ identity = { sha256: null }) {
243
235
  // (宿主不会加载这样的插件,见 approvals.ts;单独构造 ctx 的测试会走到这里)
244
236
  const storageApi = perms.storage
245
237
  ? new PrefixedStorage({
246
- provider: () => extensionPointAccess.providers(OBJECT_STORE_EXTENSION_POINT)[0]?.impl,
238
+ provider: objectStore,
247
239
  plugins: async () => [name],
248
240
  }).forPlugin(name)
249
241
  : undefined;
@@ -667,10 +659,6 @@ identity = { sha256: null }) {
667
659
  const declaredHooks = new Set(perms.hooks ?? []);
668
660
  const declaredPolicyHooks = new Set(perms.policyHooks ?? []);
669
661
  const registeredHooks = [];
670
- const declaredPoints = new Set([
671
- ...(manifest.requires ?? []),
672
- ...(manifest.optional ?? []),
673
- ]);
674
662
  const uiReg = new PluginUiRegistration(manifest, deny);
675
663
  const declaredSetupChecks = new Set(perms.setupChecks ?? []);
676
664
  const setupChecks = new Map();
@@ -722,83 +710,6 @@ identity = { sha256: null }) {
722
710
  };
723
711
  /** Ids of the extension's `platform.page` contributions (their invalidate takes no orgId). */
724
712
  const platformUi = new Set([...uiSlots].filter(([, s]) => s.id === "platform.page").map(([id]) => id));
725
- /** 校验能力可取用(非 brokered、已在清单声明),返回其登记信息。 */
726
- const checkExtensionPoint = (ref) => {
727
- const capName = parseExtensionPoint(ref).name;
728
- const info = Object.hasOwn(EXTENSION_POINTS, capName) ? EXTENSION_POINTS[capName] : undefined;
729
- if (info?.brokered) {
730
- throw new Error(`plugin ${name}: extension point ${ref} is brokered and can only be used through the platform API`);
731
- }
732
- if (!info || !declaredPoints.has(ref))
733
- return deny(`requires/optional ${ref}`);
734
- return info;
735
- };
736
- /** 部署级视角选出提供方:指定 provider 时按名找;单选能力取唯一提供方;多选能力必须指定。 */
737
- const pick = (ref, provider) => {
738
- const info = checkExtensionPoint(ref);
739
- const providers = extensionPointAccess.providers(ref);
740
- if (provider !== undefined) {
741
- const chosen = providers.find((p) => p.plugin === provider);
742
- if (!chosen) {
743
- throw new ExtensionPointUnavailableError(`extension point ${ref} is not provided by plugin ${provider}`);
744
- }
745
- return { info, chosen };
746
- }
747
- if (info.cardinality === "multi") {
748
- // 多选能力即使只有一个提供者也要显式指定,避免新增提供者后行为悄悄变化
749
- throw new Error(`plugin ${name}: extension point ${ref} is multi-provider; specify a provider name (available: ${providers.map((p) => p.plugin).join(", ") || "none"})`);
750
- }
751
- const chosen = providers[0];
752
- if (!chosen)
753
- throw new ExtensionPointUnavailableError(`extension point ${ref} has no provider`);
754
- return { info, chosen };
755
- };
756
- /**
757
- * The org's view of the providers: an orgScoped point keeps only those the org enabled (queried
758
- * every time, not cached), and every point drops those whose effective config is not valid in
759
- * the org (layering spec A §6: a call on behalf of an org never reaches such a provider).
760
- */
761
- const forOrg = async (orgScoped, orgId, entries) => {
762
- if (orgId === "" || entries.length === 0)
763
- return [];
764
- return withOrgScope(orgId, async () => {
765
- let out = entries;
766
- if (orgScoped) {
767
- const enabled = await extensionPointAccess.enabledPlugins(orgId);
768
- out = out.filter((e) => enabled.has(e.plugin));
769
- }
770
- const ok = await Promise.all(out.map((e) => extensionPointAccess.configOk(orgId, e.plugin)));
771
- return out.filter((_, i) => ok[i]);
772
- });
773
- };
774
- const listAll = (ref) => {
775
- const info = checkExtensionPoint(ref);
776
- return { info, entries: extensionPointAccess.providers(ref).map((p) => ({ ...p })) };
777
- };
778
- // 不传 orgId:同步返回;传 orgId:返回 Promise,所有错误都以 reject 交出
779
- const extensionPoints = {
780
- get(ref, provider, opts) {
781
- const orgId = opts?.orgId;
782
- if (orgId === undefined)
783
- return pick(ref, provider).chosen.impl;
784
- return (async () => {
785
- const { info, chosen } = pick(ref, provider);
786
- if ((await forOrg(info.orgScoped, orgId, [chosen])).length === 0) {
787
- throw new ExtensionPointUnavailableError(`extension point ${ref} provider ${chosen.plugin} is not available in organization ${orgId} (not enabled there, or its configuration is not valid there)`);
788
- }
789
- return chosen.impl;
790
- })();
791
- },
792
- list(ref, opts) {
793
- const orgId = opts?.orgId;
794
- if (orgId === undefined)
795
- return listAll(ref).entries;
796
- return (async () => {
797
- const { info, entries } = listAll(ref);
798
- return forOrg(info.orgScoped, orgId, entries);
799
- })();
800
- },
801
- };
802
713
  const ctx = {
803
714
  kv: createKv(deps.redis, name),
804
715
  lock: {
@@ -817,7 +728,6 @@ identity = { sha256: null }) {
817
728
  };
818
729
  },
819
730
  },
820
- extensionPoints,
821
731
  // the kernel's guarded client for person-supplied URLs, no permission needed; without the
822
732
  // services (a ctx built alone in a test) it refuses rather than reaching the network unguarded
823
733
  net: deps.net
@@ -1,6 +1,4 @@
1
1
  import { type ExtensionDbIdentity } from "../db/extension-db.js";
2
- import { ExtensionRegistry } from "../extensions/registry.js";
3
- import { ReplicaStatusStore } from "../extensions/sources.js";
4
2
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
3
  import { KernelDb } from "../infra/database/kernel-db.js";
6
4
  import { LockService } from "../infra/lock/lock.service.js";
@@ -13,16 +11,15 @@ export declare class ExtensionEffectRelay {
13
11
  private readonly effects;
14
12
  private readonly keys;
15
13
  private readonly identity;
16
- private readonly registry;
17
- private readonly status;
18
14
  private readonly db;
19
15
  readonly config: KernelConfigService;
20
16
  readonly lockService: LockService;
21
17
  readonly log: KernelLogger;
22
- constructor(dispatcher: OutboxDispatcher, effects: ExtensionEffects, keys: ExtensionEffectKeys, identity: ExtensionDbIdentity, registry: ExtensionRegistry, status: ReplicaStatusStore, db: KernelDb, config: KernelConfigService, lockService: LockService, log: KernelLogger);
18
+ constructor(dispatcher: OutboxDispatcher, effects: ExtensionEffects, keys: ExtensionEffectKeys, identity: ExtensionDbIdentity, db: KernelDb, config: KernelConfigService, lockService: LockService, log: KernelLogger);
23
19
  relay(signal?: AbortSignal): Promise<void>;
24
20
  retireKeys(): Promise<void>;
25
21
  relayOnce(signal?: AbortSignal): Promise<void>;
22
+ private handoffHealth;
26
23
  private redrive;
27
24
  private ingest;
28
25
  private cleanup;
@@ -10,11 +10,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
- import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
14
- import { ExtensionRegistry } from "../extensions/registry.js";
15
- import { ReplicaStatusStore } from "../extensions/sources.js";
13
+ import { ConfiguredExtensionDbIdentity, pluginSchemaName, } from "../db/extension-db.js";
16
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
17
- import { handoffReference, markHandoffParked, readHandoff, readHandoffRow, readUnreferencedParks, retryHandoff, settleHandoff, } from "../infra/database/extension-handoff.js";
15
+ import { EXTENSION_EFFECT_HANDOFF, handoffReference, handoffTable, markHandoffParked, readHandoff, readHandoffRow, readUnreferencedParks, retryHandoff, settleHandoff, } from "../infra/database/extension-handoff.js";
18
16
  import { KernelDb } from "../infra/database/kernel-db.js";
19
17
  import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
20
18
  import { LockService } from "../infra/lock/lock.service.js";
@@ -36,19 +34,15 @@ let ExtensionEffectRelay = class ExtensionEffectRelay {
36
34
  effects;
37
35
  keys;
38
36
  identity;
39
- registry;
40
- status;
41
37
  db;
42
38
  config;
43
39
  lockService;
44
40
  log;
45
- constructor(dispatcher, effects, keys, identity, registry, status, db, config, lockService, log) {
41
+ constructor(dispatcher, effects, keys, identity, db, config, lockService, log) {
46
42
  this.dispatcher = dispatcher;
47
43
  this.effects = effects;
48
44
  this.keys = keys;
49
45
  this.identity = identity;
50
- this.registry = registry;
51
- this.status = status;
52
46
  this.db = db;
53
47
  this.config = config;
54
48
  this.lockService = lockService;
@@ -61,11 +55,18 @@ let ExtensionEffectRelay = class ExtensionEffectRelay {
61
55
  await this.keys.retireUnused();
62
56
  }
63
57
  async relayOnce(signal) {
64
- const plugins = await asPlatform("Find known extension handoff tables", () => this.db.db.selectFrom("extension_name_owners").select("name").execute());
65
- const names = new Set([
66
- ...plugins.map(({ name }) => name),
67
- ...this.registry.all().map(({ name }) => name),
68
- ]);
58
+ const tables = await asPlatform("Find provisioned extension handoff tables", async () => {
59
+ // During a rolling upgrade an older provisioner can still create a table without recording it.
60
+ await sql `
61
+ insert into capybara.extension_handoff_tables (schema_name)
62
+ select n.nspname from pg_catalog.pg_class c
63
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
64
+ where c.relname = ${EXTENSION_EFFECT_HANDOFF} and c.relkind = 'r'
65
+ and n.nspname ~ '^plugin_[a-z][a-z0-9_]{1,40}$'
66
+ on conflict do nothing
67
+ `.execute(this.db.db);
68
+ return this.db.db.selectFrom("extension_handoff_tables").select("schema_name").execute();
69
+ });
69
70
  let loaded;
70
71
  let loadedAt = 0;
71
72
  let refreshed = false;
@@ -89,10 +90,11 @@ let ExtensionEffectRelay = class ExtensionEffectRelay {
89
90
  }
90
91
  return keys;
91
92
  };
92
- for (const plugin of names) {
93
+ for (const { schema_name: schema } of tables) {
93
94
  if (signal?.aborted)
94
95
  return;
95
- if (!EXTENSION_NAME_RE.test(plugin))
96
+ const plugin = schema.slice("plugin_".length).replaceAll("_", "-");
97
+ if (!EXTENSION_NAME_RE.test(plugin) || pluginSchemaName(plugin) !== schema)
96
98
  continue;
97
99
  const lease = await this.lockService.acquire(`extension-effect-relay-${plugin}`, {
98
100
  ttlMs: 30_000,
@@ -102,6 +104,11 @@ let ExtensionEffectRelay = class ExtensionEffectRelay {
102
104
  continue;
103
105
  const active = signal ? AbortSignal.any([lease.lost, signal]) : lease.lost;
104
106
  try {
107
+ const { rows: [table], } = await sql `
108
+ select pg_catalog.to_regclass(${handoffTable(plugin)}) is not null as present
109
+ `.execute(this.db.db);
110
+ if (!table?.present)
111
+ throw new ExtensionEffectFailure("handoff_missing", "The extension handoff table is missing");
105
112
  const identity = this.identity.resolve(plugin);
106
113
  const login = identity.separate ? identity.login : null;
107
114
  await asPlatform("Relay extension handoffs and their outbox references", async () => {
@@ -109,17 +116,21 @@ let ExtensionEffectRelay = class ExtensionEffectRelay {
109
116
  await this.ingest(plugin, login, ring, active);
110
117
  await this.cleanup(plugin, login, ring, active);
111
118
  });
112
- await this.status.clearNote(plugin, HANDOFF_MISSING);
119
+ if (!active.aborted)
120
+ await this.handoffHealth(schema, plugin, false);
113
121
  }
114
122
  catch (error) {
123
+ if (active.aborted)
124
+ continue;
115
125
  const failure = classifyEffectFailure(error);
116
126
  if (failure.code === "handoff_missing") {
117
- this.log.error("Extension handoff health fault", {
118
- plugin,
119
- code: failure.code,
120
- message: failure.message,
121
- });
122
- await this.status.note(plugin, HANDOFF_MISSING);
127
+ if (await this.handoffHealth(schema, plugin, true)) {
128
+ this.log.error("Extension handoff health fault", {
129
+ plugin,
130
+ code: failure.code,
131
+ message: failure.message,
132
+ });
133
+ }
123
134
  }
124
135
  else {
125
136
  this.log.warn("Extension handoff relay failed", { plugin, code: failure.code });
@@ -130,6 +141,24 @@ let ExtensionEffectRelay = class ExtensionEffectRelay {
130
141
  }
131
142
  }
132
143
  }
144
+ async handoffHealth(schema, plugin, missing) {
145
+ const transition = await this.db.db
146
+ .updateTable("extension_handoff_tables")
147
+ .set({ missing })
148
+ .where("schema_name", "=", schema)
149
+ .where("missing", "=", !missing)
150
+ .returning("schema_name")
151
+ .executeTakeFirst();
152
+ // Admission and setup errors take precedence over the handoff note.
153
+ await this.db.db
154
+ .updateTable("extension_replica_status")
155
+ .set({ detail: missing ? HANDOFF_MISSING : null })
156
+ .where("plugin", "=", plugin)
157
+ .$if(missing, (query) => query.where("detail", "is", null))
158
+ .$if(!missing, (query) => query.where("detail", "=", HANDOFF_MISSING))
159
+ .execute();
160
+ return transition !== undefined;
161
+ }
133
162
  async redrive(plugin, login, ring, signal) {
134
163
  // org-filter: deployment-wide outbox scan by plugin; only the verified envelope supplies delivery scope.
135
164
  const rows = await asPlatform("Find due extension redrive references", () => this.db.db
@@ -240,11 +269,9 @@ ExtensionEffectRelay = __decorate([
240
269
  __param(1, Inject(ExtensionEffects)),
241
270
  __param(2, Inject(ExtensionEffectKeys)),
242
271
  __param(3, Inject(ConfiguredExtensionDbIdentity)),
243
- __param(4, Inject(ExtensionRegistry)),
244
- __param(5, Inject(ReplicaStatusStore)),
245
- __param(6, Inject(KernelDb)),
246
- __param(7, Inject(KernelConfigService)),
247
- __param(8, Inject(LockService)),
248
- __param(9, Inject(KERNEL_LOGGER))
272
+ __param(4, Inject(KernelDb)),
273
+ __param(5, Inject(KernelConfigService)),
274
+ __param(6, Inject(LockService)),
275
+ __param(7, Inject(KERNEL_LOGGER))
249
276
  ], ExtensionEffectRelay);
250
277
  export { ExtensionEffectRelay };
@@ -21,6 +21,9 @@ function createHandoffTable(table, ifNotExists = true) {
21
21
  create index if not exists _capybara_effect_key on ${table} ((envelope->>'keyId'))
22
22
  `;
23
23
  }
24
+ async function recordHandoffTable(owner, schema) {
25
+ await owner.query("insert into capybara.extension_handoff_tables (schema_name) values ($1) on conflict do nothing", [schema]);
26
+ }
24
27
  /** Creates a handoff owned by the one-shot provisioner. The extension can append only. */
25
28
  export async function provisionExtensionHandoff(owner, schema, extensionLogin, runtimeLogin, legacyOwner) {
26
29
  await lockMigrationSchema(owner, schema, "transaction");
@@ -79,6 +82,7 @@ export async function provisionExtensionHandoff(owner, schema, extensionLogin, r
79
82
  await owner.query(`grant usage on schema ${ns} to ${reader}`);
80
83
  await owner.query(`grant select, delete on table ${table} to ${reader}`);
81
84
  await owner.query(`grant update (attempts, last_error, next_attempt_at, parked_at) on table ${table} to ${reader}`);
85
+ await recordHandoffTable(owner, schema);
82
86
  }
83
87
  /** Single-login deployments use the kernel's own connection for this table. */
84
88
  export async function ensureLocalExtensionHandoff(db, dbUrl, schema, connectTimeoutMs) {
@@ -102,6 +106,7 @@ export async function ensureLocalExtensionHandoff(db, dbUrl, schema, connectTime
102
106
  const table = `${ns}.${pg.escapeIdentifier(EXTENSION_EFFECT_HANDOFF)}`;
103
107
  await client.query(`create schema if not exists ${ns}`);
104
108
  await client.query(createHandoffTable(table));
109
+ await recordHandoffTable(client, schema);
105
110
  await client.query("commit");
106
111
  }
107
112
  finally {
@@ -1514,6 +1514,8 @@ export interface ExtensionPackagesTable {
1514
1514
  zh: string;
1515
1515
  en: string;
1516
1516
  } | null, string | null | undefined, string | null>;
1517
+ /** 0235: lowercase hex sha512 of the archive; filled at ingest and backfilled by plan task 1.2b. */
1518
+ sha512: ColumnType<string | null, string | null | undefined, string | null>;
1517
1519
  }
1518
1520
  /**
1519
1521
  * 0100: catalog display files (plugin icons, connector template icons, setup guide files) by
@@ -1554,6 +1556,66 @@ export interface ExtensionInstallsTable {
1554
1556
  * refused) the earliest enabled is the one every replica loads.
1555
1557
  */
1556
1558
  enabled_at: TsNullable;
1559
+ /**
1560
+ * 0235: the approved revision and the grant generation it was promoted under, or NULL. The
1561
+ * foreign key guarantees that grant exists; its state is read at admission.
1562
+ */
1563
+ approved_version: ColumnType<string | null, string | null | undefined, string | null>;
1564
+ approved_sha512: ColumnType<string | null, string | null | undefined, string | null>;
1565
+ approved_generation: ColumnType<number | null, number | null | undefined, number | null>;
1566
+ /** 0235: a candidate revision waiting for review (it may have no grant), or NULL. */
1567
+ candidate_version: ColumnType<string | null, string | null | undefined, string | null>;
1568
+ candidate_sha512: ColumnType<string | null, string | null | undefined, string | null>;
1569
+ }
1570
+ /** 0235: one admin approval bound to an exact package revision (see extensions/revision-grants.ts). */
1571
+ export interface ExtensionRevisionGrantsTable {
1572
+ plugin: string;
1573
+ version: string;
1574
+ /** Lowercase hex sha512 of the package archive. */
1575
+ sha512: string;
1576
+ /** A new review of the same revision after revocation or retirement is the next generation. */
1577
+ generation: number;
1578
+ keys: Json<string[]>;
1579
+ purposes: Json<{
1580
+ key: string;
1581
+ zh: string;
1582
+ en: string;
1583
+ }[]>;
1584
+ purposes_digest: string;
1585
+ realms: ColumnType<Record<string, string[]>, string | undefined, string>;
1586
+ review_hash: string;
1587
+ approval_scope: "all" | "optional" | "named";
1588
+ source: "review" | "operator_config" | "operator_cli" | "auto" | "continuity";
1589
+ authority: "super_admin" | "operator" | "auto";
1590
+ publisher: ColumnType<Record<string, string> | null, string | null | undefined, string | null>;
1591
+ publisher_evidence: "verified" | "pin_only" | "none";
1592
+ continued_version: ColumnType<string | null, string | null | undefined, string | null>;
1593
+ continued_sha512: ColumnType<string | null, string | null | undefined, string | null>;
1594
+ continued_generation: ColumnType<number | null, number | null | undefined, number | null>;
1595
+ state: ColumnType<"approved" | "partially_revoked" | "revoked" | "retired", "approved" | undefined, "approved" | "partially_revoked" | "revoked" | "retired">;
1596
+ disabled_keys: ColumnType<string[], string | undefined, string>;
1597
+ retired_keys: ColumnType<string[], string | undefined, string>;
1598
+ retired_forcing: ColumnType<Record<string, string[]>, string | undefined, string>;
1599
+ approved_by: string | null;
1600
+ approved_at: Ts;
1601
+ state_changed_by: ColumnType<string | null, string | null | undefined, string | null>;
1602
+ state_changed_at: TsNullable;
1603
+ }
1604
+ /** 0235: the orgs of a revision grant whose approval scope is `named`. */
1605
+ export interface ExtensionRevisionGrantOrgsTable {
1606
+ plugin: string;
1607
+ version: string;
1608
+ sha512: string;
1609
+ generation: number;
1610
+ org_id: string;
1611
+ }
1612
+ export interface ExtensionHandoffTablesTable {
1613
+ schema_name: string;
1614
+ missing: Generated<boolean>;
1615
+ }
1616
+ export interface ExtensionAdmissionRefusalsTable {
1617
+ plugin: string;
1618
+ sha256: string;
1557
1619
  }
1558
1620
  /** Which npm package owns an extension name (Ruling P3): written on first install, kept on uninstall. */
1559
1621
  export interface ExtensionNameOwnersTable {
@@ -1568,6 +1630,13 @@ export interface ExtensionDeploymentConfigsTable {
1568
1630
  updated_by: string | null;
1569
1631
  updated_at: Ts;
1570
1632
  }
1633
+ /** The deployment grant epoch (migration 0234): one row, advanced by triggers at commit. */
1634
+ export interface ExtensionGrantEpochTable {
1635
+ id: Generated<number>;
1636
+ /** bigint; pg returns it as a string. */
1637
+ epoch: Generated<string>;
1638
+ changed_at: Generated<Date>;
1639
+ }
1571
1640
  export interface ExtensionReplicaStatusTable {
1572
1641
  replica_id: string;
1573
1642
  plugin: string;
@@ -2176,8 +2245,13 @@ export interface KernelDatabase {
2176
2245
  extension_packages: ExtensionPackagesTable;
2177
2246
  extension_blobs: ExtensionBlobsTable;
2178
2247
  extension_installs: ExtensionInstallsTable;
2248
+ extension_revision_grants: ExtensionRevisionGrantsTable;
2249
+ extension_revision_grant_orgs: ExtensionRevisionGrantOrgsTable;
2179
2250
  extension_replica_status: ExtensionReplicaStatusTable;
2251
+ extension_grant_epoch: ExtensionGrantEpochTable;
2180
2252
  extension_name_owners: ExtensionNameOwnersTable;
2253
+ extension_handoff_tables: ExtensionHandoffTablesTable;
2254
+ extension_admission_refusals: ExtensionAdmissionRefusalsTable;
2181
2255
  extension_deployment_configs: ExtensionDeploymentConfigsTable;
2182
2256
  catalog_items: CatalogItemsTable;
2183
2257
  catalog_item_versions: CatalogItemVersionsTable;
@@ -123,6 +123,8 @@ const rules = [
123
123
  clear("extension_installs", "installed_by", deployment, "name"),
124
124
  clear("extension_installs", "updated_by", deployment, "name"),
125
125
  clear("extension_permission_snapshots", "approved_by", deployment, "plugin,version"),
126
+ clear("extension_revision_grants", "approved_by", deployment, "plugin,version,sha512,generation"),
127
+ clear("extension_revision_grants", "state_changed_by", deployment, "plugin,version,sha512,generation"),
126
128
  clear("extension_packages", "uploaded_by", deployment, "sha256"),
127
129
  clear("extension_org_configs", "updated_by"),
128
130
  clear("extension_org_overrides", "created_by"),
@@ -46,6 +46,7 @@ const direct = [
46
46
  ["extension_org_overrides", "created_by updated_by"],
47
47
  ["extension_packages", "uploaded_by"],
48
48
  ["extension_permission_snapshots", "approved_by"],
49
+ ["extension_revision_grants", "approved_by state_changed_by"],
49
50
  ["file_shares", "created_by revoked_by"],
50
51
  ["files", "account_id"],
51
52
  ["identities", "account_id"],
@@ -1,6 +1,11 @@
1
1
  import { sql } from "kysely";
2
- // PostgreSQL 17 after 0232. Re-review the ownership map before updating this fingerprint.
3
- // It includes relation/column identities and ordered PK, UNIQUE and inbound/outbound FK
2
+ // PostgreSQL 17 after 0237. Re-review the ownership map before updating this fingerprint.
3
+ // 0234 adds extension_grant_epoch: deployment state with no org or account reference, so it
4
+ // needs no erasure rule. 0235 adds extension_revision_grants (approver columns cleared by account
5
+ // erasure, deployment scope) and extension_revision_grant_orgs (an org row rule; the org FK
6
+ // cascades), plus the install revision columns, their grant foreign key and extension_packages.sha512.
7
+ // 0237 adds the handoff inventory and admission refusals, both deployment metadata.
8
+ // The fingerprint includes relation/column identities and ordered PK, UNIQUE and inbound/outbound FK
4
9
  // columns and actions, including FKs from outside the kernel schema.
5
10
  export async function orgCatalogDrift(db) {
6
11
  const { rows } = await sql `
@@ -30,5 +35,5 @@ WITH catalog AS (
30
35
  )
31
36
  SELECT md5(string_agg(entry, chr(10) ORDER BY entry COLLATE "C")) AS fingerprint FROM catalog
32
37
  `.execute(db);
33
- return rows[0]?.fingerprint === "d14c7d273dd0ffd58e26d01d3ceb95a4" ? undefined : "schema-drift";
38
+ return rows[0]?.fingerprint === "a9f59a4747b2fa6ee329121f9a0af5b3" ? undefined : "schema-drift";
34
39
  }
@@ -32,6 +32,7 @@ export const rowRules = [
32
32
  rule("extension_client_reports", "plugin, build, org_id, contribution, kind"),
33
33
  rule("extension_org_configs", "plugin, org_id"),
34
34
  rule("extension_org_overrides", "plugin, org_id"),
35
+ rule("extension_revision_grant_orgs", "plugin, version, sha512, generation, org_id"),
35
36
  rule("file_previewers", "org_id, plugin, previewer_id"),
36
37
  rule("inbox_items", "id"),
37
38
  rule("invitations", "id"),
@@ -71,17 +71,27 @@ export declare const EvalRunStartBody: z.ZodObject<{
71
71
  tokenCap: z.ZodOptional<z.ZodNumber>;
72
72
  }, z.core.$strict>;
73
73
  /**
74
- * `view=light`: no content blocks (result tables and polling; the response carries `asOf`);
75
- * default `full`. `updatedSince` (ISO time) takes only what changed after it.
74
+ * A page of a run's results by page number (table pagination spec §2.3, no snapshot: every result
75
+ * exists from the run's start). `view=light`: no content blocks (the results table and its
76
+ * polling, which reads the page again); default `full`.
76
77
  */
77
78
  export declare const EvalRunResultsQuery: z.ZodObject<{
78
- after: z.ZodOptional<z.ZodString>;
79
- limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
79
+ page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
80
+ size: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
80
81
  view: z.ZodDefault<z.ZodEnum<{
81
82
  full: "full";
82
83
  light: "light";
83
84
  }>>;
84
- updatedSince: z.ZodOptional<z.ZodString>;
85
+ }, z.core.$strict>;
86
+ /**
87
+ * `GET …/eval-sets/:setId/runs`: page numbers on a snapshot (table pagination spec §2.3). Runs are
88
+ * only appended and never move, newest first by `(created_at, id)`; `asOf` is the point in time of
89
+ * the first read, so runs started later stay out and count in `newer`.
90
+ */
91
+ export declare const EvalSetRunsQuery: z.ZodObject<{
92
+ page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
93
+ size: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
94
+ asOf: z.ZodOptional<z.ZodISODateTime>;
85
95
  }, z.core.$strict>;
86
96
  export declare const EvalLabelBody: z.ZodObject<{
87
97
  label: z.ZodNullable<z.ZodEnum<{
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { ModelRef } from "../agents/definition.js";
3
+ import { PageQueryFields, timeAsOf } from "../infra/paging/paged-read.js";
3
4
  const NAME = z.string().trim().min(1).max(200);
4
5
  const DESCRIPTION = z.string().max(2000);
5
6
  const RUBRIC = z.string().min(1).max(20_000);
@@ -49,19 +50,25 @@ export const EvalRunEstimateBody = z
49
50
  .strict();
50
51
  export const EvalRunStartBody = EvalRunEstimateBody;
51
52
  /**
52
- * `view=light`: no content blocks (result tables and polling; the response carries `asOf`);
53
- * default `full`. `updatedSince` (ISO time) takes only what changed after it.
53
+ * A page of a run's results by page number (table pagination spec §2.3, no snapshot: every result
54
+ * exists from the run's start). `view=light`: no content blocks (the results table and its
55
+ * polling, which reads the page again); default `full`.
54
56
  */
55
57
  export const EvalRunResultsQuery = z
56
58
  .object({
57
- after: z.string().max(100).optional(),
58
- limit: z.coerce.number().int().min(1).max(200).default(50),
59
+ ...PageQueryFields,
59
60
  view: z.enum(["full", "light"]).default("full"),
60
- updatedSince: z
61
- .string()
62
- .max(64)
63
- .refine((v) => !Number.isNaN(Date.parse(v)), { message: "must be an ISO timestamp" })
64
- .optional(),
61
+ })
62
+ .strict();
63
+ /**
64
+ * `GET …/eval-sets/:setId/runs`: page numbers on a snapshot (table pagination spec §2.3). Runs are
65
+ * only appended and never move, newest first by `(created_at, id)`; `asOf` is the point in time of
66
+ * the first read, so runs started later stay out and count in `newer`.
67
+ */
68
+ export const EvalSetRunsQuery = z
69
+ .object({
70
+ ...PageQueryFields,
71
+ asOf: timeAsOf(),
65
72
  })
66
73
  .strict();
67
74
  export const EvalLabelBody = z
@@ -98,7 +105,7 @@ export const EVAL_ROUTES = [
98
105
  body: EvalRunEstimateBody,
99
106
  },
100
107
  { route: `POST ${O}/eval-sets/:setId/runs`, params: EvalSetParams, body: EvalRunStartBody },
101
- { route: `GET ${O}/eval-sets/:setId/runs`, params: EvalSetParams },
108
+ { route: `GET ${O}/eval-sets/:setId/runs`, params: EvalSetParams, query: EvalSetRunsQuery },
102
109
  { route: `GET ${O}/eval-runs/:runId`, params: EvalRunParams },
103
110
  { route: `GET ${O}/eval-runs/:runId/results`, params: EvalRunParams, query: EvalRunResultsQuery },
104
111
  { route: `GET ${O}/eval-runs/:runId/results/:resultId`, params: EvalResultParams },
@@ -1,7 +1,8 @@
1
1
  import type { z } from "zod";
2
2
  import { type Principal } from "../identity/principal.js";
3
+ import type { Page, Paged } from "../infra/paging/paged-read.js";
3
4
  import { type OrgContext } from "../orgs/org.guard.js";
4
- import { EvalRunEstimateBody as EstimateBody, EvalLabelBody as LabelBody, EvalRunResultsQuery as ResultsQuery, EvalRunStartBody as StartBody } from "./evals.schemas.js";
5
+ import { EvalRunEstimateBody as EstimateBody, EvalLabelBody as LabelBody, EvalRunResultsQuery as ResultsQuery, EvalSetRunsQuery as SetRunsQuery, EvalRunStartBody as StartBody } from "./evals.schemas.js";
5
6
  import { type EvalEstimate, type EvalResultLight, type EvalResultView, EvalRunsService, type EvalRunView, type EvalTokenCaps } from "./runs.service.js";
6
7
  /**
7
8
  * 评测运行(`/api/v1/orgs/:orgId/eval-sets/:setId/runs`、`/api/v1/orgs/:orgId/eval-runs/:runId[/results[/:resultId]]`)与
@@ -17,20 +18,11 @@ export declare class EvalRunsController {
17
18
  start(principal: Principal, org: OrgContext, setId: string, body: z.infer<typeof StartBody>): Promise<{
18
19
  run: EvalRunView;
19
20
  }>;
20
- list(principal: Principal, org: OrgContext, setId: string): Promise<{
21
- runs: EvalRunView[];
22
- }>;
21
+ list(principal: Principal, org: OrgContext, setId: string, q: z.infer<typeof SetRunsQuery>): Promise<Paged<EvalRunView>>;
23
22
  get(principal: Principal, org: OrgContext, runId: string): Promise<{
24
23
  run: EvalRunView;
25
24
  }>;
26
- results(principal: Principal, org: OrgContext, runId: string, q: z.infer<typeof ResultsQuery>): Promise<{
27
- results: EvalResultView[];
28
- next: string | null;
29
- } | {
30
- results: EvalResultLight[];
31
- next: string | null;
32
- asOf: string;
33
- }>;
25
+ results(principal: Principal, org: OrgContext, runId: string, q: z.infer<typeof ResultsQuery>): Promise<Page<EvalResultView> | Page<EvalResultLight>>;
34
26
  /** 一条结果的完整行(查看器按需读取)。 */
35
27
  result(principal: Principal, org: OrgContext, runId: string, resultId: string): Promise<{
36
28
  result: EvalResultView;