@capybara-hq/kernel 0.1.0-rc.136 → 0.1.0-rc.138

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 (203) hide show
  1. package/dist/admin/audit-log.service.d.ts +96 -12
  2. package/dist/admin/audit-log.service.js +508 -44
  3. package/dist/admin/audit-targets.d.ts +17 -0
  4. package/dist/admin/audit-targets.js +84 -0
  5. package/dist/admin/audit.controller.d.ts +12 -9
  6. package/dist/admin/audit.controller.js +29 -8
  7. package/dist/admin/audit.schemas.d.ts +20 -4
  8. package/dist/admin/audit.schemas.js +42 -17
  9. package/dist/admin/extensions.controller.d.ts +5 -2
  10. package/dist/admin/extensions.controller.js +10 -1
  11. package/dist/admin/extensions.schemas.d.ts +4 -0
  12. package/dist/admin/extensions.schemas.js +9 -0
  13. package/dist/admin/health.service.d.ts +1 -1
  14. package/dist/admin/health.service.js +3 -3
  15. package/dist/agents/templates.js +3 -10
  16. package/dist/app.d.ts +3 -1
  17. package/dist/app.js +1 -0
  18. package/dist/automations/automations.service.js +4 -5
  19. package/dist/catalog/catalog-content.d.ts +6 -8
  20. package/dist/catalog/catalog-content.js +17 -22
  21. package/dist/catalog/catalog-items.d.ts +5 -10
  22. package/dist/catalog/catalog-items.js +27 -51
  23. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  24. package/dist/catalog/catalog-scope.service.js +109 -145
  25. package/dist/catalog/catalog.module.js +7 -4
  26. package/dist/catalog/catalog.service.d.ts +10 -4
  27. package/dist/catalog/catalog.service.js +52 -10
  28. package/dist/catalog/cli.js +17 -0
  29. package/dist/catalog/component-promotion.js +8 -4
  30. package/dist/catalog/component-scope.service.d.ts +3 -1
  31. package/dist/catalog/component-scope.service.js +101 -140
  32. package/dist/catalog/component-state.d.ts +10 -8
  33. package/dist/catalog/component-state.js +42 -30
  34. package/dist/catalog/dependency-edges.d.ts +25 -0
  35. package/dist/catalog/dependency-edges.js +125 -0
  36. package/dist/catalog/effect-work.d.ts +27 -0
  37. package/dist/catalog/effect-work.js +151 -0
  38. package/dist/catalog/jobs.d.ts +4 -1
  39. package/dist/catalog/jobs.js +14 -4
  40. package/dist/catalog/org-catalog.service.d.ts +5 -1
  41. package/dist/catalog/org-catalog.service.js +101 -106
  42. package/dist/catalog/org-intent.d.ts +45 -0
  43. package/dist/catalog/org-intent.js +205 -0
  44. package/dist/catalog/owned-items.d.ts +6 -2
  45. package/dist/catalog/owned-items.js +27 -32
  46. package/dist/catalog/ownership.d.ts +2 -3
  47. package/dist/catalog/ownership.js +10 -28
  48. package/dist/catalog/platform-components.d.ts +3 -1
  49. package/dist/catalog/platform-components.js +9 -1
  50. package/dist/catalog/plugin-import.d.ts +4 -2
  51. package/dist/catalog/plugin-import.js +22 -21
  52. package/dist/catalog/plugin-install.d.ts +19 -54
  53. package/dist/catalog/plugin-install.js +221 -271
  54. package/dist/catalog/plugin-upgrade.d.ts +10 -5
  55. package/dist/catalog/plugin-upgrade.js +80 -67
  56. package/dist/catalog/request-rules.js +20 -8
  57. package/dist/catalog/scope-orgs.js +2 -7
  58. package/dist/catalog/scope-state.d.ts +6 -6
  59. package/dist/catalog/scope-state.js +24 -43
  60. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  61. package/dist/catalog/scope-sync-workers.js +10 -26
  62. package/dist/catalog/scope-sync.d.ts +19 -116
  63. package/dist/catalog/scope-sync.js +228 -275
  64. package/dist/catalog/scope-writer.d.ts +87 -0
  65. package/dist/catalog/scope-writer.js +239 -0
  66. package/dist/catalog/template-connector-ensure.js +1 -1
  67. package/dist/catalog/unshare.js +9 -43
  68. package/dist/channels/connections.service.js +6 -6
  69. package/dist/channels/supervisor.js +3 -7
  70. package/dist/client/client-access.service.js +2 -12
  71. package/dist/config/schema.d.ts +6 -0
  72. package/dist/config/schema.js +32 -1
  73. package/dist/ctx/create-ctx.d.ts +2 -2
  74. package/dist/ctx/create-ctx.js +2 -60
  75. package/dist/ctx/guard-db.d.ts +6 -0
  76. package/dist/ctx/guard-db.js +55 -0
  77. package/dist/db/extension-handoff-schema.d.ts +1 -1
  78. package/dist/db/extension-handoff-schema.js +48 -10
  79. package/dist/db/extension-schema-transfer.js +5 -2
  80. package/dist/db/kernel-schema.d.ts +32 -6
  81. package/dist/device-access/host-services.d.ts +2 -2
  82. package/dist/device-access/host-services.js +5 -6
  83. package/dist/erasure/org-catalog.js +2 -2
  84. package/dist/erasure/org-rules.js +7 -0
  85. package/dist/extensions/admin-ops.d.ts +10 -6
  86. package/dist/extensions/admin-ops.js +53 -9
  87. package/dist/extensions/admin-view.d.ts +4 -1
  88. package/dist/extensions/admin-view.js +27 -14
  89. package/dist/extensions/bootstrap.d.ts +1 -1
  90. package/dist/extensions/bootstrap.js +6 -4
  91. package/dist/extensions/cli.js +1 -0
  92. package/dist/extensions/effective-config.js +1 -4
  93. package/dist/extensions/enabled.d.ts +183 -29
  94. package/dist/extensions/enabled.js +148 -62
  95. package/dist/extensions/host.d.ts +65 -45
  96. package/dist/extensions/host.js +446 -128
  97. package/dist/extensions/installs.d.ts +9 -0
  98. package/dist/extensions/installs.js +23 -0
  99. package/dist/extensions/isolated/admission.d.ts +10 -0
  100. package/dist/extensions/isolated/admission.js +206 -0
  101. package/dist/extensions/isolated/authorization.d.ts +45 -0
  102. package/dist/extensions/isolated/authorization.js +191 -0
  103. package/dist/extensions/isolated/broker.d.ts +15 -0
  104. package/dist/extensions/isolated/broker.js +471 -0
  105. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  106. package/dist/extensions/isolated/child-protocol.js +21 -0
  107. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  108. package/dist/extensions/isolated/child-registration.js +152 -0
  109. package/dist/extensions/isolated/child-session.d.ts +6 -0
  110. package/dist/extensions/isolated/child-session.js +343 -0
  111. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  112. package/dist/extensions/isolated/child-streams.js +142 -0
  113. package/dist/extensions/isolated/child.d.ts +1 -0
  114. package/dist/extensions/isolated/child.js +10 -0
  115. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  116. package/dist/extensions/isolated/configured-package.js +73 -0
  117. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  118. package/dist/extensions/isolated/engine-binds.js +82 -0
  119. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  120. package/dist/extensions/isolated/engine-policy.js +75 -0
  121. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  122. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  123. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  124. package/dist/extensions/isolated/engine-proxy.js +408 -0
  125. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  126. package/dist/extensions/isolated/engine-vaults.js +93 -0
  127. package/dist/extensions/isolated/lanes.d.ts +108 -0
  128. package/dist/extensions/isolated/lanes.js +726 -0
  129. package/dist/extensions/isolated/postgres-gate.d.ts +15 -0
  130. package/dist/extensions/isolated/postgres-gate.js +255 -0
  131. package/dist/extensions/isolated/revision.d.ts +32 -0
  132. package/dist/extensions/isolated/revision.js +359 -0
  133. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  134. package/dist/extensions/isolated/rpc-frame.js +193 -0
  135. package/dist/extensions/isolated/rpc.d.ts +66 -0
  136. package/dist/extensions/isolated/rpc.js +314 -0
  137. package/dist/extensions/isolated/sandbox.d.ts +39 -0
  138. package/dist/extensions/isolated/sandbox.js +356 -0
  139. package/dist/extensions/isolated/tier.d.ts +6 -0
  140. package/dist/extensions/isolated/tier.js +45 -0
  141. package/dist/extensions/ledger.d.ts +1 -1
  142. package/dist/extensions/lifecycle-topics.d.ts +2 -0
  143. package/dist/extensions/lifecycle-topics.js +2 -0
  144. package/dist/extensions/lifecycle.d.ts +3 -1
  145. package/dist/extensions/lifecycle.js +53 -5
  146. package/dist/extensions/locks.d.ts +2 -0
  147. package/dist/extensions/locks.js +7 -0
  148. package/dist/extensions/org-config.d.ts +17 -27
  149. package/dist/extensions/org-config.js +114 -129
  150. package/dist/extensions/permission-view.d.ts +6 -1
  151. package/dist/extensions/plugin-guides.d.ts +5 -10
  152. package/dist/extensions/plugin-guides.js +18 -37
  153. package/dist/extensions/plugin-icons.d.ts +3 -21
  154. package/dist/extensions/plugin-icons.js +9 -44
  155. package/dist/extensions/plugin-items.d.ts +10 -30
  156. package/dist/extensions/plugin-items.js +32 -73
  157. package/dist/extensions/source-intent.d.ts +14 -0
  158. package/dist/extensions/source-intent.js +77 -0
  159. package/dist/inbox/platform-inbox.service.js +16 -27
  160. package/dist/index.d.ts +2 -1
  161. package/dist/index.js +2 -1
  162. package/dist/infra/database/database.module.js +6 -1
  163. package/dist/infra/database/kernel-db.d.ts +3 -1
  164. package/dist/infra/database/kernel-db.js +4 -0
  165. package/dist/infra/events/kernel-events.d.ts +4 -0
  166. package/dist/infra/outbox/registry.d.ts +3 -36
  167. package/dist/infra/outbox/registry.js +4 -49
  168. package/dist/infra/paging/paged-read.d.ts +56 -0
  169. package/dist/infra/paging/paged-read.js +78 -0
  170. package/dist/infra/queue/queue-names.d.ts +1 -1
  171. package/dist/infra/queue/queue-names.js +1 -1
  172. package/dist/kernel.d.ts +3 -2
  173. package/dist/kernel.js +21 -2
  174. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  175. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  176. package/dist/lifecycle/tokens.d.ts +8 -0
  177. package/dist/lifecycle/tokens.js +2 -0
  178. package/dist/orgs/directory-sync.js +1 -4
  179. package/dist/orgs/org-lock.d.ts +3 -1
  180. package/dist/orgs/org-lock.js +3 -1
  181. package/dist/orgs/orgs.service.d.ts +3 -1
  182. package/dist/orgs/orgs.service.js +15 -8
  183. package/dist/overrides.d.ts +0 -3
  184. package/dist/overrides.js +0 -2
  185. package/dist/platform/ops/admin.ops.js +14 -3
  186. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  187. package/dist/platform/ops/org-plugins.ops.js +5 -2
  188. package/dist/platform/ops/orgs.ops.js +13 -3
  189. package/dist/platform/ops/plugins.ops.js +11 -10
  190. package/dist/setup/setup-checks.service.js +3 -2
  191. package/dist/skills/usable.js +41 -30
  192. package/dist/themes/theme-state.js +3 -3
  193. package/dist/tools/registry.d.ts +2 -2
  194. package/dist/tools/registry.js +7 -3
  195. package/package.json +2 -2
  196. package/src/migrations/0228_extension_org_switches.sql +56 -0
  197. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  198. package/src/migrations/0230_audit_filter_idx.sql +18 -0
  199. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  200. package/dist/catalog/install-status.d.ts +0 -6
  201. package/dist/catalog/install-status.js +0 -6
  202. package/dist/catalog/scope-jobs.d.ts +0 -59
  203. package/dist/catalog/scope-jobs.js +0 -78
@@ -0,0 +1,50 @@
1
+ export declare const VERSION = 1;
2
+ export declare const HEADER_BYTES = 4;
3
+ declare const messages: {
4
+ readonly closed: "Isolated RPC channel closed";
5
+ readonly invalid: "Invalid isolated RPC frame";
6
+ readonly overloaded: "Isolated RPC budget exhausted";
7
+ readonly deadline: "Isolated RPC deadline exceeded";
8
+ readonly cancelled: "Isolated RPC call cancelled";
9
+ readonly refused: "Isolated RPC call refused";
10
+ readonly failed: "Isolated RPC handler failed";
11
+ };
12
+ export type IsolatedRpcErrorCode = keyof typeof messages;
13
+ export declare class IsolatedRpcError extends Error {
14
+ readonly code: IsolatedRpcErrorCode;
15
+ constructor(code: IsolatedRpcErrorCode);
16
+ }
17
+ /** One pull response or granted write. Stream owners account for credit per handle. */
18
+ export declare class RpcByteChunk {
19
+ readonly metadata: unknown;
20
+ readonly bytes: Uint8Array;
21
+ constructor(metadata: unknown, bytes: Uint8Array);
22
+ }
23
+ type Message = {
24
+ v: typeof VERSION;
25
+ id: number;
26
+ };
27
+ export type RpcRequest = Message & {
28
+ t: "request";
29
+ method: string;
30
+ payload: unknown;
31
+ timeoutMs: number;
32
+ };
33
+ export type RpcFrame = RpcRequest | (Message & {
34
+ t: "reply";
35
+ payload: unknown;
36
+ }) | (Message & {
37
+ t: "error";
38
+ code: IsolatedRpcErrorCode;
39
+ }) | (Message & {
40
+ t: "cancel";
41
+ });
42
+ export declare const isId: (value: unknown) => value is number;
43
+ export declare const isMethod: (value: unknown) => value is string;
44
+ export declare function decodeFrame(body: Buffer, binary: boolean, timeoutMs: number): RpcFrame;
45
+ export declare function readFrameHeader(header: Buffer): {
46
+ length: number;
47
+ binary: boolean;
48
+ };
49
+ export declare function encodeFrame(frame: RpcFrame, maxBytes: number, remaining: number): Buffer;
50
+ export {};
@@ -0,0 +1,193 @@
1
+ export const VERSION = 1;
2
+ export const HEADER_BYTES = 4;
3
+ // Bit 31 marks a JSON length followed by JSON metadata and the raw binary tail.
4
+ const BINARY_FLAG = 0x8000_0000;
5
+ const MAX_METHOD_LENGTH = 64;
6
+ const MAX_JSON_DEPTH = 32;
7
+ const METHOD = /^[a-z][A-Za-z0-9]*(?:\.[a-z][A-Za-z0-9]*)*$/;
8
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
9
+ const messages = {
10
+ closed: "Isolated RPC channel closed",
11
+ invalid: "Invalid isolated RPC frame",
12
+ overloaded: "Isolated RPC budget exhausted",
13
+ deadline: "Isolated RPC deadline exceeded",
14
+ cancelled: "Isolated RPC call cancelled",
15
+ refused: "Isolated RPC call refused",
16
+ failed: "Isolated RPC handler failed",
17
+ };
18
+ export class IsolatedRpcError extends Error {
19
+ code;
20
+ constructor(code) {
21
+ super(messages[code]);
22
+ this.code = code;
23
+ this.name = "IsolatedRpcError";
24
+ }
25
+ }
26
+ /** One pull response or granted write. Stream owners account for credit per handle. */
27
+ export class RpcByteChunk {
28
+ metadata;
29
+ bytes;
30
+ constructor(metadata, bytes) {
31
+ this.metadata = metadata;
32
+ this.bytes = bytes;
33
+ }
34
+ }
35
+ export const isId = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
36
+ export const isMethod = (value) => typeof value === "string" && value.length <= MAX_METHOD_LENGTH && METHOD.test(value);
37
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
38
+ function validateDecoded(value, depth = 0) {
39
+ if (depth > MAX_JSON_DEPTH || (typeof value === "number" && !Number.isFinite(value))) {
40
+ throw new IsolatedRpcError("invalid");
41
+ }
42
+ if (value !== null && typeof value === "object") {
43
+ for (const child of Object.values(value))
44
+ validateDecoded(child, depth + 1);
45
+ }
46
+ }
47
+ export function decodeFrame(body, binary, timeoutMs) {
48
+ let json = body;
49
+ let binaryPayload;
50
+ if (binary) {
51
+ if (body.length <= HEADER_BYTES)
52
+ throw new IsolatedRpcError("invalid");
53
+ const end = body.readUInt32BE() + HEADER_BYTES;
54
+ if (end > body.length)
55
+ throw new IsolatedRpcError("invalid");
56
+ json = body.subarray(HEADER_BYTES, end);
57
+ binaryPayload = body.subarray(end);
58
+ }
59
+ const value = JSON.parse(utf8.decode(json));
60
+ validateDecoded(value);
61
+ if (!isRecord(value) || value.v !== VERSION || !isId(value.id)) {
62
+ throw new IsolatedRpcError("invalid");
63
+ }
64
+ const count = Object.keys(value).length;
65
+ const common = { v: VERSION, id: value.id };
66
+ const payload = binaryPayload ? new RpcByteChunk(value.payload, binaryPayload) : value.payload;
67
+ switch (value.t) {
68
+ case "request":
69
+ if (count === 6 &&
70
+ isMethod(value.method) &&
71
+ Object.hasOwn(value, "payload") &&
72
+ isId(value.timeoutMs) &&
73
+ value.timeoutMs <= timeoutMs) {
74
+ return {
75
+ ...common,
76
+ t: "request",
77
+ method: value.method,
78
+ payload,
79
+ timeoutMs: value.timeoutMs,
80
+ };
81
+ }
82
+ break;
83
+ case "reply":
84
+ if (count === 4 && Object.hasOwn(value, "payload")) {
85
+ return { ...common, t: "reply", payload };
86
+ }
87
+ break;
88
+ case "error":
89
+ if (!binary &&
90
+ count === 4 &&
91
+ typeof value.code === "string" &&
92
+ Object.hasOwn(messages, value.code)) {
93
+ return { ...common, t: "error", code: value.code };
94
+ }
95
+ break;
96
+ case "cancel":
97
+ if (!binary && count === 3)
98
+ return { ...common, t: "cancel" };
99
+ break;
100
+ }
101
+ throw new IsolatedRpcError("invalid");
102
+ }
103
+ function stringBytes(value, limit) {
104
+ if (value.length + 2 > limit)
105
+ throw new IsolatedRpcError("invalid");
106
+ return Buffer.byteLength(JSON.stringify(value));
107
+ }
108
+ /** Refuse deep, cyclic or oversized values before producing a frame-sized string. */
109
+ function jsonBytes(value, limit, depth = 0) {
110
+ if (depth > MAX_JSON_DEPTH || limit < 1)
111
+ throw new IsolatedRpcError("invalid");
112
+ if (value === null || value === undefined)
113
+ return 4;
114
+ switch (typeof value) {
115
+ case "string":
116
+ return stringBytes(value, limit);
117
+ case "boolean":
118
+ return value ? 4 : 5;
119
+ case "number":
120
+ if (!Number.isFinite(value))
121
+ throw new IsolatedRpcError("invalid");
122
+ return String(value).length;
123
+ case "object": {
124
+ let bytes = 2;
125
+ if (Array.isArray(value)) {
126
+ if (value.length > limit)
127
+ throw new IsolatedRpcError("invalid");
128
+ if (Object.getPrototypeOf(value) !== Array.prototype || Object.hasOwn(value, "toJSON")) {
129
+ throw new IsolatedRpcError("invalid");
130
+ }
131
+ for (let index = 0; index < value.length; index++) {
132
+ if (index !== 0)
133
+ bytes++;
134
+ const property = Object.getOwnPropertyDescriptor(value, index);
135
+ if (property && !Object.hasOwn(property, "value"))
136
+ throw new IsolatedRpcError("invalid");
137
+ bytes += jsonBytes(property?.value, limit - bytes, depth + 1);
138
+ }
139
+ return bytes;
140
+ }
141
+ const prototype = Object.getPrototypeOf(value);
142
+ if (prototype !== null && prototype !== Object.prototype)
143
+ throw new IsolatedRpcError("invalid");
144
+ if (Object.hasOwn(value, "toJSON"))
145
+ throw new IsolatedRpcError("invalid");
146
+ for (const key of Object.keys(value)) {
147
+ const property = Object.getOwnPropertyDescriptor(value, key);
148
+ if (!property || !Object.hasOwn(property, "value"))
149
+ throw new IsolatedRpcError("invalid");
150
+ if (property.value === undefined)
151
+ continue;
152
+ if (bytes !== 2)
153
+ bytes++;
154
+ bytes += stringBytes(key, limit - bytes) + 1;
155
+ bytes += jsonBytes(property.value, limit - bytes, depth + 1);
156
+ }
157
+ return bytes;
158
+ }
159
+ default:
160
+ throw new IsolatedRpcError("invalid");
161
+ }
162
+ }
163
+ export function readFrameHeader(header) {
164
+ const encoded = header.readUInt32BE();
165
+ const binary = encoded >= BINARY_FLAG;
166
+ return { length: binary ? encoded - BINARY_FLAG : encoded, binary };
167
+ }
168
+ export function encodeFrame(frame, maxBytes, remaining) {
169
+ const binary = "payload" in frame && frame.payload instanceof RpcByteChunk ? frame.payload : undefined;
170
+ if (binary && !(binary.bytes instanceof Uint8Array))
171
+ throw new IsolatedRpcError("invalid");
172
+ const frameForJson = binary ? { ...frame, payload: binary.metadata ?? null } : frame;
173
+ const binaryBytes = binary ? HEADER_BYTES + binary.bytes.byteLength : 0;
174
+ if (jsonBytes(frameForJson, maxBytes - binaryBytes) + binaryBytes > maxBytes) {
175
+ throw new IsolatedRpcError("invalid");
176
+ }
177
+ const json = JSON.stringify(frameForJson);
178
+ const jsonLength = Buffer.byteLength(json);
179
+ const length = jsonLength + binaryBytes;
180
+ if (length > maxBytes)
181
+ throw new IsolatedRpcError("invalid");
182
+ if (length > remaining)
183
+ throw new IsolatedRpcError("overloaded");
184
+ const bytes = Buffer.allocUnsafe(HEADER_BYTES + length);
185
+ bytes.writeUInt32BE(length + (binary ? BINARY_FLAG : 0), 0);
186
+ const jsonStart = binary ? HEADER_BYTES * 2 : HEADER_BYTES;
187
+ if (binary)
188
+ bytes.writeUInt32BE(jsonLength, HEADER_BYTES);
189
+ bytes.write(json, jsonStart, jsonLength, "utf8");
190
+ if (binary)
191
+ bytes.set(binary.bytes, jsonStart + jsonLength);
192
+ return bytes;
193
+ }
@@ -0,0 +1,66 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { IsolatedRpcError } from "./rpc-frame.js";
3
+ export { IsolatedRpcError, type IsolatedRpcErrorCode, RpcByteChunk } from "./rpc-frame.js";
4
+ export interface RpcBudget {
5
+ /** Charge a frame before allocating its body or dispatching its method. */
6
+ take(bytes: number): boolean;
7
+ retryAfter?(bytes: number): number;
8
+ }
9
+ /** Bound the number and size of frames admitted over time. */
10
+ export declare function createRpcBudget({ framesPerSecond, bytesPerSecond, now, }?: {
11
+ framesPerSecond?: number;
12
+ bytesPerSecond?: number;
13
+ now?: () => number;
14
+ }): RpcBudget;
15
+ export interface RpcLimits {
16
+ frameBytes: number;
17
+ inFlight: number;
18
+ timeoutMs: number;
19
+ writeBytes: number;
20
+ }
21
+ export type RpcHandler = (method: string, payload: unknown, signal: AbortSignal) => unknown | Promise<unknown>;
22
+ type RpcCloseCause = "transport" | "supervisor" | "grace" | "protocol" | "pressure";
23
+ export interface IsolatedRpcOptions {
24
+ limits?: Partial<RpcLimits>;
25
+ budget?: RpcBudget;
26
+ requestBudget?: RpcBudget;
27
+ handle?: RpcHandler;
28
+ onClose?: (error: IsolatedRpcError, cause: RpcCloseCause) => void;
29
+ }
30
+ export interface RpcCallOptions {
31
+ signal?: AbortSignal;
32
+ timeoutMs?: number;
33
+ /** Keep the call pending through cancellation until its handler exits or this grace expires. */
34
+ cancelGraceMs?: number;
35
+ }
36
+ /** One authenticated supervisor pipe. The caller owns higher-level identity and method authority. */
37
+ export declare class IsolatedRpcPeer {
38
+ private readonly input;
39
+ private readonly output;
40
+ private readonly options;
41
+ private readonly limits;
42
+ private readonly budget;
43
+ private readonly outgoing;
44
+ private readonly incoming;
45
+ private readonly header;
46
+ private headerLength;
47
+ private body;
48
+ private bodyLength;
49
+ private bodyIsBinary;
50
+ private lastSent;
51
+ private lastReceived;
52
+ private failure?;
53
+ private readTimer?;
54
+ constructor(input: Readable, output: Writable, options?: IsolatedRpcOptions);
55
+ get closed(): boolean;
56
+ call(method: string, payload: unknown, { signal, timeoutMs, cancelGraceMs }?: RpcCallOptions): Promise<unknown>;
57
+ close(error?: IsolatedRpcError): void;
58
+ private terminate;
59
+ private takeOutgoing;
60
+ private cancelOutgoing;
61
+ private read;
62
+ private receive;
63
+ private dispatch;
64
+ private writeOrClose;
65
+ private write;
66
+ }
@@ -0,0 +1,314 @@
1
+ import { decodeFrame, encodeFrame, HEADER_BYTES, IsolatedRpcError, isId, isMethod, readFrameHeader, VERSION, } from "./rpc-frame.js";
2
+ export { IsolatedRpcError, RpcByteChunk } from "./rpc-frame.js";
3
+ /** Bound the number and size of frames admitted over time. */
4
+ export function createRpcBudget({ framesPerSecond = 512, bytesPerSecond = 4 * 1024 * 1024, now = () => performance.now(), } = {}) {
5
+ if (!isId(framesPerSecond) || !isId(bytesPerSecond))
6
+ throw new IsolatedRpcError("invalid");
7
+ let frames = framesPerSecond;
8
+ let bytes = bytesPerSecond;
9
+ let updated = now();
10
+ return {
11
+ retryAfter(size) {
12
+ if (size > bytesPerSecond)
13
+ return Infinity;
14
+ return Math.max(1, Math.ceil(Math.max((1 - frames) / framesPerSecond, (size - bytes) / bytesPerSecond) * 1_000));
15
+ },
16
+ take(size) {
17
+ const current = now();
18
+ const elapsed = Math.max(0, current - updated) / 1_000;
19
+ frames = Math.min(framesPerSecond, frames + elapsed * framesPerSecond);
20
+ bytes = Math.min(bytesPerSecond, bytes + elapsed * bytesPerSecond);
21
+ updated = current;
22
+ if (frames < 1 || bytes < size)
23
+ return false;
24
+ frames--;
25
+ bytes -= size;
26
+ return true;
27
+ },
28
+ };
29
+ }
30
+ const DEFAULTS = {
31
+ frameBytes: 256 * 1024,
32
+ inFlight: 32,
33
+ timeoutMs: 60_000,
34
+ writeBytes: 1024 * 1024,
35
+ };
36
+ /** One authenticated supervisor pipe. The caller owns higher-level identity and method authority. */
37
+ export class IsolatedRpcPeer {
38
+ input;
39
+ output;
40
+ options;
41
+ limits;
42
+ budget;
43
+ outgoing = new Map();
44
+ incoming = new Map();
45
+ header = Buffer.alloc(HEADER_BYTES);
46
+ headerLength = 0;
47
+ body;
48
+ bodyLength = 0;
49
+ bodyIsBinary = false;
50
+ lastSent = 0;
51
+ lastReceived = 0;
52
+ failure;
53
+ readTimer;
54
+ constructor(input, output, options = {}) {
55
+ this.input = input;
56
+ this.output = output;
57
+ this.options = options;
58
+ this.limits = { ...DEFAULTS, ...options.limits };
59
+ for (const key of Object.keys(DEFAULTS)) {
60
+ if (!isId(this.limits[key]) || this.limits[key] > DEFAULTS[key]) {
61
+ throw new IsolatedRpcError("invalid");
62
+ }
63
+ }
64
+ this.budget = options.budget ?? createRpcBudget();
65
+ input.on("data", (bytes) => this.read(bytes));
66
+ const disconnected = () => this.terminate(new IsolatedRpcError("closed"), "transport");
67
+ input.on("end", disconnected);
68
+ input.on("close", disconnected);
69
+ input.on("error", disconnected);
70
+ output.on("finish", disconnected);
71
+ output.on("close", disconnected);
72
+ output.on("error", disconnected);
73
+ if (input.destroyed || input.readableEnded || output.destroyed || output.writableEnded) {
74
+ disconnected();
75
+ }
76
+ }
77
+ get closed() {
78
+ return this.failure !== undefined;
79
+ }
80
+ async call(method, payload, { signal, timeoutMs = this.limits.timeoutMs, cancelGraceMs } = {}) {
81
+ if (this.failure)
82
+ throw this.failure;
83
+ if (signal?.aborted)
84
+ throw new IsolatedRpcError("cancelled");
85
+ if (!isMethod(method) ||
86
+ !isId(timeoutMs) ||
87
+ timeoutMs > this.limits.timeoutMs ||
88
+ (cancelGraceMs !== undefined &&
89
+ (!isId(cancelGraceMs) || cancelGraceMs > this.limits.timeoutMs))) {
90
+ throw new IsolatedRpcError("invalid");
91
+ }
92
+ if (this.outgoing.size >= this.limits.inFlight)
93
+ throw new IsolatedRpcError("overloaded");
94
+ const id = ++this.lastSent;
95
+ if (!isId(id))
96
+ throw new IsolatedRpcError("overloaded");
97
+ return new Promise((resolve, reject) => {
98
+ const onAbort = () => this.cancelOutgoing(id, "cancelled", cancelGraceMs);
99
+ const timer = setTimeout(() => this.cancelOutgoing(id, "deadline", cancelGraceMs), timeoutMs);
100
+ const pending = {
101
+ resolve,
102
+ reject,
103
+ cleanup: () => {
104
+ clearTimeout(timer);
105
+ clearTimeout(pending.graceTimer);
106
+ signal?.removeEventListener("abort", onAbort);
107
+ },
108
+ };
109
+ this.outgoing.set(id, pending);
110
+ signal?.addEventListener("abort", onAbort, { once: true });
111
+ try {
112
+ this.write({ v: VERSION, t: "request", id, method, payload: payload ?? null, timeoutMs });
113
+ }
114
+ catch (error) {
115
+ this.takeOutgoing(id)?.reject(safeError(error, "invalid"));
116
+ }
117
+ });
118
+ }
119
+ close(error = new IsolatedRpcError("closed")) {
120
+ this.terminate(error, "supervisor");
121
+ }
122
+ terminate(error, cause) {
123
+ if (this.failure)
124
+ return;
125
+ clearTimeout(this.readTimer);
126
+ this.failure = error;
127
+ this.body = undefined;
128
+ for (const pending of this.outgoing.values()) {
129
+ pending.cleanup();
130
+ pending.reject(pending.cancellation ?? error);
131
+ }
132
+ this.outgoing.clear();
133
+ for (const ctrl of this.incoming.values())
134
+ ctrl.abort(error);
135
+ this.incoming.clear();
136
+ this.input.destroy();
137
+ this.output.destroy();
138
+ try {
139
+ void Promise.resolve(this.options.onClose?.(error, cause)).catch(() => { });
140
+ }
141
+ catch {
142
+ // A failed supervisor notification cannot reopen the closed channel.
143
+ }
144
+ }
145
+ takeOutgoing(id) {
146
+ const pending = this.outgoing.get(id);
147
+ if (pending) {
148
+ this.outgoing.delete(id);
149
+ pending.cleanup();
150
+ }
151
+ return pending;
152
+ }
153
+ cancelOutgoing(id, code, graceMs) {
154
+ const pending = this.outgoing.get(id);
155
+ if (!pending || pending.cancellation)
156
+ return;
157
+ const cancellation = new IsolatedRpcError(code);
158
+ if (graceMs === undefined) {
159
+ this.takeOutgoing(id);
160
+ pending.reject(cancellation);
161
+ }
162
+ else {
163
+ pending.cancellation = cancellation;
164
+ pending.cleanup();
165
+ pending.graceTimer = setTimeout(() => this.terminate(new IsolatedRpcError("closed"), "grace"), graceMs);
166
+ pending.graceTimer.unref();
167
+ }
168
+ this.writeOrClose({ v: VERSION, t: "cancel", id });
169
+ }
170
+ read(chunk, offset = 0) {
171
+ if (this.closed)
172
+ return;
173
+ if (!Buffer.isBuffer(chunk)) {
174
+ this.terminate(new IsolatedRpcError("invalid"), "protocol");
175
+ return;
176
+ }
177
+ try {
178
+ while (!this.closed && (offset < chunk.length || this.headerLength === HEADER_BYTES)) {
179
+ if (!this.body) {
180
+ const copied = chunk.copy(this.header, this.headerLength, offset, offset + HEADER_BYTES - this.headerLength);
181
+ this.headerLength += copied;
182
+ offset += copied;
183
+ if (this.headerLength < HEADER_BYTES)
184
+ return;
185
+ const { length, binary } = readFrameHeader(this.header);
186
+ this.bodyIsBinary = binary;
187
+ if (length === 0 || length > this.limits.frameBytes)
188
+ throw new IsolatedRpcError("invalid");
189
+ const size = length + HEADER_BYTES;
190
+ if (!this.budget.take(size)) {
191
+ const wait = this.budget.retryAfter?.(size) ?? Infinity;
192
+ if (!Number.isFinite(wait)) {
193
+ this.terminate(new IsolatedRpcError("overloaded"), "pressure");
194
+ return;
195
+ }
196
+ // Keep one unread chunk and let the stream apply backpressure to the attachment.
197
+ this.input.pause();
198
+ this.readTimer = setTimeout(() => {
199
+ this.readTimer = undefined;
200
+ this.read(chunk, offset);
201
+ if (!this.readTimer && !this.closed)
202
+ this.input.resume();
203
+ }, wait);
204
+ this.readTimer.unref();
205
+ return;
206
+ }
207
+ // Exposed byte views must have an exact-length backing buffer outside Node's slab.
208
+ this.body = this.bodyIsBinary
209
+ ? Buffer.allocUnsafeSlow(length)
210
+ : Buffer.allocUnsafe(length);
211
+ this.bodyLength = 0;
212
+ this.headerLength = 0;
213
+ }
214
+ const copied = chunk.copy(this.body, this.bodyLength, offset, offset + this.body.length - this.bodyLength);
215
+ this.bodyLength += copied;
216
+ offset += copied;
217
+ if (this.bodyLength === this.body.length) {
218
+ const bytes = this.body.length + HEADER_BYTES;
219
+ const frame = decodeFrame(this.body, this.bodyIsBinary, this.limits.timeoutMs);
220
+ this.body = undefined;
221
+ this.receive(frame, bytes);
222
+ }
223
+ }
224
+ }
225
+ catch (error) {
226
+ this.terminate(safeError(error, "invalid"), "protocol");
227
+ }
228
+ }
229
+ receive(frame, bytes) {
230
+ switch (frame.t) {
231
+ case "request":
232
+ if (frame.id <= this.lastReceived)
233
+ throw new IsolatedRpcError("invalid");
234
+ this.lastReceived = frame.id;
235
+ if (this.incoming.size >= this.limits.inFlight ||
236
+ this.options.requestBudget?.take(bytes) === false) {
237
+ this.writeOrClose({ v: VERSION, t: "error", id: frame.id, code: "overloaded" });
238
+ return;
239
+ }
240
+ void this.dispatch(frame);
241
+ return;
242
+ case "cancel":
243
+ if (frame.id > this.lastReceived)
244
+ throw new IsolatedRpcError("invalid");
245
+ this.incoming.get(frame.id)?.abort(new IsolatedRpcError("cancelled"));
246
+ return;
247
+ case "reply":
248
+ case "error": {
249
+ if (frame.id > this.lastSent)
250
+ throw new IsolatedRpcError("invalid");
251
+ // A reply to a cancelled outgoing request may already be in the pipe.
252
+ const pending = this.takeOutgoing(frame.id);
253
+ if (pending?.cancellation)
254
+ pending.reject(pending.cancellation);
255
+ else if (frame.t === "reply")
256
+ pending?.resolve(frame.payload);
257
+ else
258
+ pending?.reject(new IsolatedRpcError(frame.code));
259
+ }
260
+ }
261
+ }
262
+ async dispatch(frame) {
263
+ const ctrl = new AbortController();
264
+ const timer = setTimeout(() => ctrl.abort(new IsolatedRpcError("deadline")), frame.timeoutMs);
265
+ // Every terminal frame acknowledges that the handler has exited.
266
+ const clear = () => clearTimeout(timer);
267
+ ctrl.signal.addEventListener("abort", clear, { once: true });
268
+ this.incoming.set(frame.id, ctrl);
269
+ let terminal;
270
+ try {
271
+ if (!this.options.handle)
272
+ throw new IsolatedRpcError("refused");
273
+ const result = await this.options.handle(frame.method, frame.payload, ctrl.signal);
274
+ terminal = { v: VERSION, t: "reply", id: frame.id, payload: result ?? null };
275
+ }
276
+ catch (error) {
277
+ terminal = { v: VERSION, t: "error", id: frame.id, code: safeError(error, "failed").code };
278
+ }
279
+ finally {
280
+ clear();
281
+ this.incoming.delete(frame.id);
282
+ }
283
+ if (this.closed)
284
+ return;
285
+ if (ctrl.signal.aborted) {
286
+ terminal = {
287
+ v: VERSION,
288
+ t: "error",
289
+ id: frame.id,
290
+ code: safeError(ctrl.signal.reason, "cancelled").code,
291
+ };
292
+ }
293
+ this.writeOrClose(terminal);
294
+ }
295
+ writeOrClose(frame) {
296
+ try {
297
+ this.write(frame);
298
+ }
299
+ catch (error) {
300
+ this.terminate(safeError(error, "failed"), "pressure");
301
+ }
302
+ }
303
+ write(frame) {
304
+ if (this.failure)
305
+ throw this.failure;
306
+ const remaining = Math.min(this.limits.frameBytes, this.limits.writeBytes - this.output.writableLength - HEADER_BYTES);
307
+ if (remaining < 1)
308
+ throw new IsolatedRpcError("overloaded");
309
+ this.output.write(encodeFrame(frame, this.limits.frameBytes, remaining));
310
+ }
311
+ }
312
+ function safeError(error, fallback) {
313
+ return new IsolatedRpcError(error instanceof IsolatedRpcError ? error.code : fallback);
314
+ }
@@ -0,0 +1,39 @@
1
+ import { type Readable, type Writable } from "node:stream";
2
+ export { SANDBOX_POSTGRES_DIR } from "./engine-policy.js";
3
+ export interface ExtensionSandboxOptions {
4
+ /** The private restricted HTTP Engine API proxy origin. */
5
+ engineUrl: string;
6
+ /** The operator-reviewed, preloaded immutable image digest or image ID. */
7
+ image: string;
8
+ /** The verified package tree at the same absolute path on the daemon host. */
9
+ packageRoot: string;
10
+ stagingDir: string;
11
+ sandboxId: string;
12
+ /** Omit on metadata and read-only setup-check lanes. */
13
+ postgresSocket?: string;
14
+ /** Cancels admission only. The supervisor owns the resulting sandbox lifetime. */
15
+ signal?: AbortSignal;
16
+ }
17
+ export interface ExtensionSandbox {
18
+ input: Writable;
19
+ output: Readable;
20
+ stderr: Readable;
21
+ /** Settles when the private transport ends. `close` acknowledges OCI cleanup. */
22
+ exited: Promise<void>;
23
+ close(): Promise<void>;
24
+ }
25
+ export declare class ExtensionSandboxError extends Error {
26
+ readonly name: string;
27
+ }
28
+ export declare class ExtensionSandboxCapacityError extends ExtensionSandboxError {
29
+ readonly name = "ExtensionSandboxCapacityError";
30
+ }
31
+ /** The daemon may have accepted create or start before its response arrived. */
32
+ export declare class ExtensionSandboxUnconfirmedCleanupError extends ExtensionSandboxError {
33
+ readonly retryRemove: () => Promise<void>;
34
+ constructor(retryRemove: () => Promise<void>);
35
+ }
36
+ /** On a shared Engine, only a terminal state can establish that another replica is done. */
37
+ export declare function sweepExtensionSandboxOrphans(engineUrl: string): Promise<void>;
38
+ /** Starts only after the sandbox runtime and an exclusive private attach channel are ready. */
39
+ export declare function startExtensionSandbox(options: ExtensionSandboxOptions): Promise<ExtensionSandbox>;