@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
@@ -27,17 +27,41 @@ export async function readIsolatedGrant(db, grant) {
27
27
  const snapshot = await query.executeTakeFirst();
28
28
  return snapshotCovers(snapshot, permissions);
29
29
  }
30
- const MAX_GRANTS_PER_INSTANCE = 128;
31
- const GRANT_TTL_MS = 60_000;
30
+ /** A grant checked at the current epoch is still rechecked after this long (backstop only). */
31
+ export const GRANT_FULL_REVALIDATION_MS = 5 * 60_000;
32
32
  const REVALIDATION_BATCH = 8;
33
- /** Replica-local cache of authority checked against deployment and org state. */
33
+ const IN_FLIGHT_RECHECK_BATCH = 64;
34
+ /**
35
+ * Replica-local cache of authority checked against deployment and org state.
36
+ *
37
+ * A cached grant is valid only while it was checked at the current grant epoch and the epoch was
38
+ * read successfully within its maximum age. When the epoch cannot be confirmed, new admissions
39
+ * wait for a fresh read and are refused if it fails (fail closed). Bus hints still fence affected
40
+ * grants at once; the epoch covers hints that never arrive.
41
+ */
34
42
  export class IsolatedInvocationGrants {
43
+ epochs;
44
+ capacity;
45
+ now;
35
46
  instances = new Map();
36
47
  rechecks = new Map();
48
+ /** Every cached grant across instances, least recently used first. */
49
+ lru = new Map();
37
50
  revalidating;
51
+ constructor(epochs, capacity, now = () => performance.now()) {
52
+ this.epochs = epochs;
53
+ this.capacity = capacity;
54
+ this.now = now;
55
+ }
38
56
  async issue({ plugin, orgId }, check, onRevoked, instance) {
39
57
  if (instance.aborted)
40
58
  return undefined;
59
+ this.epochs.start();
60
+ // No await when the epoch is fresh: the grant entry must exist before a revocation can race it.
61
+ if (this.epochs.fresh() === undefined) {
62
+ if ((await this.epochs.ensureFresh()) === undefined || instance.aborted)
63
+ return undefined;
64
+ }
41
65
  let bucket = this.instances.get(instance);
42
66
  if (!bucket) {
43
67
  bucket = { plugin, orgs: new Map() };
@@ -45,8 +69,11 @@ export class IsolatedInvocationGrants {
45
69
  this.instances.set(instance, bucket);
46
70
  instance.addEventListener("abort", () => {
47
71
  this.instances.delete(instance);
48
- for (const grant of orgs.values())
72
+ for (const grant of orgs.values()) {
73
+ this.lru.delete(grant);
74
+ this.rechecks.delete(grant);
49
75
  grant.abort.abort();
76
+ }
50
77
  orgs.clear();
51
78
  }, { once: true });
52
79
  }
@@ -54,34 +81,38 @@ export class IsolatedInvocationGrants {
54
81
  let entry = orgs.get(orgId);
55
82
  if (entry) {
56
83
  // Move it to the back so an idle least recently used grant is the first eviction candidate.
57
- orgs.delete(orgId);
84
+ this.lru.delete(entry);
58
85
  }
59
86
  else {
60
- if (orgs.size >= MAX_GRANTS_PER_INSTANCE) {
61
- for (const [key, idle] of orgs) {
62
- if (idle.calls !== 0 || idle.pending)
63
- continue;
64
- orgs.delete(key);
65
- break;
66
- }
67
- if (orgs.size >= MAX_GRANTS_PER_INSTANCE)
68
- return undefined;
69
- }
87
+ if (this.lru.size >= this.capacity && !this.evictIdle())
88
+ return undefined;
70
89
  entry = {
71
90
  abort: new AbortController(),
72
91
  check,
73
92
  onRevoked: onRevoked ?? (() => { }),
74
- checkedUntil: 0,
93
+ epoch: undefined,
94
+ checkedAt: Number.NEGATIVE_INFINITY,
75
95
  calls: 0,
96
+ admitting: 0,
76
97
  };
98
+ orgs.set(orgId, entry);
77
99
  }
78
- orgs.set(orgId, entry);
79
- while (Date.now() >= entry.checkedUntil) {
80
- if (!(await this.validate(orgs, orgId, entry)))
81
- return undefined;
100
+ this.lru.set(entry, { orgs, orgId, entry });
101
+ entry.admitting += 1;
102
+ try {
103
+ for (;;) {
104
+ const epoch = this.epochs.fresh() ?? (await this.epochs.ensureFresh());
105
+ if (epoch === undefined || entry.abort.signal.aborted)
106
+ return undefined;
107
+ if (this.valid(entry, epoch))
108
+ break;
109
+ if (!(await this.validate(orgs, orgId, entry)))
110
+ return undefined;
111
+ }
112
+ }
113
+ finally {
114
+ entry.admitting -= 1;
82
115
  }
83
- if (entry.abort.signal.aborted)
84
- return undefined;
85
116
  const call = new AbortController();
86
117
  entry.calls += 1;
87
118
  return {
@@ -101,7 +132,7 @@ export class IsolatedInvocationGrants {
101
132
  for (const [key, entry] of bucket.orgs) {
102
133
  if (orgId !== undefined && orgId !== key)
103
134
  continue;
104
- bucket.orgs.delete(key);
135
+ this.drop(bucket.orgs, key, entry);
105
136
  entry.abort.abort();
106
137
  }
107
138
  }
@@ -114,7 +145,7 @@ export class IsolatedInvocationGrants {
114
145
  for (const grant of this.retained()) {
115
146
  if (grant.orgId === undefined || (orgId !== undefined && orgId !== grant.orgId))
116
147
  continue;
117
- grant.entry.checkedUntil = 0;
148
+ grant.entry.epoch = undefined;
118
149
  delete grant.entry.pending;
119
150
  this.rechecks.set(grant.entry, grant);
120
151
  }
@@ -123,11 +154,71 @@ export class IsolatedInvocationGrants {
123
154
  /** Recheck retained grants, including idle lanes, when periodic reconciliation fires. */
124
155
  revalidate() {
125
156
  for (const grant of this.retained()) {
126
- if (grant.entry.checkedUntil > 0)
157
+ if (grant.entry.epoch !== undefined)
127
158
  this.rechecks.set(grant.entry, grant);
128
159
  }
129
160
  return this.runRechecks();
130
161
  }
162
+ /**
163
+ * The grant epoch advanced: some committed change may have revoked any cached grant. Every
164
+ * entry is stale for admission already ({@link valid} compares epochs), so idle entries are
165
+ * rechecked lazily by their next admission or the periodic reconcile. Entries with calls in
166
+ * flight are rechecked now, all together, so a call whose grant is gone is aborted quickly;
167
+ * {@link fenceStale} aborts the ones still unconfirmed at the settle deadline.
168
+ */
169
+ async epochChanged() {
170
+ const inFlight = [...this.retained()].filter(({ entry }) => entry.calls > 0);
171
+ for (let start = 0; start < inFlight.length; start += IN_FLIGHT_RECHECK_BATCH) {
172
+ await Promise.all(inFlight.slice(start, start + IN_FLIGHT_RECHECK_BATCH).map(({ orgs, orgId, entry }) => {
173
+ // A check started before the change cannot confirm the new epoch: supersede it.
174
+ delete entry.pending;
175
+ return this.validate(orgs, orgId, entry);
176
+ }));
177
+ }
178
+ }
179
+ /**
180
+ * The settle deadline after an epoch change: abort calls whose grant was not confirmed at the
181
+ * current epoch, so no call outlives a revocation by more than the bound. Lanes stay up; the
182
+ * next admission checks PostgreSQL again.
183
+ */
184
+ fenceStale() {
185
+ const epoch = this.epochs.fresh();
186
+ for (const { orgs, orgId, entry } of [...this.retained()]) {
187
+ if (entry.calls === 0 || (epoch !== undefined && this.valid(entry, epoch)))
188
+ continue;
189
+ this.drop(orgs, orgId, entry);
190
+ entry.abort.abort();
191
+ }
192
+ }
193
+ /**
194
+ * The epoch has not been confirmed for the whole revocation bound. Fence every cached grant:
195
+ * in-flight calls are cancelled and the next admission checks PostgreSQL again. Lanes stay up,
196
+ * because nothing is known to be revoked.
197
+ */
198
+ fenceAll() {
199
+ this.revoke({});
200
+ }
201
+ valid(entry, epoch) {
202
+ return (entry.pending === undefined &&
203
+ entry.epoch === epoch &&
204
+ this.now() - entry.checkedAt < GRANT_FULL_REVALIDATION_MS);
205
+ }
206
+ evictIdle() {
207
+ for (const { orgs, orgId, entry } of this.lru.values()) {
208
+ if (entry.calls !== 0 || entry.admitting !== 0 || entry.pending)
209
+ continue;
210
+ this.drop(orgs, orgId, entry);
211
+ entry.abort.abort();
212
+ return true;
213
+ }
214
+ return false;
215
+ }
216
+ drop(orgs, orgId, entry) {
217
+ if (orgs.get(orgId) === entry)
218
+ orgs.delete(orgId);
219
+ this.lru.delete(entry);
220
+ this.rechecks.delete(entry);
221
+ }
131
222
  *retained() {
132
223
  for (const { orgs } of this.instances.values()) {
133
224
  for (const [orgId, entry] of orgs)
@@ -162,29 +253,51 @@ export class IsolatedInvocationGrants {
162
253
  if (entry.pending)
163
254
  return entry.pending;
164
255
  this.rechecks.delete(entry);
165
- const checkedUntil = Date.now() + GRANT_TTL_MS;
166
- const pending = Promise.resolve()
167
- .then(entry.check)
168
- .catch(() => false)
169
- .then((allowed) => {
256
+ const run = async (epoch) => {
257
+ // The epoch is captured before the query starts. A revocation committed after the query's
258
+ // snapshot advances the epoch past this value, so the result is never trusted beyond it.
259
+ const checkedAt = this.now();
260
+ let failed = false;
261
+ const allowed = epoch !== undefined &&
262
+ (await Promise.resolve()
263
+ .then(entry.check)
264
+ .catch(() => {
265
+ failed = true;
266
+ return false;
267
+ }));
170
268
  if (entry.pending !== pending) {
171
269
  // A catalog hint superseded this query. Share the next decision or reuse it if complete.
172
270
  if (entry.abort.signal.aborted || orgs.get(orgId) !== entry)
173
271
  return false;
174
- return entry.checkedUntil > Date.now() || this.validate(orgs, orgId, entry);
272
+ const current = this.epochs.fresh();
273
+ return ((current !== undefined && this.valid(entry, current)) || this.validate(orgs, orgId, entry));
175
274
  }
176
275
  delete entry.pending;
177
276
  if (entry.abort.signal.aborted)
178
277
  return false;
278
+ if (epoch === undefined) {
279
+ // The epoch could not be confirmed: refuse this admission but keep the lane, since
280
+ // nothing is known to be revoked.
281
+ entry.epoch = undefined;
282
+ return false;
283
+ }
179
284
  if (allowed) {
180
- entry.checkedUntil = checkedUntil;
285
+ entry.epoch = epoch;
286
+ entry.checkedAt = checkedAt;
181
287
  return true;
182
288
  }
183
- orgs.delete(orgId);
289
+ // Denied or not checkable: fence the grant (calls abort, the next admission checks again).
290
+ // Only a decision that denies retires the lanes; a failed query (a transient database error
291
+ // during any catalog write's recheck) is not a revocation.
292
+ this.drop(orgs, orgId, entry);
184
293
  entry.abort.abort();
185
- entry.onRevoked();
294
+ if (!failed)
295
+ entry.onRevoked();
186
296
  return false;
187
- });
297
+ };
298
+ // Start the query in this tick when the epoch is fresh, so concurrent callers coalesce on it.
299
+ const known = this.epochs.fresh();
300
+ const pending = known !== undefined ? run(known) : this.epochs.ensureFresh().then(run);
188
301
  entry.pending = pending;
189
302
  return pending;
190
303
  }
@@ -153,7 +153,6 @@ export function createChildSession(root, send) {
153
153
  get secrets() {
154
154
  return noGroup();
155
155
  },
156
- extensionPoints: { get: unsupported, list: unsupported },
157
156
  log: { info: logFor("info"), warn: logFor("warn"), error: logFor("error") },
158
157
  kv: {
159
158
  get: (key) => broker("kv", "get", [key]),
@@ -214,7 +214,7 @@ export async function isolatedRevision(options) {
214
214
  key: manifest.name,
215
215
  dispose: () => instance.close(),
216
216
  });
217
- const descriptors = callbackList(await instance.register(), section.manifest.permissions.tools ?? []);
217
+ const descriptors = callbackList(await instance.register(), manifest.permissions?.tools ?? []);
218
218
  for (const descriptor of descriptors) {
219
219
  await bind(ctx, instance, descriptor, options.effective, options.authorize, options.roles, options.quota);
220
220
  }
@@ -0,0 +1,34 @@
1
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { LockService } from "../infra/lock/lock.service.js";
4
+ import type { KernelLogger } from "../log.js";
5
+ import { ExtensionBlobs } from "./blobs.js";
6
+ export declare const PACKAGE_SHA512_BACKFILL_JOB = "extension-package-sha512-backfill";
7
+ /** Packages read per page, and pages per tick: each read is a full archive, bounded by `packages.maxBytes`. */
8
+ export declare const PACKAGE_SHA512_BACKFILL_BATCH = 50;
9
+ /**
10
+ * Fills `extension_packages.sha512` for packages stored before migration 0235 (plan task 1.2b), so
11
+ * every install resolves its revision grant by `(version, sha512)`. New packages get it at ingest.
12
+ *
13
+ * Idempotent and once per tick across replicas (`@LockedInterval`, worker role): each row is
14
+ * written only while still NULL, from bytes `ExtensionBlobs.get` verified against the sha256. A
15
+ * package whose bytes cannot be read stays NULL and is retried on the next tick; the shadow
16
+ * decision reports it as an unknown digest meanwhile. Once every row is filled a tick is one empty
17
+ * query.
18
+ */
19
+ export declare class PackageDigestBackfillJob {
20
+ private readonly kdb;
21
+ private readonly blobs;
22
+ readonly config: KernelConfigService;
23
+ readonly lockService: LockService;
24
+ readonly log: KernelLogger;
25
+ constructor(kdb: KernelDb, blobs: Pick<ExtensionBlobs, "get">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
26
+ backfill(stop?: AbortSignal): Promise<void>;
27
+ /** One pass of the backfill (the locked tick runs it); returns what it filled and could not. */
28
+ fill(stop?: AbortSignal,
29
+ /** Tests only: the cursor the tick starts at (random otherwise). */
30
+ start?: string): Promise<{
31
+ filled: number;
32
+ failed: number;
33
+ }>;
34
+ }
@@ -0,0 +1,121 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { randomBytes } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { LockService } from "../infra/lock/lock.service.js";
15
+ import { LockedInterval } from "../infra/schedule/locked-interval.js";
16
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
17
+ import { ExtensionBlobs, packageSha512 } from "./blobs.js";
18
+ export const PACKAGE_SHA512_BACKFILL_JOB = "extension-package-sha512-backfill";
19
+ /** Packages read per page, and pages per tick: each read is a full archive, bounded by `packages.maxBytes`. */
20
+ export const PACKAGE_SHA512_BACKFILL_BATCH = 50;
21
+ const PACKAGE_SHA512_BACKFILL_PAGES = 4;
22
+ const PACKAGE_SHA512_BACKFILL_PERIOD_MS = 10 * 60_000;
23
+ /**
24
+ * Fills `extension_packages.sha512` for packages stored before migration 0235 (plan task 1.2b), so
25
+ * every install resolves its revision grant by `(version, sha512)`. New packages get it at ingest.
26
+ *
27
+ * Idempotent and once per tick across replicas (`@LockedInterval`, worker role): each row is
28
+ * written only while still NULL, from bytes `ExtensionBlobs.get` verified against the sha256. A
29
+ * package whose bytes cannot be read stays NULL and is retried on the next tick; the shadow
30
+ * decision reports it as an unknown digest meanwhile. Once every row is filled a tick is one empty
31
+ * query.
32
+ */
33
+ let PackageDigestBackfillJob = class PackageDigestBackfillJob {
34
+ kdb;
35
+ blobs;
36
+ config;
37
+ lockService;
38
+ log;
39
+ constructor(kdb, blobs, config, lockService, log) {
40
+ this.kdb = kdb;
41
+ this.blobs = blobs;
42
+ this.config = config;
43
+ this.lockService = lockService;
44
+ this.log = log;
45
+ }
46
+ async backfill(stop) {
47
+ await this.fill(stop);
48
+ }
49
+ /** One pass of the backfill (the locked tick runs it); returns what it filled and could not. */
50
+ async fill(stop,
51
+ /** Tests only: the cursor the tick starts at (random otherwise). */
52
+ start = randomBytes(32).toString("hex")) {
53
+ let filled = 0;
54
+ let failed = 0;
55
+ // Each tick starts at a random point of the sha256 order and wraps around, so packages whose
56
+ // bytes cannot be read never use up every tick's budget ahead of the same rows: every row is
57
+ // reached within a few ticks however many are unreadable.
58
+ const budget = PACKAGE_SHA512_BACKFILL_BATCH * PACKAGE_SHA512_BACKFILL_PAGES;
59
+ let read = 0;
60
+ for (const half of ["after", "upto"]) {
61
+ let after = half === "after" ? start : "";
62
+ while (read < budget && !stop?.aborted) {
63
+ const limit = Math.min(PACKAGE_SHA512_BACKFILL_BATCH, budget - read);
64
+ let query = this.kdb.db
65
+ .selectFrom("extension_packages")
66
+ .select("sha256")
67
+ .where("sha512", "is", null)
68
+ .where("sha256", ">", after);
69
+ if (half === "upto")
70
+ query = query.where("sha256", "<=", start);
71
+ const rows = await query.orderBy("sha256").limit(limit).execute();
72
+ for (const { sha256 } of rows) {
73
+ if (stop?.aborted)
74
+ break;
75
+ after = sha256;
76
+ read += 1;
77
+ let sha512;
78
+ try {
79
+ sha512 = packageSha512(await this.blobs.get(sha256));
80
+ }
81
+ catch (err) {
82
+ failed += 1;
83
+ this.log.warn("cannot read a stored extension package to record its sha512", {
84
+ sha256,
85
+ err,
86
+ });
87
+ continue;
88
+ }
89
+ const result = await this.kdb.db
90
+ .updateTable("extension_packages")
91
+ .set({ sha512 })
92
+ .where("sha256", "=", sha256)
93
+ .where("sha512", "is", null)
94
+ .executeTakeFirst();
95
+ if (result.numUpdatedRows > 0n)
96
+ filled += 1;
97
+ }
98
+ if (rows.length < limit)
99
+ break;
100
+ }
101
+ }
102
+ if (filled > 0 || failed > 0) {
103
+ this.log.info("extension package sha512 backfill", { filled, failed });
104
+ }
105
+ return { filled, failed };
106
+ }
107
+ };
108
+ __decorate([
109
+ LockedInterval(PACKAGE_SHA512_BACKFILL_JOB, () => PACKAGE_SHA512_BACKFILL_PERIOD_MS, {
110
+ runOnStart: true,
111
+ })
112
+ ], PackageDigestBackfillJob.prototype, "backfill", null);
113
+ PackageDigestBackfillJob = __decorate([
114
+ Injectable(),
115
+ __param(0, Inject(KernelDb)),
116
+ __param(1, Inject(ExtensionBlobs)),
117
+ __param(2, Inject(KernelConfigService)),
118
+ __param(3, Inject(LockService)),
119
+ __param(4, Inject(KERNEL_LOGGER))
120
+ ], PackageDigestBackfillJob);
121
+ export { PackageDigestBackfillJob };
@@ -1,13 +1,13 @@
1
1
  import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
2
  import { dirname, join, posix, relative, resolve as resolvePath } from "node:path";
3
- import { checkEntryImports, isSafePackagePath, PLUGIN_MANIFEST_FILE, parsePluginManifest, } from "@capybara-hq/plugin-sdk";
3
+ import { checkEntryImports, isSafePackagePath, PLUGIN_MANIFEST_FILE, parsePluginManifest, staticPermissionDeclarations, } from "@capybara-hq/plugin-sdk";
4
4
  import { init as lexerInit, parse as lexerParse } from "es-module-lexer";
5
5
  import { PluginPackageError, readPluginPackage, withoutRemovedManifestFields, } from "../catalog/plugin-package.js";
6
6
  import { pluginSchemaName } from "../ctx/create-ctx.js";
7
7
  import { MIGRATION_FILE_RE } from "../db/migrator.js";
8
8
  import { ApiError } from "../errors.js";
9
9
  import { HOST_ZOD_VERSION, PACKAGE_TGZ_LIMITS, PackageTgzError, packagePath, unpackPackageTgz, } from "../packages/tgz.js";
10
- import { buildPermissionSet, parseCreatedTables } from "./permission-set.js";
10
+ import { buildPermissionSet, FULL_ACCESS_UNSUPPORTED, parseCreatedTables, } from "./permission-set.js";
11
11
  import { migrationWarnings, warningsDigest } from "./permission-view.js";
12
12
  /**
13
13
  * Reading and validating an extension package: a plugin tgz (`readPluginPackage`,
@@ -137,6 +137,8 @@ export async function readExtensionPackage(bytes, opts) {
137
137
  `plugin ${manifest.name} has no extension (no "extension" in ${PLUGIN_MANIFEST_FILE}); import it into the catalog instead`,
138
138
  ], "extension.no_extension");
139
139
  }
140
+ if (ext.manifest.permissions.fullAccess !== undefined)
141
+ throw new ExtensionPackageError([FULL_ACCESS_UNSUPPORTED]);
140
142
  await lexerInit;
141
143
  const issues = checkModuleGraph(packagePath(ext.entry), files);
142
144
  const migrationSql = [];
@@ -179,16 +181,18 @@ export function permissionSetOfPackage(p) {
179
181
  */
180
182
  export function permissionSetOfSection(section, migrationSql) {
181
183
  const m = section.manifest;
184
+ const declaration = staticPermissionDeclarations(m);
182
185
  const schema = pluginSchemaName(m.name);
183
186
  const tables = migrationSql.flatMap((f) => parseCreatedTables(f.sql, schema));
184
187
  const strip = (fs) => fs.map((f) => ({ path: f.path, secret: f.secret }));
185
188
  return buildPermissionSet({
186
- provides: m.provides,
187
- requires: m.requires,
188
- optional: m.optional,
189
+ provides: declaration.provides,
190
+ requires: declaration.requires,
191
+ optional: declaration.optional,
189
192
  config: { deployment: strip(m.config.deployment) },
190
193
  tables,
191
- permissions: m.permissions,
194
+ permissions: declaration.permissions,
195
+ purposes: declaration.purposes,
192
196
  warningsDigest: warningsDigest(migrationWarnings(migrationSql, m.name)),
193
197
  });
194
198
  }
@@ -1,4 +1,5 @@
1
- import type { ExtensionManifest, ExtensionPermissions, HttpAccess } from "@capybara-hq/plugin-sdk";
1
+ import { type ExtensionManifest, type ExtensionPermissions, type HttpAccess, type PermissionPurpose } from "@capybara-hq/plugin-sdk";
2
+ export { AGENTS_KEY, CLIENT_KEY, CONVERSATIONS_KEY, DEVICE_ACCESS_KEY_PREFIX, DEVICE_HOST_KEY_PREFIX, DEVICE_LOOPBACK_PORTS_KEY, DEVICE_SITE_ACCESS_KEY, DIAL_IN_KEY_PREFIX, INBOX_KEY, PEOPLE_KEY, POLICY_HOOK_KEY_PREFIX, SETUP_CHECK_KEY_PREFIX, TRIGGERS_KEY_PREFIX, UI_COMPONENT_KEY_PREFIX, UI_VIEW_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "@capybara-hq/plugin-sdk";
2
3
  /** 一个配置字段:点路径(根即叶子时为空串)与是否密钥。 */
3
4
  export interface PermissionConfigField {
4
5
  path: string;
@@ -18,9 +19,15 @@ export interface PermissionSet {
18
19
  };
19
20
  /** 插件迁移里 `CREATE TABLE` 的表名(插件自己 schema 下的不带前缀)。 */
20
21
  tables: string[];
22
+ purposes?: Record<string, PermissionPurpose>;
21
23
  permissions: {
22
24
  secrets: boolean;
23
25
  storage: boolean;
26
+ kv?: true;
27
+ lock?: true;
28
+ bus?: true;
29
+ queue?: true;
30
+ outbox?: true;
24
31
  http: {
25
32
  method: string;
26
33
  path: string;
@@ -55,6 +62,8 @@ export interface PermissionSet {
55
62
  views: string[];
56
63
  embeds: string[];
57
64
  components: string[];
65
+ queries?: string[];
66
+ actions?: string[];
58
67
  };
59
68
  /**
60
69
  * Setup check ids (`permissions.setupChecks`, setup guides v2 §10.2): recorded and shown at
@@ -117,8 +126,6 @@ export interface PermissionSet {
117
126
  */
118
127
  warningsDigest?: string;
119
128
  }
120
- /** 迁移警告摘要的权限键前缀(`migration.warnings:<摘要>`)。 */
121
- export declare const WARNINGS_KEY_PREFIX = "migration.warnings:";
122
129
  /**
123
130
  * 解析 SQL 中 `CREATE [TEMP|UNLOGGED] TABLE [IF NOT EXISTS] [schema.]name` 的表名(按出现顺序,不去重);
124
131
  * 其他语句忽略。schema 等于 `ownSchema` 时去掉前缀(与不带前缀等价),其他 schema 保留 `schema.name`。
@@ -151,83 +158,12 @@ export declare function buildPermissionSet(input: {
151
158
  tables: readonly string[];
152
159
  permissions?: ExtensionPermissions | undefined;
153
160
  warningsDigest?: string | undefined;
161
+ purposes?: ReadonlyMap<string, PermissionPurpose>;
154
162
  }): PermissionSet;
155
- /**
156
- * The stable string keys of a permission set (sorted), such as `provides:channel@1`,
157
- * `config.deployment.secret:apiKey`, `table:todos`, `permissions.tools:write`,
158
- * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
159
- * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`,
160
- * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`,
161
- * `permissions.deviceaccess.loopbackports`,
162
- * `permissions.triggers:item.created`, `permissions.inbox`.
163
- * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
164
- */
163
+ /** Legacy approval cannot authorize a privileged execution realm. */
164
+ export declare const FULL_ACCESS_UNSUPPORTED = "permissions.fullAccess is not yet supported by extension approval";
165
+ /** Expand the kernel snapshot's declarations using the SDK's canonical catalog. */
165
166
  export declare function permissionKeys(set: PermissionSet): string[];
166
- /**
167
- * Key prefix of a policy hook mount (manifest `permissions.policyHooks`): needs approval like any hook.
168
- * Lower-case letters and dots only, as catalog permission keys require (`PERMISSION_KEY_RE`).
169
- */
170
- export declare const POLICY_HOOK_KEY_PREFIX = "permissions.hooks.policy:";
171
- /**
172
- * Permission key of client code (`permissions.client`): sensitive and blocking. The key, not the
173
- * bundle's bytes, is reviewed: an upgrade that only changes the bundle adds no key.
174
- */
175
- export declare const CLIENT_KEY = "permissions.client";
176
- /**
177
- * Key prefix of a dial-in protocol (`permissions.dialIn`): blocking. Lower-case letters and dots
178
- * before the colon, as catalog permission keys require (`PERMISSION_KEY_RE`).
179
- */
180
- export declare const DIAL_IN_KEY_PREFIX = "permissions.dialin:";
181
- /**
182
- * Key prefix of a device service (`permissions.deviceAccess.services`): sensitive and blocking, so
183
- * an upgrade adding a service waits for approval. Lower-case letters and dots before the colon, as
184
- * catalog permission keys require (`PERMISSION_KEY_RE`).
185
- */
186
- export declare const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
187
- /**
188
- * Permission key of loopback port grants (`permissions.deviceAccess.loopbackPorts: true`, browser
189
- * loopback port grants design): sensitive and blocking, so an approved extension never gains it on
190
- * upgrade without approval again. Recorded only when declared.
191
- */
192
- export declare const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
193
- /**
194
- * Key prefix of a host service (`permissions.deviceAccess.hostServices`): the service runs on the
195
- * owner's machine outside the sandbox; sensitive and blocking like any device service key.
196
- */
197
- export declare const DEVICE_HOST_KEY_PREFIX = "permissions.deviceaccess.host:";
198
- /** Blocking permission for profile decisions on non-loopback site actions. */
199
- export declare const DEVICE_SITE_ACCESS_KEY = "permissions.deviceaccess.siteaccess";
200
- /**
201
- * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
202
- * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
203
- * Lower-case letters and dots before the colon, as catalog permission keys require
204
- * (`PERMISSION_KEY_RE`).
205
- */
206
- export declare const TRIGGERS_KEY_PREFIX = "permissions.triggers:";
207
- /**
208
- * Permission key of personal inbox items (`permissions.inbox`): blocking, not sensitive (an item
209
- * reaches only members of orgs that enabled the extension, links only to its own pages, and its
210
- * buttons call its UI actions as the person who clicks).
211
- */
212
- export declare const INBOX_KEY = "permissions.inbox";
213
- /**
214
- * Permission keys of the read-only org facts: blocking, not sensitive (`ctx.agents` lists the
215
- * agents a member may use, `ctx.conversations` the metadata of the extension's own subjects'
216
- * conversations, `ctx.people` the members' names and avatars: no content, no email).
217
- */
218
- export declare const AGENTS_KEY = "permissions.agents";
219
- export declare const CONVERSATIONS_KEY = "permissions.conversations";
220
- export declare const PEOPLE_KEY = "permissions.people";
221
- /** Key prefix of a client component (`ui.component:<id>`): sensitive and blocking. */
222
- export declare const UI_COMPONENT_KEY_PREFIX = "ui.component:";
223
- /** 渲染 schema 视图的权限键前缀:记入快照但不卡加载(见 {@link blockingKeys})。 */
224
- export declare const UI_VIEW_KEY_PREFIX = "ui.view:";
225
- /**
226
- * Key prefix of a setup check id (`permissions.setupChecks`): recorded but never blocking
227
- * ({@link blockingKeys}). Lower-case letters and dots before the colon, as catalog permission keys
228
- * require (`PERMISSION_KEY_RE` of the marketplace format).
229
- */
230
- export declare const SETUP_CHECK_KEY_PREFIX = "setup.check:";
231
167
  /**
232
168
  * 新增项里需要批准(卡加载)的部分:除 `ui.view:*` 与 `setup.check:*` 之外的全部。视图只是把插件已有的数据交给
233
169
  * 内核组件来画,不给插件新能力(spec §4.1);setup checks get only data the extension already gets