@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,152 @@
1
+ import { TRIGGER_SOURCE_EXTENSION_POINT, validateToolSpec, } from "@capybara-hq/plugin-sdk";
2
+ import { ISOLATED_MAX_CALLBACKS } from "./child-protocol.js";
3
+ /** Functions stay in the child. The kernel receives only validated registration data and IDs. */
4
+ export class ChildRegistrationLedger {
5
+ callbacks = [];
6
+ handlers = new Map();
7
+ sealed = false;
8
+ nextOrdinal = 0;
9
+ get declarations() {
10
+ return structuredClone(this.callbacks);
11
+ }
12
+ seal() {
13
+ this.sealed = true;
14
+ }
15
+ handler(id) {
16
+ const handler = this.handlers.get(id);
17
+ if (!handler)
18
+ throw new Error("The isolated callback is unavailable");
19
+ return handler;
20
+ }
21
+ add(descriptor, handlers) {
22
+ if (this.sealed)
23
+ throw new Error("Isolated callbacks must be registered during setup");
24
+ if (this.handlers.size + handlers.length > ISOLATED_MAX_CALLBACKS)
25
+ throw new Error("The extension exceeded the callback limit");
26
+ for (const [id] of handlers) {
27
+ if (id.length > 256 || this.handlers.has(id))
28
+ throw new Error("The isolated callback ID is invalid or already registered");
29
+ }
30
+ this.callbacks.push(structuredClone(descriptor));
31
+ for (const [id, handler] of handlers)
32
+ this.handlers.set(id, handler);
33
+ }
34
+ static withCall(value, signal, config) {
35
+ if (typeof value !== "object" || value === null || Array.isArray(value))
36
+ throw new Error("The isolated call context is invalid");
37
+ return { ...value, config, signal };
38
+ }
39
+ runners() {
40
+ return {
41
+ tools: {
42
+ register: (spec, handler, opts) => {
43
+ if (validateToolSpec(spec).length > 0 || typeof handler !== "function")
44
+ throw new Error("The isolated tool declaration is invalid");
45
+ const id = `tool:${spec.name}`;
46
+ const watchers = [];
47
+ const watcher = opts?.watch;
48
+ const watchId = watcher === undefined ? undefined : `watch:${spec.name}`;
49
+ if (watcher && watchId) {
50
+ watchers.push([
51
+ watchId,
52
+ ([arg], signal, config) => watcher(ChildRegistrationLedger.withCall(arg, signal, config)),
53
+ ]);
54
+ }
55
+ this.add({ kind: "tool", id, spec, ...(watchId && { watchId }) }, [
56
+ [
57
+ id,
58
+ ([input, call], signal, config) => handler(input, ChildRegistrationLedger.withCall(call, signal, config)),
59
+ ],
60
+ ...watchers,
61
+ ]);
62
+ },
63
+ },
64
+ setup: {
65
+ check: (target, def) => {
66
+ const id = `setup.check:${target}`;
67
+ this.add({ kind: "setup.check", id, target, place: def.place }, [
68
+ [
69
+ id,
70
+ ([arg], signal, config) => def.run(ChildRegistrationLedger.withCall(arg, signal, config)),
71
+ ],
72
+ ]);
73
+ },
74
+ },
75
+ hooks: {
76
+ on: (mount, handler, options) => {
77
+ if (options?.mode !== "observe")
78
+ throw new Error("Policy hooks require a trusted extension");
79
+ const id = `hook.observe:${mount}:${this.nextOrdinal++}`;
80
+ this.add({ kind: "hook.observe", id, mount, options }, [
81
+ [
82
+ id,
83
+ async ([payload], signal, config) => {
84
+ await handler(payload, signal, { config });
85
+ },
86
+ ],
87
+ ]);
88
+ },
89
+ },
90
+ provide: (point, impl) => {
91
+ if (point !== TRIGGER_SOURCE_EXTENSION_POINT)
92
+ throw new Error("This extension point requires a trusted extension");
93
+ const source = impl;
94
+ if (typeof source?.events !== "function" || typeof source?.visible !== "function")
95
+ throw new Error("The isolated trigger source declaration is invalid");
96
+ const visibility = "trigger-source.visible";
97
+ const subjectLink = "trigger-source.subjectLink";
98
+ const handlers = [
99
+ [
100
+ visibility,
101
+ ([arg], _signal, config) => source.visible({ ...arg, config }),
102
+ ],
103
+ ];
104
+ if (typeof source.subjectLink === "function") {
105
+ const link = source.subjectLink.bind(source);
106
+ handlers.push([
107
+ subjectLink,
108
+ ([arg]) => link(arg),
109
+ ]);
110
+ }
111
+ this.add({
112
+ kind: "trigger-source",
113
+ id: "trigger-source",
114
+ events: source.events(),
115
+ visibleId: visibility,
116
+ ...(handlers.length > 1 && { subjectLinkId: subjectLink }),
117
+ }, handlers);
118
+ },
119
+ };
120
+ }
121
+ ui(key, target, handler) {
122
+ const kind = `ui.${key}`;
123
+ const id = `${kind}:${target}`;
124
+ this.add({ kind, id, target }, [
125
+ [
126
+ id,
127
+ ([arg], signal, config) => handler(ChildRegistrationLedger.withCall(arg, signal, config)),
128
+ ],
129
+ ]);
130
+ }
131
+ queue(name, handler, concurrency) {
132
+ const id = `queue:${name}`;
133
+ this.add({ kind: "queue", id, name, ...(concurrency !== undefined && { concurrency }) }, [
134
+ [id, ([data]) => handler(data)],
135
+ ]);
136
+ }
137
+ bus(topic, handler) {
138
+ const id = `bus:${topic}:${this.nextOrdinal++}`;
139
+ this.add({ kind: "bus", id, topic }, [[id, ([data]) => handler(data)]]);
140
+ return id;
141
+ }
142
+ unsubscribe(id) {
143
+ if (this.sealed) {
144
+ this.handlers.set(id, async () => undefined);
145
+ return;
146
+ }
147
+ this.handlers.delete(id);
148
+ const at = this.callbacks.findIndex((callback) => callback.id === id);
149
+ if (at >= 0)
150
+ this.callbacks.splice(at, 1);
151
+ }
152
+ }
@@ -0,0 +1,6 @@
1
+ import { type ChildBrokerCall } from "./child-protocol.js";
2
+ /** Dispatches only parent-issued calls and retains no live broker authority once a call settles. */
3
+ export declare function createChildSession(root: string, send: ChildBrokerCall): {
4
+ handle: (method: string, payload: unknown, signal: AbortSignal) => Promise<unknown>;
5
+ close: () => Promise<void>;
6
+ };
@@ -0,0 +1,343 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { configJsonSchema, defineExtension, staticManifestOf, } from "@capybara-hq/plugin-sdk";
5
+ import pg from "pg";
6
+ import { guardDb } from "../../ctx/guard-db.js";
7
+ import { extensionDbPool, pluginSchemaName } from "../../db/extension-db.js";
8
+ import { pinSigningKey } from "../../infra/database/extension-effect-key-lock.js";
9
+ import { appendEffect } from "../../infra/database/extension-handoff.js";
10
+ import { withOrgScope } from "../../infra/database/org-scope.js";
11
+ import { childInitSchema, childInvokeSchema, ISOLATED_MODEL_RESULT_BYTES, ISOLATED_STREAM_CHUNK, } from "./child-protocol.js";
12
+ import { ChildRegistrationLedger } from "./child-registration.js";
13
+ import { childNet, childStorage } from "./child-streams.js";
14
+ import { RpcByteChunk } from "./rpc.js";
15
+ /** Disabled capability groups fail at access instead of exposing a partial service. */
16
+ const unsupported = () => {
17
+ throw new Error("The capability is unavailable to isolated extensions");
18
+ };
19
+ const allowedDuringCheck = new Set(["log.info", "log.warn", "log.error", "net.probe"]);
20
+ function cleanCause(event) {
21
+ if (!event.cause || !("call" in event.cause))
22
+ return event;
23
+ // The kernel replaces this marker using its own original tool call.
24
+ return { ...event, cause: { call: true } };
25
+ }
26
+ function dbFor(init, plugin) {
27
+ if (init.mode !== "org")
28
+ return undefined;
29
+ if (!init.orgId || !init.db)
30
+ throw new Error("An extension org lane requires its own credentials");
31
+ const client = new pg.Client({ connectionString: init.db.url });
32
+ if (client.user !== init.db.login || client.host !== "/run/extension-postgres") {
33
+ throw new Error("The isolated database endpoint is invalid");
34
+ }
35
+ return extensionDbPool({ ...init.db, separate: true, dedicated: true }, plugin, {
36
+ rls: init.rls ?? "enforce",
37
+ extensionPoolMax: 2,
38
+ connectTimeoutMs: 3000,
39
+ });
40
+ }
41
+ /** Dispatches only parent-issued calls and retains no live broker authority once a call settles. */
42
+ export function createChildSession(root, send) {
43
+ const scope = new AsyncLocalStorage();
44
+ const lifecycle = new AbortController();
45
+ const ledger = new ChildRegistrationLedger();
46
+ const transactions = new WeakMap();
47
+ let initialized = false;
48
+ let ready = false;
49
+ let mode;
50
+ let orgId;
51
+ let manifest;
52
+ let context;
53
+ let pool;
54
+ let database;
55
+ function invocation() {
56
+ const state = scope.getStore();
57
+ if (!state?.active)
58
+ throw new Error("The capability is unavailable outside an invocation");
59
+ state.signal.throwIfAborted();
60
+ return state;
61
+ }
62
+ const broker = async (domain, method, args, signal, bytes) => {
63
+ const state = invocation();
64
+ const qualified = `${domain}.${method}`;
65
+ if (mode === "setupCheck" && !allowedDuringCheck.has(qualified))
66
+ return unsupported();
67
+ while (args.length > 0 && args.at(-1) === undefined)
68
+ args.pop();
69
+ const payload = { invocation: state.id, args };
70
+ return (await send(`broker.${qualified}`, bytes === undefined ? payload : new RpcByteChunk(payload, bytes), { signal: signal ? AbortSignal.any([state.signal, signal]) : state.signal }));
71
+ };
72
+ async function stage(effect, options) {
73
+ const state = invocation();
74
+ const transaction = options.tx && transactions.get(options.tx);
75
+ if (mode !== "org" || !transaction || !manifest)
76
+ throw new Error("A staged effect needs a live local extension transaction");
77
+ const key = options.idempotencyKey;
78
+ for (let attempt = 0; attempt < 2; attempt++) {
79
+ const envelope = await broker("outbox", "stage", [effect, key]);
80
+ if (!(await pinSigningKey(transaction, envelope.keyId)))
81
+ continue;
82
+ if (!(await broker("outbox", "confirmKey", [envelope.keyId])))
83
+ continue;
84
+ state.signal.throwIfAborted();
85
+ await appendEffect(transaction, manifest.name, envelope);
86
+ return { status: "staged", idempotencyKey: key };
87
+ }
88
+ throw new Error("The extension effect signing key changed while staging");
89
+ }
90
+ async function modelResult(method, request, signal) {
91
+ const { stream, bytes } = await broker("models", method, [request], signal);
92
+ if (typeof stream !== "string" ||
93
+ !Number.isSafeInteger(bytes) ||
94
+ bytes < 1 ||
95
+ bytes > ISOLATED_MODEL_RESULT_BYTES)
96
+ throw new Error("Invalid isolated model result size");
97
+ const result = new Uint8Array(bytes);
98
+ let offset = 0;
99
+ try {
100
+ while (offset < bytes) {
101
+ const chunk = await broker("models", "read", [stream], signal);
102
+ if (!(chunk instanceof RpcByteChunk) ||
103
+ chunk.bytes.length === 0 ||
104
+ chunk.bytes.length > ISOLATED_STREAM_CHUNK ||
105
+ offset + chunk.bytes.length > bytes) {
106
+ throw new Error("Invalid isolated model result frame");
107
+ }
108
+ result.set(chunk.bytes, offset);
109
+ offset += chunk.bytes.length;
110
+ }
111
+ const terminal = await broker("models", "read", [stream], signal);
112
+ if (terminal?.done !== true)
113
+ throw new Error("Missing isolated model result completion");
114
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(result));
115
+ }
116
+ finally {
117
+ await broker("models", "close", [stream]).catch(() => { });
118
+ }
119
+ }
120
+ function buildContext() {
121
+ const capability = ledger.runners();
122
+ const noGroup = () => unsupported();
123
+ const logFor = (level) => (message, fields) => {
124
+ if (!scope.getStore()?.active)
125
+ return;
126
+ void broker("log", level, [message, fields]).catch(() => { });
127
+ };
128
+ const ctx = {
129
+ ...capability,
130
+ get config() {
131
+ const state = scope.getStore();
132
+ return state ? state.config : {};
133
+ },
134
+ get signal() {
135
+ return scope.getStore()?.signal ?? lifecycle.signal;
136
+ },
137
+ get db() {
138
+ invocation();
139
+ return database ?? unsupported();
140
+ },
141
+ get http() {
142
+ return noGroup();
143
+ },
144
+ get dialIn() {
145
+ return noGroup();
146
+ },
147
+ get devices() {
148
+ return noGroup();
149
+ },
150
+ get deviceAccess() {
151
+ return noGroup();
152
+ },
153
+ get secrets() {
154
+ return noGroup();
155
+ },
156
+ extensionPoints: { get: unsupported, list: unsupported },
157
+ log: { info: logFor("info"), warn: logFor("warn"), error: logFor("error") },
158
+ kv: {
159
+ get: (key) => broker("kv", "get", [key]),
160
+ set: (key, value, opts) => broker("kv", "set", [key, value, opts]),
161
+ del: (key) => broker("kv", "del", [key]),
162
+ incr: (key, opts) => broker("kv", "incr", [key, opts]),
163
+ },
164
+ lock: {
165
+ async acquire(key, opts) {
166
+ const handle = await broker("lock", "acquire", [key, opts]);
167
+ return handle === null
168
+ ? null
169
+ : {
170
+ renew: () => broker("lock", "renew", [handle]),
171
+ release: () => broker("lock", "release", [handle]),
172
+ };
173
+ },
174
+ },
175
+ bus: {
176
+ publish: (topic, data) => broker("bus", "publish", [topic, data]),
177
+ async subscribe(topic, handler) {
178
+ const id = ledger.bus(topic, handler);
179
+ return async () => ledger.unsubscribe(id);
180
+ },
181
+ },
182
+ queue: {
183
+ define: (name, handler, opts) => ledger.queue(name, (data) => handler(data), opts?.concurrency),
184
+ add: (name, data, opts) => broker("queue", "add", [name, data, opts]),
185
+ },
186
+ models: {
187
+ embed: ({ signal, ...req }) => modelResult("embed", req, signal),
188
+ generateImage: ({ signal, ...req }) => modelResult("generateImage", req, signal),
189
+ describe: (req) => broker("models", "describe", [req]),
190
+ },
191
+ net: childNet(broker, () => invocation().signal, () => mode === "setupCheck"),
192
+ storage: childStorage(broker, () => invocation().signal, unsupported),
193
+ outbox: {
194
+ add: (async (effect, opts) => opts?.tx
195
+ ? stage(effect, opts)
196
+ : broker("outbox", "add", [effect, opts])),
197
+ },
198
+ triggers: {
199
+ causeOf: () => broker("triggers", "causeOf", []),
200
+ emit: (async (event, opts) => {
201
+ const data = cleanCause(event);
202
+ return opts?.tx
203
+ ? stage({ kind: "trigger", data }, opts)
204
+ : broker("triggers", "emit", [data, opts]);
205
+ }),
206
+ },
207
+ inbox: {
208
+ post: (async (data, opts) => opts?.tx
209
+ ? stage({ kind: "inbox.post", data }, opts)
210
+ : broker("inbox", "post", [data, opts])),
211
+ resolve: (args) => broker("inbox", "resolve", [args]),
212
+ },
213
+ ui: {
214
+ view: (target, render) => ledger.ui("view", target, (arg) => render(arg)),
215
+ action: (target, action) => ledger.ui("action", target, (arg) => action(arg)),
216
+ query: (target, query) => ledger.ui("query", target, (arg) => query(arg)),
217
+ invalidate: (target) => broker("ui", "invalidate", [target]),
218
+ verifyEmbedToken: unsupported,
219
+ },
220
+ agents: { usableBy: (args) => broker("agents", "usableBy", [args]) },
221
+ conversations: {
222
+ bySubject: (args) => broker("conversations", "bySubject", [args]),
223
+ appendExternal: unsupported,
224
+ setExternalState: unsupported,
225
+ streamExternalText: unsupported,
226
+ },
227
+ people: {
228
+ get: (args) => broker("people", "get", [args]),
229
+ search: (args) => broker("people", "search", [args]),
230
+ },
231
+ };
232
+ return ctx;
233
+ }
234
+ async function destroyPool() {
235
+ const owned = pool;
236
+ pool = undefined;
237
+ database = undefined;
238
+ await owned?.destroy();
239
+ }
240
+ async function initialize(value, remoteSignal) {
241
+ if (initialized)
242
+ throw new Error("The isolated process was already initialized");
243
+ initialized = true;
244
+ const signal = AbortSignal.any([lifecycle.signal, remoteSignal]);
245
+ signal.throwIfAborted();
246
+ const init = childInitSchema.parse(value);
247
+ mode = init.mode;
248
+ orgId = init.orgId;
249
+ if (mode !== "org" && init.db)
250
+ throw new Error("Database credentials require an organization lane");
251
+ if (mode === "org" && (!orgId || !init.db))
252
+ throw new Error("The isolated organization lane is not configured");
253
+ const entry = pathToFileURL(join(root, init.entry));
254
+ const loaded = (await import(entry.href));
255
+ signal.throwIfAborted();
256
+ if (!loaded.default)
257
+ throw new Error("The isolated extension has no manifest");
258
+ const declared = defineExtension(loaded.default);
259
+ if ((declared.permissions?.policyHooks?.length ?? 0) > 0)
260
+ throw new Error("Policy hooks require a trusted extension");
261
+ manifest = declared;
262
+ pool = dbFor(init, manifest.name);
263
+ database =
264
+ pool &&
265
+ guardDb(pool.withSchema(pluginSchemaName(manifest.name)), manifest.name, transactions);
266
+ const staticManifest = staticManifestOf(manifest);
267
+ const schema = manifest.config?.deployment;
268
+ context = buildContext();
269
+ try {
270
+ await manifest.setup(context);
271
+ signal.throwIfAborted();
272
+ }
273
+ catch (error) {
274
+ await destroyPool();
275
+ throw error;
276
+ }
277
+ finally {
278
+ ledger.seal();
279
+ }
280
+ ready = true;
281
+ return {
282
+ nonce: init.nonce,
283
+ manifest: staticManifest,
284
+ ...(schema && { configSchemas: { deployment: configJsonSchema(schema) } }),
285
+ callbacks: ledger.declarations,
286
+ };
287
+ }
288
+ async function invoke(value, remoteSignal) {
289
+ if (!ready || mode === "registration")
290
+ throw new Error("The isolated callback lane is unavailable");
291
+ const call = childInvokeSchema.parse(value);
292
+ if ((mode === "setupCheck") !== call.callback.startsWith("setup.check:"))
293
+ throw new Error("This callback is unavailable in the isolated lane");
294
+ const run = ledger.handler(call.callback);
295
+ const signal = AbortSignal.any([lifecycle.signal, remoteSignal]);
296
+ signal.throwIfAborted();
297
+ const schema = manifest?.config?.deployment;
298
+ const raw = call.config === undefined ? {} : call.config;
299
+ const parsed = await schema?.safeParseAsync(raw);
300
+ if (parsed?.success === false)
301
+ throw new Error("The isolated extension configuration is invalid");
302
+ signal.throwIfAborted();
303
+ const state = {
304
+ id: call.invocation,
305
+ config: parsed?.success ? parsed.data : raw,
306
+ active: true,
307
+ signal,
308
+ };
309
+ try {
310
+ const execute = () => scope.run(state, () => run(call.args, signal, state.config));
311
+ return await (orgId ? withOrgScope(orgId, execute) : execute());
312
+ }
313
+ finally {
314
+ state.active = false;
315
+ }
316
+ }
317
+ async function close() {
318
+ if (lifecycle.signal.aborted)
319
+ return;
320
+ lifecycle.abort();
321
+ try {
322
+ if (ready && context)
323
+ await manifest?.dispose?.(context);
324
+ }
325
+ finally {
326
+ await destroyPool();
327
+ }
328
+ }
329
+ async function handle(method, payload, signal) {
330
+ switch (method) {
331
+ case "initialize":
332
+ return initialize(payload, signal);
333
+ case "invoke":
334
+ return invoke(payload, signal);
335
+ case "dispose":
336
+ await close();
337
+ return null;
338
+ default:
339
+ throw new Error("Unknown isolated runtime method");
340
+ }
341
+ }
342
+ return { handle, close };
343
+ }
@@ -0,0 +1,4 @@
1
+ import type { ExtensionContext } from "@capybara-hq/plugin-sdk";
2
+ export type InvokeBroker = <T>(domain: string, method: string, args: unknown[], signal?: AbortSignal | null, bytes?: Uint8Array) => Promise<T>;
3
+ export declare function childNet(call: InvokeBroker, currentSignal: () => AbortSignal, probeOnly: () => boolean): ExtensionContext["net"];
4
+ export declare function childStorage(call: InvokeBroker, currentSignal: () => AbortSignal, deny: () => never): ExtensionContext["storage"];
@@ -0,0 +1,142 @@
1
+ import { ISOLATED_STREAM_CHUNK } from "./child-protocol.js";
2
+ import { RpcByteChunk } from "./rpc.js";
3
+ function readStream(call, domain, handle, signal) {
4
+ return new ReadableStream({
5
+ async pull(controller) {
6
+ const part = await call(domain, "read", [handle], signal);
7
+ if (!(part instanceof RpcByteChunk)) {
8
+ if (part?.done !== true)
9
+ throw new Error("The broker returned invalid bytes");
10
+ controller.close();
11
+ return;
12
+ }
13
+ const { bytes, metadata } = part;
14
+ if (metadata?.done !== false ||
15
+ bytes.byteLength === 0 ||
16
+ bytes.byteLength > ISOLATED_STREAM_CHUNK)
17
+ throw new Error("The broker exceeded the stream credit");
18
+ controller.enqueue(bytes);
19
+ },
20
+ async cancel() {
21
+ await call(domain, "close", [handle]).catch(() => { });
22
+ },
23
+ }, { highWaterMark: 0 });
24
+ }
25
+ async function requestBytes(body, signal) {
26
+ const reader = body.getReader();
27
+ const chunks = [];
28
+ let size = 0;
29
+ const abort = () => void reader.cancel().catch(() => { });
30
+ signal.addEventListener("abort", abort, { once: true });
31
+ try {
32
+ signal.throwIfAborted();
33
+ for (;;) {
34
+ const part = await reader.read();
35
+ if (part.done)
36
+ break;
37
+ size += part.value.byteLength;
38
+ if (size > ISOLATED_STREAM_CHUNK)
39
+ throw new Error("The HTTP request body exceeds 64 KiB");
40
+ chunks.push(part.value);
41
+ }
42
+ signal.throwIfAborted();
43
+ return Buffer.concat(chunks, size).toString("base64");
44
+ }
45
+ finally {
46
+ signal.removeEventListener("abort", abort);
47
+ await reader.cancel().catch(() => { });
48
+ reader.releaseLock();
49
+ }
50
+ }
51
+ export function childNet(call, currentSignal, probeOnly) {
52
+ return {
53
+ async fetch(url, init, opts) {
54
+ const active = currentSignal();
55
+ const request = new Request(url, init);
56
+ const s = AbortSignal.any([active, request.signal]);
57
+ if (probeOnly()) {
58
+ if (request.method !== "HEAD" ||
59
+ [...request.headers].length > 0 ||
60
+ opts?.orgId !== undefined) {
61
+ throw new Error("Setup checks may only make header-free HEAD probes");
62
+ }
63
+ const result = await call("net", "probe", [request.url], s);
64
+ return new Response(null, { status: result.status });
65
+ }
66
+ const response = await call("net", "fetch", [
67
+ request.url,
68
+ {
69
+ method: request.method,
70
+ headers: [...request.headers],
71
+ redirect: request.redirect,
72
+ ...(request.body && { body: await requestBytes(request.body, s) }),
73
+ },
74
+ opts,
75
+ ], s);
76
+ return new Response(response.stream === undefined ? null : readStream(call, "net", response.stream, s), {
77
+ status: response.status,
78
+ statusText: response.statusText,
79
+ headers: response.headers,
80
+ });
81
+ },
82
+ };
83
+ }
84
+ async function writeStream(call, handle, input, signal) {
85
+ const send = async (chunk) => {
86
+ for (let at = 0; at < chunk.byteLength; at += ISOLATED_STREAM_CHUNK) {
87
+ const bytes = chunk.subarray(at, at + ISOLATED_STREAM_CHUNK);
88
+ await call("storage", "write", [handle], signal, bytes);
89
+ }
90
+ };
91
+ try {
92
+ if (input instanceof Uint8Array) {
93
+ await send(input);
94
+ }
95
+ else {
96
+ const reader = input.getReader();
97
+ const abort = () => void reader.cancel().catch(() => { });
98
+ signal?.addEventListener("abort", abort, { once: true });
99
+ try {
100
+ signal?.throwIfAborted();
101
+ for (;;) {
102
+ const part = await reader.read();
103
+ if (part.done)
104
+ break;
105
+ await send(part.value);
106
+ }
107
+ signal?.throwIfAborted();
108
+ }
109
+ finally {
110
+ signal?.removeEventListener("abort", abort);
111
+ await reader.cancel().catch(() => { });
112
+ reader.releaseLock();
113
+ }
114
+ }
115
+ return await call("storage", "finishPut", [handle], signal);
116
+ }
117
+ catch (error) {
118
+ await call("storage", "abortPut", [handle]).catch(() => { });
119
+ throw error;
120
+ }
121
+ }
122
+ export function childStorage(call, currentSignal, deny) {
123
+ return {
124
+ async put(orgId, key, body, { signal, ...options }) {
125
+ const active = currentSignal();
126
+ const s = signal ? AbortSignal.any([active, signal]) : active;
127
+ const handle = await call("storage", "openPut", [orgId, key, options], s);
128
+ return writeStream(call, handle, body, s);
129
+ },
130
+ async get(orgId, key, opts) {
131
+ const { signal, ...options } = opts ?? {};
132
+ const result = await call("storage", "get", [orgId, key, options], signal);
133
+ return (result && { head: result.head, body: readStream(call, "storage", result.stream, signal) });
134
+ },
135
+ head: (orgId, key) => call("storage", "head", [orgId, key]),
136
+ delete: (orgId, key) => call("storage", "delete", [orgId, key]),
137
+ deletePrefix: (orgId, prefix) => call("storage", "deletePrefix", [orgId, prefix]),
138
+ list: (orgId, prefix, opts) => call("storage", "list", [orgId, prefix, opts]),
139
+ presignGet: deny,
140
+ presignPut: deny,
141
+ };
142
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import { ISOLATED_PACKAGE_ROOT } from "./child-protocol.js";
2
+ import { createChildSession } from "./child-session.js";
3
+ import { IsolatedRpcPeer } from "./rpc.js";
4
+ const session = createChildSession(ISOLATED_PACKAGE_ROOT, (method, payload, options) => peer.call(method, payload, options));
5
+ const peer = new IsolatedRpcPeer(process.stdin, process.stdout, {
6
+ handle: session.handle,
7
+ onClose: () => {
8
+ void session.close().catch(() => { });
9
+ },
10
+ });
@@ -0,0 +1,15 @@
1
+ import { type ExtensionPackage } from "../package.js";
2
+ export interface ConfiguredExtensionPackage {
3
+ readonly archiveUrl: string;
4
+ readonly review: ExtensionPackage;
5
+ readonly maxBytes: number;
6
+ /** A copy of the captured archive. Writes to the copy cannot change the reviewed package. */
7
+ bytes(): Uint8Array;
8
+ }
9
+ /** Reads one bounded local file snapshot and reviews its static package without executing it. */
10
+ export declare function readConfiguredExtensionPackage(specifier: string, resolveFrom: string, maxBytes?: number): Promise<ConfiguredExtensionPackage>;
11
+ /** Extracts the reviewed bytes into the kernel's content-addressed cache. */
12
+ export declare function stageConfiguredExtensionPackage(snapshot: ConfiguredExtensionPackage, cacheDir: string): Promise<{
13
+ entryUrl: string;
14
+ root: string;
15
+ }>;