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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/dist/admin/extensions.controller.d.ts +0 -11
  2. package/dist/admin/extensions.controller.js +0 -28
  3. package/dist/admin/health.service.d.ts +25 -1
  4. package/dist/admin/health.service.js +50 -18
  5. package/dist/audit/full-access.d.ts +78 -0
  6. package/dist/audit/full-access.js +283 -0
  7. package/dist/automations/automations.service.d.ts +1 -0
  8. package/dist/automations/automations.service.js +3 -1
  9. package/dist/automations/calendar.js +3 -1
  10. package/dist/automations/grant-rules.d.ts +2 -1
  11. package/dist/automations/grant-rules.js +8 -1
  12. package/dist/automations/unattended.d.ts +13 -1
  13. package/dist/automations/unattended.js +13 -1
  14. package/dist/catalog/admin-catalog.controller.d.ts +8 -0
  15. package/dist/catalog/admin-catalog.controller.js +8 -2
  16. package/dist/catalog/admin-catalog.schemas.d.ts +10 -0
  17. package/dist/catalog/admin-catalog.schemas.js +8 -1
  18. package/dist/catalog/catalog-content.d.ts +6 -0
  19. package/dist/catalog/catalog-scope.service.d.ts +22 -2
  20. package/dist/catalog/catalog-scope.service.js +27 -3
  21. package/dist/catalog/catalog.service.js +19 -2
  22. package/dist/catalog/marketplaces.service.d.ts +1 -1
  23. package/dist/catalog/org-catalog.service.d.ts +8 -1
  24. package/dist/catalog/org-catalog.service.js +36 -3
  25. package/dist/catalog/platform-components.js +3 -2
  26. package/dist/catalog/platform-import-update.d.ts +2 -0
  27. package/dist/catalog/platform-import-update.js +8 -1
  28. package/dist/catalog/plugin-connectors.d.ts +11 -0
  29. package/dist/catalog/plugin-connectors.js +33 -0
  30. package/dist/catalog/plugin-import.d.ts +35 -15
  31. package/dist/catalog/plugin-import.js +110 -35
  32. package/dist/catalog/plugin-install.js +6 -0
  33. package/dist/catalog/provenance.d.ts +71 -0
  34. package/dist/catalog/provenance.js +112 -0
  35. package/dist/config/auto-approve.d.ts +16 -0
  36. package/dist/config/auto-approve.js +24 -0
  37. package/dist/config/capacity-presets.d.ts +243 -0
  38. package/dist/config/capacity-presets.js +195 -0
  39. package/dist/config/env.d.ts +2 -1
  40. package/dist/config/env.js +6 -1
  41. package/dist/config/load.js +15 -0
  42. package/dist/config/schema.d.ts +46 -9
  43. package/dist/config/schema.js +154 -30
  44. package/dist/ctx/create-ctx.d.ts +16 -0
  45. package/dist/ctx/create-ctx.js +269 -34
  46. package/dist/ctx/net.d.ts +5 -1
  47. package/dist/ctx/net.js +62 -12
  48. package/dist/db/kernel-schema.d.ts +31 -0
  49. package/dist/db/migrator.js +0 -36
  50. package/dist/dial-in/routes.js +1 -1
  51. package/dist/erasure/org-batches.js +1 -6
  52. package/dist/erasure/org-catalog.js +6 -2
  53. package/dist/erasure/org-rules.js +1 -0
  54. package/dist/erasure/org-worker.js +0 -13
  55. package/dist/errors.d.ts +6 -0
  56. package/dist/errors.js +6 -0
  57. package/dist/extensions/admin-ops.d.ts +14 -1
  58. package/dist/extensions/admin-ops.js +30 -3
  59. package/dist/extensions/admin-view.d.ts +21 -1
  60. package/dist/extensions/admin-view.js +43 -0
  61. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  62. package/dist/extensions/bootstrap-packages.js +1 -1
  63. package/dist/extensions/bootstrap-review.d.ts +251 -0
  64. package/dist/extensions/bootstrap-review.js +676 -0
  65. package/dist/extensions/bootstrap.d.ts +21 -1
  66. package/dist/extensions/bootstrap.js +72 -2
  67. package/dist/extensions/cli.d.ts +6 -0
  68. package/dist/extensions/cli.js +4 -0
  69. package/dist/extensions/enabled.d.ts +3 -0
  70. package/dist/extensions/execution-realm.d.ts +96 -0
  71. package/dist/extensions/execution-realm.js +141 -0
  72. package/dist/extensions/extensions.module.js +12 -0
  73. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  74. package/dist/extensions/full-access-disclosure.js +57 -0
  75. package/dist/extensions/grant-epoch.d.ts +9 -2
  76. package/dist/extensions/grant-epoch.js +13 -2
  77. package/dist/extensions/host.d.ts +96 -4
  78. package/dist/extensions/host.js +411 -33
  79. package/dist/extensions/installs.d.ts +18 -0
  80. package/dist/extensions/installs.js +28 -0
  81. package/dist/extensions/instance.d.ts +2 -0
  82. package/dist/extensions/instance.js +1 -0
  83. package/dist/extensions/isolated/admission.d.ts +23 -2
  84. package/dist/extensions/isolated/admission.js +32 -7
  85. package/dist/extensions/isolated/authorization.d.ts +8 -2
  86. package/dist/extensions/isolated/authorization.js +11 -3
  87. package/dist/extensions/isolated/broker.d.ts +3 -0
  88. package/dist/extensions/isolated/broker.js +50 -14
  89. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  90. package/dist/extensions/isolated/configured-package.js +2 -0
  91. package/dist/extensions/isolated/lanes.d.ts +44 -3
  92. package/dist/extensions/isolated/lanes.js +263 -80
  93. package/dist/extensions/isolated/metrics.d.ts +146 -0
  94. package/dist/extensions/isolated/metrics.js +304 -0
  95. package/dist/extensions/isolated/revision.d.ts +7 -1
  96. package/dist/extensions/isolated/revision.js +26 -5
  97. package/dist/extensions/isolated/rpc.d.ts +5 -0
  98. package/dist/extensions/isolated/rpc.js +7 -2
  99. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  100. package/dist/extensions/isolated/sandbox.js +50 -0
  101. package/dist/extensions/isolated/status.d.ts +79 -0
  102. package/dist/extensions/isolated/status.js +216 -0
  103. package/dist/extensions/isolated/tier.d.ts +127 -2
  104. package/dist/extensions/isolated/tier.js +266 -7
  105. package/dist/extensions/isolated/usage.d.ts +134 -0
  106. package/dist/extensions/isolated/usage.js +322 -0
  107. package/dist/extensions/ledger.d.ts +5 -0
  108. package/dist/extensions/ledger.js +16 -0
  109. package/dist/extensions/lifecycle.d.ts +42 -2
  110. package/dist/extensions/lifecycle.js +100 -4
  111. package/dist/extensions/org-config.js +11 -0
  112. package/dist/extensions/package.d.ts +14 -0
  113. package/dist/extensions/package.js +23 -0
  114. package/dist/extensions/permission-view.d.ts +2 -2
  115. package/dist/extensions/permissions.controller.d.ts +35 -0
  116. package/dist/extensions/permissions.controller.js +98 -0
  117. package/dist/extensions/permissions.schemas.d.ts +288 -0
  118. package/dist/extensions/permissions.schemas.js +96 -0
  119. package/dist/extensions/permissions.service.d.ts +116 -0
  120. package/dist/extensions/permissions.service.js +428 -0
  121. package/dist/extensions/realm-retirement.d.ts +65 -0
  122. package/dist/extensions/realm-retirement.js +150 -0
  123. package/dist/extensions/registry.d.ts +6 -0
  124. package/dist/extensions/registry.js +8 -0
  125. package/dist/extensions/review-hash.d.ts +114 -0
  126. package/dist/extensions/review-hash.js +145 -0
  127. package/dist/extensions/revision-approvals.d.ts +58 -3
  128. package/dist/extensions/revision-approvals.js +135 -14
  129. package/dist/extensions/revision-grants.d.ts +10 -0
  130. package/dist/extensions/revision-review.d.ts +144 -0
  131. package/dist/extensions/revision-review.js +297 -0
  132. package/dist/extensions/revocation-leases.d.ts +273 -0
  133. package/dist/extensions/revocation-leases.js +533 -0
  134. package/dist/extensions/revocation.d.ts +78 -0
  135. package/dist/extensions/revocation.js +205 -0
  136. package/dist/extensions/state.module.js +12 -0
  137. package/dist/git/run-end.d.ts +35 -7
  138. package/dist/git/run-end.js +87 -38
  139. package/dist/http/api.module.js +2 -0
  140. package/dist/identity/audit.d.ts +2 -1
  141. package/dist/identity/audit.js +4 -17
  142. package/dist/index.d.ts +10 -2
  143. package/dist/index.js +10 -2
  144. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  145. package/dist/infra/config/kernel-config.service.js +21 -0
  146. package/dist/infra/outbox/registry.d.ts +13 -0
  147. package/dist/infra/outbox/registry.js +8 -0
  148. package/dist/lifecycle/kernel-lifecycle.d.ts +27 -1
  149. package/dist/lifecycle/kernel-lifecycle.js +83 -22
  150. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  151. package/dist/net/private-endpoint-preflight.js +417 -0
  152. package/dist/net/private-endpoints.d.ts +68 -0
  153. package/dist/net/private-endpoints.js +164 -0
  154. package/dist/net/public-address.d.ts +14 -0
  155. package/dist/net/public-address.js +15 -1
  156. package/dist/net/safe-fetch.d.ts +2 -1
  157. package/dist/net/safe-fetch.js +10 -3
  158. package/dist/overrides.d.ts +9 -1
  159. package/dist/overrides.js +4 -0
  160. package/dist/packages/official-publisher.d.ts +65 -1
  161. package/dist/packages/official-publisher.js +171 -46
  162. package/dist/packages/provenance.d.ts +11 -0
  163. package/dist/packages/provenance.js +24 -0
  164. package/dist/platform/exclusions.js +4 -4
  165. package/dist/platform/ops/automations.ops.js +1 -1
  166. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  167. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  168. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  169. package/dist/platform/platform-ops.module.d.ts +2 -1
  170. package/dist/platform/platform-ops.module.js +2 -0
  171. package/dist/platform/route-schemas.js +2 -0
  172. package/dist/retention/purge-batch.js +10 -14
  173. package/dist/runtime/maintenance.d.ts +4 -2
  174. package/dist/runtime/maintenance.js +16 -3
  175. package/dist/runtime/run-finish.d.ts +3 -3
  176. package/dist/runtime/run-finish.js +7 -3
  177. package/dist/sandbox/permission-availability.d.ts +17 -2
  178. package/dist/sandbox/permission-availability.js +22 -1
  179. package/dist/sandbox/permission-facts.js +7 -1
  180. package/dist/tools/builtins/sandbox/common.js +2 -0
  181. package/dist/tools/pipeline.d.ts +2 -1
  182. package/dist/tools/pipeline.js +7 -2
  183. package/package.json +4 -3
  184. package/src/migrations/0238_extension_usage.sql +40 -0
  185. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -0,0 +1,322 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { randomUUID } from "node:crypto";
3
+ import { sql } from "kysely";
4
+ import { asPlatform } from "../../infra/database/org-scope.js";
5
+ /**
6
+ * Isolated extension usage counters (isolation capacity spec 2026-12-04, §7 "Usage counters";
7
+ * plan task 1.2c): invocations, busy lane time, stream frames, broker callbacks by family and
8
+ * `ctx.net` bytes out and in per (org, plugin), in hourly buckets of `capybara.extension_usage`.
9
+ * Work with no org (deployment mode) is not metered here; the metrics cover it.
10
+ *
11
+ * A replica-local timer flushes this replica's own in-process increments, as AGENTS.md
12
+ * "Multi-replica discipline" allows when the flush is:
13
+ * - **idempotent:** each batch is one statement that records its id in `extension_usage_batches`
14
+ * and adds its rows (`amount = amount + EXCLUDED.amount`, rows sorted by key so two replicas
15
+ * lock shared rows in the same order). Replicas writing the same bucket never overwrite each
16
+ * other, and a batch whose outcome is unknown is retried with its id and counts once;
17
+ * - **bounded:** at most {@link MAX_KEYS} keys are held between flushes, and at most
18
+ * {@link MAX_UNCONFIRMED_BATCHES} batches ({@link MAX_UNCONFIRMED_ROWS} rows) wait for a retry;
19
+ * past either cap the oldest increments are dropped with a warning;
20
+ * - **stopped on shutdown:** the extension host's close stops the timer and makes one last
21
+ * flush, cut off after {@link USAGE_FINAL_FLUSH_TIMEOUT_MS};
22
+ * - **lossy within a stated window:** a crash loses the increments since the last flush, at most
23
+ * one interval ({@link USAGE_FLUSH_INTERVAL_MS}, 10 s). While PostgreSQL is unreachable the
24
+ * unflushed backlog grows up to the caps above (about {@link MAX_UNCONFIRMED_BATCHES} intervals
25
+ * for a busy replica) and a crash then loses that backlog; a batch still failing after an hour
26
+ * is dropped. These are capacity and usage-trend counters, not a ledger.
27
+ *
28
+ * Why not `@LockedInterval`: a locked interval runs once per tick across all replicas, so only one
29
+ * replica would flush and every other replica's counters would never reach PostgreSQL. Each
30
+ * replica (api, worker and gateway alike) runs isolated calls and must flush its own increments;
31
+ * the timer carries no cross-replica state, and the source of truth is the table.
32
+ */
33
+ export const USAGE_FLUSH_INTERVAL_MS = 10_000;
34
+ /** The last flush on shutdown gives up after this long (the batch is then lost). */
35
+ export const USAGE_FINAL_FLUSH_TIMEOUT_MS = 5_000;
36
+ /** A batch that keeps failing is retried this long, then dropped (with a warning). */
37
+ const RETRY_FOR_MS = 60 * 60_000;
38
+ /** Applied batch ids are kept this long, far beyond the retry window. */
39
+ const BATCH_RETENTION = "1 day";
40
+ const BATCH_SWEEP_EVERY_MS = 60 * 60_000;
41
+ /** Distinct (org, plugin, hour, counter) keys held between flushes, against a runaway. */
42
+ export const MAX_KEYS = 100_000;
43
+ /** Batches kept for a retry while PostgreSQL fails; the oldest go first past the cap. */
44
+ export const MAX_UNCONFIRMED_BATCHES = 360;
45
+ /** Rows across those batches; the oldest batches go first past the cap. */
46
+ export const MAX_UNCONFIRMED_ROWS = 200_000;
47
+ const ROWS_PER_STATEMENT = 1_000;
48
+ export function hourOf(at) {
49
+ const date = new Date(at);
50
+ date.setUTCMinutes(0, 0, 0);
51
+ return date.toISOString();
52
+ }
53
+ /** This replica's increments since the last flush, summed per (org, plugin, hour, counter). */
54
+ export class ExtensionUsageCounters {
55
+ now;
56
+ pending = new Map();
57
+ checkpoints = new Set();
58
+ dropped = 0;
59
+ constructor(now = Date.now) {
60
+ this.now = now;
61
+ }
62
+ add(orgId, plugin, counter, amount) {
63
+ if (!Number.isFinite(amount) || amount <= 0)
64
+ return;
65
+ const hour = hourOf(this.now());
66
+ const key = JSON.stringify([orgId, plugin, hour, counter]);
67
+ const entry = this.pending.get(key);
68
+ if (entry) {
69
+ entry.amount += amount;
70
+ return;
71
+ }
72
+ if (this.pending.size >= MAX_KEYS) {
73
+ this.dropped += amount;
74
+ return;
75
+ }
76
+ this.pending.set(key, { orgId, plugin, hour, counter, amount });
77
+ }
78
+ /** A function that books work still running (busy lanes) before each {@link take}. */
79
+ onCheckpoint(checkpoint) {
80
+ this.checkpoints.add(checkpoint);
81
+ return () => {
82
+ this.checkpoints.delete(checkpoint);
83
+ };
84
+ }
85
+ /** Books running work, then hands over and clears everything counted so far. */
86
+ take() {
87
+ for (const checkpoint of this.checkpoints) {
88
+ try {
89
+ checkpoint();
90
+ }
91
+ catch {
92
+ // A failing checkpoint loses only its own running time.
93
+ }
94
+ }
95
+ const increments = [...this.pending.values()];
96
+ const dropped = this.dropped;
97
+ this.pending = new Map();
98
+ this.dropped = 0;
99
+ return { increments, dropped };
100
+ }
101
+ }
102
+ /**
103
+ * Applies one batch: records its id and adds every increment, in one statement (one transaction).
104
+ * A batch id already recorded adds nothing. Rows of an org deleted since are skipped.
105
+ */
106
+ export async function applyUsageBatch(db, id, increments) {
107
+ if (increments.length === 0)
108
+ return true;
109
+ // One key order for every replica: concurrent upserts of shared rows cannot deadlock.
110
+ const sorted = [...increments].sort(compareKeys);
111
+ const values = sql.join(sorted.map((row) => sql `(${row.orgId}, ${row.plugin}, ${row.hour}::timestamptz, ${row.counter}, ${row.amount}::bigint)`));
112
+ // org-filter: deployment-wide a replica's flush carries increments of every org it served
113
+ const result = await asPlatform("flush isolated extension usage counters", () => sql `
114
+ WITH batch AS (
115
+ INSERT INTO capybara.extension_usage_batches (id) VALUES (${id})
116
+ ON CONFLICT (id) DO NOTHING
117
+ RETURNING id
118
+ ), added AS (
119
+ INSERT INTO capybara.extension_usage (org_id, plugin, hour, counter, amount)
120
+ SELECT v.org_id, v.plugin, v.hour, v.counter, v.amount
121
+ FROM (VALUES ${values}) AS v (org_id, plugin, hour, counter, amount)
122
+ JOIN capybara.orgs o ON o.id = v.org_id
123
+ WHERE EXISTS (SELECT 1 FROM batch)
124
+ ON CONFLICT (org_id, plugin, hour, counter)
125
+ DO UPDATE SET amount = capybara.extension_usage.amount + EXCLUDED.amount
126
+ RETURNING 1
127
+ )
128
+ SELECT EXISTS (SELECT 1 FROM batch) AS applied
129
+ `.execute(db));
130
+ return result.rows[0]?.applied === true;
131
+ }
132
+ function compareKeys(a, b) {
133
+ for (const [x, y] of [
134
+ [a.orgId, b.orgId],
135
+ [a.plugin, b.plugin],
136
+ [a.hour, b.hour],
137
+ [a.counter, b.counter],
138
+ ]) {
139
+ if (x !== y)
140
+ return x < y ? -1 : 1;
141
+ }
142
+ return 0;
143
+ }
144
+ /** Splits a large flush into batches of at most {@link ROWS_PER_STATEMENT} rows, in key order. */
145
+ function chunks(increments) {
146
+ const sorted = [...increments].sort(compareKeys);
147
+ const out = [];
148
+ for (let start = 0; start < sorted.length; start += ROWS_PER_STATEMENT) {
149
+ out.push(sorted.slice(start, start + ROWS_PER_STATEMENT));
150
+ }
151
+ return out;
152
+ }
153
+ /** Flushes one replica's {@link ExtensionUsageCounters} every interval; see the module comment. */
154
+ export class ExtensionUsageFlusher {
155
+ options;
156
+ /** Batches taken but not yet confirmed applied, retried in order with their ids. */
157
+ unconfirmed = [];
158
+ timer;
159
+ flushing;
160
+ running = false;
161
+ lastSweep = Number.NEGATIVE_INFINITY;
162
+ inOwnContext = AsyncLocalStorage.snapshot();
163
+ constructor(options) {
164
+ this.options = options;
165
+ }
166
+ start() {
167
+ if (this.running)
168
+ return;
169
+ this.running = true;
170
+ this.schedule();
171
+ }
172
+ /**
173
+ * Graceful shutdown: stops the timer, then one last flush of everything counted, cut off after
174
+ * `timeoutMs` (what is still unflushed then is lost and reported).
175
+ */
176
+ async stop(timeoutMs = USAGE_FINAL_FLUSH_TIMEOUT_MS) {
177
+ this.running = false;
178
+ clearTimeout(this.timer);
179
+ this.timer = undefined;
180
+ let timer;
181
+ const done = await Promise.race([
182
+ this.flush().then(() => true),
183
+ new Promise((resolve) => {
184
+ timer = setTimeout(() => resolve(false), timeoutMs);
185
+ timer.unref?.();
186
+ }),
187
+ ]);
188
+ clearTimeout(timer);
189
+ if (!done)
190
+ this.options.onError?.(new Error("The final usage flush timed out"));
191
+ const left = this.unconfirmed.reduce((rows, batch) => rows + batch.increments.length, 0);
192
+ if (left > 0)
193
+ this.options.onDropped?.({ rows: left });
194
+ }
195
+ /** One flush; concurrent callers share it. Never rejects. */
196
+ flush() {
197
+ this.flushing ??= this.flushOnce().finally(() => {
198
+ this.flushing = undefined;
199
+ });
200
+ return this.flushing;
201
+ }
202
+ now() {
203
+ return this.options.now?.() ?? Date.now();
204
+ }
205
+ async flushOnce() {
206
+ const { increments, dropped } = this.options.counters.take();
207
+ if (dropped > 0)
208
+ this.options.onDropped?.({ rows: 0, amount: dropped });
209
+ // Nothing counted and nothing owed: no statement at all (no sweep either).
210
+ if (increments.length === 0 && this.unconfirmed.length === 0)
211
+ return;
212
+ for (const part of chunks(increments)) {
213
+ this.unconfirmed.push({ id: randomUUID(), increments: part, firstTriedAt: this.now() });
214
+ }
215
+ this.capUnconfirmed();
216
+ while (this.unconfirmed.length > 0) {
217
+ const batch = this.unconfirmed[0];
218
+ try {
219
+ await applyUsageBatch(this.options.db, batch.id, batch.increments);
220
+ this.unconfirmed.shift();
221
+ }
222
+ catch (err) {
223
+ this.options.onError?.(err);
224
+ // Keep the batch and its id: the next flush retries it, and if this attempt did commit,
225
+ // the recorded id turns the retry into a no-op. Give up on a batch only after an hour.
226
+ for (let i = this.unconfirmed.length - 1; i >= 0; i--) {
227
+ const stale = this.unconfirmed[i];
228
+ if (this.now() - stale.firstTriedAt >= RETRY_FOR_MS) {
229
+ this.unconfirmed.splice(i, 1);
230
+ this.options.onDropped?.({ rows: stale.increments.length });
231
+ }
232
+ }
233
+ return;
234
+ }
235
+ }
236
+ if (this.now() - this.lastSweep >= BATCH_SWEEP_EVERY_MS) {
237
+ this.lastSweep = this.now();
238
+ await sweepUsageBatches(this.options.db).catch((err) => this.options.onError?.(err));
239
+ }
240
+ }
241
+ /** Drops the oldest unconfirmed batches beyond the batch and row caps, with a warning. */
242
+ capUnconfirmed() {
243
+ let rows = this.unconfirmed.reduce((total, batch) => total + batch.increments.length, 0);
244
+ while (this.unconfirmed.length > MAX_UNCONFIRMED_BATCHES ||
245
+ (rows > MAX_UNCONFIRMED_ROWS && this.unconfirmed.length > 1)) {
246
+ const oldest = this.unconfirmed.shift();
247
+ rows -= oldest.increments.length;
248
+ this.options.onDropped?.({ rows: oldest.increments.length });
249
+ }
250
+ }
251
+ /** Batches waiting for a retry (tests and diagnostics). */
252
+ get pendingBatches() {
253
+ return this.unconfirmed.length;
254
+ }
255
+ schedule() {
256
+ if (!this.running)
257
+ return;
258
+ this.timer = setTimeout(() => this.inOwnContext(() => {
259
+ void this.flush().finally(() => this.schedule());
260
+ }), this.options.intervalMs ?? USAGE_FLUSH_INTERVAL_MS);
261
+ this.timer.unref?.();
262
+ }
263
+ }
264
+ /** Forgets applied batch ids older than a day (deployment state, no org). */
265
+ export async function sweepUsageBatches(db) {
266
+ // org-filter: deployment-wide the batch ids carry no org
267
+ await asPlatform("forget old isolated usage flush batches", () => sql `DELETE FROM capybara.extension_usage_batches
268
+ WHERE flushed_at < now() - ${BATCH_RETENTION}::interval`.execute(db));
269
+ }
270
+ /**
271
+ * The read seam for saturation views (plan task 4.2d) and a later chargeback: usage rows in
272
+ * `[from, to)` by org, plugin and hour. It reads under the caller's scope: an org scope sees that
273
+ * org's rows (RLS); a deployment-wide view calls it inside `asPlatform`.
274
+ */
275
+ export async function readExtensionUsage(db, filter) {
276
+ let query = db
277
+ .selectFrom("extension_usage")
278
+ .select(["org_id", "plugin", "hour", "counter", "amount"])
279
+ .where("hour", ">=", filter.from)
280
+ .where("hour", "<", filter.to);
281
+ if (filter.orgId !== undefined)
282
+ query = query.where("org_id", "=", filter.orgId);
283
+ if (filter.plugin !== undefined)
284
+ query = query.where("plugin", "=", filter.plugin);
285
+ const rows = await query.orderBy("hour").orderBy("org_id").orderBy("plugin").execute();
286
+ const out = new Map();
287
+ for (const row of rows) {
288
+ const hour = new Date(row.hour);
289
+ const key = JSON.stringify([row.org_id, row.plugin, hour.toISOString()]);
290
+ let entry = out.get(key);
291
+ if (!entry) {
292
+ entry = {
293
+ orgId: row.org_id,
294
+ plugin: row.plugin,
295
+ hour,
296
+ invocations: 0,
297
+ busyLaneSeconds: 0,
298
+ streamFrames: 0,
299
+ netBytesOut: 0,
300
+ netBytesIn: 0,
301
+ brokerCallbacks: {},
302
+ };
303
+ out.set(key, entry);
304
+ }
305
+ const amount = Number(row.amount);
306
+ if (row.counter === "invocations")
307
+ entry.invocations += amount;
308
+ else if (row.counter === "busy_lane_ms")
309
+ entry.busyLaneSeconds += amount / 1000;
310
+ else if (row.counter === "stream_frames")
311
+ entry.streamFrames += amount;
312
+ else if (row.counter === "net_bytes_out")
313
+ entry.netBytesOut += amount;
314
+ else if (row.counter === "net_bytes_in")
315
+ entry.netBytesIn += amount;
316
+ else if (row.counter.startsWith("broker.")) {
317
+ const family = row.counter.slice("broker.".length);
318
+ entry.brokerCallbacks[family] = (entry.brokerCallbacks[family] ?? 0) + amount;
319
+ }
320
+ }
321
+ return [...out.values()];
322
+ }
@@ -25,6 +25,11 @@ export declare class RegistrationLedger {
25
25
  get sealed(): boolean;
26
26
  /** 封账:此后的登记立即撤销并抛错。 */
27
27
  seal(): void;
28
+ /**
29
+ * Takes every entry of one kind off the ledger and disposes it (newest first): the handles held
30
+ * under a revoked permission (plan task 1.3e). A failure goes to `onError`; the rest continue.
31
+ */
32
+ disposeKind(kind: RegistrationKind, onError: (r: Registration, e: unknown) => void): Promise<void>;
28
33
  /** 封账并按登记的倒序逐项撤销;单项失败交给 `onError`,继续其余各项。 */
29
34
  disposeAll(onError: (r: Registration, e: unknown) => void): Promise<void>;
30
35
  }
@@ -34,6 +34,22 @@ export class RegistrationLedger {
34
34
  seal() {
35
35
  this.closed = true;
36
36
  }
37
+ /**
38
+ * Takes every entry of one kind off the ledger and disposes it (newest first): the handles held
39
+ * under a revoked permission (plan task 1.3e). A failure goes to `onError`; the rest continue.
40
+ */
41
+ async disposeKind(kind, onError) {
42
+ const taken = this.items.filter((r) => r.kind === kind).reverse();
43
+ this.items = this.items.filter((r) => r.kind !== kind);
44
+ for (const r of taken) {
45
+ try {
46
+ await r.dispose();
47
+ }
48
+ catch (e) {
49
+ onError(r, e);
50
+ }
51
+ }
52
+ }
37
53
  /** 封账并按登记的倒序逐项撤销;单项失败交给 `onError`,继续其余各项。 */
38
54
  async disposeAll(onError) {
39
55
  this.seal();
@@ -5,11 +5,19 @@ import { LockService } from "../infra/lock/lock.service.js";
5
5
  import type { KernelLogger } from "../log.js";
6
6
  import { ExtensionHost } from "./host.js";
7
7
  import { ExtensionInstalls } from "./installs.js";
8
+ import { ReplicaIsolationStore } from "./isolated/status.js";
8
9
  import { PLUGINS_CHANGED_TOPIC, PLUGINS_RECONCILE_JOB, PLUGINS_RECONCILE_TOPIC, STALE_RECONCILE_PERIODS } from "./lifecycle-topics.js";
9
10
  import { PLUGINS_MIGRATED_TOPIC } from "./migrate-lock.js";
11
+ import { HostReasonRetirement } from "./realm-retirement.js";
10
12
  import { ReplicaStatusStore } from "./sources.js";
11
13
  import { UsageSubscribers } from "./usage-subscribers.js";
12
14
  export { PLUGINS_CHANGED_TOPIC, PLUGINS_MIGRATED_TOPIC, PLUGINS_RECONCILE_JOB, PLUGINS_RECONCILE_TOPIC, STALE_RECONCILE_PERIODS, };
15
+ /**
16
+ * Consecutive `available` readiness probes (the first convergence, then one per periodic
17
+ * reconcile) before this replica retires `host.no-isolation`: a stability window of at least two
18
+ * reconcile intervals with no failing probe.
19
+ */
20
+ export declare const RETIREMENT_STABLE_PROBES = 3;
13
21
  /**
14
22
  * 每副本一个:把本副本的插件加载状态收敛到 PG 期望状态(C16)。
15
23
  * 触发来源:bus `kernel.plugins.changed`(后台 / CLI 改了期望状态或快照)、`kernel.plugins.reconcile`(维护任务周期兜底,
@@ -29,6 +37,10 @@ export declare class ExtensionLifecycle {
29
37
  /** "Does any plugin subscribe to usage.report": its cached answer is cleared on PLUGINS_CHANGED. */
30
38
  private readonly usageSubscribers;
31
39
  private readonly events;
40
+ /** Retires `host.no-isolation` once the supervisor is ready (plan task 1.3b). */
41
+ private readonly retirement?;
42
+ /** This replica's isolation probe and shadow placements, read deployment-wide (1.4j). */
43
+ private readonly isolation?;
32
44
  private running;
33
45
  private queued;
34
46
  private unsubs;
@@ -39,7 +51,11 @@ export declare class ExtensionLifecycle {
39
51
  /** Every install record's name (any desired state): prunes status rows this replica no longer knows. */
40
52
  installs: ExtensionInstalls, config: KernelConfigService, log: KernelLogger,
41
53
  /** "Does any plugin subscribe to usage.report": its cached answer is cleared on PLUGINS_CHANGED. */
42
- usageSubscribers: Pick<UsageSubscribers, "invalidate">, events: KernelEvents);
54
+ usageSubscribers: Pick<UsageSubscribers, "invalidate">, events: KernelEvents,
55
+ /** Retires `host.no-isolation` once the supervisor is ready (plan task 1.3b). */
56
+ retirement?: Pick<HostReasonRetirement, "retireAll"> | undefined,
57
+ /** This replica's isolation probe and shadow placements, read deployment-wide (1.4j). */
58
+ isolation?: Pick<ReplicaIsolationStore, "write" | "prune"> | undefined);
43
59
  /** 订阅三个主题(订阅失败只记 error:周期任务的消息同样收不到时,下次启动再来)。 */
44
60
  start(): Promise<void>;
45
61
  /**
@@ -54,10 +70,34 @@ export declare class ExtensionLifecycle {
54
70
  * 宿主那一步失败只记 error(下一个周期再来);之后照常刷新心跳。
55
71
  */
56
72
  reconcile(reason: string): Promise<void>;
57
- /** 用同一个包重新 setup(配置的非 hot 改动、依赖方联动;与 reconcile 一样在宿主的串行队列里)。 */
73
+ /**
74
+ * Runs setup again with the same package (a non-hot config change, a dependent following its
75
+ * provider), in the host's serial queue like reconcile.
76
+ */
58
77
  reload(name: string): Promise<void>;
78
+ /** The first convergence on this replica checked host-reason retirement. */
79
+ private retirementChecked;
80
+ /** Consecutive readiness probes this replica saw `available` (reset by any other result). */
81
+ private readyStreak;
82
+ /**
83
+ * The generation swap when the isolation supervisor becomes available (plan task 1.3b; spec
84
+ * "Purpose and boundary"). Only on a stable positive readiness signal: `extensionHost.isolation`
85
+ * is configured and the supervisor's own Engine and image checks passed on
86
+ * {@link RETIREMENT_STABLE_PROBES} consecutive probes, never on configuration alone. Then
87
+ * `host.no-isolation` is retired from every live grant still carrying it (audited, epoch bump,
88
+ * fence and hint). The leases see the lost server full access, and the next convergence places
89
+ * the revision isolated: the in-process generation drains and an isolated one starts (1.3e's
90
+ * path, enforced from task 1.5a; reported until then).
91
+ */
92
+ private retireHostReasons;
59
93
  private trigger;
60
94
  private run;
95
+ /**
96
+ * Writes this replica's isolation row (its last probe and shadow placements), and with `prune`
97
+ * deletes stale replicas' rows. Never after the stop, which removes the row: a convergence still
98
+ * running then must not bring it back.
99
+ */
100
+ private recordIsolation;
61
101
  }
62
102
  /**
63
103
  * The periodic reconcile fallback (job `plugins-reconcile`, once per
@@ -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 { Inject, Injectable } from "@nestjs/common";
10
+ import { Inject, Injectable, Optional } from "@nestjs/common";
11
11
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
12
12
  import { KernelEvents } from "../infra/events/kernel-events.js";
13
13
  import { LockService } from "../infra/lock/lock.service.js";
@@ -15,11 +15,19 @@ import { LockedInterval } from "../infra/schedule/locked-interval.js";
15
15
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
16
16
  import { ExtensionHost } from "./host.js";
17
17
  import { ExtensionInstalls } from "./installs.js";
18
+ import { ReplicaIsolationStore } from "./isolated/status.js";
18
19
  import { ISOLATED_REVOKED_TOPIC, PLUGIN_DEPLOYMENT_CONFIG_TOPIC, PLUGINS_CHANGED_TOPIC, PLUGINS_RECONCILE_JOB, PLUGINS_RECONCILE_TOPIC, STALE_RECONCILE_PERIODS, } from "./lifecycle-topics.js";
19
20
  import { PLUGINS_MIGRATED_TOPIC } from "./migrate-lock.js";
21
+ import { HostReasonRetirement } from "./realm-retirement.js";
20
22
  import { ReplicaStatusStore } from "./sources.js";
21
23
  import { UsageSubscribers } from "./usage-subscribers.js";
22
24
  export { PLUGINS_CHANGED_TOPIC, PLUGINS_MIGRATED_TOPIC, PLUGINS_RECONCILE_JOB, PLUGINS_RECONCILE_TOPIC, STALE_RECONCILE_PERIODS, };
25
+ /**
26
+ * Consecutive `available` readiness probes (the first convergence, then one per periodic
27
+ * reconcile) before this replica retires `host.no-isolation`: a stability window of at least two
28
+ * reconcile intervals with no failing probe.
29
+ */
30
+ export const RETIREMENT_STABLE_PROBES = 3;
23
31
  /** 心跳超过这么多个周期的行直接删除(副本早已退出;读的一方本来就不计入)。 */
24
32
  const PRUNE_RECONCILE_PERIODS = 10;
25
33
  /**
@@ -39,6 +47,8 @@ let ExtensionLifecycle = class ExtensionLifecycle {
39
47
  log;
40
48
  usageSubscribers;
41
49
  events;
50
+ retirement;
51
+ isolation;
42
52
  running;
43
53
  queued;
44
54
  unsubs = [];
@@ -49,7 +59,11 @@ let ExtensionLifecycle = class ExtensionLifecycle {
49
59
  /** Every install record's name (any desired state): prunes status rows this replica no longer knows. */
50
60
  installs, config, log,
51
61
  /** "Does any plugin subscribe to usage.report": its cached answer is cleared on PLUGINS_CHANGED. */
52
- usageSubscribers, events) {
62
+ usageSubscribers, events,
63
+ /** Retires `host.no-isolation` once the supervisor is ready (plan task 1.3b). */
64
+ retirement,
65
+ /** This replica's isolation probe and shadow placements, read deployment-wide (1.4j). */
66
+ isolation) {
53
67
  this.host = host;
54
68
  this.bus = bus;
55
69
  this.status = status;
@@ -58,6 +72,8 @@ let ExtensionLifecycle = class ExtensionLifecycle {
58
72
  this.log = log;
59
73
  this.usageSubscribers = usageSubscribers;
60
74
  this.events = events;
75
+ this.retirement = retirement;
76
+ this.isolation = isolation;
61
77
  }
62
78
  /** 订阅三个主题(订阅失败只记 error:周期任务的消息同样收不到时,下次启动再来)。 */
63
79
  async start() {
@@ -171,10 +187,60 @@ let ExtensionLifecycle = class ExtensionLifecycle {
171
187
  });
172
188
  return this.queued;
173
189
  }
174
- /** 用同一个包重新 setup(配置的非 hot 改动、依赖方联动;与 reconcile 一样在宿主的串行队列里)。 */
190
+ /**
191
+ * Runs setup again with the same package (a non-hot config change, a dependent following its
192
+ * provider), in the host's serial queue like reconcile.
193
+ */
175
194
  async reload(name) {
176
195
  await this.host.reload(name);
177
196
  }
197
+ /** The first convergence on this replica checked host-reason retirement. */
198
+ retirementChecked = false;
199
+ /** Consecutive readiness probes this replica saw `available` (reset by any other result). */
200
+ readyStreak = 0;
201
+ /**
202
+ * The generation swap when the isolation supervisor becomes available (plan task 1.3b; spec
203
+ * "Purpose and boundary"). Only on a stable positive readiness signal: `extensionHost.isolation`
204
+ * is configured and the supervisor's own Engine and image checks passed on
205
+ * {@link RETIREMENT_STABLE_PROBES} consecutive probes, never on configuration alone. Then
206
+ * `host.no-isolation` is retired from every live grant still carrying it (audited, epoch bump,
207
+ * fence and hint). The leases see the lost server full access, and the next convergence places
208
+ * the revision isolated: the in-process generation drains and an isolated one starts (1.3e's
209
+ * path, enforced from task 1.5a; reported until then).
210
+ */
211
+ async retireHostReasons() {
212
+ if (!this.retirement)
213
+ return;
214
+ // the first convergence and then every periodic one: a probe is a request to the Engine
215
+ this.retirementChecked = true;
216
+ try {
217
+ if ((await this.host.probeIsolation()) !== "available") {
218
+ this.readyStreak = 0;
219
+ return;
220
+ }
221
+ // Retirement is final and deployment-wide, so one good probe is not enough: the supervisor
222
+ // must stay ready across a stability window of consecutive periodic probes.
223
+ this.readyStreak += 1;
224
+ if (this.readyStreak < RETIREMENT_STABLE_PROBES)
225
+ return;
226
+ const retired = await this.retirement.retireAll();
227
+ if (retired.length === 0)
228
+ return;
229
+ this.log.info("isolation supervisor available: retired host.no-isolation from revision grants", {
230
+ revisions: retired.map((r) => ({
231
+ plugin: `${r.revision.plugin}@${r.revision.version}`,
232
+ generation: r.generation,
233
+ realmRetired: r.realmRetired,
234
+ remaining: r.remaining,
235
+ })),
236
+ });
237
+ // converge again on this replica: the shadow report then shows the new placement
238
+ this.trigger("host-reason-retired");
239
+ }
240
+ catch (err) {
241
+ this.log.warn("retiring host.no-isolation failed; retrying on the next cycle", { err });
242
+ }
243
+ }
178
244
  trigger(reason) {
179
245
  this.reconcile(reason).catch((err) => this.log.error("plugin reconcile failed", { reason, err }));
180
246
  }
@@ -183,6 +249,8 @@ let ExtensionLifecycle = class ExtensionLifecycle {
183
249
  await this.status.heartbeat().catch((err) => {
184
250
  this.log.warn("cannot refresh plugin replica status heartbeats", { err });
185
251
  });
252
+ // the isolation row too: a long convergence must not let it go stale (1.4j)
253
+ await this.recordIsolation();
186
254
  try {
187
255
  await this.host.converge();
188
256
  }
@@ -191,6 +259,10 @@ let ExtensionLifecycle = class ExtensionLifecycle {
191
259
  return;
192
260
  this.log.error("plugin reconcile failed; retrying on the next cycle", { reason, err });
193
261
  }
262
+ if (this.stopped)
263
+ return;
264
+ if (reason === "periodic" || !this.retirementChecked)
265
+ await this.retireHostReasons();
194
266
  if (this.stopped)
195
267
  return;
196
268
  if (reason === "periodic") {
@@ -220,6 +292,26 @@ let ExtensionLifecycle = class ExtensionLifecycle {
220
292
  catch (err) {
221
293
  this.log.warn("cannot refresh plugin replica status heartbeats", { err });
222
294
  }
295
+ // after the probe and the convergence: the isolation status and shadow decisions read it
296
+ await this.recordIsolation(true);
297
+ }
298
+ /**
299
+ * Writes this replica's isolation row (its last probe and shadow placements), and with `prune`
300
+ * deletes stale replicas' rows. Never after the stop, which removes the row: a convergence still
301
+ * running then must not bring it back.
302
+ */
303
+ async recordIsolation(prune = false) {
304
+ if (!this.isolation || this.stopped)
305
+ return;
306
+ try {
307
+ await this.isolation.write(this.status.replicaId, this.host.isolationRecord());
308
+ if (prune) {
309
+ await this.isolation.prune(PRUNE_RECONCILE_PERIODS * this.config.get().extensionHost.reconcileIntervalSeconds);
310
+ }
311
+ }
312
+ catch (err) {
313
+ this.log.warn("cannot record this replica's isolation status", { err });
314
+ }
223
315
  }
224
316
  };
225
317
  ExtensionLifecycle = __decorate([
@@ -231,7 +323,11 @@ ExtensionLifecycle = __decorate([
231
323
  __param(4, Inject(KernelConfigService)),
232
324
  __param(5, Inject(KERNEL_LOGGER)),
233
325
  __param(6, Inject(UsageSubscribers)),
234
- __param(7, Inject(KernelEvents))
326
+ __param(7, Inject(KernelEvents)),
327
+ __param(8, Optional()),
328
+ __param(8, Inject(HostReasonRetirement)),
329
+ __param(9, Optional()),
330
+ __param(9, Inject(ReplicaIsolationStore))
235
331
  ], ExtensionLifecycle);
236
332
  export { ExtensionLifecycle };
237
333
  const pluginOf = (p) => typeof p === "object" && p !== null && typeof p.plugin === "string"
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { EXTENSION_POINTS, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
+ import { auditFullAccessEnabled } from "../audit/full-access.js";
12
13
  import { cancelEnableRequestsOfProvider, settleEnableRequests, } from "../catalog/enable-requests.js";
13
14
  import { orgUsable } from "../catalog/org-intent.js";
14
15
  import { assertItemInstallable, assertPluginSourcesInstallable, disabledPluginItems, pluginItemDisabled, } from "../catalog/request-rules.js";
@@ -342,6 +343,16 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
342
343
  ...opts.auditDetail,
343
344
  },
344
345
  });
346
+ // switched on: the full-access disclosure in the org and the deployment audit (plan task 1.4c)
347
+ if (enabled && !before) {
348
+ await auditFullAccessEnabled(t, {
349
+ orgId,
350
+ plugin,
351
+ via: "org",
352
+ actorAccountId,
353
+ ...(actorTokenId !== undefined && { actorTokenId }),
354
+ });
355
+ }
345
356
  // the org's extension switch moved: its members' pickers refetch
346
357
  if (enabled !== before)
347
358
  publishCapabilities(this.hints, [orgId]);
@@ -70,6 +70,20 @@ export interface ExtensionPackage {
70
70
  sql: string;
71
71
  }[];
72
72
  }
73
+ /** The client code of an extension in a review. */
74
+ export interface PackageClientReview {
75
+ /** Entry, styles and assets in that order; `path` is the manifest key (`./dist/client/...`). */
76
+ files: {
77
+ path: string;
78
+ size: number;
79
+ }[];
80
+ /** Total bytes. */
81
+ totalBytes: number;
82
+ /** The client API version the bundle was built against. */
83
+ apiVersion: number;
84
+ }
85
+ /** The client code of a read extension package for its review (sizes from the package's files). */
86
+ export declare function reviewPackageClient(pkg: ExtensionPackage): PackageClientReview | undefined;
73
87
  /** Options of {@link readExtensionPackage}; `hostZodVersion` defaults to {@link HOST_ZOD_VERSION}. */
74
88
  export interface ReadExtensionPackageOptions extends ExtensionPackageLimits {
75
89
  hostSdkVersion: string;