@capybara-hq/kernel 0.1.0-rc.146 → 0.1.0-rc.148

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 (172) hide show
  1. package/dist/admin/extensions.controller.d.ts +0 -11
  2. package/dist/admin/extensions.controller.js +0 -28
  3. package/dist/admin/health.service.d.ts +25 -1
  4. package/dist/admin/health.service.js +50 -18
  5. package/dist/audit/full-access.d.ts +78 -0
  6. package/dist/audit/full-access.js +283 -0
  7. package/dist/automations/automations.service.d.ts +1 -0
  8. package/dist/automations/automations.service.js +3 -1
  9. package/dist/automations/calendar.js +3 -1
  10. package/dist/automations/grant-rules.d.ts +2 -1
  11. package/dist/automations/grant-rules.js +8 -1
  12. package/dist/automations/unattended.d.ts +13 -1
  13. package/dist/automations/unattended.js +13 -1
  14. package/dist/catalog/admin-catalog.controller.d.ts +8 -0
  15. package/dist/catalog/admin-catalog.controller.js +8 -2
  16. package/dist/catalog/admin-catalog.schemas.d.ts +10 -0
  17. package/dist/catalog/admin-catalog.schemas.js +8 -1
  18. package/dist/catalog/catalog-content.d.ts +6 -0
  19. package/dist/catalog/catalog-scope.service.d.ts +22 -2
  20. package/dist/catalog/catalog-scope.service.js +27 -3
  21. package/dist/catalog/catalog.service.js +19 -2
  22. package/dist/catalog/marketplaces.service.d.ts +1 -1
  23. package/dist/catalog/org-catalog.service.d.ts +8 -1
  24. package/dist/catalog/org-catalog.service.js +36 -3
  25. package/dist/catalog/platform-components.js +3 -2
  26. package/dist/catalog/platform-import-update.d.ts +2 -0
  27. package/dist/catalog/platform-import-update.js +8 -1
  28. package/dist/catalog/plugin-connectors.d.ts +11 -0
  29. package/dist/catalog/plugin-connectors.js +33 -0
  30. package/dist/catalog/plugin-import.d.ts +35 -15
  31. package/dist/catalog/plugin-import.js +110 -35
  32. package/dist/catalog/plugin-install.js +6 -0
  33. package/dist/catalog/provenance.d.ts +2 -0
  34. package/dist/catalog/provenance.js +5 -1
  35. package/dist/config/auto-approve.d.ts +16 -0
  36. package/dist/config/auto-approve.js +24 -0
  37. package/dist/config/capacity-presets.d.ts +243 -0
  38. package/dist/config/capacity-presets.js +195 -0
  39. package/dist/config/env.d.ts +2 -1
  40. package/dist/config/env.js +6 -1
  41. package/dist/config/load.js +15 -0
  42. package/dist/config/schema.d.ts +46 -9
  43. package/dist/config/schema.js +154 -30
  44. package/dist/ctx/net.d.ts +5 -1
  45. package/dist/ctx/net.js +62 -12
  46. package/dist/db/kernel-schema.d.ts +31 -0
  47. package/dist/db/migrator.js +0 -36
  48. package/dist/dial-in/routes.js +1 -1
  49. package/dist/erasure/org-batches.js +1 -6
  50. package/dist/erasure/org-catalog.js +6 -2
  51. package/dist/erasure/org-rules.js +1 -0
  52. package/dist/erasure/org-worker.js +0 -13
  53. package/dist/errors.d.ts +6 -0
  54. package/dist/errors.js +6 -0
  55. package/dist/extensions/admin-ops.d.ts +14 -1
  56. package/dist/extensions/admin-ops.js +30 -3
  57. package/dist/extensions/admin-view.d.ts +21 -1
  58. package/dist/extensions/admin-view.js +43 -0
  59. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  60. package/dist/extensions/bootstrap-packages.js +1 -1
  61. package/dist/extensions/bootstrap-review.d.ts +251 -0
  62. package/dist/extensions/bootstrap-review.js +676 -0
  63. package/dist/extensions/bootstrap.d.ts +21 -1
  64. package/dist/extensions/bootstrap.js +72 -2
  65. package/dist/extensions/cli.d.ts +6 -0
  66. package/dist/extensions/cli.js +4 -0
  67. package/dist/extensions/enabled.d.ts +3 -0
  68. package/dist/extensions/extensions.module.js +9 -0
  69. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  70. package/dist/extensions/full-access-disclosure.js +57 -0
  71. package/dist/extensions/grant-epoch.d.ts +5 -0
  72. package/dist/extensions/grant-epoch.js +9 -0
  73. package/dist/extensions/host.d.ts +71 -2
  74. package/dist/extensions/host.js +293 -27
  75. package/dist/extensions/installs.d.ts +18 -0
  76. package/dist/extensions/installs.js +28 -0
  77. package/dist/extensions/isolated/admission.d.ts +17 -2
  78. package/dist/extensions/isolated/admission.js +18 -8
  79. package/dist/extensions/isolated/authorization.d.ts +8 -2
  80. package/dist/extensions/isolated/authorization.js +11 -3
  81. package/dist/extensions/isolated/broker.d.ts +3 -0
  82. package/dist/extensions/isolated/broker.js +50 -14
  83. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  84. package/dist/extensions/isolated/configured-package.js +2 -0
  85. package/dist/extensions/isolated/lanes.d.ts +44 -3
  86. package/dist/extensions/isolated/lanes.js +263 -80
  87. package/dist/extensions/isolated/metrics.d.ts +146 -0
  88. package/dist/extensions/isolated/metrics.js +304 -0
  89. package/dist/extensions/isolated/revision.d.ts +7 -1
  90. package/dist/extensions/isolated/revision.js +26 -5
  91. package/dist/extensions/isolated/rpc.d.ts +5 -0
  92. package/dist/extensions/isolated/rpc.js +7 -2
  93. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  94. package/dist/extensions/isolated/sandbox.js +50 -0
  95. package/dist/extensions/isolated/status.d.ts +79 -0
  96. package/dist/extensions/isolated/status.js +216 -0
  97. package/dist/extensions/isolated/tier.d.ts +127 -2
  98. package/dist/extensions/isolated/tier.js +266 -7
  99. package/dist/extensions/isolated/usage.d.ts +134 -0
  100. package/dist/extensions/isolated/usage.js +322 -0
  101. package/dist/extensions/lifecycle.d.ts +42 -2
  102. package/dist/extensions/lifecycle.js +100 -4
  103. package/dist/extensions/org-config.js +11 -0
  104. package/dist/extensions/package.d.ts +14 -0
  105. package/dist/extensions/package.js +24 -3
  106. package/dist/extensions/permission-set.d.ts +12 -3
  107. package/dist/extensions/permission-set.js +5 -5
  108. package/dist/extensions/permission-view.d.ts +12 -5
  109. package/dist/extensions/permission-view.js +23 -2
  110. package/dist/extensions/permissions.controller.d.ts +35 -0
  111. package/dist/extensions/permissions.controller.js +98 -0
  112. package/dist/extensions/permissions.schemas.d.ts +288 -0
  113. package/dist/extensions/permissions.schemas.js +96 -0
  114. package/dist/extensions/permissions.service.d.ts +116 -0
  115. package/dist/extensions/permissions.service.js +428 -0
  116. package/dist/extensions/realm-retirement.d.ts +65 -0
  117. package/dist/extensions/realm-retirement.js +150 -0
  118. package/dist/extensions/revision-approvals.d.ts +58 -3
  119. package/dist/extensions/revision-approvals.js +135 -14
  120. package/dist/extensions/revision-review.d.ts +144 -0
  121. package/dist/extensions/revision-review.js +297 -0
  122. package/dist/extensions/revocation.js +3 -0
  123. package/dist/extensions/state.module.js +12 -0
  124. package/dist/git/run-end.d.ts +35 -7
  125. package/dist/git/run-end.js +87 -38
  126. package/dist/http/api.module.js +2 -0
  127. package/dist/identity/audit.d.ts +2 -1
  128. package/dist/identity/audit.js +4 -17
  129. package/dist/index.d.ts +6 -2
  130. package/dist/index.js +6 -2
  131. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  132. package/dist/infra/config/kernel-config.service.js +21 -0
  133. package/dist/infra/outbox/registry.d.ts +13 -0
  134. package/dist/infra/outbox/registry.js +8 -0
  135. package/dist/lifecycle/kernel-lifecycle.d.ts +25 -1
  136. package/dist/lifecycle/kernel-lifecycle.js +73 -18
  137. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  138. package/dist/net/private-endpoint-preflight.js +417 -0
  139. package/dist/net/private-endpoints.d.ts +68 -0
  140. package/dist/net/private-endpoints.js +164 -0
  141. package/dist/net/public-address.d.ts +14 -0
  142. package/dist/net/public-address.js +15 -1
  143. package/dist/net/safe-fetch.d.ts +2 -1
  144. package/dist/net/safe-fetch.js +10 -3
  145. package/dist/overrides.d.ts +4 -0
  146. package/dist/overrides.js +2 -0
  147. package/dist/packages/official-publisher.d.ts +26 -1
  148. package/dist/packages/official-publisher.js +48 -1
  149. package/dist/packages/provenance.d.ts +11 -0
  150. package/dist/packages/provenance.js +24 -0
  151. package/dist/platform/exclusions.js +4 -4
  152. package/dist/platform/ops/automations.ops.js +1 -1
  153. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  154. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  155. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  156. package/dist/platform/platform-ops.module.d.ts +2 -1
  157. package/dist/platform/platform-ops.module.js +2 -0
  158. package/dist/platform/route-schemas.js +2 -0
  159. package/dist/retention/purge-batch.js +10 -14
  160. package/dist/runtime/maintenance.d.ts +4 -2
  161. package/dist/runtime/maintenance.js +16 -3
  162. package/dist/runtime/run-finish.d.ts +3 -3
  163. package/dist/runtime/run-finish.js +7 -3
  164. package/dist/sandbox/permission-availability.d.ts +17 -2
  165. package/dist/sandbox/permission-availability.js +22 -1
  166. package/dist/sandbox/permission-facts.js +7 -1
  167. package/dist/tools/builtins/sandbox/common.js +2 -0
  168. package/dist/tools/pipeline.d.ts +2 -1
  169. package/dist/tools/pipeline.js +7 -2
  170. package/package.json +4 -3
  171. package/src/migrations/0238_extension_usage.sql +40 -0
  172. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -0,0 +1,146 @@
1
+ import type { ExtensionUsageCounters } from "./usage.js";
2
+ /**
3
+ * The isolated host's metrics (isolation capacity spec 2026-12-04, §7; plan task 1.2c), on the
4
+ * kernel meter (`capybara.kernel`, exported by the OpenTelemetry SDK `capybara start` configures:
5
+ * OTLP or the SDK's Prometheus listener, never a kernel route). The SDK's Prometheus exporter
6
+ * replaces `.` with `_` and appends `_total` to counters, but never adds a unit suffix, so the
7
+ * histogram and gauge names carry their unit themselves: `capybara.isolation.queue_seconds` is
8
+ * scraped as `capybara_isolation_queue_seconds`, the counter `capybara.isolation.lane_starts` as
9
+ * `capybara_isolation_lane_starts_total`, exactly the §7 names (a test serializes them).
10
+ *
11
+ * Every series carries `plugin`, `revision`, `lane_class`, `mode`, `role` and `org`. `org` is the
12
+ * org id only for the few largest orgs ({@link OrgLabels}); every other org is `other`, and work
13
+ * that belongs to no org (deployment mode, registration) is `none`. Metrics are per replica:
14
+ * sum the counters across replicas.
15
+ *
16
+ * Not defined yet, because the code they measure does not exist: the PostgreSQL multiplexer's
17
+ * `pg_backends`, `pg_wait_seconds` and `pg_cancelled_total` and the guard's
18
+ * `node_sandbox_bytes` (C3), and `credit_wait_seconds` (credit-framed streams, C4).
19
+ */
20
+ /** Today every serving lane is the `standard` floor; `stream` arrives with lane classes (C2). */
21
+ export type LaneClass = "standard" | "control";
22
+ export type LaneMode = "org" | "deployment" | "setupCheck" | "registration";
23
+ export type LaneState = "starting" | "warm" | "busy" | "draining";
24
+ /** `crash`: the start that replaces a serving lane whose sandbox exited unexpectedly. */
25
+ export type LaneStartReason = "demand" | "crash" | "registration" | "setup_check";
26
+ /**
27
+ * Why an initialized lane ended: `normal` (a planned close: registration or setup check done,
28
+ * room made for another lane, shutdown), `idle_reap`, `crash` (the sandbox exited unexpectedly)
29
+ * or `killed` (stopped by a revocation).
30
+ */
31
+ export type LaneExitReason = "normal" | "idle_reap" | "crash" | "killed";
32
+ /**
33
+ * Why a lane start failed before `initialize` returned: the guard refused the launch for lack of
34
+ * capacity (`engine_capacity`, not a crash and no backoff), the caller gave up (`cancelled`),
35
+ * `initialize` timed out or was refused, the sandbox exited during start, or anything else.
36
+ */
37
+ export type LaneStartFailure = "engine_capacity" | "cancelled" | "timeout" | "refused" | "exited" | "error";
38
+ /**
39
+ * Why isolated work was refused as `overloaded`: a call before it reached a lane (`queue_full`,
40
+ * `deadline`, `call_limit`, `preflight_limit`, `crash_backoff`), or a lane's broker callback
41
+ * (`callback_budget`: the lane's request ingress budget was spent; `callback_limit`: too many
42
+ * callbacks in flight on the lane or the extension).
43
+ */
44
+ export type RejectionReason = "queue_full" | "deadline" | "call_limit" | "preflight_limit" | "crash_backoff" | "callback_budget" | "callback_limit";
45
+ export type StreamKind = "net" | "storage" | "models" | "upload";
46
+ export interface CallLabels {
47
+ laneClass: LaneClass;
48
+ mode: LaneMode;
49
+ role: string;
50
+ orgId: string | undefined;
51
+ }
52
+ /** One lane as the gauges see it. */
53
+ export interface LaneSnapshot extends CallLabels {
54
+ state: LaneState;
55
+ /** Calls in flight on the lane. */
56
+ calls: number;
57
+ /** Calls the lane admits at once. */
58
+ capacity: number;
59
+ }
60
+ type LaneSource = () => Iterable<LaneSnapshot>;
61
+ type LagSource = () => number | undefined;
62
+ /** Reports the grant epoch's age on this replica until the returned function is called. */
63
+ export declare function observeGrantEpochLag(source: LagSource): () => void;
64
+ type OrgLabeler = (orgId: string | undefined) => string;
65
+ /** A short, bounded revision label: the archive digest prefix, or `local` for a source tree. */
66
+ export declare function revisionLabel(revision: string): string;
67
+ /**
68
+ * The org ids that get their own label: at least `minMembers` members, the largest `maxOrgs` of
69
+ * them (ties broken by id so every replica picks the same set). Never more than `maxOrgs`.
70
+ */
71
+ export declare function pickLabelledOrgs(counts: readonly {
72
+ orgId: string;
73
+ members: number;
74
+ }[], minMembers: number, maxOrgs: number): Set<string>;
75
+ export declare const ORG_LABEL_REFRESH_MS: number;
76
+ /**
77
+ * Which orgs get their own `org` label, refreshed lazily (at most every 5 minutes, in the
78
+ * background, by the first label lookup after that) from the member counts. Replica-local and
79
+ * advisory: until the first read completes every org is `other`.
80
+ */
81
+ export declare class OrgLabels {
82
+ private readonly options;
83
+ private labelled;
84
+ private readAt;
85
+ private reading;
86
+ /** The read runs in the context the labels were built in, not in the calling request's. */
87
+ private readonly inOwnContext;
88
+ constructor(options: {
89
+ /** Member counts of orgs with at least `minMembers`, at most `maxOrgs` rows, largest first. */
90
+ read: (minMembers: number, maxOrgs: number) => Promise<{
91
+ orgId: string;
92
+ members: number;
93
+ }[]>;
94
+ limits: () => {
95
+ minMembers: number;
96
+ maxOrgs: number;
97
+ };
98
+ onError?: (err: unknown) => void;
99
+ now?: () => number;
100
+ });
101
+ label: (orgId: string | undefined) => string;
102
+ /** The current labelled set (tests and diagnostics). */
103
+ current(): ReadonlySet<string>;
104
+ refresh(): Promise<void>;
105
+ private refreshIfStale;
106
+ private now;
107
+ }
108
+ /** The broker callback family of an RPC method: `broker.kv.get` is `kv`. */
109
+ export declare function callbackFamily(method: string): string;
110
+ /**
111
+ * What one isolated revision reports: metrics labelled with its plugin and revision, and the usage
112
+ * counters of {@link ExtensionUsageCounters}. One per revision; the lanes, the broker and the
113
+ * callback adapters all report through it.
114
+ */
115
+ export declare class IsolationObserver {
116
+ readonly plugin: string;
117
+ private readonly org;
118
+ private readonly usage?;
119
+ readonly revisionLabel: string;
120
+ constructor(plugin: string, revision: string, org: OrgLabeler, usage?: ExtensionUsageCounters | undefined);
121
+ private labels;
122
+ queued(call: CallLabels, seconds: number): void;
123
+ overhead(call: CallLabels, seconds: number, cold: boolean): void;
124
+ laneStarted(call: CallLabels, reason: LaneStartReason, seconds: number): void;
125
+ laneExited(call: CallLabels, reason: LaneExitReason): void;
126
+ laneStartFailed(call: CallLabels, reason: LaneStartFailure): void;
127
+ coldWait(call: CallLabels): void;
128
+ rejected(call: CallLabels, reason: RejectionReason): void;
129
+ streamOpened(call: CallLabels, kind: StreamKind): void;
130
+ streamClosed(call: CallLabels, kind: StreamKind): void;
131
+ streamFrame(call: CallLabels, kind: StreamKind): void;
132
+ /** An invocation dispatched to a lane (usage only; the latency metrics cover the rest). */
133
+ invoked(orgId: string | undefined): void;
134
+ callback(orgId: string | undefined, method: string): void;
135
+ /** Request body bytes sent through `ctx.net`. */
136
+ netBytesOut(orgId: string | undefined, bytes: number): void;
137
+ /** Response body bytes read back through `ctx.net`. */
138
+ netBytesIn(orgId: string | undefined, bytes: number): void;
139
+ busy(orgId: string | undefined, ms: number): void;
140
+ /** Adds this revision's lanes to the gauges until the returned function is called. */
141
+ observeLanes(source: LaneSource): () => void;
142
+ /** Registers a function that books busy time still running, before each usage flush. */
143
+ onCheckpoint(checkpoint: () => void): () => void;
144
+ private count;
145
+ }
146
+ export {};
@@ -0,0 +1,304 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { kernelMeter } from "../../infra/metrics/kernel-metrics.js";
3
+ const SECONDS_BUCKETS = [
4
+ 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30,
5
+ ];
6
+ function create(meter) {
7
+ const seconds = { unit: "s", advice: { explicitBucketBoundaries: SECONDS_BUCKETS } };
8
+ return {
9
+ queue: meter.createHistogram("capybara.isolation.queue_seconds", {
10
+ ...seconds,
11
+ description: "Time an isolated call waited for a serving lane, by fairness level",
12
+ }),
13
+ overhead: meter.createHistogram("capybara.isolation.call_overhead_seconds", {
14
+ ...seconds,
15
+ description: "Kernel-side time of an isolated call before its frame is sent to the lane (config, grant check, admission and lane start), warm or cold",
16
+ }),
17
+ laneStarts: meter.createCounter("capybara.isolation.lane_starts", {
18
+ unit: "{lane}",
19
+ description: "Isolated lanes started (until initialize returned), by reason",
20
+ }),
21
+ startSeconds: meter.createHistogram("capybara.isolation.lane_start_seconds", {
22
+ unit: "s",
23
+ advice: { explicitBucketBoundaries: [0.1, 0.25, 0.5, 1, 1.5, 2, 3, 5, 10, 15, 30] },
24
+ description: "Time from a lane start's admission to its initialize returning, by reason",
25
+ }),
26
+ laneExits: meter.createCounter("capybara.isolation.lane_exits", {
27
+ unit: "{lane}",
28
+ description: "Initialized isolated lanes that ended, by reason (normal, idle_reap, crash, killed)",
29
+ }),
30
+ startFailures: meter.createCounter("capybara.isolation.lane_start_failures", {
31
+ unit: "{lane}",
32
+ description: "Isolated lane starts that failed before initialize returned, by reason",
33
+ }),
34
+ coldWait: meter.createCounter("capybara.isolation.cold_wait", {
35
+ unit: "{call}",
36
+ description: "Isolated calls that waited on a lane start",
37
+ }),
38
+ rejections: meter.createCounter("capybara.isolation.rejections", {
39
+ unit: "{call}",
40
+ description: "Isolated calls refused as overloaded before they reached a lane, and broker callbacks refused by a lane's budget or in-flight limit, by reason",
41
+ }),
42
+ streams: meter.createUpDownCounter("capybara.isolation.streams", {
43
+ unit: "{stream}",
44
+ description: "Open broker streams (net, storage, model result reads and uploads)",
45
+ }),
46
+ streamFrames: meter.createCounter("capybara.isolation.stream_frames", {
47
+ unit: "{frame}",
48
+ description: "Byte frames carried by broker streams",
49
+ }),
50
+ lanes: meter.createObservableGauge("capybara.isolation.lanes", {
51
+ unit: "{lane}",
52
+ description: "Isolated lanes by state: starting, warm (idle), busy, draining",
53
+ }),
54
+ utilization: meter.createObservableGauge("capybara.isolation.lane_utilization", {
55
+ unit: "1",
56
+ description: "Calls in flight over the call capacity of the running lanes, per lane group",
57
+ }),
58
+ epochLag: meter.createObservableGauge("capybara.isolation.grant_epoch_lag_seconds", {
59
+ unit: "s",
60
+ description: "Age of the replica's last successful grant epoch read (absent until isolated work starts)",
61
+ }),
62
+ };
63
+ }
64
+ /**
65
+ * Per-process registry behind the observable gauges. Several kernel applications in one process
66
+ * (tests, the load harness) add their sources here and the gauges report their sums.
67
+ */
68
+ const laneSources = new Map();
69
+ const lagSources = new Set();
70
+ let state;
71
+ function instruments() {
72
+ const meter = kernelMeter();
73
+ if (state?.meter === meter)
74
+ return state.instruments;
75
+ state?.detach?.();
76
+ const created = create(meter);
77
+ const observe = (result) => {
78
+ const lanes = new Map();
79
+ const groups = new Map();
80
+ for (const [source, base] of laneSources) {
81
+ for (const lane of source()) {
82
+ const group = attributes(base.plugin, base.revision, lane, base.org);
83
+ const groupKey = JSON.stringify(group);
84
+ const byState = { ...group, state: lane.state };
85
+ const stateKey = JSON.stringify(byState);
86
+ const counted = lanes.get(stateKey) ?? { attributes: byState, value: 0 };
87
+ counted.value += 1;
88
+ lanes.set(stateKey, counted);
89
+ if (lane.state === "starting")
90
+ continue;
91
+ const total = groups.get(groupKey) ?? { attributes: group, calls: 0, capacity: 0 };
92
+ total.calls += lane.calls;
93
+ total.capacity += lane.capacity;
94
+ groups.set(groupKey, total);
95
+ }
96
+ }
97
+ for (const { attributes: labels, value } of lanes.values()) {
98
+ result.observe(created.lanes, value, labels);
99
+ }
100
+ for (const { attributes: labels, calls, capacity } of groups.values()) {
101
+ result.observe(created.utilization, capacity === 0 ? 0 : Math.min(1, calls / capacity), labels);
102
+ }
103
+ let lag;
104
+ for (const source of lagSources) {
105
+ const value = source();
106
+ if (value !== undefined)
107
+ lag = Math.max(lag ?? 0, value);
108
+ }
109
+ if (lag !== undefined)
110
+ result.observe(created.epochLag, lag);
111
+ };
112
+ const gauges = [created.lanes, created.utilization, created.epochLag];
113
+ meter.addBatchObservableCallback(observe, gauges);
114
+ state = {
115
+ meter,
116
+ instruments: created,
117
+ detach: () => meter.removeBatchObservableCallback(observe, gauges),
118
+ };
119
+ return created;
120
+ }
121
+ /** Reports the grant epoch's age on this replica until the returned function is called. */
122
+ export function observeGrantEpochLag(source) {
123
+ instruments();
124
+ lagSources.add(source);
125
+ return () => {
126
+ lagSources.delete(source);
127
+ };
128
+ }
129
+ function attributes(plugin, revision, labels, org) {
130
+ return {
131
+ plugin,
132
+ revision,
133
+ lane_class: labels.laneClass,
134
+ mode: labels.mode,
135
+ role: labels.role,
136
+ org: org(labels.orgId),
137
+ };
138
+ }
139
+ /** A short, bounded revision label: the archive digest prefix, or `local` for a source tree. */
140
+ export function revisionLabel(revision) {
141
+ return /^[a-f0-9]{64}$/.test(revision) ? revision.slice(0, 12) : "local";
142
+ }
143
+ /**
144
+ * The org ids that get their own label: at least `minMembers` members, the largest `maxOrgs` of
145
+ * them (ties broken by id so every replica picks the same set). Never more than `maxOrgs`.
146
+ */
147
+ export function pickLabelledOrgs(counts, minMembers, maxOrgs) {
148
+ return new Set(counts
149
+ .filter(({ members }) => members >= minMembers)
150
+ .sort((a, b) => b.members - a.members || (a.orgId < b.orgId ? -1 : a.orgId > b.orgId ? 1 : 0))
151
+ .slice(0, Math.max(0, maxOrgs))
152
+ .map(({ orgId }) => orgId));
153
+ }
154
+ export const ORG_LABEL_REFRESH_MS = 5 * 60_000;
155
+ /**
156
+ * Which orgs get their own `org` label, refreshed lazily (at most every 5 minutes, in the
157
+ * background, by the first label lookup after that) from the member counts. Replica-local and
158
+ * advisory: until the first read completes every org is `other`.
159
+ */
160
+ export class OrgLabels {
161
+ options;
162
+ labelled = new Set();
163
+ readAt = Number.NEGATIVE_INFINITY;
164
+ reading = false;
165
+ /** The read runs in the context the labels were built in, not in the calling request's. */
166
+ inOwnContext = AsyncLocalStorage.snapshot();
167
+ constructor(options) {
168
+ this.options = options;
169
+ }
170
+ label = (orgId) => {
171
+ if (orgId === undefined)
172
+ return "none";
173
+ this.refreshIfStale();
174
+ return this.labelled.has(orgId) ? orgId : "other";
175
+ };
176
+ /** The current labelled set (tests and diagnostics). */
177
+ current() {
178
+ return this.labelled;
179
+ }
180
+ async refresh() {
181
+ if (this.reading)
182
+ return;
183
+ this.reading = true;
184
+ this.readAt = this.now();
185
+ try {
186
+ const { minMembers, maxOrgs } = this.options.limits();
187
+ const counts = maxOrgs <= 0 ? [] : await this.options.read(minMembers, maxOrgs);
188
+ this.labelled = pickLabelledOrgs(counts, minMembers, maxOrgs);
189
+ }
190
+ catch (err) {
191
+ this.options.onError?.(err);
192
+ }
193
+ finally {
194
+ this.reading = false;
195
+ }
196
+ }
197
+ refreshIfStale() {
198
+ if (this.reading || this.now() - this.readAt < ORG_LABEL_REFRESH_MS)
199
+ return;
200
+ this.inOwnContext(() => void this.refresh());
201
+ }
202
+ now() {
203
+ return this.options.now?.() ?? performance.now();
204
+ }
205
+ }
206
+ /** The broker callback family of an RPC method: `broker.kv.get` is `kv`. */
207
+ export function callbackFamily(method) {
208
+ const name = method.startsWith("broker.") ? method.slice("broker.".length) : method;
209
+ const family = name.split(".")[0] ?? "";
210
+ return /^[a-z]{1,16}$/.test(family) ? family : "other";
211
+ }
212
+ /**
213
+ * What one isolated revision reports: metrics labelled with its plugin and revision, and the usage
214
+ * counters of {@link ExtensionUsageCounters}. One per revision; the lanes, the broker and the
215
+ * callback adapters all report through it.
216
+ */
217
+ export class IsolationObserver {
218
+ plugin;
219
+ org;
220
+ usage;
221
+ revisionLabel;
222
+ constructor(plugin, revision, org, usage) {
223
+ this.plugin = plugin;
224
+ this.org = org;
225
+ this.usage = usage;
226
+ this.revisionLabel = revisionLabel(revision);
227
+ }
228
+ labels(call) {
229
+ return attributes(this.plugin, this.revisionLabel, call, this.org);
230
+ }
231
+ queued(call, seconds) {
232
+ instruments().queue.record(seconds, { ...this.labels(call), fairness_level: "org" });
233
+ }
234
+ overhead(call, seconds, cold) {
235
+ instruments().overhead.record(seconds, {
236
+ ...this.labels(call),
237
+ temperature: cold ? "cold" : "warm",
238
+ });
239
+ }
240
+ laneStarted(call, reason, seconds) {
241
+ const labels = { ...this.labels(call), reason };
242
+ instruments().laneStarts.add(1, labels);
243
+ instruments().startSeconds.record(seconds, labels);
244
+ }
245
+ laneExited(call, reason) {
246
+ instruments().laneExits.add(1, { ...this.labels(call), reason });
247
+ }
248
+ laneStartFailed(call, reason) {
249
+ instruments().startFailures.add(1, { ...this.labels(call), reason });
250
+ }
251
+ coldWait(call) {
252
+ instruments().coldWait.add(1, this.labels(call));
253
+ }
254
+ rejected(call, reason) {
255
+ instruments().rejections.add(1, { ...this.labels(call), reason });
256
+ }
257
+ streamOpened(call, kind) {
258
+ instruments().streams.add(1, { ...this.labels(call), kind });
259
+ }
260
+ streamClosed(call, kind) {
261
+ instruments().streams.add(-1, { ...this.labels(call), kind });
262
+ }
263
+ streamFrame(call, kind) {
264
+ instruments().streamFrames.add(1, { ...this.labels(call), kind });
265
+ this.count(call.orgId, "stream_frames", 1);
266
+ }
267
+ /** An invocation dispatched to a lane (usage only; the latency metrics cover the rest). */
268
+ invoked(orgId) {
269
+ this.count(orgId, "invocations", 1);
270
+ }
271
+ callback(orgId, method) {
272
+ this.count(orgId, `broker.${callbackFamily(method)}`, 1);
273
+ }
274
+ /** Request body bytes sent through `ctx.net`. */
275
+ netBytesOut(orgId, bytes) {
276
+ if (bytes > 0)
277
+ this.count(orgId, "net_bytes_out", bytes);
278
+ }
279
+ /** Response body bytes read back through `ctx.net`. */
280
+ netBytesIn(orgId, bytes) {
281
+ if (bytes > 0)
282
+ this.count(orgId, "net_bytes_in", bytes);
283
+ }
284
+ busy(orgId, ms) {
285
+ if (ms > 0)
286
+ this.count(orgId, "busy_lane_ms", Math.round(ms));
287
+ }
288
+ /** Adds this revision's lanes to the gauges until the returned function is called. */
289
+ observeLanes(source) {
290
+ instruments();
291
+ laneSources.set(source, { plugin: this.plugin, revision: this.revisionLabel, org: this.org });
292
+ return () => {
293
+ laneSources.delete(source);
294
+ };
295
+ }
296
+ /** Registers a function that books busy time still running, before each usage flush. */
297
+ onCheckpoint(checkpoint) {
298
+ return this.usage?.onCheckpoint(checkpoint) ?? (() => { });
299
+ }
300
+ count(orgId, counter, amount) {
301
+ if (orgId !== undefined)
302
+ this.usage?.add(orgId, this.plugin, counter, amount);
303
+ }
304
+ }
@@ -1,14 +1,18 @@
1
1
  import { type ExtensionManifest, type PluginExtensionSection } from "@capybara-hq/plugin-sdk";
2
2
  import { type ExtensionDbConnection } from "../../db/extension-db.js";
3
3
  import type { RlsMode } from "../../infra/database/scoped-dialect.js";
4
+ import { type IsolatedSectionGrant } from "./admission.js";
4
5
  import type { IsolatedInvocationGrant } from "./authorization.js";
5
6
  import { type BrokerOptions } from "./broker.js";
6
7
  import { type IsolatedExtensionQuota, IsolatedLanes, type ServingRole } from "./lanes.js";
8
+ import type { IsolationObserver } from "./metrics.js";
7
9
  import { type ExtensionSandboxOptions } from "./sandbox.js";
8
10
  interface RevisionOptions {
9
11
  manifest: ExtensionManifest;
10
12
  revision: string;
11
13
  section: PluginExtensionSection;
14
+ /** What the revision's grant admits beside the isolated server (its browser full access). */
15
+ grant?: IsolatedSectionGrant | undefined;
12
16
  sandbox: Omit<ExtensionSandboxOptions, "signal" | "stagingDir" | "sandboxId">;
13
17
  identity: ExtensionDbConnection;
14
18
  socketDir: string;
@@ -16,8 +20,10 @@ interface RevisionOptions {
16
20
  signal: AbortSignal;
17
21
  quota: IsolatedExtensionQuota;
18
22
  cleanupFault: () => void;
19
- onCrash?: ((retryAfterMs: number) => void) | undefined;
23
+ onCrash?: ((retryAfterMs: number, cause: "exited" | "start_failed") => void) | undefined;
20
24
  onLanes?: ((lanes: IsolatedLanes) => void) | undefined;
25
+ /** Metrics and usage counters of this revision. */
26
+ observer?: IsolationObserver | undefined;
21
27
  rls: RlsMode;
22
28
  roles: readonly ServingRole[];
23
29
  broker: Omit<BrokerOptions, "ctx" | "redactLog">;
@@ -12,7 +12,7 @@ import { packagePath } from "../../packages/tgz.js";
12
12
  import { assertIsolatedSection, assertIsolatedToolSchema, isolatedDeploymentSchema, } from "./admission.js";
13
13
  import { createIsolatedBroker } from "./broker.js";
14
14
  import { ISOLATED_MAX_CALLBACKS } from "./child-protocol.js";
15
- import { IsolatedLanes, } from "./lanes.js";
15
+ import { IsolatedLanes, IsolatedRejection, } from "./lanes.js";
16
16
  import { IsolatedRpcError } from "./rpc.js";
17
17
  import { SANDBOX_POSTGRES_DIR } from "./sandbox.js";
18
18
  const key = z.string().min(1).max(256);
@@ -148,7 +148,7 @@ async function verifyDatabase(options, socket) {
148
148
  }
149
149
  /** A manifest whose setup only installs reviewed kernel adapters and whose dispose closes its lanes. */
150
150
  export async function isolatedRevision(options) {
151
- assertIsolatedSection(options.section);
151
+ assertIsolatedSection(options.section, options.grant);
152
152
  const { identity, sandbox, section, manifest } = options;
153
153
  const socket = sandbox.postgresSocket;
154
154
  if (!identity.dedicated || !socket) {
@@ -192,9 +192,11 @@ export async function isolatedRevision(options) {
192
192
  quota: options.quota,
193
193
  cleanupFault: options.cleanupFault,
194
194
  ...(options.onCrash && { onCrash: options.onCrash }),
195
+ observer: options.observer,
195
196
  broker: createIsolatedBroker({
196
197
  ...options.broker,
197
198
  ctx,
199
+ observer: options.observer,
198
200
  redactLog(message, effectiveConfig) {
199
201
  const secrets = [
200
202
  ...databaseSecrets,
@@ -216,7 +218,7 @@ export async function isolatedRevision(options) {
216
218
  });
217
219
  const descriptors = callbackList(await instance.register(), manifest.permissions?.tools ?? []);
218
220
  for (const descriptor of descriptors) {
219
- await bind(ctx, instance, descriptor, options.effective, options.authorize, options.roles, options.quota);
221
+ await bind(ctx, instance, descriptor, options.effective, options.authorize, options.roles, options.quota, options.observer);
220
222
  }
221
223
  },
222
224
  async dispose() {
@@ -228,7 +230,7 @@ function serializable(value) {
228
230
  const { signal: _, config: _config, ...publicArgs } = value;
229
231
  return publicArgs;
230
232
  }
231
- async function bind(ctx, lanes, descriptor, effective, authorize, roles, quota) {
233
+ async function bind(ctx, lanes, descriptor, effective, authorize, roles, quota, observer) {
232
234
  const requested = descriptor.kind === "queue"
233
235
  ? "worker"
234
236
  : descriptor.kind.startsWith("ui.") || descriptor.kind === "setup.check"
@@ -252,8 +254,25 @@ async function bind(ctx, lanes, descriptor, effective, authorize, roles, quota)
252
254
  if (!role || !roles.includes(role) || meta.signal?.aborted) {
253
255
  throw new IsolatedRpcError("refused");
254
256
  }
257
+ const receivedAt = performance.now();
255
258
  // Reserve against the same callback quota before decrypted config or grant queries can queue.
256
- const releaseAdmission = quota.admitPreflight(orgId, role, setupCheck);
259
+ let releaseAdmission;
260
+ try {
261
+ releaseAdmission = quota.admitPreflight(orgId, role, setupCheck);
262
+ }
263
+ catch (error) {
264
+ if (error instanceof IsolatedRejection) {
265
+ observer?.rejected(setupCheck
266
+ ? { laneClass: "control", mode: "setupCheck", role: "none", orgId }
267
+ : {
268
+ laneClass: "standard",
269
+ mode: orgId === undefined ? "deployment" : "org",
270
+ role,
271
+ orgId,
272
+ }, error.reason);
273
+ }
274
+ throw error;
275
+ }
257
276
  let config;
258
277
  let grant;
259
278
  try {
@@ -281,6 +300,8 @@ async function bind(ctx, lanes, descriptor, effective, authorize, roles, quota)
281
300
  config,
282
301
  signal,
283
302
  toolCall,
303
+ receivedAt,
304
+ grantChecked: grant.checked === true,
284
305
  };
285
306
  return (await lanes.invoke(id, args, scope));
286
307
  }
@@ -26,6 +26,11 @@ export interface IsolatedRpcOptions {
26
26
  requestBudget?: RpcBudget;
27
27
  handle?: RpcHandler;
28
28
  onClose?: (error: IsolatedRpcError, cause: RpcCloseCause) => void;
29
+ /**
30
+ * An incoming request was answered `overloaded` without dispatch: too many in flight, or the
31
+ * request ingress budget was spent (for the rejection metrics).
32
+ */
33
+ onOverloaded?: (cause: "in_flight" | "budget") => void;
29
34
  }
30
35
  export interface RpcCallOptions {
31
36
  signal?: AbortSignal;
@@ -232,9 +232,14 @@ export class IsolatedRpcPeer {
232
232
  if (frame.id <= this.lastReceived)
233
233
  throw new IsolatedRpcError("invalid");
234
234
  this.lastReceived = frame.id;
235
- if (this.incoming.size >= this.limits.inFlight ||
236
- this.options.requestBudget?.take(bytes) === false) {
235
+ if (this.incoming.size >= this.limits.inFlight) {
237
236
  this.writeOrClose({ v: VERSION, t: "error", id: frame.id, code: "overloaded" });
237
+ this.options.onOverloaded?.("in_flight");
238
+ return;
239
+ }
240
+ if (this.options.requestBudget?.take(bytes) === false) {
241
+ this.writeOrClose({ v: VERSION, t: "error", id: frame.id, code: "overloaded" });
242
+ this.options.onOverloaded?.("budget");
238
243
  return;
239
244
  }
240
245
  void this.dispatch(frame);
@@ -35,5 +35,28 @@ export declare class ExtensionSandboxUnconfirmedCleanupError extends ExtensionSa
35
35
  }
36
36
  /** On a shared Engine, only a terminal state can establish that another replica is done. */
37
37
  export declare function sweepExtensionSandboxOrphans(engineUrl: string): Promise<void>;
38
+ /** A supervisor readiness check, in the order {@link probeExtensionSandboxChecks} runs them. */
39
+ export type SandboxCheck = "guard_reachability" | "engine_runtime" | "image" | "postgres_socket";
40
+ /** The outcome of {@link probeExtensionSandboxChecks}: ready, or the first check that failed. */
41
+ export type SandboxProbe = {
42
+ ok: true;
43
+ } | {
44
+ ok: false;
45
+ check: SandboxCheck;
46
+ message: string;
47
+ };
48
+ /**
49
+ * The supervisor's readiness as named checks (plan task 1.4j's isolation status), read-only and
50
+ * under the Engine deadline: the Engine guard answers (`guard_reachability`), the daemon provides
51
+ * the mandatory isolation (`engine_runtime`), the runtime image is a local Linux image without
52
+ * volumes (`image`), and the staged PostgreSQL socket and the socket directory are real local
53
+ * paths (`postgres_socket`). The same checks a sandbox start runs; never throws.
54
+ */
55
+ export declare function probeExtensionSandboxChecks(isolation: {
56
+ engineUrl: string;
57
+ image: string;
58
+ socketDir: string;
59
+ postgresSocket: string;
60
+ }): Promise<SandboxProbe>;
38
61
  /** Starts only after the sandbox runtime and an exclusive private attach channel are ready. */
39
62
  export declare function startExtensionSandbox(options: ExtensionSandboxOptions): Promise<ExtensionSandbox>;