@capybara-hq/kernel 0.1.0-rc.137 → 0.1.0-rc.139

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 (101) hide show
  1. package/bootstrap.json +31 -31
  2. package/dist/admin/extensions.controller.d.ts +5 -2
  3. package/dist/admin/extensions.controller.js +10 -1
  4. package/dist/admin/extensions.schemas.d.ts +4 -0
  5. package/dist/admin/extensions.schemas.js +9 -0
  6. package/dist/admin/health.service.d.ts +1 -1
  7. package/dist/admin/health.service.js +3 -3
  8. package/dist/catalog/catalog-content.d.ts +5 -7
  9. package/dist/catalog/catalog-items.js +1 -1
  10. package/dist/catalog/catalog-scope.service.js +5 -5
  11. package/dist/catalog/catalog.module.js +5 -4
  12. package/dist/catalog/catalog.service.d.ts +7 -1
  13. package/dist/catalog/catalog.service.js +19 -2
  14. package/dist/catalog/effect-work.d.ts +27 -0
  15. package/dist/catalog/effect-work.js +151 -0
  16. package/dist/catalog/jobs.d.ts +4 -1
  17. package/dist/catalog/jobs.js +14 -4
  18. package/dist/catalog/org-catalog.service.d.ts +2 -0
  19. package/dist/catalog/org-catalog.service.js +68 -12
  20. package/dist/catalog/org-intent.d.ts +4 -2
  21. package/dist/catalog/org-intent.js +25 -4
  22. package/dist/catalog/owned-items.d.ts +5 -1
  23. package/dist/catalog/owned-items.js +18 -3
  24. package/dist/catalog/plugin-import.d.ts +4 -2
  25. package/dist/catalog/plugin-import.js +10 -5
  26. package/dist/catalog/plugin-install.d.ts +17 -51
  27. package/dist/catalog/plugin-install.js +209 -235
  28. package/dist/catalog/plugin-upgrade.d.ts +8 -3
  29. package/dist/catalog/plugin-upgrade.js +63 -34
  30. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  31. package/dist/catalog/scope-sync-workers.js +10 -26
  32. package/dist/catalog/scope-sync.d.ts +19 -114
  33. package/dist/catalog/scope-sync.js +220 -239
  34. package/dist/catalog/scope-writer.d.ts +10 -1
  35. package/dist/catalog/scope-writer.js +62 -4
  36. package/dist/catalog/template-connector-ensure.js +1 -1
  37. package/dist/catalog/unshare.js +1 -2
  38. package/dist/config/schema.d.ts +1 -1
  39. package/dist/config/schema.js +7 -4
  40. package/dist/db/kernel-schema.d.ts +18 -17
  41. package/dist/erasure/org-catalog.js +2 -2
  42. package/dist/erasure/org-rules.js +2 -2
  43. package/dist/extensions/admin-ops.d.ts +1 -1
  44. package/dist/extensions/admin-ops.js +1 -1
  45. package/dist/extensions/admin-view.d.ts +4 -1
  46. package/dist/extensions/admin-view.js +27 -11
  47. package/dist/extensions/bootstrap.d.ts +1 -1
  48. package/dist/extensions/bootstrap.js +2 -3
  49. package/dist/extensions/enabled.d.ts +159 -0
  50. package/dist/extensions/enabled.js +7 -0
  51. package/dist/extensions/host.d.ts +1 -0
  52. package/dist/extensions/host.js +5 -2
  53. package/dist/extensions/isolated/authorization.d.ts +8 -0
  54. package/dist/extensions/isolated/authorization.js +56 -11
  55. package/dist/extensions/isolated/broker.js +30 -11
  56. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  57. package/dist/extensions/isolated/engine-binds.js +82 -0
  58. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  59. package/dist/extensions/isolated/engine-policy.js +75 -0
  60. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  61. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  62. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  63. package/dist/extensions/isolated/engine-proxy.js +408 -0
  64. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  65. package/dist/extensions/isolated/engine-vaults.js +93 -0
  66. package/dist/extensions/isolated/lanes.d.ts +11 -3
  67. package/dist/extensions/isolated/lanes.js +43 -16
  68. package/dist/extensions/isolated/postgres-gate.d.ts +1 -0
  69. package/dist/extensions/isolated/postgres-gate.js +6 -6
  70. package/dist/extensions/isolated/revision.d.ts +1 -1
  71. package/dist/extensions/isolated/revision.js +3 -2
  72. package/dist/extensions/isolated/sandbox.d.ts +10 -6
  73. package/dist/extensions/isolated/sandbox.js +101 -117
  74. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  75. package/dist/extensions/lifecycle-topics.js +1 -0
  76. package/dist/extensions/lifecycle.js +23 -2
  77. package/dist/extensions/permission-view.d.ts +6 -1
  78. package/dist/inbox/platform-inbox.service.js +16 -27
  79. package/dist/infra/events/kernel-events.d.ts +4 -0
  80. package/dist/infra/outbox/registry.d.ts +3 -36
  81. package/dist/infra/outbox/registry.js +4 -49
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -1
  84. package/dist/orgs/org-lock.d.ts +3 -1
  85. package/dist/orgs/org-lock.js +3 -1
  86. package/dist/orgs/orgs.service.d.ts +3 -1
  87. package/dist/orgs/orgs.service.js +15 -8
  88. package/dist/overrides.d.ts +0 -3
  89. package/dist/overrides.js +0 -2
  90. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  91. package/dist/platform/ops/org-plugins.ops.js +5 -2
  92. package/dist/platform/ops/plugins.ops.js +11 -10
  93. package/dist/tools/registry.d.ts +1 -1
  94. package/dist/tools/registry.js +6 -2
  95. package/package.json +2 -2
  96. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  97. package/src/migrations/0232_contract_plugin_effect_schema.sql +49 -0
  98. package/dist/catalog/install-status.d.ts +0 -5
  99. package/dist/catalog/install-status.js +0 -5
  100. package/dist/catalog/scope-jobs.d.ts +0 -59
  101. package/dist/catalog/scope-jobs.js +0 -78
@@ -2,6 +2,7 @@ export interface PostgresGateOptions {
2
2
  /** A kernel-owned local directory at the same absolute path on the daemon host. */
3
3
  directory: string;
4
4
  upstreamSocket: string;
5
+ sandboxId?: string;
5
6
  login: string;
6
7
  database: string;
7
8
  signal?: AbortSignal;
@@ -1,5 +1,6 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { once } from "node:events";
2
- import { chmod, lstat, mkdtemp, realpath, rm } from "node:fs/promises";
3
+ import { chmod, lstat, realpath, rm } from "node:fs/promises";
3
4
  import { createConnection, createServer } from "node:net";
4
5
  import { basename, isAbsolute, join } from "node:path";
5
6
  const STARTUP_BYTES = 1024;
@@ -192,7 +193,7 @@ function forwardSession(client, options, closed) {
192
193
  }
193
194
  /** The child gets a socket that permits only a single startup principal and database. */
194
195
  export async function startPostgresGate(options) {
195
- let directory;
196
+ let socket;
196
197
  const sessions = new Set();
197
198
  const server = createServer((client) => {
198
199
  if (options.signal?.aborted || sessions.size >= MAX_CONNECTIONS) {
@@ -217,8 +218,8 @@ export async function startPostgresGate(options) {
217
218
  resolve();
218
219
  });
219
220
  await Promise.all([stopServer, ...Array.from(sessions, (stop) => stop())]);
220
- if (directory)
221
- await rm(directory, { recursive: true, force: true });
221
+ if (socket)
222
+ await rm(socket, { force: true });
222
223
  })();
223
224
  return stopping;
224
225
  };
@@ -237,8 +238,7 @@ export async function startPostgresGate(options) {
237
238
  Buffer.byteLength(options.database) > 63 ||
238
239
  !(await lstat(options.upstreamSocket)).isSocket())
239
240
  throw new Error("invalid PostgreSQL gate configuration");
240
- directory = await mkdtemp(join(await realpath(options.directory), ".pg-"));
241
- const socket = join(directory, name);
241
+ socket = join(await realpath(options.directory), `.pg-${options.sandboxId ?? randomUUID()}.${port}`);
242
242
  server.listen(socket);
243
243
  await once(server, "listening");
244
244
  server.on("error", abort);
@@ -9,7 +9,7 @@ interface RevisionOptions {
9
9
  manifest: ExtensionManifest;
10
10
  revision: string;
11
11
  section: PluginExtensionSection;
12
- sandbox: Omit<ExtensionSandboxOptions, "signal">;
12
+ sandbox: Omit<ExtensionSandboxOptions, "signal" | "stagingDir" | "sandboxId">;
13
13
  identity: ExtensionDbConnection;
14
14
  socketDir: string;
15
15
  runtimeUrl: string;
@@ -258,7 +258,8 @@ async function bind(ctx, lanes, descriptor, effective, authorize, roles, quota)
258
258
  let grant;
259
259
  try {
260
260
  config = meta.config;
261
- if (orgId !== undefined && !setupCheck) {
261
+ // Trusted dispatchers can supply the effective config, including an explicit undefined.
262
+ if (orgId !== undefined && !setupCheck && !Object.hasOwn(meta, "config")) {
262
263
  const resolved = await withOrgScope(orgId, () => effective(orgId));
263
264
  if (!resolved.ok || meta.signal?.aborted)
264
265
  throw new IsolatedRpcError("refused");
@@ -327,7 +328,7 @@ async function bind(ctx, lanes, descriptor, effective, authorize, roles, quota)
327
328
  case "hook.observe": {
328
329
  const observe = async (event, signal, config) => {
329
330
  const orgId = "orgId" in event && typeof event.orgId === "string" ? event.orgId : undefined;
330
- await send(id, [event], { orgId, signal, config: config?.config });
331
+ await send(id, [event], { orgId, signal, ...(config && { config: config.config }) });
331
332
  };
332
333
  ctx.hooks.on(descriptor.mount, observe, { mode: "observe" });
333
334
  break;
@@ -1,13 +1,14 @@
1
1
  import { type Readable, type Writable } from "node:stream";
2
- export declare const SANDBOX_PACKAGE_ROOT = "/app/extension";
3
- export declare const SANDBOX_POSTGRES_DIR = "/run/extension-postgres";
2
+ export { SANDBOX_POSTGRES_DIR } from "./engine-policy.js";
4
3
  export interface ExtensionSandboxOptions {
5
- /** A local Docker Engine Unix socket in the trusted control plane. */
6
- dockerSocket: string;
4
+ /** The private restricted HTTP Engine API proxy origin. */
5
+ engineUrl: string;
7
6
  /** The operator-reviewed, preloaded immutable image digest or image ID. */
8
7
  image: string;
9
8
  /** The verified package tree at the same absolute path on the daemon host. */
10
9
  packageRoot: string;
10
+ stagingDir: string;
11
+ sandboxId: string;
11
12
  /** Omit on metadata and read-only setup-check lanes. */
12
13
  postgresSocket?: string;
13
14
  /** Cancels admission only. The supervisor owns the resulting sandbox lifetime. */
@@ -22,7 +23,10 @@ export interface ExtensionSandbox {
22
23
  close(): Promise<void>;
23
24
  }
24
25
  export declare class ExtensionSandboxError extends Error {
25
- readonly name = "ExtensionSandboxError";
26
+ readonly name: string;
27
+ }
28
+ export declare class ExtensionSandboxCapacityError extends ExtensionSandboxError {
29
+ readonly name = "ExtensionSandboxCapacityError";
26
30
  }
27
31
  /** The daemon may have accepted create or start before its response arrived. */
28
32
  export declare class ExtensionSandboxUnconfirmedCleanupError extends ExtensionSandboxError {
@@ -30,6 +34,6 @@ export declare class ExtensionSandboxUnconfirmedCleanupError extends ExtensionSa
30
34
  constructor(retryRemove: () => Promise<void>);
31
35
  }
32
36
  /** On a shared Engine, only a terminal state can establish that another replica is done. */
33
- export declare function sweepExtensionSandboxOrphans(dockerSocket: string): Promise<void>;
37
+ export declare function sweepExtensionSandboxOrphans(engineUrl: string): Promise<void>;
34
38
  /** Starts only after the sandbox runtime and an exclusive private attach channel are ready. */
35
39
  export declare function startExtensionSandbox(options: ExtensionSandboxOptions): Promise<ExtensionSandbox>;
@@ -1,33 +1,26 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
2
  import { once } from "node:events";
3
- import { lstat, opendir, realpath } from "node:fs/promises";
3
+ import { lstat, opendir, readFile, realpath, rm, writeFile } from "node:fs/promises";
4
4
  import { request } from "node:http";
5
5
  import { basename, isAbsolute, join } from "node:path";
6
6
  import { PassThrough } from "node:stream";
7
7
  import { HOST_PROVIDED_PACKAGES } from "@capybara-hq/plugin-sdk";
8
- export const SANDBOX_PACKAGE_ROOT = "/app/extension";
9
- export const SANDBOX_POSTGRES_DIR = "/run/extension-postgres";
10
- const API = "/v1.44";
8
+ import { packPackageTgz } from "../../packages/tgz.js";
9
+ import { MAX_STAGED_ARCHIVE, MAX_STAGED_UNPACKED } from "./engine-binds.js";
10
+ import { ATTACH_QUERY, CONTAINER_ID, EXTENSION_ENGINE_API, EXTENSION_ENGINE_CAPACITY_CODE, EXTENSION_ENGINE_OWNER_HEADER, extensionEngineCapacityMessage, OWNER_ID, OWNER_LABEL, SANDBOX_LABEL, SHA256, } from "./engine-policy.js";
11
+ export { SANDBOX_POSTGRES_DIR } from "./engine-policy.js";
11
12
  const ENGINE_TIMEOUT_MS = 5_000;
12
13
  const MAX_ENGINE_RESPONSE = 256 * 1024;
13
14
  const MAX_ATTACH_FRAME = 1024 * 1024;
14
15
  const MAX_PACKAGE_PATHS = 16_384;
15
- const MEMORY_BYTES = 192 * 1024 * 1024;
16
- const NANO_CPUS = 500_000_000;
17
- const PROCESS_LIMIT = 32;
18
- const FD_LIMIT = 128;
19
- const SANDBOX_USER = "10001:10001";
20
- const SANDBOX_LABEL = "com.capybara.extension-sandbox";
21
- const OWNER_LABEL = "com.capybara.extension-sandbox.owner";
22
16
  const SANDBOX_OWNER = randomUUID();
23
- const OWNER_ID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
24
- const CONTAINER_ID = /^[a-f0-9]{64}$/;
25
- const SHA256 = /^sha256:[a-f0-9]{64}$/;
26
- const PINNED_IMAGE = /^(?:[a-z0-9][a-z0-9._:/-]*@)?sha256:[a-f0-9]{64}$/;
27
- const POSTGRES_SOCKET = /^\.s\.PGSQL\.([1-9][0-9]{0,4})$/;
17
+ const ENGINE_OWNER_SECRET = randomBytes(32).toString("hex");
28
18
  export class ExtensionSandboxError extends Error {
29
19
  name = "ExtensionSandboxError";
30
20
  }
21
+ export class ExtensionSandboxCapacityError extends ExtensionSandboxError {
22
+ name = "ExtensionSandboxCapacityError";
23
+ }
31
24
  /** The daemon may have accepted create or start before its response arrived. */
32
25
  export class ExtensionSandboxUnconfirmedCleanupError extends ExtensionSandboxError {
33
26
  retryRemove;
@@ -41,25 +34,40 @@ function deadline(signal) {
41
34
  return signal ? AbortSignal.any([signal, timeout]) : timeout;
42
35
  }
43
36
  class Engine {
44
- socketPath;
45
- constructor(socketPath) {
46
- this.socketPath = socketPath;
37
+ origin;
38
+ constructor(value) {
39
+ const url = new URL(value);
40
+ if (url.protocol !== "http:" ||
41
+ url.username ||
42
+ url.password ||
43
+ url.pathname !== "/" ||
44
+ url.search ||
45
+ url.hash)
46
+ throw new ExtensionSandboxError("Expected a private HTTP Engine proxy origin");
47
+ this.origin = url;
47
48
  }
48
49
  json(method, path, status, body, signal) {
49
50
  return new Promise((resolve, reject) => {
50
51
  const fail = () => reject(new ExtensionSandboxError("The isolated Docker daemon refused the request"));
51
52
  const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body));
52
- const req = request({
53
- socketPath: this.socketPath,
54
- path: `${API}${path}`,
53
+ const req = request(this.origin, {
54
+ path: `${EXTENSION_ENGINE_API}${path}`,
55
55
  method,
56
56
  agent: false,
57
57
  signal: deadline(signal),
58
- ...(payload && {
59
- headers: { "Content-Length": payload.length, "Content-Type": "application/json" },
60
- }),
58
+ headers: {
59
+ [EXTENSION_ENGINE_OWNER_HEADER]: ENGINE_OWNER_SECRET,
60
+ ...(payload && {
61
+ "Content-Length": payload.length,
62
+ "Content-Type": "application/json",
63
+ }),
64
+ },
61
65
  }, (res) => {
62
- if (!status.includes(res.statusCode ?? 0)) {
66
+ const capacity = res.statusCode === 503 &&
67
+ method === "POST" &&
68
+ path.startsWith("/containers/create?name=") &&
69
+ res.headers["content-type"] === "application/json";
70
+ if (!capacity && !status.includes(res.statusCode ?? 0)) {
63
71
  res.destroy();
64
72
  fail();
65
73
  return;
@@ -78,7 +86,19 @@ class Engine {
78
86
  });
79
87
  res.on("end", () => {
80
88
  try {
81
- resolve((length === 0 ? undefined : JSON.parse(Buffer.concat(chunks).toString())));
89
+ const reply = length === 0 ? undefined : JSON.parse(Buffer.concat(chunks).toString());
90
+ if (capacity) {
91
+ if (reply?.code === EXTENSION_ENGINE_CAPACITY_CODE &&
92
+ (reply.kind === "vaults" || reply.kind === "launches") &&
93
+ Number.isSafeInteger(reply.limit) &&
94
+ reply.limit > 0) {
95
+ reject(new ExtensionSandboxCapacityError(extensionEngineCapacityMessage(reply.kind, reply.limit)));
96
+ }
97
+ else
98
+ fail();
99
+ }
100
+ else
101
+ resolve(reply);
82
102
  }
83
103
  catch {
84
104
  fail();
@@ -95,11 +115,14 @@ class Engine {
95
115
  attach(id, signal) {
96
116
  return new Promise((resolve, reject) => {
97
117
  const fail = () => reject(new ExtensionSandboxError("The isolated Docker daemon refused the private transport"));
98
- const req = request({
99
- socketPath: this.socketPath,
118
+ const req = request(this.origin, {
100
119
  method: "POST",
101
- path: `${API}/containers/${id}/attach?stream=true&stdin=true&stdout=true&stderr=true`,
102
- headers: { Connection: "Upgrade", Upgrade: "tcp" },
120
+ path: `${EXTENSION_ENGINE_API}/containers/${id}/attach?${ATTACH_QUERY}`,
121
+ headers: {
122
+ [EXTENSION_ENGINE_OWNER_HEADER]: ENGINE_OWNER_SECRET,
123
+ Connection: "Upgrade",
124
+ Upgrade: "tcp",
125
+ },
103
126
  agent: false,
104
127
  signal: deadline(signal),
105
128
  });
@@ -123,8 +146,8 @@ class Engine {
123
146
  }
124
147
  }
125
148
  /** On a shared Engine, only a terminal state can establish that another replica is done. */
126
- export async function sweepExtensionSandboxOrphans(dockerSocket) {
127
- const engine = new Engine(await verifiedPath(dockerSocket, "socket"));
149
+ export async function sweepExtensionSandboxOrphans(engineUrl) {
150
+ const engine = new Engine(engineUrl);
128
151
  const signal = deadline();
129
152
  const filters = new URLSearchParams({
130
153
  all: "true",
@@ -181,20 +204,13 @@ async function verifiedPath(path, kind) {
181
204
  }
182
205
  throw new ExtensionSandboxError(`The isolated runtime requires a real local ${kind}`);
183
206
  }
184
- function bind(source, target) {
185
- return {
186
- Type: "bind",
187
- Source: source,
188
- Target: target,
189
- ReadOnly: true,
190
- BindOptions: { NonRecursive: true, Propagation: "rprivate" },
191
- };
192
- }
193
- /** A read-only bind still permits opening Unix sockets already present in the source tree. */
194
- async function assertPackageTree(root) {
207
+ /** Stage only ordinary package files. Host dependencies resolve from the runtime image. */
208
+ async function stagePackage(root, destination) {
195
209
  const trustedLinks = new Set(HOST_PROVIDED_PACKAGES.map((name) => join("node_modules", name)));
196
210
  const directories = [""];
211
+ const files = new Map();
197
212
  let paths = 0;
213
+ let size = 0;
198
214
  try {
199
215
  while (directories.length !== 0) {
200
216
  const directory = directories.pop();
@@ -204,71 +220,28 @@ async function assertPackageTree(root) {
204
220
  const path = join(directory, entry.name);
205
221
  if (entry.isDirectory())
206
222
  directories.push(path);
207
- else if (!entry.isFile() && !(entry.isSymbolicLink() && trustedLinks.has(path))) {
223
+ else if (entry.isFile()) {
224
+ const data = await readFile(join(root, path));
225
+ size += data.length;
226
+ if (size > MAX_STAGED_UNPACKED)
227
+ throw new Error("package too large");
228
+ files.set(path, data);
229
+ }
230
+ else if (!(entry.isSymbolicLink() && trustedLinks.has(path))) {
208
231
  throw new Error("special package file");
209
232
  }
210
233
  }
211
234
  }
235
+ const archive = await packPackageTgz(files);
236
+ if (archive.byteLength > MAX_STAGED_ARCHIVE)
237
+ throw new Error("package too large");
238
+ await writeFile(destination, archive, { flag: "wx", mode: 0o640 });
239
+ return createHash("sha256").update(archive).digest("hex");
212
240
  }
213
241
  catch {
214
242
  throw new ExtensionSandboxError("The isolated package tree must contain only reviewed package files");
215
243
  }
216
244
  }
217
- async function mounts(options) {
218
- const packageRoot = await verifiedPath(options.packageRoot, "directory");
219
- await assertPackageTree(packageRoot);
220
- const list = [bind(packageRoot, SANDBOX_PACKAGE_ROOT)];
221
- if (options.postgresSocket !== undefined) {
222
- const source = await verifiedPath(options.postgresSocket, "socket");
223
- const name = basename(source);
224
- const match = POSTGRES_SOCKET.exec(name);
225
- if (!match || Number(match[1]) > 65535)
226
- throw new ExtensionSandboxError("The isolated runtime requires a dedicated PostgreSQL socket");
227
- list.push(bind(source, `${SANDBOX_POSTGRES_DIR}/${name}`));
228
- }
229
- return list;
230
- }
231
- function containerOptions(image, fsMounts) {
232
- return {
233
- Image: image,
234
- User: SANDBOX_USER,
235
- Hostname: "extension",
236
- WorkingDir: SANDBOX_PACKAGE_ROOT,
237
- Entrypoint: ["/usr/local/bin/node", "/app/sandbox-entry.mjs"],
238
- Labels: { [SANDBOX_LABEL]: "1", [OWNER_LABEL]: SANDBOX_OWNER },
239
- Cmd: [],
240
- Env: [],
241
- Healthcheck: { Test: ["NONE"] },
242
- OpenStdin: true,
243
- StdinOnce: true,
244
- AttachStdin: true,
245
- AttachStdout: true,
246
- AttachStderr: true,
247
- Tty: false,
248
- HostConfig: {
249
- AutoRemove: true,
250
- NetworkMode: "none",
251
- IpcMode: "none",
252
- CgroupnsMode: "private",
253
- ReadonlyRootfs: true,
254
- Privileged: false,
255
- Init: false,
256
- CapDrop: ["ALL"],
257
- SecurityOpt: ["no-new-privileges=true", "seccomp=builtin"],
258
- Memory: MEMORY_BYTES,
259
- MemorySwap: MEMORY_BYTES,
260
- NanoCpus: NANO_CPUS,
261
- PidsLimit: PROCESS_LIMIT,
262
- Ulimits: [
263
- { Name: "nofile", Soft: FD_LIMIT, Hard: FD_LIMIT },
264
- { Name: "core", Soft: 0, Hard: 0 },
265
- ],
266
- LogConfig: { Type: "none" },
267
- Tmpfs: { "/tmp": "rw,noexec,nosuid,nodev,size=16777216,mode=1777" },
268
- Mounts: fsMounts,
269
- },
270
- };
271
- }
272
245
  /** Docker attach adds its own 8-byte stdout/stderr envelope around the private protocol. */
273
246
  async function demultiplex(channel, output, stderr, signal) {
274
247
  const header = Buffer.alloc(8);
@@ -306,25 +279,32 @@ async function demultiplex(channel, output, stderr, signal) {
306
279
  }
307
280
  /** Starts only after the sandbox runtime and an exclusive private attach channel are ready. */
308
281
  export async function startExtensionSandbox(options) {
309
- if (!PINNED_IMAGE.test(options.image))
282
+ if (!SHA256.test(options.image))
310
283
  throw new ExtensionSandboxError("The isolated runtime image must be pinned by SHA-256");
311
284
  if (options.signal?.aborted)
312
285
  throw new ExtensionSandboxError("Extension sandbox admission was cancelled");
313
- const socketPath = await verifiedPath(options.dockerSocket, "socket");
314
- const engine = new Engine(socketPath);
315
- const fsMounts = await mounts(options);
316
- const name = `capybara-extension-${randomUUID()}`;
317
- await checkEngine(engine, options.image, options.signal);
318
- let id = name;
286
+ const engine = new Engine(options.engineUrl);
287
+ if (!OWNER_ID.test(options.sandboxId))
288
+ throw new ExtensionSandboxError("Invalid isolated sandbox identity");
289
+ const name = `capybara-extension-${options.sandboxId}`;
290
+ const path = join(await verifiedPath(options.stagingDir, "directory"), `${name}.tgz`);
291
+ const port = options.postgresSocket &&
292
+ /^\.pg-[a-f0-9-]{36}\.([1-9][0-9]{0,4})$/.exec(basename(options.postgresSocket))?.[1];
293
+ if (options.postgresSocket &&
294
+ (!port ||
295
+ Number(port) > 65535 ||
296
+ options.postgresSocket !== join(options.stagingDir, `.pg-${options.sandboxId}.${port}`)))
297
+ throw new ExtensionSandboxError("Invalid isolated PostgreSQL staging socket");
298
+ const digest = await stagePackage(await verifiedPath(options.packageRoot, "directory"), path);
299
+ let launching = false;
319
300
  let channel;
320
301
  try {
321
- const created = await engine.json("POST", `/containers/create?name=${name}`, [201], containerOptions(options.image, fsMounts), options.signal);
302
+ await checkEngine(engine, options.image, options.signal);
303
+ launching = true;
304
+ const created = await engine.json("POST", `/containers/create?name=${name}`, [201], { digest, incarnation: SANDBOX_OWNER, ...(port && { postgresPort: port }) }, options.signal);
322
305
  if (!created?.Id || !CONTAINER_ID.test(created.Id))
323
306
  throw new ExtensionSandboxError("The Docker daemon did not create a valid sandbox");
324
- id = created.Id;
325
- if (created.Warnings?.length)
326
- throw new ExtensionSandboxError("The Docker daemon warned about the isolation or resource settings");
327
- channel = await engine.attach(id, options.signal);
307
+ channel = await engine.attach(created.Id, options.signal);
328
308
  const transport = channel;
329
309
  const output = new PassThrough();
330
310
  const stderr = new PassThrough();
@@ -336,7 +316,6 @@ export async function startExtensionSandbox(options) {
336
316
  output.end();
337
317
  stderr.end();
338
318
  });
339
- await engine.json("POST", `/containers/${id}/start`, [204], undefined, options.signal);
340
319
  let disconnected = false;
341
320
  let removal;
342
321
  return {
@@ -350,7 +329,7 @@ export async function startExtensionSandbox(options) {
350
329
  stop.abort();
351
330
  transport.destroy();
352
331
  }
353
- removal ??= engine.remove(id).catch((error) => {
332
+ removal ??= engine.remove(name).catch((error) => {
354
333
  // A transport disconnection does not confirm removal. Keep the same identity for retry.
355
334
  removal = undefined;
356
335
  throw error;
@@ -361,12 +340,17 @@ export async function startExtensionSandbox(options) {
361
340
  }
362
341
  catch (error) {
363
342
  channel?.destroy();
343
+ if (!launching || error instanceof ExtensionSandboxCapacityError)
344
+ throw error;
364
345
  try {
365
- await engine.remove(id);
346
+ await engine.remove(name);
366
347
  }
367
348
  catch {
368
- throw new ExtensionSandboxUnconfirmedCleanupError(() => engine.remove(id));
349
+ throw new ExtensionSandboxUnconfirmedCleanupError(() => engine.remove(name));
369
350
  }
370
351
  throw error;
371
352
  }
353
+ finally {
354
+ await rm(path, { force: true }).catch(() => undefined);
355
+ }
372
356
  }
@@ -16,4 +16,5 @@ export declare const STALE_RECONCILE_PERIODS = 3;
16
16
  * 插件此刻待配置时,下一次 reconcile 加载它。
17
17
  */
18
18
  export declare const PLUGIN_DEPLOYMENT_CONFIG_TOPIC = "plugin-deployment-config";
19
+ /** Revokes a direct grant or refreshes org grants when catalog eligibility may have changed. */
19
20
  export declare const ISOLATED_REVOKED_TOPIC = "plugins.isolated-revoked";
@@ -16,4 +16,5 @@ export const STALE_RECONCILE_PERIODS = 3;
16
16
  * 插件此刻待配置时,下一次 reconcile 加载它。
17
17
  */
18
18
  export const PLUGIN_DEPLOYMENT_CONFIG_TOPIC = "plugin-deployment-config";
19
+ /** Revokes a direct grant or refreshes org grants when catalog eligibility may have changed. */
19
20
  export const ISOLATED_REVOKED_TOPIC = "plugins.isolated-revoked";
@@ -78,9 +78,21 @@ let ExtensionLifecycle = class ExtensionLifecycle {
78
78
  this.host.revokeIsolatedInvocations(plugin === "?" ? {} : { plugin });
79
79
  this.trigger(`changed:${plugin}`);
80
80
  });
81
+ const refreshCatalogIntent = (orgId) => {
82
+ void this.host
83
+ .refreshIsolatedOrgIntent(orgId)
84
+ .catch((err) => this.log.warn("isolated extension catalog grant refresh failed", { orgId, err }));
85
+ };
81
86
  await on(ISOLATED_REVOKED_TOPIC, (payload) => {
82
- const { orgId, plugin } = (payload ?? {});
83
- if (typeof orgId !== "string" || (plugin !== undefined && typeof plugin !== "string"))
87
+ const { catalog, orgId, plugin, origin } = (payload ?? {});
88
+ if (orgId !== undefined && typeof orgId !== "string")
89
+ return;
90
+ if (catalog === true && plugin === undefined) {
91
+ if (origin !== this.status.replicaId)
92
+ refreshCatalogIntent(orgId);
93
+ return;
94
+ }
95
+ if (orgId === undefined || (plugin !== undefined && typeof plugin !== "string"))
84
96
  return;
85
97
  this.host.revokeIsolatedInvocations(plugin === undefined ? { orgId } : { orgId, plugin });
86
98
  });
@@ -90,9 +102,18 @@ let ExtensionLifecycle = class ExtensionLifecycle {
90
102
  };
91
103
  const removeOrg = this.events.on("org.deleted", ({ orgId }) => announce({ orgId }));
92
104
  const removePlugin = this.events.on("extension.org-disabled", announce);
105
+ const removeCatalog = this.events.on("catalog.org-intent-changed", ({ orgId }) => {
106
+ refreshCatalogIntent(orgId);
107
+ return this.bus.publish(ISOLATED_REVOKED_TOPIC, {
108
+ catalog: true,
109
+ orgId,
110
+ origin: this.status.replicaId,
111
+ });
112
+ });
93
113
  this.unsubs.push(async () => {
94
114
  removeOrg();
95
115
  removePlugin();
116
+ removeCatalog();
96
117
  });
97
118
  await on(PLUGINS_RECONCILE_TOPIC, () => {
98
119
  void this.host
@@ -149,7 +149,7 @@ export interface AdminExtensionView {
149
149
  /** The scope of the catalog plugin the extension ships in (builtin: `all`); null without one. */
150
150
  scope: PluginScope | null;
151
151
  /** Orgs where the extension is enabled (a required plugin: every org). */
152
- enabledOrgs: number;
152
+ enabledOrgs?: number;
153
153
  /** Shipped with the deployment (a builtin plugin or a required bootstrap plugin). */
154
154
  builtin: boolean;
155
155
  /** Where the install record came from (`bootstrap` for the bootstrap step); null for config-declared. */
@@ -296,3 +296,8 @@ export interface PackageWarning {
296
296
  /** 语句(压成一行,字符串字面量已抹掉)。 */
297
297
  statement: string;
298
298
  }
299
+ export interface ExtensionOrgCounts {
300
+ name: string;
301
+ enabledOrgs: number;
302
+ orgsNeedingConfig?: number;
303
+ }
@@ -10,7 +10,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { CatalogService } from "../catalog/catalog.service.js";
13
- import { LIVE_INSTALL_STATUSES } from "../catalog/install-status.js";
14
13
  import { CatalogRequestsService } from "../catalog/requests.service.js";
15
14
  import { ApiError } from "../errors.js";
16
15
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -211,23 +210,12 @@ let PlatformInboxService = class PlatformInboxService {
211
210
  */
212
211
  failureRows() {
213
212
  return this.kdb.db
214
- .selectFrom("plugin_scope_sync_failures as f")
213
+ .selectFrom("plugin_installs as f")
215
214
  .innerJoin("catalog_items as i", "i.id", "f.item_id")
216
215
  .innerJoin("orgs as o", "o.id", "f.org_id")
217
216
  .where("i.deleted_at", "is", null)
218
217
  .where("o.deleted_at", "is", null)
219
- .where((eb) => {
220
- const live = eb.exists(eb
221
- .selectFrom("plugin_installs as p")
222
- .select("p.id")
223
- .whereRef("p.org_id", "=", "f.org_id")
224
- .whereRef("p.item_id", "=", "f.item_id")
225
- .where("p.status", "in", [...LIVE_INSTALL_STATUSES]));
226
- return eb.or([
227
- eb.and([eb("f.op", "=", "install"), eb.not(live)]),
228
- eb.and([eb("f.op", "in", ["uninstall", "dependencies"]), live]),
229
- ]);
230
- });
218
+ .where("f.status", "=", "install_failed");
231
219
  }
232
220
  async countScopeSyncFailures() {
233
221
  const r = await this.failureRows()
@@ -244,24 +232,25 @@ let PlatformInboxService = class PlatformInboxService {
244
232
  "i.display_name",
245
233
  "f.org_id",
246
234
  "o.name as org_name",
247
- "f.op",
248
- "f.code",
249
- "f.message",
250
- "f.failed_at",
235
+ "f.error",
251
236
  ])
252
- .orderBy("f.failed_at", "desc")
237
+ .orderBy(sql `(f.error->>'attemptedAt')::timestamptz`, "desc")
253
238
  .orderBy("f.item_id")
254
239
  .orderBy("f.org_id")
255
240
  .limit(SCOPE_SYNC_FAILURES_LIST_MAX)
256
241
  .execute();
257
- return rows.map((r) => ({
258
- item: { id: r.item_id, name: r.item_name, displayName: r.display_name },
259
- org: { id: r.org_id, name: r.org_name },
260
- op: r.op,
261
- code: r.code,
262
- message: r.message,
263
- failedAt: r.failed_at.toISOString(),
264
- }));
242
+ return rows.flatMap((r) => r.error === null
243
+ ? []
244
+ : [
245
+ {
246
+ item: { id: r.item_id, name: r.item_name, displayName: r.display_name },
247
+ org: { id: r.org_id, name: r.org_name },
248
+ op: r.error.operation,
249
+ code: r.error.code,
250
+ message: r.error.message,
251
+ failedAt: r.error.attemptedAt,
252
+ },
253
+ ]);
265
254
  }
266
255
  };
267
256
  PlatformInboxService = __decorate([
@@ -21,6 +21,10 @@ export interface KernelEventMap {
21
21
  orgId: string;
22
22
  plugin: string;
23
23
  };
24
+ /** A committed catalog write may have removed access through an org's dependency graph. */
25
+ "catalog.org-intent-changed": {
26
+ orgId?: string;
27
+ };
24
28
  /**
25
29
  * A person decided a tool call approval (after the commit, exactly once: only the decision that
26
30
  * changed it from pending). The decision's transaction resumed the run and, for a conversation