@sorbetai/plugins 0.0.0-stage → 0.1.0-alpha.17

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.
package/dist/node.js ADDED
@@ -0,0 +1,2844 @@
1
+ import { B as ModelToolMetadataProperties, C as PluginStateReadResultSchema, D as capturePluginPrefixes, E as PluginPrefixContributionSchema, F as SessionBehaviorCommandSchema, H as JsonValueSchema, N as PluginInputSchema, O as PreparationHookMetadataProperties, U as captureJsonValue, V as captureModelToolMetadata, a as capturePluginContributions, b as decodeCallback, c as ToolHookCallbacksProperties, f as ToolHookPreparationSchema, j as InputTransformMetadataProperties, l as ToolHookFeedbackSchema, m as captureToolHookMetadata, r as bindCallbackRetention, u as ToolHookMetadataProperties, w as captureNamedStateMetadata, x as NamedStateMetadataProperties, y as ToolResultSchema } from "./object-borrow-C81Gj5tq.js";
2
+ import "./run-yield-B1AE7-PN.js";
3
+ import { A as PluginAdmissionError, C as contextComponent, D as aggregateCleanupFailure, E as objectSelfStateHost, M as PluginLeaseDeadlineErrorSchema, _ as encodePluginPackage, a as PluginAuthorityCheckpointSchema, g as decodePluginPackage, i as MAX_PLUGIN_RETRY_COMMANDS, k as contributionAdmission, m as PluginPackageDocumentProperties, o as PluginAuthorityError, p as NativePluginPackageAbiSchema, r as AuthorityBatchSchema, s as captureCompositionData, v as PluginPackageIdSchema, x as captureDefinition } from "./authority-Ci--C1Np.js";
4
+ import "./objects-DdioT9PR.js";
5
+ import { t as ObjectInvocationUnknownError } from "./object-invocation-DC6PCiFY.js";
6
+ import { c as decodeObjectFacetReply, l as decodeObjectFacetRequest, o as ObjectFacetUnavailableError, t as validateDataSchema } from "./data-schema-CHZWAtoX.js";
7
+ import { createRequire, registerHooks } from "node:module";
8
+ import * as s from "@earendil-works/pi-schema";
9
+ import { check, compile, decode, decodeWith } from "@sorbetai/schema";
10
+ import * as Context from "effect/Context";
11
+ import * as Effect from "effect/Effect";
12
+ import ensureError from "ensure-error";
13
+ import { isEqual, isError, isPromise, sortBy } from "es-toolkit";
14
+ import * as Exit from "effect/Exit";
15
+ import * as Scope from "effect/Scope";
16
+ import * as Semaphore from "effect/Semaphore";
17
+ import * as Stream from "effect/Stream";
18
+ import { mkdir, open, readFile, readdir, realpath } from "node:fs/promises";
19
+ import { dirname, extname, isAbsolute, join, resolve } from "node:path";
20
+ import { DatabaseSync } from "node:sqlite";
21
+ import { isUint8Array } from "node:util/types";
22
+ import { watch } from "node:fs";
23
+ import { randomUUID } from "node:crypto";
24
+ import { Socket } from "node:net";
25
+ import { spawn } from "node:child_process";
26
+ import { once } from "node:events";
27
+ import { fileURLToPath, pathToFileURL } from "node:url";
28
+ import * as Pull from "effect/Pull";
29
+ import { isObject } from "es-toolkit/compat";
30
+
31
+ //#region src/node/sqlite-store.ts
32
+ const BodyRow = s.obj({ body: s.str() }, { open: true });
33
+ const PositionRow = s.obj({ sequence: s.int() }, { open: true });
34
+ /** One exclusive connection; an uncertain commit requires closing and reopening the owner and store. */
35
+ var SqlitePluginStore = class SqlitePluginStore {
36
+ #database;
37
+ #sequence = 0;
38
+ #checkpointSequence = 0;
39
+ #closed = false;
40
+ #uncertain = false;
41
+ constructor(authorityId, database) {
42
+ this.authorityId = authorityId;
43
+ this.#database = database;
44
+ }
45
+ static async open(directory, authorityId) {
46
+ await mkdir(directory, {
47
+ recursive: true,
48
+ mode: 448
49
+ });
50
+ const resolved = await realpath(directory);
51
+ const database = new DatabaseSync(join(resolved, "plugins.sqlite"), { timeout: 0 });
52
+ try {
53
+ const version = decode(s.obj({ user_version: s.int() }, { open: true }), database.prepare("PRAGMA user_version").get()).user_version;
54
+ const existing = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all();
55
+ if ((existing.length > 0 || version !== 0) && version !== 3) throw new Error("Unsupported Plugin store format; original database was preserved");
56
+ if (existing.length === 0) database.exec("PRAGMA auto_vacuum=INCREMENTAL");
57
+ database.exec(`
58
+ PRAGMA locking_mode=EXCLUSIVE;
59
+ PRAGMA journal_mode=DELETE;
60
+ PRAGMA synchronous=EXTRA;
61
+ PRAGMA fullfsync=ON;
62
+ BEGIN EXCLUSIVE;
63
+ PRAGMA user_version=3;
64
+ CREATE TABLE IF NOT EXISTS authority (authority_id TEXT PRIMARY KEY, recovery_barrier INTEGER NOT NULL) STRICT;
65
+ CREATE TABLE IF NOT EXISTS batches (commit_id TEXT PRIMARY KEY, sequence INTEGER UNIQUE NOT NULL, body TEXT NOT NULL) STRICT;
66
+ CREATE TABLE IF NOT EXISTS packages (id TEXT PRIMARY KEY, bytes BLOB NOT NULL) STRICT;
67
+ CREATE TABLE IF NOT EXISTS checkpoint (id INTEGER PRIMARY KEY CHECK (id = 1), sequence INTEGER NOT NULL, body TEXT NOT NULL) STRICT;
68
+ `);
69
+ const metadata = database.prepare("SELECT authority_id FROM authority").get();
70
+ if (metadata === void 0) database.prepare("INSERT INTO authority VALUES (?, 0)").run(authorityId);
71
+ else if (decode(s.obj({ authority_id: s.str() }, { open: true }), metadata).authority_id !== authorityId) throw new PluginAuthorityError("conflict");
72
+ database.exec("UPDATE authority SET recovery_barrier = 1 - recovery_barrier; COMMIT");
73
+ await syncDirectory(resolved);
74
+ await syncDirectory(dirname(resolved));
75
+ const store = new SqlitePluginStore(authorityId, database);
76
+ store.#checkpointSequence = (await store.readCheckpoint())?.sequence ?? 0;
77
+ store.#sequence = decode(PositionRow, database.prepare("SELECT max(coalesce(max(sequence), 0), ?) AS sequence FROM batches").get(store.#checkpointSequence)).sequence;
78
+ return store;
79
+ } catch (error) {
80
+ database.close();
81
+ if (isError(error) && Reflect.get(error, "errcode") === 5) throw new PluginAuthorityError("conflict");
82
+ throw error;
83
+ }
84
+ }
85
+ async read() {
86
+ this.#assertReadable();
87
+ return this.#database.prepare("SELECT body FROM batches ORDER BY sequence").all().map((row) => decode(AuthorityBatchSchema, JSON.parse(decode(BodyRow, row).body)));
88
+ }
89
+ async readCheckpoint() {
90
+ this.#assertReadable();
91
+ const row = this.#database.prepare("SELECT body FROM checkpoint WHERE id = 1").get();
92
+ if (row === void 0) return;
93
+ const checkpoint = decode(PluginAuthorityCheckpointSchema, JSON.parse(decode(BodyRow, row).body));
94
+ if (checkpoint.authorityId !== this.authorityId) throw new PluginAuthorityError("invalid-data");
95
+ return checkpoint;
96
+ }
97
+ async readPackage(packageId) {
98
+ this.#assertReadable();
99
+ const row = this.#database.prepare("SELECT bytes FROM packages WHERE id = ?").get(packageId);
100
+ if (row === void 0) return;
101
+ if (!isUint8Array(row.bytes)) throw new TypeError("Invalid package bytes");
102
+ return {
103
+ packageId,
104
+ bytes: row.bytes
105
+ };
106
+ }
107
+ async append(batch, data = {}) {
108
+ this.#assertReadable();
109
+ if (this.#database.prepare("SELECT commit_id FROM batches WHERE commit_id = ?").get(batch[0].entryId) !== void 0) return "committed";
110
+ if (batch[0].sequence !== this.#sequence + 1) return "conflict";
111
+ const body = JSON.stringify(structuredClone(batch));
112
+ const pkg = data.package;
113
+ const bytes = pkg?.bytes.slice();
114
+ const sequence = this.#sequence + batch.length;
115
+ let committing = false;
116
+ try {
117
+ this.#database.exec("BEGIN EXCLUSIVE");
118
+ if (pkg !== void 0 && bytes !== void 0) this.#database.prepare("INSERT INTO packages VALUES (?, ?) ON CONFLICT(id) DO NOTHING").run(pkg.packageId, bytes);
119
+ this.#database.prepare("INSERT INTO batches VALUES (?, ?, ?)").run(batch[0].entryId, sequence, body);
120
+ this.#trimReceipts(this.#checkpointSequence);
121
+ committing = true;
122
+ this.#database.exec("COMMIT");
123
+ this.#sequence = sequence;
124
+ return "committed";
125
+ } catch {
126
+ if (!committing) try {
127
+ if (this.#database.isTransaction) this.#database.exec("ROLLBACK");
128
+ return "not-committed";
129
+ } catch {}
130
+ this.#uncertain = true;
131
+ return "unknown";
132
+ }
133
+ }
134
+ async reconcile(batch) {
135
+ if (this.#closed) throw new PluginAuthorityError("closed");
136
+ if (this.#uncertain) return "unknown";
137
+ if (this.#database.prepare("SELECT commit_id FROM batches WHERE commit_id = ?").get(batch[0].entryId) !== void 0) return "committed";
138
+ if (batch[0].sequence <= this.#checkpointSequence) throw new PluginAuthorityError("stale-command");
139
+ return "absent";
140
+ }
141
+ async compact(checkpoint) {
142
+ this.#assertReadable();
143
+ const snapshot = captureCompositionData(PluginAuthorityCheckpointSchema, checkpoint);
144
+ if (snapshot.authorityId !== this.authorityId) throw new PluginAuthorityError("invalid-data");
145
+ if (snapshot.sequence !== this.#sequence) return "conflict";
146
+ const body = JSON.stringify(snapshot);
147
+ let committing = false;
148
+ try {
149
+ this.#database.exec("BEGIN EXCLUSIVE");
150
+ this.#database.prepare("INSERT INTO checkpoint VALUES (1, ?, ?) ON CONFLICT(id) DO UPDATE SET sequence = excluded.sequence, body = excluded.body").run(snapshot.sequence, body);
151
+ const collectPackage = this.#database.prepare("DELETE FROM packages WHERE id = ?");
152
+ for (const registration of snapshot.registrations) if (registration.retired) collectPackage.run(registration.packageId);
153
+ this.#trimReceipts(snapshot.sequence);
154
+ committing = true;
155
+ this.#database.exec("COMMIT");
156
+ this.#checkpointSequence = snapshot.sequence;
157
+ } catch {
158
+ if (!committing) try {
159
+ if (this.#database.isTransaction) this.#database.exec("ROLLBACK");
160
+ return "not-committed";
161
+ } catch {}
162
+ this.#uncertain = true;
163
+ return "unknown";
164
+ }
165
+ try {
166
+ this.#database.exec("PRAGMA incremental_vacuum");
167
+ } catch {}
168
+ return "committed";
169
+ }
170
+ close() {
171
+ if (this.#closed) return;
172
+ this.#database.close();
173
+ this.#closed = true;
174
+ }
175
+ #assertReadable() {
176
+ if (this.#closed) throw new PluginAuthorityError("closed");
177
+ if (this.#uncertain) throw new PluginAuthorityError("fenced");
178
+ }
179
+ #trimReceipts(sequence) {
180
+ this.#database.prepare("DELETE FROM batches WHERE sequence <= ? AND commit_id NOT IN (SELECT commit_id FROM batches ORDER BY sequence DESC LIMIT ?)").run(sequence, MAX_PLUGIN_RETRY_COMMANDS);
181
+ }
182
+ };
183
+ async function syncDirectory(directory) {
184
+ if (process.platform === "win32") return;
185
+ const handle = await open(directory, "r");
186
+ try {
187
+ await handle.sync();
188
+ } finally {
189
+ await handle.close();
190
+ }
191
+ }
192
+
193
+ //#endregion
194
+ //#region src/node/plugin-directory.ts
195
+ const EntryPrefix = "directory:";
196
+ const StaleCommand = s.obj({
197
+ name: s.lit("PluginAuthorityError"),
198
+ code: s.lit("stale-command")
199
+ }, { open: true });
200
+ const InvalidModuleSource = s.obj({
201
+ name: s.lit("PluginModuleError"),
202
+ code: s.union([
203
+ s.lit("invalid-syntax"),
204
+ s.lit("unsupported-import"),
205
+ s.lit("missing-module"),
206
+ s.lit("unsupported-module"),
207
+ s.lit("missing-default-export")
208
+ ])
209
+ }, { open: true });
210
+ /** Host-trusted package containers; filesystem changes submit Desired, never manage Mount resources. */
211
+ var NodePluginDirectory = class NodePluginDirectory {
212
+ #authority;
213
+ #directory;
214
+ #onError;
215
+ #nativeOnly;
216
+ #packageProfiles;
217
+ #sources;
218
+ #resourceExtensions;
219
+ #include;
220
+ #shutdown = new AbortController();
221
+ #packages = /* @__PURE__ */ new Map();
222
+ #diagnostics = [];
223
+ #lane = Promise.resolve();
224
+ #watcher;
225
+ #rootWatcher;
226
+ #timer;
227
+ #closed = false;
228
+ constructor(options) {
229
+ this.#directory = resolve(options.directory);
230
+ this.#authority = options.authority;
231
+ this.#onError = options.onError ?? (() => {});
232
+ this.#nativeOnly = options.nativeOnly ?? false;
233
+ this.#resourceExtensions = new Set(decode(s.arr(s.str({ pattern: "^\\.[a-z0-9]+$" }), { uniqueItems: true }), options.resourceExtensions ?? []));
234
+ this.#packageProfiles = options.packageProfiles?.map((profile) => ({
235
+ abi: profile.abi,
236
+ sourceProfile: profile.sourceProfile,
237
+ inspect: profile.inspect.bind(profile)
238
+ }));
239
+ this.#sources = options.sources ?? [];
240
+ this.#include = options.include;
241
+ }
242
+ static async open(options) {
243
+ const source = new NodePluginDirectory(options);
244
+ await mkdir(source.#directory, {
245
+ recursive: true,
246
+ mode: 448
247
+ });
248
+ try {
249
+ if (options.watch) {
250
+ source.#rootWatcher = watch(source.#directory, () => source.#schedule());
251
+ source.#rootWatcher.on("error", (error) => source.#report(error));
252
+ source.#armRecursiveWatcher();
253
+ }
254
+ await source.refresh();
255
+ return source;
256
+ } catch (error) {
257
+ await source.close();
258
+ throw error;
259
+ }
260
+ }
261
+ /** Only current Host source generations are eligible for new Client intent. */
262
+ allows(packageId) {
263
+ return [...this.#packages.values()].some((record) => record.packageId === packageId);
264
+ }
265
+ /** Current source failures; an invalid edit retains only that source's last accepted generation. */
266
+ diagnostics() {
267
+ return structuredClone(this.#diagnostics);
268
+ }
269
+ /** Cancellation joins any in-flight Authority append; uncertain writes are never retried. */
270
+ refresh(signal) {
271
+ if (this.#closed) return Promise.reject(/* @__PURE__ */ new Error("Plugin directory is closed"));
272
+ const waiting = signal === void 0 ? this.#shutdown.signal : AbortSignal.any([signal, this.#shutdown.signal]);
273
+ const run = this.#lane.then(async () => {
274
+ if (this.#closed) return;
275
+ let retryDelayMs = 10;
276
+ while (!waiting.aborted) {
277
+ try {
278
+ await this.#synchronize(waiting);
279
+ if (this.#watcher !== void 0) this.#armRecursiveWatcher();
280
+ return;
281
+ } catch (cause) {
282
+ if (!check(StaleCommand, cause)) throw cause;
283
+ }
284
+ await Effect.runPromise(Effect.sleep(retryDelayMs), { signal: waiting });
285
+ retryDelayMs = Math.min(1e3, retryDelayMs * 2);
286
+ }
287
+ waiting.throwIfAborted();
288
+ });
289
+ this.#lane = run.catch(() => {});
290
+ return run;
291
+ }
292
+ async close() {
293
+ this.#closed = true;
294
+ this.#shutdown.abort();
295
+ this.#watcher?.close();
296
+ this.#watcher = void 0;
297
+ this.#rootWatcher?.close();
298
+ this.#rootWatcher = void 0;
299
+ clearTimeout(this.#timer);
300
+ this.#timer = void 0;
301
+ await this.#lane;
302
+ }
303
+ #report(error) {
304
+ try {
305
+ this.#onError(error);
306
+ } catch {}
307
+ }
308
+ #armRecursiveWatcher() {
309
+ this.#watcher?.close();
310
+ this.#watcher = watch(this.#directory, { recursive: true }, () => this.#schedule());
311
+ this.#watcher.on("error", (error) => this.#report(error));
312
+ }
313
+ #schedule() {
314
+ if (this.#closed) return;
315
+ clearTimeout(this.#timer);
316
+ this.#timer = setTimeout(() => {
317
+ this.#timer = void 0;
318
+ this.refresh().catch((cause) => this.#report(ensureError(cause)));
319
+ }, 100);
320
+ this.#timer.unref();
321
+ }
322
+ #retainRejectedSource(source, cause, next, diagnostics) {
323
+ const { entryId, path } = source;
324
+ let retained = this.#packages.get(entryId);
325
+ if (retained === void 0) {
326
+ const existing = this.#authority.status().desired.entries.find((entry) => entry.entryId === entryId);
327
+ if (existing !== void 0) retained = {
328
+ packageId: existing.packageId,
329
+ document: this.#authority.packageDetails(existing.packageId).document
330
+ };
331
+ }
332
+ if (retained !== void 0) next.set(entryId, retained);
333
+ const diagnostic = {
334
+ entryId,
335
+ path,
336
+ message: cause.message,
337
+ retainedPrevious: retained !== void 0
338
+ };
339
+ diagnostics.push(diagnostic);
340
+ if (!this.#diagnostics.some((last) => isEqual(last, diagnostic))) this.#report(new Error(`Plugin source ${path} (${entryId}): ${cause.message}; ${retained === void 0 ? "skipped" : "retaining previous generation"}`, { cause }));
341
+ }
342
+ async #synchronize(signal) {
343
+ signal.throwIfAborted();
344
+ const candidates = sortBy((await readdir(this.#directory, { withFileTypes: true })).filter((entry) => entry.isDirectory() || entry.isFile() && entry.name.endsWith(".json")), ["name"]).map((file, order) => ({
345
+ file,
346
+ order,
347
+ entryId: `${EntryPrefix}${file.isDirectory() ? file.name : file.name.slice(0, -5)}`,
348
+ path: join(this.#directory, file.name)
349
+ }));
350
+ const identities = /* @__PURE__ */ new Map();
351
+ for (const { entryId } of candidates) identities.set(entryId, (identities.get(entryId) ?? 0) + 1);
352
+ const documents = await Promise.allSettled(candidates.map(async ({ file, entryId, path }) => {
353
+ decode(s.str({
354
+ minLength: 1,
355
+ maxLength: 200
356
+ }), entryId);
357
+ if (identities.get(entryId) !== 1) throw new Error(`Multiple directory sources use ${entryId}`);
358
+ let document;
359
+ if (file.isDirectory()) if ((await readdir(path)).includes("plugin.json")) {
360
+ const manifest = decode(PluginPackageDocumentProperties.manifest, JSON.parse(await readFile(join(path, "plugin.json"), "utf8")));
361
+ document = await decodePluginPackage(await encodePluginPackage({
362
+ formatVersion: 1,
363
+ manifest,
364
+ files: await this.#readModules(path, "", !check(NativePluginPackageAbiSchema, manifest.abi))
365
+ }));
366
+ } else {
367
+ let adapted;
368
+ for (const source of this.#sources) {
369
+ adapted = await source.read(path);
370
+ if (adapted !== void 0) break;
371
+ }
372
+ if (adapted === void 0) throw new TypeError(`Plugin directory ${path} has no plugin.json or recognized source manifest`);
373
+ document = await decodePluginPackage(await encodePluginPackage(adapted));
374
+ }
375
+ else {
376
+ const bytes = await readFile(path);
377
+ document = await decodePluginPackage({
378
+ packageId: randomUUID(),
379
+ bytes
380
+ });
381
+ }
382
+ if (this.#nativeOnly) decode(NativePluginPackageAbiSchema, document.manifest.abi);
383
+ const pkg = await encodePluginPackage(document);
384
+ if (this.#packageProfiles !== void 0 && !check(NativePluginPackageAbiSchema, document.manifest.abi)) {
385
+ const profile = this.#packageProfiles.find((candidate) => candidate.abi === document.manifest.abi);
386
+ if (profile === void 0) throw new TypeError(`Unsupported Plugin Package ABI: ${document.manifest.abi}`);
387
+ await profile.inspect(pkg, document);
388
+ }
389
+ return {
390
+ document,
391
+ pkg
392
+ };
393
+ }));
394
+ const next = /* @__PURE__ */ new Map();
395
+ const diagnostics = [];
396
+ const replacements = /* @__PURE__ */ new Map();
397
+ const additions = [];
398
+ for (const [index, result] of documents.entries()) {
399
+ signal.throwIfAborted();
400
+ const candidate = candidates[index];
401
+ if (candidate === void 0) throw new Error("Missing directory source identity");
402
+ const { entryId, order } = candidate;
403
+ const previous = this.#packages.get(entryId);
404
+ if (result.status === "rejected") {
405
+ this.#retainRejectedSource(candidate, ensureError(result.reason), next, diagnostics);
406
+ continue;
407
+ }
408
+ const existing = this.#authority.status().desired.entries.find((entry) => entry.entryId === entryId);
409
+ const { document, pkg } = result.value;
410
+ if (this.#include?.(entryId, document) === false) continue;
411
+ if (previous !== void 0 && isEqual(previous.document, document)) {
412
+ next.set(entryId, previous);
413
+ continue;
414
+ }
415
+ let record;
416
+ if (existing !== void 0 && isEqual(this.#authority.packageDetails(existing.packageId).document, document)) record = {
417
+ packageId: existing.packageId,
418
+ document
419
+ };
420
+ else {
421
+ const commandId = randomUUID();
422
+ try {
423
+ await this.#authority.register({
424
+ commandId,
425
+ idempotencyKey: commandId,
426
+ baseSequence: this.#authority.status().sequence,
427
+ action: {
428
+ kind: "register",
429
+ packageId: pkg.packageId
430
+ }
431
+ }, pkg);
432
+ } catch (cause) {
433
+ if (!check(InvalidModuleSource, cause)) throw cause;
434
+ this.#retainRejectedSource(candidate, ensureError(cause), next, diagnostics);
435
+ continue;
436
+ }
437
+ record = {
438
+ packageId: pkg.packageId,
439
+ document
440
+ };
441
+ }
442
+ next.set(entryId, record);
443
+ if (previous !== void 0) replacements.set(previous.packageId, record.packageId);
444
+ if (existing !== void 0) replacements.set(existing.packageId, record.packageId);
445
+ else if (previous === void 0) additions.push({
446
+ kind: "add",
447
+ entry: {
448
+ entryId,
449
+ packageId: record.packageId,
450
+ parentId: null,
451
+ order,
452
+ enabled: true
453
+ }
454
+ });
455
+ }
456
+ const desired = this.#authority.status().desired;
457
+ const removedPackages = new Set([...this.#packages].filter(([key]) => !next.has(key)).map(([, record]) => record.packageId));
458
+ for (const entry of desired.entries) if (entry.entryId.startsWith(EntryPrefix) && !next.has(entry.entryId)) removedPackages.add(entry.packageId);
459
+ const removed = new Set(desired.entries.filter((entry) => removedPackages.has(entry.packageId) || entry.entryId.startsWith(EntryPrefix) && !next.has(entry.entryId)).map((entry) => entry.entryId));
460
+ for (const entry of desired.entries) {
461
+ let parentId = entry.parentId;
462
+ while (parentId !== null) {
463
+ if (removed.has(parentId)) {
464
+ removed.add(entry.entryId);
465
+ break;
466
+ }
467
+ parentId = desired.entries.find((parent) => parent.entryId === parentId)?.parentId ?? null;
468
+ }
469
+ }
470
+ const mutations = [...additions];
471
+ for (const entry of desired.entries) {
472
+ const packageId = replacements.get(entry.packageId);
473
+ if (removed.has(entry.entryId)) {
474
+ mutations.push({
475
+ kind: "remove",
476
+ entryId: entry.entryId
477
+ });
478
+ continue;
479
+ }
480
+ if (packageId === void 0) continue;
481
+ if (packageId === entry.packageId) continue;
482
+ mutations.push({
483
+ kind: "replace",
484
+ entryId: entry.entryId,
485
+ packageId
486
+ });
487
+ }
488
+ signal.throwIfAborted();
489
+ if (mutations.length > 0) await this.#authority.applyDesired({
490
+ commandId: randomUUID(),
491
+ baseGeneration: desired.sequence,
492
+ mutations
493
+ }, async () => {});
494
+ this.#packages = next;
495
+ this.#diagnostics = diagnostics;
496
+ }
497
+ async #readModules(directory, prefix = "", includeTypeScript = false) {
498
+ const files = [];
499
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
500
+ const path = join(directory, entry.name);
501
+ const relative = `${prefix}${entry.name}`;
502
+ if (entry.isDirectory() && entry.name !== "node_modules" && entry.name !== ".git") files.push(...await this.#readModules(path, `${relative}/`, includeTypeScript));
503
+ else if (entry.isFile() && entry.name !== "plugin.json" && (/\.m?js$/.test(entry.name) || includeTypeScript && (entry.name.endsWith(".ts") || this.#resourceExtensions.has(extname(entry.name))))) files.push({
504
+ path: relative,
505
+ content: new TextDecoder("utf-8", {
506
+ fatal: true,
507
+ ignoreBOM: true
508
+ }).decode(await readFile(path))
509
+ });
510
+ }
511
+ return files;
512
+ }
513
+ };
514
+
515
+ //#endregion
516
+ //#region src/node/process/protocol.ts
517
+ const Id = s.int({
518
+ minimum: 1,
519
+ maximum: Number.MAX_SAFE_INTEGER
520
+ });
521
+ const ObjectId = s.str({
522
+ minLength: 1,
523
+ maxLength: 200
524
+ });
525
+ const DataSchema = s.map(JsonValueSchema);
526
+ const IsolateObjectFactorySchema = s.obj({
527
+ handle: Id,
528
+ descriptor: s.obj({
529
+ id: s.str({ minLength: 1 }),
530
+ version: Id,
531
+ key: DataSchema,
532
+ methods: s.map(s.obj({
533
+ input: DataSchema,
534
+ output: DataSchema
535
+ }, { open: false }), {})
536
+ }, { open: false })
537
+ }, { open: false });
538
+ const IsolateObjectCreateSchema = s.obj({
539
+ objectId: ObjectId,
540
+ factory: Id,
541
+ key: JsonValueSchema
542
+ }, { open: false });
543
+ const IsolateObjectCallSchema = s.obj({
544
+ objectId: ObjectId,
545
+ method: s.str({ minLength: 1 }),
546
+ input: JsonValueSchema
547
+ }, { open: false });
548
+ const IsolateObjectIdentitySchema = s.obj({ objectId: ObjectId }, { open: false });
549
+ const IsolateObjectUpdaterSchema = s.obj({
550
+ objectId: ObjectId,
551
+ updater: Id,
552
+ value: JsonValueSchema
553
+ }, { open: false });
554
+ const IsolateObjectStateDeclarationProperties = {
555
+ name: s.str({
556
+ minLength: 1,
557
+ maxLength: 200
558
+ }),
559
+ schema: DataSchema,
560
+ version: Id,
561
+ initial: JsonValueSchema,
562
+ migrate: s.opt(s.obj({
563
+ schema: DataSchema,
564
+ version: Id,
565
+ updater: Id
566
+ }, { open: false }))
567
+ };
568
+ const IsolateObjectStateDeclarationSchema = s.obj(IsolateObjectStateDeclarationProperties, { open: false });
569
+ const IsolateObjectStateOperationSchema = s.obj({
570
+ handle: Id,
571
+ value: s.opt(JsonValueSchema),
572
+ updater: s.opt(Id)
573
+ }, { open: false });
574
+ const IsolateObjectWatchSchema = s.obj({ handle: Id }, { open: false });
575
+ const IsolateObjectStateFrameSchema = s.obj({
576
+ name: s.str({ minLength: 1 }),
577
+ version: Id,
578
+ revision: s.int({
579
+ minimum: 0,
580
+ maximum: Number.MAX_SAFE_INTEGER
581
+ }),
582
+ value: JsonValueSchema
583
+ }, { open: false });
584
+ const IsolateObjectStateBatchSchema = s.arr(IsolateObjectStateFrameSchema);
585
+ const IsolateMessageSchema = s.union([
586
+ s.obj({
587
+ kind: s.lit("object-cancel"),
588
+ id: Id
589
+ }, { open: false }),
590
+ s.obj({
591
+ kind: s.lit("object-callback"),
592
+ id: Id,
593
+ objectId: ObjectId,
594
+ method: s.union([
595
+ s.lit("state-declare"),
596
+ s.lit("state-read"),
597
+ s.lit("state-update"),
598
+ s.lit("state-watch"),
599
+ s.lit("state-next"),
600
+ s.lit("state-unwatch")
601
+ ]),
602
+ value: JsonValueSchema
603
+ }, { open: false }),
604
+ s.obj({
605
+ kind: s.lit("request"),
606
+ id: Id,
607
+ method: s.str(),
608
+ value: JsonValueSchema
609
+ }, { open: false }),
610
+ s.obj({
611
+ kind: s.lit("result"),
612
+ id: Id,
613
+ value: JsonValueSchema
614
+ }, { open: false }),
615
+ s.obj({
616
+ kind: s.lit("error"),
617
+ id: Id,
618
+ message: s.str({ maxLength: 4e3 }),
619
+ code: s.opt(s.lit("unsupported"))
620
+ }, { open: false }),
621
+ s.obj({
622
+ kind: s.lit("publication"),
623
+ value: JsonValueSchema
624
+ }, { open: false }),
625
+ s.obj({
626
+ kind: s.lit("retention"),
627
+ revision: s.int({ minimum: 1 }),
628
+ handles: s.arr(Id, { uniqueItems: true })
629
+ }, { open: false }),
630
+ s.obj({
631
+ kind: s.lit("callback"),
632
+ id: Id,
633
+ callId: Id,
634
+ method: s.union([
635
+ s.lit("update"),
636
+ s.lit("feedback"),
637
+ s.lit("command")
638
+ ]),
639
+ value: JsonValueSchema
640
+ }, { open: false })
641
+ ]);
642
+ const IsolateMessageValidator = compile(IsolateMessageSchema);
643
+ const IsolateDefinitionSchema = s.obj({
644
+ requires: s.arr(s.str({ minLength: 1 })),
645
+ references: s.arr(s.str({ minLength: 1 })),
646
+ provides: s.arr(s.str({ minLength: 1 })),
647
+ realm: s.opt(s.union([s.lit("inherit"), s.lit("isolate")])),
648
+ replacement: s.opt(s.union([s.lit("staged"), s.lit("exclusive")]))
649
+ }, { open: false });
650
+ const IsolateContributionsSchema = s.obj({
651
+ revision: s.int({ minimum: 1 }),
652
+ objectFactories: s.arr(IsolateObjectFactorySchema),
653
+ tools: s.arr(s.obj({
654
+ ...ModelToolMetadataProperties,
655
+ recovery: s.opt(s.union([s.lit("unsafe"), s.lit("safe")])),
656
+ handle: Id
657
+ }, { open: false }), {}),
658
+ namedStates: s.arr(s.obj({
659
+ ...NamedStateMetadataProperties,
660
+ handle: Id
661
+ }, { open: false }), {}),
662
+ prefixes: s.arr(PluginPrefixContributionSchema),
663
+ inputTransforms: s.arr(s.obj({
664
+ ...InputTransformMetadataProperties,
665
+ handle: Id
666
+ }, { open: false }), {}),
667
+ services: s.arr(s.obj({
668
+ key: s.str(),
669
+ value: JsonValueSchema
670
+ }, { open: false }), {})
671
+ }, { open: false });
672
+ const IsolateDefinitionValidator = compile(IsolateDefinitionSchema);
673
+ const IsolateContributionsValidator = compile(IsolateContributionsSchema);
674
+ const FrameByteLimit = 16 * 1024 * 1024;
675
+ const OutputByteLimit = 32 * 1024 * 1024;
676
+ const EmptyFrame = Buffer.alloc(0);
677
+ /**
678
+ * A bounded buffer refused the value. Control frames cannot be truncated without
679
+ * corrupting the stream, so the caller sees this code instead of a generic failure
680
+ * and decides whether the invocation, not the Worker, is what fails.
681
+ */
682
+ var IsolateQuotaError = class extends Error {
683
+ code = "quota";
684
+ constructor(message, options) {
685
+ super(message, options);
686
+ this.name = "IsolateQuotaError";
687
+ }
688
+ };
689
+ function encodeIsolateMessage(message) {
690
+ const encoded = JSON.stringify(message);
691
+ if (Buffer.byteLength(encoded) > FrameByteLimit) throw new IsolateQuotaError("Plugin isolate message exceeds its byte limit");
692
+ return encoded;
693
+ }
694
+ /** Decode peer data after the channel enforces the actual wire byte limit. */
695
+ const decodeIsolateMessage = (input) => decodeWith(IsolateMessageValidator, input);
696
+ var IsolateNotDispatchedError = class extends Error {
697
+ code = "not-dispatched";
698
+ constructor(options) {
699
+ super("Channel message was not dispatched", options);
700
+ this.name = "IsolateNotDispatchedError";
701
+ }
702
+ };
703
+ /** Fixed-size JSON control frames, not a bulk-content transport. The Writable owns
704
+ * buffered writes; each returned Promise joins its write callback without another queue. */
705
+ function isolateChannel(input, output, receive, failed, options = {}) {
706
+ const { observation } = options;
707
+ let frame = EmptyFrame;
708
+ let bytes = 0;
709
+ let stopped;
710
+ const writes = /* @__PURE__ */ new Set();
711
+ const decoder = new TextDecoder("utf-8", { fatal: true });
712
+ const observe = (callback) => {
713
+ try {
714
+ callback();
715
+ } catch {}
716
+ };
717
+ const stop = (error, report = true) => {
718
+ if (stopped !== void 0) return;
719
+ stopped = error;
720
+ frame = EmptyFrame;
721
+ bytes = 0;
722
+ for (const reject of writes) reject(error);
723
+ writes.clear();
724
+ if (report) failed(error);
725
+ };
726
+ const append = (part) => {
727
+ const required = bytes + part.byteLength;
728
+ if (required > FrameByteLimit) throw new IsolateQuotaError("Plugin isolate frame exceeds its byte limit");
729
+ if (required > frame.byteLength) {
730
+ let capacity = Math.max(1024, frame.byteLength);
731
+ while (capacity < required) capacity = Math.min(FrameByteLimit, capacity * 2);
732
+ const grown = Buffer.allocUnsafe(capacity);
733
+ frame.copy(grown, 0, 0, bytes);
734
+ frame = grown;
735
+ }
736
+ part.copy(frame, bytes);
737
+ bytes = required;
738
+ };
739
+ input.on("data", (chunk) => {
740
+ if (stopped !== void 0) return;
741
+ let reason = "framing";
742
+ try {
743
+ let offset = 0;
744
+ for (let newline = chunk.indexOf(10); newline >= 0; newline = chunk.indexOf(10, offset)) {
745
+ const part = chunk.subarray(offset, newline);
746
+ let complete = part;
747
+ if (bytes > 0) {
748
+ append(part);
749
+ complete = frame.subarray(0, bytes);
750
+ } else if (part.byteLength > FrameByteLimit) throw new IsolateQuotaError("Plugin isolate frame exceeds its byte limit");
751
+ const text = decoder.decode(complete);
752
+ frame = EmptyFrame;
753
+ bytes = 0;
754
+ offset = newline + 1;
755
+ const parsed = JSON.parse(text);
756
+ reason = "schema";
757
+ const message = decodeIsolateMessage(parsed);
758
+ reason = "framing";
759
+ if (observation?.frame !== void 0) observe(() => observation.frame?.("inbound", complete.byteLength + 1));
760
+ Promise.resolve(receive(message)).catch((cause) => stop(ensureError(cause)));
761
+ if (stopped !== void 0) return;
762
+ }
763
+ if (offset < chunk.byteLength) append(chunk.subarray(offset));
764
+ } catch (cause) {
765
+ if (observation?.failed !== void 0) observe(() => observation.failed?.(reason));
766
+ stop(ensureError(cause));
767
+ }
768
+ });
769
+ const transportFailed = (error) => {
770
+ if (observation?.failed !== void 0) observe(() => observation.failed?.("transport"));
771
+ stop(error);
772
+ };
773
+ input.on("error", transportFailed);
774
+ output.on("error", transportFailed);
775
+ input.once("end", () => stop(/* @__PURE__ */ new Error("Channel input ended"), false));
776
+ output.once("close", () => stop(/* @__PURE__ */ new Error("Channel output closed"), false));
777
+ options.signal?.addEventListener("abort", () => stop(/* @__PURE__ */ new Error("Channel owner closed"), false), { once: true });
778
+ if (options.signal?.aborted) stop(/* @__PURE__ */ new Error("Channel owner closed"), false);
779
+ if (observation?.queue !== void 0) output.on("drain", () => observe(() => observation.queue?.(output.writableLength)));
780
+ return (message, signal) => new Promise((resolve$1, reject) => {
781
+ if (stopped !== void 0) {
782
+ reject(new IsolateNotDispatchedError({ cause: stopped }));
783
+ return;
784
+ }
785
+ let encoded;
786
+ try {
787
+ signal?.throwIfAborted();
788
+ if (output.destroyed) throw new Error("Channel output closed");
789
+ encoded = Buffer.from(encodeIsolateMessage(message) + "\n");
790
+ if (output.writableLength + encoded.byteLength > OutputByteLimit) {
791
+ if (observation?.failed !== void 0) observe(() => observation.failed?.("output_limit"));
792
+ throw new IsolateQuotaError("Plugin isolate output queue exceeds its byte limit");
793
+ }
794
+ options.admit?.(message);
795
+ } catch (cause) {
796
+ reject(new IsolateNotDispatchedError({ cause: ensureError(cause) }));
797
+ return;
798
+ }
799
+ writes.add(reject);
800
+ try {
801
+ output.write(encoded, (error) => {
802
+ writes.delete(reject);
803
+ if (isError(error)) reject(error);
804
+ else resolve$1();
805
+ });
806
+ if (observation?.frame !== void 0) observe(() => observation.frame?.("outbound", encoded.byteLength));
807
+ if (observation?.queue !== void 0) observe(() => observation.queue?.(output.writableLength));
808
+ } catch (cause) {
809
+ writes.delete(reject);
810
+ stop(ensureError(cause));
811
+ reject(ensureError(cause));
812
+ }
813
+ });
814
+ }
815
+
816
+ //#endregion
817
+ //#region src/node/object-facet.ts
818
+ const CancelDecoder = compile(s.obj({ id: s.int({
819
+ minimum: 1,
820
+ maximum: Number.MAX_SAFE_INTEGER
821
+ }) }, { open: false }));
822
+ const ControlActions = new Set([
823
+ "watch",
824
+ "release",
825
+ "hello",
826
+ "lookup",
827
+ "abandon",
828
+ "rehold"
829
+ ]);
830
+ const PositiveInteger = s.int({
831
+ minimum: 1,
832
+ maximum: Number.MAX_SAFE_INTEGER
833
+ });
834
+ const TimerDuration = s.int({
835
+ minimum: 1,
836
+ maximum: 2147483647
837
+ });
838
+ /** The Host owns connection authentication and placement. Closing the wire aborts requests
839
+ * and releases only this connection's holds; already dispatched effects are never replayed. */
840
+ function serveObjectFacet(socket, facet, options = {}) {
841
+ if (socket instanceof Socket) socket.setNoDelay(true);
842
+ const window = Semaphore.makeUnsafe(decode(PositiveInteger, options.concurrency ?? 4096));
843
+ const pending = /* @__PURE__ */ new Map();
844
+ let stopping;
845
+ let finish;
846
+ let fail;
847
+ const done = new Promise((resolve$1, reject) => {
848
+ finish = resolve$1;
849
+ fail = reject;
850
+ });
851
+ const stop = (error) => {
852
+ stopping ??= (async () => {
853
+ for (const call of pending.values()) call.controller.abort();
854
+ socket.destroy();
855
+ const errors = (await Promise.allSettled([...facet.resumable ? [] : [Effect.runPromise(facet.close)], ...[...pending.values()].map((call) => call.settled)])).flatMap((outcome) => outcome.status === "rejected" ? [ensureError(outcome.reason)] : []);
856
+ if (error !== void 0) errors.push(error);
857
+ const failure = aggregateCleanupFailure([...new Set(errors)], "Object facet connection cleanup failed");
858
+ if (failure !== void 0) throw failure;
859
+ })();
860
+ stopping.then(() => finish?.(), (cause) => fail?.(ensureError(cause)));
861
+ };
862
+ const send = isolateChannel(socket, socket, receive, stop);
863
+ function receive(message) {
864
+ if (stopping !== void 0) return;
865
+ if (message.kind !== "request") {
866
+ stop(/* @__PURE__ */ new Error("Unexpected Object facet message"));
867
+ return;
868
+ }
869
+ if (message.method === "facet.cancel") {
870
+ const cancelled = decodeWith(CancelDecoder, message.value);
871
+ pending.get(cancelled.id)?.controller.abort();
872
+ return;
873
+ }
874
+ if (message.method !== "facet.request" || pending.has(message.id)) {
875
+ stop(/* @__PURE__ */ new Error("Invalid Object facet request identity"));
876
+ return;
877
+ }
878
+ let request;
879
+ try {
880
+ request = decodeObjectFacetRequest(message.value);
881
+ } catch {
882
+ return send({
883
+ kind: "result",
884
+ id: message.id,
885
+ value: {
886
+ ok: false,
887
+ code: "invalid-request",
888
+ message: "Invalid Object facet request"
889
+ }
890
+ });
891
+ }
892
+ const controller = new AbortController();
893
+ const work = facet.request(request, ControlActions.has(request.action) ? void 0 : window);
894
+ const settled = Effect.runPromise(work, { signal: controller.signal }).then((reply) => {
895
+ if (stopping === void 0) return send({
896
+ kind: "result",
897
+ id: message.id,
898
+ value: reply
899
+ });
900
+ }).catch((cause) => {
901
+ if (stopping !== void 0) return;
902
+ if (!controller.signal.aborted) {
903
+ stop(ensureError(cause));
904
+ return;
905
+ }
906
+ return send({
907
+ kind: "result",
908
+ id: message.id,
909
+ value: {
910
+ ok: false,
911
+ code: "outcome-unknown",
912
+ message: "Object request was interrupted after dispatch; the external effect may have occurred"
913
+ }
914
+ });
915
+ }).finally(() => pending.delete(message.id));
916
+ pending.set(message.id, {
917
+ controller,
918
+ settled
919
+ });
920
+ return settled;
921
+ }
922
+ socket.once("close", () => stop());
923
+ socket.once("end", () => stop());
924
+ return done;
925
+ }
926
+ /** Owns a preconnected authenticated Duplex. It never reconnects or retries a request. */
927
+ function objectFacetTransport(socket, options = {}) {
928
+ if (socket instanceof Socket) socket.setNoDelay(true);
929
+ const captured = decode(s.obj({
930
+ requestTimeoutMs: s.opt(TimerDuration),
931
+ cancellationTimeoutMs: s.opt(TimerDuration),
932
+ concurrency: s.opt(PositiveInteger)
933
+ }, { open: true }), options);
934
+ const window = Semaphore.makeUnsafe(captured.concurrency ?? 4096);
935
+ const connection = new AbortController();
936
+ const pending = /* @__PURE__ */ new Map();
937
+ let nextId = 0;
938
+ const fail = (error) => {
939
+ if (connection.signal.aborted) return;
940
+ connection.abort(error);
941
+ for (const call of pending.values()) {
942
+ call.dispose();
943
+ call.reject(error);
944
+ }
945
+ pending.clear();
946
+ socket.destroy();
947
+ };
948
+ const send = isolateChannel(socket, socket, (message) => {
949
+ if (message.kind !== "result") {
950
+ fail(/* @__PURE__ */ new Error("Unexpected Object facet response"));
951
+ return;
952
+ }
953
+ const reply = decodeObjectFacetReply(message.value);
954
+ const call = pending.get(message.id);
955
+ if (call === void 0) return;
956
+ pending.delete(message.id);
957
+ call.dispose();
958
+ call.resolve(reply);
959
+ }, fail, {
960
+ signal: connection.signal,
961
+ admit: (message) => {
962
+ if (message.kind !== "request" || message.method !== "facet.request") return;
963
+ const call = pending.get(message.id);
964
+ if (call !== void 0) call.dispatched = true;
965
+ }
966
+ });
967
+ socket.once("end", () => fail(/* @__PURE__ */ new Error("Object facet connection ended")));
968
+ socket.once("close", () => fail(/* @__PURE__ */ new Error("Object facet connection closed")));
969
+ return {
970
+ signal: connection.signal,
971
+ request: async (request, signal) => {
972
+ const queued = AbortSignal.any([signal, connection.signal]);
973
+ const limited = !ControlActions.has(request.action);
974
+ const permitScope = Scope.makeUnsafe();
975
+ if (limited) try {
976
+ await Effect.runPromise(Scope.provide(Effect.uninterruptibleMask((restore) => Effect.acquireRelease(restore(window.take(1)), () => window.release(1))), permitScope), { signal: queued });
977
+ } catch (cause) {
978
+ Effect.runSync(Scope.close(permitScope, Exit.void));
979
+ throw new ObjectFacetUnavailableError("Object facet request was not dispatched", { cause });
980
+ }
981
+ const release = () => {
982
+ Effect.runSync(Scope.close(permitScope, Exit.void));
983
+ };
984
+ return new Promise((resolve$1, reject) => {
985
+ if (connection.signal.aborted || socket.destroyed || signal.aborted) {
986
+ release();
987
+ reject(new ObjectFacetUnavailableError("Object facet request was not dispatched"));
988
+ return;
989
+ }
990
+ if (nextId >= Number.MAX_SAFE_INTEGER) {
991
+ release();
992
+ reject(new ObjectFacetUnavailableError("Object facet request identity exhausted"));
993
+ return;
994
+ }
995
+ const id = ++nextId;
996
+ let cancelling = false;
997
+ let timer;
998
+ let cancellationTimer;
999
+ const cancel = () => {
1000
+ const call = pending.get(id);
1001
+ if (call === void 0 || !call.dispatched || cancelling) return;
1002
+ cancelling = true;
1003
+ if (nextId >= Number.MAX_SAFE_INTEGER) {
1004
+ fail(/* @__PURE__ */ new Error("Object facet cancellation capacity exceeded"));
1005
+ return;
1006
+ }
1007
+ const cancellationId = ++nextId;
1008
+ clearTimeout(timer);
1009
+ if (captured.cancellationTimeoutMs !== void 0) {
1010
+ cancellationTimer = setTimeout(() => reject(/* @__PURE__ */ new Error("Object facet cancellation observation ended")), captured.cancellationTimeoutMs);
1011
+ cancellationTimer.unref();
1012
+ }
1013
+ send({
1014
+ kind: "request",
1015
+ id: cancellationId,
1016
+ method: "facet.cancel",
1017
+ value: { id }
1018
+ }).catch((cause) => {
1019
+ if (pending.has(id)) fail(ensureError(cause));
1020
+ });
1021
+ };
1022
+ pending.set(id, {
1023
+ resolve: resolve$1,
1024
+ reject,
1025
+ dispatched: false,
1026
+ dispose: () => {
1027
+ clearTimeout(timer);
1028
+ clearTimeout(cancellationTimer);
1029
+ signal.removeEventListener("abort", cancel);
1030
+ release();
1031
+ }
1032
+ });
1033
+ if (captured.requestTimeoutMs !== void 0 && request.action !== "watch") {
1034
+ timer = setTimeout(cancel, captured.requestTimeoutMs);
1035
+ timer.unref();
1036
+ }
1037
+ signal.addEventListener("abort", cancel, { once: true });
1038
+ send({
1039
+ kind: "request",
1040
+ id,
1041
+ method: "facet.request",
1042
+ value: request
1043
+ }, signal).catch((cause) => {
1044
+ if (cause instanceof IsolateNotDispatchedError) {
1045
+ const call = pending.get(id);
1046
+ pending.delete(id);
1047
+ call?.dispose();
1048
+ call?.reject(new ObjectFacetUnavailableError("Object facet request was not dispatched", { cause }));
1049
+ } else fail(ensureError(cause));
1050
+ });
1051
+ });
1052
+ },
1053
+ close: async () => {
1054
+ if (socket.closed) return;
1055
+ const closed = new Promise((resolve$1) => socket.once("close", resolve$1));
1056
+ fail(/* @__PURE__ */ new Error("Object facet transport closed by its owner"));
1057
+ await closed;
1058
+ }
1059
+ };
1060
+ }
1061
+
1062
+ //#endregion
1063
+ //#region src/node/process/error.ts
1064
+ /** The first process termination cause applies to every invocation sharing that worker. */
1065
+ var PluginProcessError = class extends Error {
1066
+ constructor(code, message, options) {
1067
+ super(message, options);
1068
+ this.code = code;
1069
+ this.name = "PluginProcessError";
1070
+ }
1071
+ };
1072
+
1073
+ //#endregion
1074
+ //#region src/node/process/diagnostics.ts
1075
+ const MetadataBytes = 192;
1076
+ /** The Loader owns one capture budget shared by all of its workers. */
1077
+ var PluginDiagnosticCapture = class {
1078
+ #options;
1079
+ #lineLimit;
1080
+ #workerRate;
1081
+ #hostRate;
1082
+ #workerLimit;
1083
+ #hostLimit;
1084
+ #retention;
1085
+ #diagnostic;
1086
+ #dropped;
1087
+ #buffer = [];
1088
+ #workerBytes = /* @__PURE__ */ new Map();
1089
+ #hostWindow = {
1090
+ startedAt: performance.now(),
1091
+ bytes: 0
1092
+ };
1093
+ #drops = {
1094
+ rate: 0,
1095
+ size: 0,
1096
+ buffer: 0,
1097
+ redaction: 0,
1098
+ invalid_utf8: 0,
1099
+ expired: 0,
1100
+ closed: 0
1101
+ };
1102
+ #bytes = 0;
1103
+ #observerFailures = 0;
1104
+ #closed = false;
1105
+ constructor(options = {}, diagnostic = () => {}, dropped = () => {}) {
1106
+ this.#options = { ...options };
1107
+ this.#diagnostic = diagnostic;
1108
+ this.#dropped = dropped;
1109
+ const byteBudget = s.int({
1110
+ minimum: MetadataBytes,
1111
+ maximum: 16 * 1024 * 1024
1112
+ });
1113
+ this.#lineLimit = decode(byteBudget, options.maxLineBytes ?? 4096);
1114
+ this.#workerRate = decode(byteBudget, options.maxWorkerBytesPerSecond ?? 64 * 1024);
1115
+ this.#hostRate = decode(byteBudget, options.maxHostBytesPerSecond ?? 1024 * 1024);
1116
+ this.#workerLimit = decode(byteBudget, options.maxWorkerBufferBytes ?? 64 * 1024);
1117
+ this.#hostLimit = decode(byteBudget, options.maxHostBufferBytes ?? 1024 * 1024);
1118
+ this.#retention = decode(s.int({
1119
+ minimum: 1,
1120
+ maximum: 864e5
1121
+ }), options.retentionMs ?? 3e5);
1122
+ }
1123
+ snapshot() {
1124
+ this.#expire(performance.now());
1125
+ return {
1126
+ bytes: this.#bytes,
1127
+ drops: { ...this.#drops },
1128
+ records: this.#buffer.map(({ record }) => ({ ...record })),
1129
+ observerFailures: this.#observerFailures
1130
+ };
1131
+ }
1132
+ drain(identity) {
1133
+ const identityCharacters = identity.workerId.length + identity.activationId.length + identity.entryId.length;
1134
+ const metadataBytes = identityCharacters > this.#hostLimit ? MetadataBytes + 6 * identityCharacters : MetadataBytes + Buffer.byteLength(JSON.stringify(identity));
1135
+ const prefix = Buffer.alloc(this.#options.sanitize === void 0 ? 0 : this.#lineLimit);
1136
+ const window = {
1137
+ startedAt: performance.now(),
1138
+ bytes: 0
1139
+ };
1140
+ let prefixBytes = 0;
1141
+ let lineBytes = 0;
1142
+ let ended = false;
1143
+ const batch = /* @__PURE__ */ new Map();
1144
+ const drop = (reason, bytes) => {
1145
+ const previous = batch.get(reason);
1146
+ batch.set(reason, {
1147
+ bytes: (previous?.bytes ?? 0) + bytes,
1148
+ lines: (previous?.lines ?? 0) + 1
1149
+ });
1150
+ };
1151
+ const flushDrops = () => {
1152
+ for (const [reason, counts] of batch) this.#drop({
1153
+ ...identity,
1154
+ reason,
1155
+ ...counts
1156
+ });
1157
+ batch.clear();
1158
+ };
1159
+ const append = (part) => {
1160
+ const available = this.#lineLimit - prefixBytes;
1161
+ const copied = Math.min(available, part.byteLength);
1162
+ if (copied > 0 && prefix.byteLength > 0) part.copy(prefix, prefixBytes, 0, copied);
1163
+ prefixBytes += copied;
1164
+ lineBytes += part.byteLength;
1165
+ };
1166
+ const finish = () => {
1167
+ const now = performance.now();
1168
+ const chargedBytes = lineBytes + metadataBytes;
1169
+ if (!(this.#take(window, chargedBytes, this.#workerRate, now) && this.#take(this.#hostWindow, chargedBytes, this.#hostRate, now))) drop("rate", lineBytes);
1170
+ else {
1171
+ const truncated = lineBytes > prefixBytes;
1172
+ if (truncated) drop("size", lineBytes - prefixBytes);
1173
+ let text;
1174
+ if (this.#options.sanitize !== void 0) {
1175
+ const decoder = new TextDecoder("utf-8", { fatal: true });
1176
+ let decoded;
1177
+ try {
1178
+ decoded = decoder.decode(prefix.subarray(0, prefixBytes), { stream: truncated });
1179
+ } catch {
1180
+ drop("invalid_utf8", prefixBytes);
1181
+ }
1182
+ if (decoded !== void 0) {
1183
+ try {
1184
+ text = this.#options.sanitize(decoded);
1185
+ } catch {}
1186
+ if (text === void 0) drop("redaction", prefixBytes);
1187
+ }
1188
+ if (text !== void 0 && Buffer.byteLength(text) > this.#lineLimit) {
1189
+ drop("size", Buffer.byteLength(text));
1190
+ text = void 0;
1191
+ }
1192
+ }
1193
+ const record = {
1194
+ ...identity,
1195
+ recordedAt: Date.now(),
1196
+ source: "plugin.author.stderr",
1197
+ bytes: lineBytes,
1198
+ truncated,
1199
+ text
1200
+ };
1201
+ this.#retain(record, now, metadataBytes);
1202
+ this.#observe(() => this.#diagnostic({ ...record }));
1203
+ }
1204
+ prefixBytes = 0;
1205
+ lineBytes = 0;
1206
+ };
1207
+ return {
1208
+ write: (chunk) => {
1209
+ if (ended || this.#closed) return;
1210
+ let offset = 0;
1211
+ for (let newline = chunk.indexOf(10); newline >= 0; newline = chunk.indexOf(10, offset)) {
1212
+ append(chunk.subarray(offset, newline));
1213
+ finish();
1214
+ offset = newline + 1;
1215
+ }
1216
+ if (offset < chunk.byteLength) append(chunk.subarray(offset));
1217
+ flushDrops();
1218
+ },
1219
+ end: () => {
1220
+ if (ended) return;
1221
+ ended = true;
1222
+ if (lineBytes > 0) finish();
1223
+ flushDrops();
1224
+ },
1225
+ error: () => {
1226
+ if (ended) return;
1227
+ ended = true;
1228
+ drop("closed", lineBytes);
1229
+ flushDrops();
1230
+ }
1231
+ };
1232
+ }
1233
+ #take(window, bytes, limit, now) {
1234
+ if (now - window.startedAt >= 1e3) {
1235
+ window.startedAt = now;
1236
+ window.bytes = 0;
1237
+ }
1238
+ window.bytes = Math.min(window.bytes + bytes, limit + 1);
1239
+ return window.bytes <= limit;
1240
+ }
1241
+ #retain(record, now, metadataBytes) {
1242
+ this.#expire(now);
1243
+ const bytes = metadataBytes + 6 * (record.text?.length ?? 0);
1244
+ if (bytes > this.#workerLimit || bytes > this.#hostLimit) {
1245
+ this.#drop({
1246
+ ...record,
1247
+ reason: "buffer",
1248
+ bytes,
1249
+ lines: 1
1250
+ });
1251
+ return;
1252
+ }
1253
+ let workerBytes = this.#workerBytes.get(record.workerId) ?? 0;
1254
+ while (workerBytes + bytes > this.#workerLimit) {
1255
+ const index = this.#buffer.findIndex((entry) => entry.record.workerId === record.workerId);
1256
+ if (index < 0) break;
1257
+ workerBytes -= this.#remove(index, "buffer");
1258
+ }
1259
+ while (this.#bytes + bytes > this.#hostLimit && this.#buffer.length > 0) this.#remove(0, "buffer");
1260
+ this.#buffer.push({
1261
+ record,
1262
+ retainedAt: now,
1263
+ bytes
1264
+ });
1265
+ this.#bytes += bytes;
1266
+ this.#workerBytes.set(record.workerId, (this.#workerBytes.get(record.workerId) ?? 0) + bytes);
1267
+ }
1268
+ #expire(now) {
1269
+ while (this.#buffer[0] !== void 0 && now - this.#buffer[0].retainedAt >= this.#retention) this.#remove(0, "expired");
1270
+ }
1271
+ #remove(index, reason) {
1272
+ const [entry] = this.#buffer.splice(index, 1);
1273
+ if (entry === void 0) return 0;
1274
+ this.#bytes -= entry.bytes;
1275
+ const workerBytes = (this.#workerBytes.get(entry.record.workerId) ?? 0) - entry.bytes;
1276
+ if (workerBytes === 0) this.#workerBytes.delete(entry.record.workerId);
1277
+ else this.#workerBytes.set(entry.record.workerId, workerBytes);
1278
+ this.#drop({
1279
+ ...entry.record,
1280
+ reason,
1281
+ bytes: entry.bytes,
1282
+ lines: 1
1283
+ });
1284
+ return entry.bytes;
1285
+ }
1286
+ #drop(record) {
1287
+ this.#drops[record.reason] += record.lines;
1288
+ const observation = {
1289
+ loaderId: record.loaderId,
1290
+ workerId: record.workerId,
1291
+ activationId: record.activationId,
1292
+ entryId: record.entryId,
1293
+ pid: record.pid,
1294
+ reason: record.reason,
1295
+ bytes: record.bytes,
1296
+ lines: record.lines
1297
+ };
1298
+ this.#observe(() => this.#dropped(observation));
1299
+ }
1300
+ #observe(callback) {
1301
+ try {
1302
+ const result = callback();
1303
+ if (isPromise(result)) result.catch(() => {
1304
+ this.#observerFailures += 1;
1305
+ });
1306
+ } catch {
1307
+ this.#observerFailures += 1;
1308
+ }
1309
+ }
1310
+ /** Host-owned capture outlives borrowers; close after every attached Loader has closed. */
1311
+ close() {
1312
+ this.#closed = true;
1313
+ this.#buffer.length = 0;
1314
+ this.#workerBytes.clear();
1315
+ this.#bytes = 0;
1316
+ }
1317
+ };
1318
+
1319
+ //#endregion
1320
+ //#region src/node/process/sandbox.ts
1321
+ /** Host data/network are absent; runtime code is readable and descendants remain confined. */
1322
+ async function pluginSandboxCommand(worker, heapSize) {
1323
+ const node = await realpath(process.execPath);
1324
+ const runtime = await realpath(worker);
1325
+ const heapArguments = heapSize === void 0 ? [] : [`--max-old-space-size=${heapSize}`];
1326
+ const libraries = decode(s.obj({ sharedObjects: s.arr(s.str()) }, { open: true }), process.report.getReport()).sharedObjects.filter(isAbsolute);
1327
+ if (process.platform === "darwin") return {
1328
+ executable: "/usr/bin/sandbox-exec",
1329
+ args: [
1330
+ "-p",
1331
+ [
1332
+ "(version 1)",
1333
+ "(deny default)",
1334
+ `(allow process-exec (literal ${JSON.stringify(node)}))`,
1335
+ "(allow file-read-metadata)",
1336
+ "(allow sysctl-read)",
1337
+ "(allow file-read* (subpath \"/usr/lib\") (subpath \"/System/Library\") (literal \"/\") (literal \"/dev/null\"))",
1338
+ "(allow file-write* (literal \"/dev/null\"))",
1339
+ `(allow file-read* (literal ${JSON.stringify(runtime)}) (literal ${JSON.stringify(node)}) ${libraries.map((path) => `(literal ${JSON.stringify(path)})`).join(" ")})`
1340
+ ].join("\n"),
1341
+ node,
1342
+ ...heapArguments,
1343
+ runtime
1344
+ ]
1345
+ };
1346
+ if (process.platform === "linux") return {
1347
+ executable: "bwrap",
1348
+ args: [
1349
+ "--unshare-all",
1350
+ "--die-with-parent",
1351
+ "--new-session",
1352
+ "--tmpfs",
1353
+ "/",
1354
+ "--proc",
1355
+ "/proc",
1356
+ "--dev",
1357
+ "/dev",
1358
+ "--ro-bind-try",
1359
+ "/etc/ld.so.cache",
1360
+ "/etc/ld.so.cache",
1361
+ ...libraries.flatMap((path) => [
1362
+ "--ro-bind",
1363
+ path,
1364
+ path
1365
+ ]),
1366
+ "--ro-bind",
1367
+ node,
1368
+ node,
1369
+ "--ro-bind",
1370
+ runtime,
1371
+ runtime,
1372
+ "--chdir",
1373
+ "/",
1374
+ node,
1375
+ ...heapArguments,
1376
+ runtime
1377
+ ]
1378
+ };
1379
+ throw new Error(`Plugin process sandbox is unavailable on ${process.platform}`);
1380
+ }
1381
+
1382
+ //#endregion
1383
+ //#region src/node/process/object-factories.ts
1384
+ /** The capability borrows one native generation's state; all implementation code remains remote. */
1385
+ var IsolatedObjectFactories = class {
1386
+ #capabilities = /* @__PURE__ */ new Map();
1387
+ constructor(invoke, release, assertAuthorized) {
1388
+ this.invoke = invoke;
1389
+ this.release = release;
1390
+ this.assertAuthorized = assertAuthorized;
1391
+ }
1392
+ #call(method, value) {
1393
+ return Effect.uninterruptibleMask((restore) => Effect.gen({ self: this }, function* () {
1394
+ const controller = new AbortController();
1395
+ const pending = yield* Effect.try({
1396
+ try: () => {
1397
+ this.assertAuthorized();
1398
+ return this.invoke(method, value, controller.signal);
1399
+ },
1400
+ catch: ensureError
1401
+ });
1402
+ const settled = Effect.tryPromise({
1403
+ try: () => pending,
1404
+ catch: ensureError
1405
+ });
1406
+ return yield* restore(settled).pipe(Effect.onInterrupt(() => Effect.sync(() => controller.abort()).pipe(Effect.andThen(settled), Effect.asVoid)));
1407
+ }));
1408
+ }
1409
+ factory(declaration, retain) {
1410
+ validateDataSchema(declaration.descriptor.key);
1411
+ for (const method of Object.values(declaration.descriptor.methods)) {
1412
+ validateDataSchema(method.input);
1413
+ validateDataSchema(method.output);
1414
+ }
1415
+ return bindCallbackRetention({
1416
+ typeId: declaration.descriptor.id,
1417
+ version: declaration.descriptor.version,
1418
+ descriptor: declaration.descriptor,
1419
+ assertAvailable: this.assertAuthorized,
1420
+ create: (_key, self) => Effect.gen({ self: this }, function* () {
1421
+ const held = yield* Effect.acquireRelease(Effect.try({
1422
+ try: () => {
1423
+ this.assertAuthorized();
1424
+ const id = randomUUID();
1425
+ const capability = {
1426
+ host: objectSelfStateHost(self),
1427
+ controller: new AbortController(),
1428
+ states: /* @__PURE__ */ new Map(),
1429
+ watches: /* @__PURE__ */ new Map(),
1430
+ nextHandle: 0
1431
+ };
1432
+ const releaseFactory = retain();
1433
+ this.#capabilities.set(id, capability);
1434
+ return {
1435
+ id,
1436
+ capability,
1437
+ releaseFactory
1438
+ };
1439
+ },
1440
+ catch: ensureError
1441
+ }), ({ id, capability, releaseFactory }) => Effect.promise(async () => {
1442
+ this.assertAuthorized();
1443
+ await this.release(id);
1444
+ capability.controller.abort();
1445
+ for (const watch$1 of capability.watches.values()) await Effect.runPromise(Scope.close(watch$1.scope, Exit.void));
1446
+ this.#capabilities.delete(id);
1447
+ releaseFactory();
1448
+ }));
1449
+ yield* this.#call("object-create", {
1450
+ objectId: held.id,
1451
+ factory: declaration.handle,
1452
+ key: _key
1453
+ });
1454
+ return { call: (method, input) => {
1455
+ const contract = declaration.descriptor.methods[method];
1456
+ if (contract === void 0) return Effect.fail(/* @__PURE__ */ new TypeError("Unknown Object method"));
1457
+ return this.#call("object-call", {
1458
+ objectId: held.id,
1459
+ method,
1460
+ input
1461
+ }).pipe(Effect.flatMap((value) => Effect.try({
1462
+ try: () => decode(contract.output, value),
1463
+ catch: (cause) => new ObjectInvocationUnknownError("Isolated Object result violated its captured contract", { cause })
1464
+ })));
1465
+ } };
1466
+ })
1467
+ }, retain);
1468
+ }
1469
+ callback(objectId, method, value, signal) {
1470
+ const capability = this.#capabilities.get(objectId);
1471
+ if (capability === void 0) throw new Error("Unknown isolated Object capability");
1472
+ this.assertAuthorized();
1473
+ const operation = Effect.gen({ self: this }, function* () {
1474
+ if (method === "state-declare") {
1475
+ const declaration = decode(IsolateObjectStateDeclarationSchema, value);
1476
+ validateDataSchema(declaration.schema);
1477
+ const migration = declaration.migrate;
1478
+ if (migration !== void 0) validateDataSchema(migration.schema);
1479
+ const schema = declaration.schema;
1480
+ const port = yield* capability.host.state({
1481
+ name: declaration.name,
1482
+ schema: declaration.schema,
1483
+ version: declaration.version,
1484
+ initial: decode(schema, declaration.initial),
1485
+ migrate: migration === void 0 ? void 0 : {
1486
+ schema: migration.schema,
1487
+ version: migration.version,
1488
+ transform: (previous) => this.#call("object-update", {
1489
+ objectId,
1490
+ updater: migration.updater,
1491
+ value: previous
1492
+ }).pipe(Effect.map((next) => decode(schema, next)))
1493
+ }
1494
+ });
1495
+ const handle = ++capability.nextHandle;
1496
+ capability.states.set(handle, {
1497
+ port,
1498
+ schema: declaration.schema
1499
+ });
1500
+ return handle;
1501
+ }
1502
+ if (new Set(["state-unwatch", "state-next"]).has(method)) {
1503
+ const { handle } = decode(IsolateObjectWatchSchema, value);
1504
+ const watch$1 = capability.watches.get(handle);
1505
+ if (watch$1 === void 0) return yield* Effect.fail(/* @__PURE__ */ new Error("Unknown isolated Object state subscription"));
1506
+ if (method === "state-unwatch") {
1507
+ capability.watches.delete(handle);
1508
+ yield* Scope.close(watch$1.scope, Exit.void);
1509
+ return null;
1510
+ }
1511
+ if (watch$1.busy) return yield* Effect.fail(/* @__PURE__ */ new Error("An isolated Object state pull is already pending"));
1512
+ watch$1.busy = true;
1513
+ return yield* watch$1.pull.pipe(Pull.catchDone(() => Effect.succeed(null)), Effect.map(captureJsonValue), Effect.ensuring(Effect.sync(() => {
1514
+ watch$1.busy = false;
1515
+ })));
1516
+ }
1517
+ const stateOperation = decode(IsolateObjectStateOperationSchema, value);
1518
+ const state = capability.states.get(stateOperation.handle);
1519
+ if (state === void 0) return yield* Effect.fail(/* @__PURE__ */ new Error("Unknown isolated Object state capability"));
1520
+ if (method === "state-read") return captureJsonValue(yield* state.port.read);
1521
+ if (method === "state-update") {
1522
+ if (stateOperation.updater === void 0) return yield* Effect.fail(/* @__PURE__ */ new Error("Missing isolated Object updater"));
1523
+ const updater = stateOperation.updater;
1524
+ yield* state.port.modify((current) => this.#call("object-update", {
1525
+ objectId,
1526
+ updater,
1527
+ value: current
1528
+ }).pipe(Effect.map((next) => decode(state.schema, next))));
1529
+ return null;
1530
+ }
1531
+ if (method !== "state-watch") return yield* Effect.fail(/* @__PURE__ */ new Error("Unknown isolated Object state operation"));
1532
+ return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
1533
+ const scope = yield* Scope.make();
1534
+ const pull = yield* restore(Scope.provide(Stream.toPull(state.port.changes), scope)).pipe(Effect.onError(() => Scope.close(scope, Exit.void)));
1535
+ const handle = ++capability.nextHandle;
1536
+ capability.watches.set(handle, {
1537
+ scope,
1538
+ pull,
1539
+ busy: false
1540
+ });
1541
+ return handle;
1542
+ }));
1543
+ });
1544
+ return Effect.runPromise(operation, { signal: AbortSignal.any([signal, capability.controller.signal]) });
1545
+ }
1546
+ stop(error) {
1547
+ for (const capability of this.#capabilities.values()) capability.controller.abort(error);
1548
+ }
1549
+ };
1550
+
1551
+ //#endregion
1552
+ //#region src/node/process/loader.ts
1553
+ const SpawnPressureSchema = s.obj({ code: s.union([
1554
+ s.lit("EAGAIN"),
1555
+ s.lit("ENOMEM"),
1556
+ s.lit("EMFILE")
1557
+ ]) }, { open: true });
1558
+ var PluginProcess = class PluginProcess {
1559
+ #child;
1560
+ #write;
1561
+ #exited;
1562
+ #pending = /* @__PURE__ */ new Map();
1563
+ #lifecycleTimeout;
1564
+ #observation;
1565
+ #identity;
1566
+ #startedAt = Date.now();
1567
+ #startedMonotonic = performance.now();
1568
+ #state = "starting";
1569
+ #nextId = 0;
1570
+ #dead = false;
1571
+ #termination;
1572
+ #closing;
1573
+ publication;
1574
+ objectCallback;
1575
+ objectStopped;
1576
+ #objectPending = /* @__PURE__ */ new Map();
1577
+ constructor(child, lifecycleTimeout, authorize, observation) {
1578
+ this.#child = child;
1579
+ this.#lifecycleTimeout = lifecycleTimeout;
1580
+ this.#observation = observation;
1581
+ this.#identity = {
1582
+ ...observation.identity,
1583
+ pid: child.pid
1584
+ };
1585
+ const diagnostics = observation.capture.drain(this.#identity);
1586
+ child.stderr.on("data", (chunk) => diagnostics.write(chunk));
1587
+ child.stderr.once("end", () => diagnostics.end());
1588
+ child.stderr.on("error", () => diagnostics.error());
1589
+ this.#exited = new Promise((resolve$1) => {
1590
+ child.once("close", (code, signal) => {
1591
+ diagnostics.end();
1592
+ this.#dead = true;
1593
+ this.#termination ??= this.#closing === void 0 ? new PluginProcessError("crashed", `Plugin isolate exited with code ${code ?? "none"} and signal ${signal ?? "none"}`) : new PluginProcessError("closed", "Plugin isolate closed");
1594
+ this.#rejectAll(this.#termination);
1595
+ observation.exited(this, {
1596
+ ...this.#identity,
1597
+ reason: this.#termination.code,
1598
+ exitCode: code,
1599
+ signal,
1600
+ durationMs: performance.now() - this.#startedMonotonic,
1601
+ startedAtUnixMs: this.#startedAt,
1602
+ endedAtUnixMs: Date.now()
1603
+ });
1604
+ resolve$1();
1605
+ });
1606
+ });
1607
+ child.on("error", (cause) => {
1608
+ this.#termination ??= new PluginProcessError(child.pid === void 0 ? "spawn" : "crashed", "Plugin isolate process failed", { cause });
1609
+ });
1610
+ const receive = (message) => {
1611
+ if (this.#termination !== void 0) return;
1612
+ try {
1613
+ if (message.kind === "publication") {
1614
+ if (this.publication === void 0) throw new Error("Plugin isolate publication is not admitted");
1615
+ this.publication(message.value);
1616
+ return;
1617
+ }
1618
+ if (message.kind === "object-cancel") {
1619
+ this.#objectPending.get(message.id)?.controller.abort();
1620
+ return;
1621
+ }
1622
+ if (message.kind === "object-callback") {
1623
+ if (this.objectCallback === void 0 || this.#objectPending.has(message.id)) throw new Error("Plugin isolate Object callback is not admitted");
1624
+ const controller = new AbortController();
1625
+ const settled = this.objectCallback(message, controller.signal).then((value) => this.#send({
1626
+ kind: "result",
1627
+ id: message.id,
1628
+ value
1629
+ }), (cause) => this.#send({
1630
+ kind: "error",
1631
+ id: message.id,
1632
+ message: ensureError(cause).message.slice(0, 4e3)
1633
+ })).finally(() => this.#objectPending.delete(message.id));
1634
+ settled.catch(() => {});
1635
+ this.#objectPending.set(message.id, {
1636
+ controller,
1637
+ settled
1638
+ });
1639
+ return settled;
1640
+ }
1641
+ if (message.kind === "callback") {
1642
+ const call$1 = this.#pending.get(message.callId);
1643
+ if (call$1?.context === void 0 || call$1.responded) throw new Error("Plugin isolate callback has no active invocation");
1644
+ observation.callbackChanged(1);
1645
+ const pending = this.#callback(message, call$1.context).then((value) => this.#send({
1646
+ kind: "result",
1647
+ id: message.id,
1648
+ value
1649
+ }), async (cause) => {
1650
+ call$1.callbackFailure ??= ensureError(cause);
1651
+ await this.#send({
1652
+ kind: "error",
1653
+ id: message.id,
1654
+ message: ensureError(cause).message.slice(0, 4e3)
1655
+ });
1656
+ throw cause;
1657
+ }).finally(() => {
1658
+ observation.callbackChanged(-1);
1659
+ call$1.callbacks.delete(pending);
1660
+ });
1661
+ pending.catch(() => {});
1662
+ call$1.callbacks.add(pending);
1663
+ return pending.catch(() => {});
1664
+ }
1665
+ switch (message.kind) {
1666
+ case "request":
1667
+ case "retention": throw new Error("Unexpected Plugin isolate message");
1668
+ }
1669
+ const call = this.#pending.get(message.id);
1670
+ if (call === void 0 || call.responded) throw new Error("Unknown Plugin isolate invocation");
1671
+ call.responded = true;
1672
+ const settle = (error) => {
1673
+ if (this.#termination !== void 0) return;
1674
+ if (this.#pending.get(message.id) !== call) return;
1675
+ this.#pending.delete(message.id);
1676
+ this.#observation.changed?.();
1677
+ clearTimeout(call.timer);
1678
+ call.detach();
1679
+ this.#settled(call, error !== void 0 || message.kind === "error" ? "failed" : "succeeded");
1680
+ if (error !== void 0) call.reject(error);
1681
+ else if (message.kind === "error") call.reject(message.code === "unsupported" ? new PluginProcessError("unsupported", message.message) : new Error(message.message));
1682
+ else call.resolve(message.value);
1683
+ };
1684
+ return Promise.allSettled([...call.callbacks]).then((outcomes) => {
1685
+ const rejected = outcomes.find((outcome) => outcome.status === "rejected");
1686
+ settle(call.callbackFailure ?? (rejected === void 0 ? void 0 : ensureError(rejected.reason)));
1687
+ });
1688
+ } catch (cause) {
1689
+ observation.ipc?.failed(this.#identity, "callback");
1690
+ this.kill(new PluginProcessError("protocol", "Invalid Plugin isolate message", { cause: ensureError(cause) }));
1691
+ }
1692
+ };
1693
+ this.#write = isolateChannel(child.stdout, child.stdin, receive, (error) => {
1694
+ this.kill(error instanceof IsolateQuotaError ? new PluginProcessError("quota", "Plugin isolate exceeded its frame quota", { cause: error }) : new PluginProcessError("protocol", "Invalid Plugin isolate channel", { cause: error }));
1695
+ }, {
1696
+ admit: (message) => {
1697
+ if (message.kind !== "request") return;
1698
+ authorize();
1699
+ const call = this.#pending.get(message.id);
1700
+ if (call !== void 0) {
1701
+ call.dispatched = true;
1702
+ call.dispatchedObject = message.method === "object-call";
1703
+ }
1704
+ },
1705
+ observation: observation.ipc === void 0 ? void 0 : {
1706
+ frame: (direction, bytes) => observation.ipc?.frame(this.#identity, direction, bytes),
1707
+ queue: (bytes) => observation.ipc?.queue(this.#identity, bytes),
1708
+ failed: (reason) => observation.ipc?.failed(this.#identity, reason)
1709
+ }
1710
+ });
1711
+ child.stderr?.resume();
1712
+ }
1713
+ static async open(worker, lifecycleTimeout, heapSize, signal, authorize, observation) {
1714
+ try {
1715
+ const command = await pluginSandboxCommand(worker, heapSize);
1716
+ signal.throwIfAborted();
1717
+ authorize();
1718
+ const child = spawn(command.executable, command.args, {
1719
+ cwd: "/",
1720
+ env: { OPENSSL_CONF: "/dev/null" },
1721
+ stdio: [
1722
+ "pipe",
1723
+ "pipe",
1724
+ "pipe"
1725
+ ],
1726
+ detached: process.platform !== "win32"
1727
+ });
1728
+ const exited = new Promise((resolve$1) => child.once("close", () => resolve$1()));
1729
+ try {
1730
+ await once(child, "spawn");
1731
+ } catch (cause) {
1732
+ await exited;
1733
+ throw cause;
1734
+ }
1735
+ return new PluginProcess(child, lifecycleTimeout, authorize, observation);
1736
+ } catch (cause) {
1737
+ throw new PluginProcessError("spawn", "Plugin isolate could not start", { cause: ensureError(cause) });
1738
+ }
1739
+ }
1740
+ inventory() {
1741
+ return {
1742
+ ...this.#identity,
1743
+ state: this.#state,
1744
+ pendingCalls: this.#pending.size,
1745
+ outputQueueBytes: this.#child.stdin.writableLength,
1746
+ startedAt: this.#startedAt
1747
+ };
1748
+ }
1749
+ get state() {
1750
+ return this.#state;
1751
+ }
1752
+ get pendingCalls() {
1753
+ return this.#pending.size;
1754
+ }
1755
+ get outputQueueBytes() {
1756
+ return this.#child.stdin.writableLength;
1757
+ }
1758
+ activated() {
1759
+ this.#state = "active";
1760
+ this.#observation.changed?.();
1761
+ }
1762
+ #send(message, signal) {
1763
+ const written = this.#write(message, signal);
1764
+ if (message.kind === "request") return written;
1765
+ return written.catch((cause) => {
1766
+ this.kill(new PluginProcessError("protocol", "Plugin isolate reply could not be sent", { cause: ensureError(cause) }));
1767
+ throw cause;
1768
+ });
1769
+ }
1770
+ retainCallbacks(revision, handles) {
1771
+ if (this.#termination !== void 0) return;
1772
+ this.#send({
1773
+ kind: "retention",
1774
+ revision,
1775
+ handles
1776
+ }).catch((cause) => this.kill(new PluginProcessError("protocol", "Plugin isolate callback retention could not be sent", { cause: ensureError(cause) })));
1777
+ }
1778
+ async #callback(message, context) {
1779
+ context.signal.throwIfAborted();
1780
+ if (message.method === "feedback") {
1781
+ if (context.readToolResults === void 0) throw new Error("No Tool observation capability");
1782
+ return captureJsonValue(await context.readToolResults(context.signal));
1783
+ }
1784
+ if (message.method === "command") {
1785
+ if (context.commandBehavior === void 0) throw new Error("No behavior command capability");
1786
+ const command = decode(s.obj({
1787
+ name: s.str(),
1788
+ input: SessionBehaviorCommandSchema
1789
+ }, { open: true }), message.value);
1790
+ return captureJsonValue(await context.commandBehavior(command.name, command.input, context.signal));
1791
+ }
1792
+ if (context.onUpdate === void 0) throw new Error("No Tool update capability");
1793
+ context.onUpdate(decode(ToolResultSchema, message.value));
1794
+ return null;
1795
+ }
1796
+ call(method, value, { signal, context, lifecycleTimeoutMs, sessionId, runId } = {}) {
1797
+ if (this.#termination !== void 0) return Promise.reject(this.#termination);
1798
+ const cancellation = () => {
1799
+ const deadline = check(PluginLeaseDeadlineErrorSchema, signal?.reason);
1800
+ return new PluginProcessError(deadline ? "timeout" : "cancelled", deadline ? "Plugin isolate invocation exceeded its request deadline" : "Plugin isolate invocation cancelled", { cause: signal?.reason });
1801
+ };
1802
+ if (signal?.aborted) return Promise.reject(cancellation());
1803
+ const id = ++this.#nextId;
1804
+ const started = this.#observation.settled === void 0 ? 0 : performance.now();
1805
+ const startedAtUnixMs = this.#observation.settled === void 0 ? 0 : Date.now();
1806
+ return new Promise((resolve$1, reject) => {
1807
+ const capability = new AbortController();
1808
+ const sending = new AbortController();
1809
+ let cancelled;
1810
+ const interrupt = (error) => {
1811
+ cancelled ??= error;
1812
+ sending.abort(cancelled);
1813
+ if (this.#pending.get(id)?.dispatched) this.kill(cancelled);
1814
+ };
1815
+ const cancel = () => {
1816
+ interrupt(cancellation());
1817
+ };
1818
+ const timer = lifecycleTimeoutMs === void 0 ? void 0 : setTimeout(() => {
1819
+ this.kill(new PluginProcessError("timeout", `Plugin isolate ${method} lifecycle timed out`));
1820
+ }, lifecycleTimeoutMs);
1821
+ const pending = {
1822
+ method,
1823
+ started,
1824
+ startedAtUnixMs,
1825
+ sessionId: context?.sessionId ?? sessionId,
1826
+ runId: context?.runId ?? runId,
1827
+ toolCallId: context?.toolCallId,
1828
+ resolve: resolve$1,
1829
+ reject,
1830
+ context: context === void 0 ? void 0 : {
1831
+ ...context,
1832
+ signal: AbortSignal.any([context.signal, capability.signal])
1833
+ },
1834
+ capability,
1835
+ callbacks: /* @__PURE__ */ new Set(),
1836
+ timer,
1837
+ detach: () => signal?.removeEventListener("abort", cancel),
1838
+ responded: false,
1839
+ dispatched: false,
1840
+ dispatchedObject: false
1841
+ };
1842
+ this.#pending.set(id, pending);
1843
+ this.#observation.changed?.();
1844
+ signal?.addEventListener("abort", cancel, { once: true });
1845
+ try {
1846
+ this.#send({
1847
+ kind: "request",
1848
+ id,
1849
+ method,
1850
+ value
1851
+ }, sending.signal).catch((cause) => {
1852
+ if (cause instanceof IsolateNotDispatchedError) {
1853
+ if (this.#pending.get(id) !== pending) return;
1854
+ this.#pending.delete(id);
1855
+ clearTimeout(pending.timer);
1856
+ pending.detach();
1857
+ pending.capability.abort(cause.cause);
1858
+ pending.reject(cancelled ?? ensureError(cause.cause));
1859
+ return;
1860
+ }
1861
+ return this.kill(new PluginProcessError("protocol", "Plugin isolate request could not be sent", { cause: ensureError(cause) }));
1862
+ });
1863
+ } catch (cause) {
1864
+ this.kill(new PluginProcessError("protocol", "Plugin isolate request could not be sent", { cause: ensureError(cause) }));
1865
+ }
1866
+ });
1867
+ }
1868
+ #settled(call, outcome) {
1869
+ if (this.#observation.settled === void 0) return;
1870
+ let callType;
1871
+ switch (call.method) {
1872
+ case "init":
1873
+ case "activate":
1874
+ case "close":
1875
+ callType = call.method;
1876
+ break;
1877
+ case "execute":
1878
+ callType = "tool";
1879
+ break;
1880
+ case "read-state":
1881
+ callType = "state";
1882
+ break;
1883
+ case "transform-input":
1884
+ callType = "transform";
1885
+ break;
1886
+ default: return;
1887
+ }
1888
+ this.#observation.settled?.({
1889
+ ...this.#identity,
1890
+ sessionId: call.sessionId,
1891
+ runId: call.runId,
1892
+ toolCallId: call.toolCallId,
1893
+ callType,
1894
+ outcome,
1895
+ durationMs: performance.now() - call.started,
1896
+ startedAtUnixMs: call.startedAtUnixMs,
1897
+ endedAtUnixMs: Date.now()
1898
+ });
1899
+ }
1900
+ #rejectAll(error) {
1901
+ this.objectStopped?.(error);
1902
+ for (const callback of this.#objectPending.values()) callback.controller.abort(error);
1903
+ for (const call of this.#pending.values()) {
1904
+ call.capability.abort(error);
1905
+ clearTimeout(call.timer);
1906
+ call.detach();
1907
+ this.#settled(call, this.#termination?.code ?? "failed");
1908
+ call.reject(call.dispatchedObject && !call.responded ? new ObjectInvocationUnknownError("Isolated Object invocation lost its terminal reply", { cause: error }) : error);
1909
+ }
1910
+ this.#pending.clear();
1911
+ this.#observation.changed?.();
1912
+ }
1913
+ async kill(error) {
1914
+ this.#termination ??= error;
1915
+ this.objectStopped?.(this.#termination);
1916
+ for (const callback of this.#objectPending.values()) callback.controller.abort(this.#termination);
1917
+ for (const call of this.#pending.values()) call.capability.abort(this.#termination);
1918
+ if (!this.#dead) {
1919
+ this.#child.kill("SIGKILL");
1920
+ await this.#exited;
1921
+ }
1922
+ await Promise.allSettled([...this.#objectPending.values()].map((callback) => callback.settled));
1923
+ }
1924
+ async releaseObject(objectId) {
1925
+ try {
1926
+ if (this.#termination === void 0) await this.call("object-close", { objectId }, { lifecycleTimeoutMs: this.#lifecycleTimeout });
1927
+ } catch (cause) {
1928
+ if (this.#termination === void 0) throw cause;
1929
+ }
1930
+ if (this.#termination !== void 0) await this.#exited;
1931
+ }
1932
+ close() {
1933
+ this.#state = "retiring";
1934
+ this.#observation.changed?.();
1935
+ this.#closing ??= this.#close();
1936
+ return this.#closing;
1937
+ }
1938
+ watch(signal) {
1939
+ return new Promise((resolve$1, reject) => {
1940
+ const cancelled = () => resolve$1();
1941
+ signal.addEventListener("abort", cancelled, { once: true });
1942
+ this.#exited.then(() => {
1943
+ signal.removeEventListener("abort", cancelled);
1944
+ if (signal.aborted || this.#closing !== void 0) resolve$1();
1945
+ else reject(this.#termination);
1946
+ });
1947
+ if (signal.aborted) cancelled();
1948
+ });
1949
+ }
1950
+ async #close() {
1951
+ if (this.#dead) return;
1952
+ try {
1953
+ await this.call("close", null, { lifecycleTimeoutMs: this.#lifecycleTimeout });
1954
+ } catch {}
1955
+ this.#child.stdin.end();
1956
+ await this.kill(new PluginProcessError("closed", "Plugin isolate closed"));
1957
+ }
1958
+ };
1959
+ /** One sandboxed OS process per Activation: module globals and caches are never shared across Entries. */
1960
+ var NodePluginProcessLoader = class {
1961
+ #authority;
1962
+ #worker;
1963
+ #lifecycleTimeout;
1964
+ #capacity;
1965
+ #heapSize;
1966
+ #processes = /* @__PURE__ */ new Map();
1967
+ #capacityListeners = /* @__PURE__ */ new Set();
1968
+ #observation;
1969
+ #diagnostics;
1970
+ #loaderId = randomUUID();
1971
+ #ownsDiagnostics;
1972
+ #observerFailures = 0;
1973
+ #starting = 0;
1974
+ #pendingCallbacks = 0;
1975
+ #closed = false;
1976
+ #pressureRetry;
1977
+ #pressureDelay = 10;
1978
+ constructor(authority, options = {}) {
1979
+ const policy = decode(s.obj({
1980
+ lifecycleTimeoutMs: s.opt(s.int({
1981
+ minimum: 1,
1982
+ maximum: 2147483647
1983
+ })),
1984
+ maxProcesses: s.opt(s.int({
1985
+ minimum: 1,
1986
+ maximum: Number.MAX_SAFE_INTEGER
1987
+ })),
1988
+ maxOldSpaceSizeMb: s.opt(s.int({
1989
+ minimum: 1,
1990
+ maximum: Number.MAX_SAFE_INTEGER
1991
+ }))
1992
+ }, { open: true }), options);
1993
+ this.#authority = authority;
1994
+ this.#worker = options.workerPath ?? fileURLToPath(new URL("./isolate-worker.mjs", import.meta.url));
1995
+ this.#lifecycleTimeout = policy.lifecycleTimeoutMs;
1996
+ this.#capacity = policy.maxProcesses;
1997
+ this.#heapSize = policy.maxOldSpaceSizeMb;
1998
+ this.#observation = options.observation;
1999
+ this.#ownsDiagnostics = options.diagnosticsBudget === void 0;
2000
+ this.#diagnostics = options.diagnosticsBudget ?? new PluginDiagnosticCapture(options.diagnostics ?? {}, (record) => this.#observe(() => this.#observation?.diagnostic?.(record)), (record) => this.#observe(() => this.#observation?.diagnosticDropped?.(record)));
2001
+ this.#observeCapacity();
2002
+ }
2003
+ /** Read-only process ownership and bounded local diagnostics; no OS memory attribution is inferred. */
2004
+ snapshot() {
2005
+ const diagnostics = this.#diagnostics.snapshot();
2006
+ return {
2007
+ loaderId: this.#loaderId,
2008
+ capacity: this.#capacity ?? Number.MAX_SAFE_INTEGER,
2009
+ starting: this.#starting,
2010
+ pendingCallbacks: this.#pendingCallbacks,
2011
+ workers: [...this.#processes.keys()].map((worker) => worker.inventory()),
2012
+ observerFailures: this.#observerFailures + diagnostics.observerFailures,
2013
+ diagnosticBufferBytes: diagnostics.bytes,
2014
+ diagnosticDrops: diagnostics.drops,
2015
+ diagnostics: diagnostics.records.filter((record) => record.loaderId === this.#loaderId)
2016
+ };
2017
+ }
2018
+ #observe(callback) {
2019
+ if (this.#observation === void 0) return;
2020
+ try {
2021
+ const result = callback();
2022
+ if (isPromise(result)) result.catch(() => {
2023
+ this.#observerFailures += 1;
2024
+ });
2025
+ } catch {
2026
+ this.#observerFailures += 1;
2027
+ }
2028
+ }
2029
+ componentAt(reference) {
2030
+ const captured = structuredClone(reference);
2031
+ const resolved = this.#authority.resolveExecution(captured);
2032
+ resolved.catch(() => {});
2033
+ const admission = contributionAdmission(() => this.#assertAdmission(captured.packageId));
2034
+ let declaration;
2035
+ let requirements = [];
2036
+ const load = async ({ activationId, lifetime }) => {
2037
+ admission.assert();
2038
+ const input = await resolved;
2039
+ const child = await lifetime.acquire(async (signal) => {
2040
+ admission.assert();
2041
+ if (!this.#available()) throw new PluginAdmissionError();
2042
+ this.#starting += 1;
2043
+ try {
2044
+ const process$1 = await PluginProcess.open(this.#worker, this.#lifecycleTimeout, this.#heapSize, signal, () => this.#authority.assertPackageExecution(captured.packageId), {
2045
+ identity: {
2046
+ loaderId: this.#loaderId,
2047
+ workerId: randomUUID(),
2048
+ activationId,
2049
+ entryId: captured.entryId
2050
+ },
2051
+ capture: this.#diagnostics,
2052
+ exited: (exited, data) => {
2053
+ this.#processes.delete(exited);
2054
+ this.#notifyCapacity();
2055
+ this.#observe(() => this.#observation?.workerExited?.(data));
2056
+ },
2057
+ settled: this.#observation?.invocationSettled === void 0 ? void 0 : (data) => this.#observe(() => this.#observation?.invocationSettled?.(data)),
2058
+ changed: this.#observation?.capacityChanged === void 0 ? void 0 : () => this.#observeCapacity(),
2059
+ callbackChanged: (delta) => {
2060
+ this.#pendingCallbacks += delta;
2061
+ this.#observeCapacity();
2062
+ },
2063
+ ipc: this.#observation?.ipcFrame === void 0 && this.#observation?.ipcQueueChanged === void 0 && this.#observation?.protocolFailed === void 0 ? void 0 : {
2064
+ frame: (identity$1, direction, bytes) => this.#observe(() => this.#observation?.ipcFrame?.({
2065
+ ...identity$1,
2066
+ direction,
2067
+ bytes
2068
+ })),
2069
+ queue: (identity$1, bytes) => this.#observe(() => this.#observation?.ipcQueueChanged?.({
2070
+ ...identity$1,
2071
+ bytes
2072
+ })),
2073
+ failed: (identity$1, reason) => this.#observe(() => this.#observation?.protocolFailed?.({
2074
+ ...identity$1,
2075
+ reason
2076
+ }))
2077
+ }
2078
+ });
2079
+ this.#processes.set(process$1, captured.packageId);
2080
+ const identity = process$1.inventory();
2081
+ this.#observe(() => this.#observation?.workerStarted?.(identity));
2082
+ return process$1;
2083
+ } catch (cause) {
2084
+ if (check(SpawnPressureSchema, ensureError(cause).cause)) {
2085
+ this.#waitForPressure();
2086
+ throw new PluginAdmissionError("Plugin process resources are temporarily unavailable");
2087
+ }
2088
+ throw cause;
2089
+ } finally {
2090
+ this.#starting -= 1;
2091
+ this.#notifyCapacity();
2092
+ }
2093
+ }, async (process$1) => {
2094
+ await this.#closeProcess(process$1, captured.packageId);
2095
+ this.#processes.delete(process$1);
2096
+ this.#clearPressure();
2097
+ this.#notifyCapacity();
2098
+ });
2099
+ lifetime.supervise((signal) => child.watch(signal));
2100
+ const objects = new IsolatedObjectFactories((method, value, signal) => child.call(method, value, { signal }), (objectId) => child.releaseObject(objectId), () => admission.assert());
2101
+ child.objectCallback = (message, signal) => objects.callback(message.objectId, message.method, message.value, signal);
2102
+ child.objectStopped = (error) => objects.stop(error);
2103
+ const definition = decodeWith(IsolateDefinitionValidator, await child.call("init", captureJsonValue({
2104
+ document: input.details.document,
2105
+ entryId: captured.entryId,
2106
+ config: input.entry.config
2107
+ }), {
2108
+ signal: lifetime.signal,
2109
+ lifecycleTimeoutMs: this.#lifecycleTimeout
2110
+ }));
2111
+ if (declaration === void 0) {
2112
+ declaration = definition;
2113
+ requirements = definition.requires.map((key) => definition.references.includes(key) ? Context.Reference(key, { defaultValue: () => null }) : key);
2114
+ } else if (!isEqual(declaration, definition)) throw new Error("Plugin process changed its loaded declaration");
2115
+ admission.assert();
2116
+ return {
2117
+ ...definition,
2118
+ requires: requirements,
2119
+ activate: async ({ services }) => {
2120
+ admission.assert();
2121
+ const serialized = Object.fromEntries(definition.requires.filter((key) => !definition.references.includes(key) || services?.mapUnsafe.has(key)).map((key) => [key, decode(JsonValueSchema, services?.mapUnsafe.get(key))]));
2122
+ const retainedHandles = /* @__PURE__ */ new Map();
2123
+ let factoryCallbacks = /* @__PURE__ */ new Map();
2124
+ let currentHandles = /* @__PURE__ */ new Set();
2125
+ let currentRevision = 0;
2126
+ let retentionScheduled = false;
2127
+ const synchronizeRetention = () => {
2128
+ if (retentionScheduled || currentRevision === 0) return;
2129
+ retentionScheduled = true;
2130
+ queueMicrotask(() => {
2131
+ retentionScheduled = false;
2132
+ child.retainCallbacks(currentRevision, [...new Set([...currentHandles, ...retainedHandles.keys()])]);
2133
+ });
2134
+ };
2135
+ const retain = (handle) => () => {
2136
+ retainedHandles.set(handle, (retainedHandles.get(handle) ?? 0) + 1);
2137
+ synchronizeRetention();
2138
+ let released = false;
2139
+ return () => {
2140
+ if (released) return;
2141
+ released = true;
2142
+ const remaining = (retainedHandles.get(handle) ?? 0) - 1;
2143
+ if (remaining === 0) retainedHandles.delete(handle);
2144
+ else retainedHandles.set(handle, remaining);
2145
+ synchronizeRetention();
2146
+ };
2147
+ };
2148
+ const wrap = (output) => {
2149
+ for (const tool of output.tools) {
2150
+ validateDataSchema(tool.parameters);
2151
+ if (tool.outputSchema !== void 0) validateDataSchema(tool.outputSchema);
2152
+ }
2153
+ for (const state of output.namedStates) validateDataSchema(state.schema);
2154
+ const nextFactories = /* @__PURE__ */ new Map();
2155
+ const objectFactories = output.objectFactories.map((registration) => {
2156
+ const previous = factoryCallbacks.get(registration.handle);
2157
+ if (previous !== void 0 && !isEqual(previous.descriptor, registration.descriptor)) throw new Error("Plugin isolate changed a retained Object contract");
2158
+ const factory = previous ?? objects.factory(registration, retain(registration.handle));
2159
+ nextFactories.set(registration.handle, factory);
2160
+ return factory;
2161
+ });
2162
+ factoryCallbacks = nextFactories;
2163
+ currentRevision = output.revision;
2164
+ currentHandles = new Set([
2165
+ ...output.tools,
2166
+ ...output.namedStates,
2167
+ ...output.inputTransforms,
2168
+ ...output.objectFactories
2169
+ ].map((callback) => callback.handle));
2170
+ synchronizeRetention();
2171
+ return {
2172
+ objectFactories,
2173
+ tools: output.tools.map((tool) => bindCallbackRetention({
2174
+ ...tool,
2175
+ execute: async (parameters, context) => {
2176
+ admission.assert();
2177
+ return decode(ToolResultSchema, await child.call("execute", captureJsonValue({
2178
+ handle: tool.handle,
2179
+ input: parameters,
2180
+ context: {
2181
+ approval: context.approval,
2182
+ sessionId: context.sessionId,
2183
+ runId: context.runId,
2184
+ leaseId: context.leaseId,
2185
+ toolCallId: context.toolCallId,
2186
+ traceContext: context.traceContext,
2187
+ feedback: context.readToolResults !== void 0,
2188
+ command: context.commandBehavior !== void 0,
2189
+ updates: context.onUpdate !== void 0
2190
+ }
2191
+ }), {
2192
+ signal: context.signal,
2193
+ context
2194
+ }));
2195
+ }
2196
+ }, retain(tool.handle))),
2197
+ prefixes: output.prefixes,
2198
+ namedStates: output.namedStates.map((state) => bindCallbackRetention({
2199
+ ...state,
2200
+ read: async (context) => {
2201
+ admission.assert();
2202
+ return decode(PluginStateReadResultSchema, await child.call("read-state", captureJsonValue({
2203
+ handle: state.handle,
2204
+ input: null,
2205
+ context: {
2206
+ sessionId: context.sessionId,
2207
+ runId: context.runId,
2208
+ toolResults: context.toolResults
2209
+ }
2210
+ }), {
2211
+ signal: context.signal,
2212
+ sessionId: context.sessionId,
2213
+ runId: context.runId
2214
+ }));
2215
+ }
2216
+ }, retain(state.handle))),
2217
+ inputTransforms: output.inputTransforms.map((transform) => bindCallbackRetention({
2218
+ ...transform,
2219
+ transform: async (prompt, context) => {
2220
+ admission.assert();
2221
+ return decode(PluginInputSchema, await child.call("transform-input", captureJsonValue({
2222
+ handle: transform.handle,
2223
+ input: prompt,
2224
+ context: {
2225
+ sessionId: context.sessionId,
2226
+ runId: context.runId,
2227
+ source: context.source,
2228
+ mode: context.mode
2229
+ }
2230
+ }), {
2231
+ signal: context.signal,
2232
+ sessionId: context.sessionId,
2233
+ runId: context.runId
2234
+ }));
2235
+ }
2236
+ }, retain(transform.handle)))
2237
+ };
2238
+ };
2239
+ let revision = 0;
2240
+ let servicesRevision = 0;
2241
+ const listeners = /* @__PURE__ */ new Set();
2242
+ let current = { tools: [] };
2243
+ let provided = [];
2244
+ const captureServices = (output) => output.services.map(({ key, value }) => {
2245
+ const previous = provided.find((service) => service.key === key);
2246
+ if (previous !== void 0 && isEqual(previous.context.mapUnsafe.get(key), value)) return previous;
2247
+ return {
2248
+ key,
2249
+ context: Context.makeUnsafe(new Map([[key, value]]))
2250
+ };
2251
+ });
2252
+ const updateServices = (output) => {
2253
+ const next = captureServices(output);
2254
+ if (!isEqual(provided, next)) servicesRevision += 1;
2255
+ provided = next;
2256
+ };
2257
+ child.publication = (value) => {
2258
+ admission.assert();
2259
+ const output = decodeWith(IsolateContributionsValidator, value);
2260
+ if (output.revision <= currentRevision) throw new Error("Plugin isolate publication revision must advance");
2261
+ current = wrap(output);
2262
+ updateServices(output);
2263
+ revision += 1;
2264
+ for (const changed of listeners) changed();
2265
+ };
2266
+ lifetime.addFinalizer(async () => {
2267
+ child.publication = void 0;
2268
+ listeners.clear();
2269
+ });
2270
+ const initial = decodeWith(IsolateContributionsValidator, await child.call("activate", serialized, {
2271
+ signal: lifetime.signal,
2272
+ lifecycleTimeoutMs: this.#lifecycleTimeout
2273
+ }));
2274
+ child.activated();
2275
+ if (revision === 0) {
2276
+ current = wrap(initial);
2277
+ updateServices(initial);
2278
+ }
2279
+ const subscribe = (changed) => {
2280
+ listeners.add(changed);
2281
+ return () => {
2282
+ listeners.delete(changed);
2283
+ };
2284
+ };
2285
+ return {
2286
+ ...current,
2287
+ live: {
2288
+ get version() {
2289
+ return revision;
2290
+ },
2291
+ snapshot: () => current,
2292
+ subscribe
2293
+ },
2294
+ services: {
2295
+ get version() {
2296
+ return servicesRevision;
2297
+ },
2298
+ snapshot: () => provided,
2299
+ subscribe
2300
+ }
2301
+ };
2302
+ }
2303
+ };
2304
+ };
2305
+ return {
2306
+ componentId: captured.entryId,
2307
+ executionProfile: "isolate",
2308
+ admission: {
2309
+ available: () => this.#available(),
2310
+ subscribe: (changed) => {
2311
+ const subscription = { changed };
2312
+ this.#capacityListeners.add(subscription);
2313
+ return () => {
2314
+ this.#capacityListeners.delete(subscription);
2315
+ };
2316
+ }
2317
+ },
2318
+ load,
2319
+ activate: async (context) => (await load(context)).activate(context)
2320
+ };
2321
+ }
2322
+ #assertAdmission(packageId) {
2323
+ if (this.#closed) throw new Error("Plugin process loader is closed");
2324
+ this.#authority.assertPackageExecution(packageId);
2325
+ }
2326
+ #available() {
2327
+ return !this.#closed && this.#pressureRetry === void 0 && (this.#capacity === void 0 || this.#starting + this.#processes.size < this.#capacity);
2328
+ }
2329
+ #waitForPressure() {
2330
+ if (this.#closed || this.#pressureRetry !== void 0) return;
2331
+ this.#pressureRetry = setTimeout(() => {
2332
+ this.#pressureRetry = void 0;
2333
+ this.#notifyCapacity();
2334
+ }, this.#pressureDelay);
2335
+ this.#pressureRetry.unref();
2336
+ this.#pressureDelay = Math.min(this.#pressureDelay * 2, 1e3);
2337
+ }
2338
+ #clearPressure() {
2339
+ clearTimeout(this.#pressureRetry);
2340
+ this.#pressureRetry = void 0;
2341
+ this.#pressureDelay = 10;
2342
+ }
2343
+ #notifyCapacity() {
2344
+ this.#observeCapacity();
2345
+ for (const { changed } of this.#capacityListeners) try {
2346
+ changed();
2347
+ } catch {}
2348
+ }
2349
+ #observeCapacity() {
2350
+ if (this.#observation?.capacityChanged === void 0) return;
2351
+ let retiring = 0;
2352
+ let pendingCalls = 0;
2353
+ let outputQueueBytes = 0;
2354
+ for (const worker of this.#processes.keys()) {
2355
+ if (worker.state === "retiring") retiring += 1;
2356
+ pendingCalls += worker.pendingCalls;
2357
+ outputQueueBytes += worker.outputQueueBytes;
2358
+ }
2359
+ const observation = {
2360
+ loaderId: this.#loaderId,
2361
+ capacity: this.#capacity ?? Number.MAX_SAFE_INTEGER,
2362
+ starting: this.#starting,
2363
+ owned: this.#processes.size,
2364
+ retiring,
2365
+ pendingCalls,
2366
+ pendingCallbacks: this.#pendingCallbacks,
2367
+ outputQueueBytes,
2368
+ closed: this.#closed
2369
+ };
2370
+ this.#observe(() => this.#observation?.capacityChanged?.(observation));
2371
+ }
2372
+ async #closeProcess(process$1, packageId) {
2373
+ try {
2374
+ this.#authority.assertPackageExecution(packageId);
2375
+ } catch (cause) {
2376
+ await process$1.kill(new PluginProcessError("closed", "Denied Plugin isolate terminated", { cause: ensureError(cause) }));
2377
+ return;
2378
+ }
2379
+ await process$1.close();
2380
+ }
2381
+ /** Close borrowing Platforms first. Exiting workers releases their complete ESM cache. */
2382
+ async close() {
2383
+ this.#closed = true;
2384
+ this.#clearPressure();
2385
+ this.#observeCapacity();
2386
+ await Promise.all([...this.#processes].map(([process$1, packageId]) => this.#closeProcess(process$1, packageId)));
2387
+ this.#processes.clear();
2388
+ if (this.#ownsDiagnostics) this.#diagnostics.close();
2389
+ this.#observeCapacity();
2390
+ }
2391
+ };
2392
+
2393
+ //#endregion
2394
+ //#region src/node/native-loader.ts
2395
+ const resolveEffectModuleUrl = () => pathToFileURL(createRequire(import.meta.url).resolve("effect")).href;
2396
+ const ComponentMetadata = s.obj({
2397
+ componentId: s.str({ minLength: 1 }),
2398
+ executionProfile: s.opt(s.oneOf([
2399
+ "isolate",
2400
+ "in_process",
2401
+ "native_pi",
2402
+ "native_cordis"
2403
+ ]))
2404
+ }, { open: false });
2405
+ const ApplyExport = s.obj({ default: s.unknown() }, { open: true });
2406
+ const HostToolReferenceProperties = { hostBinding: s.str({
2407
+ minLength: 1,
2408
+ maxLength: 200
2409
+ }) };
2410
+ const HostToolReference = s.obj(HostToolReferenceProperties, { open: false });
2411
+ const ActivatedExport = s.obj({
2412
+ objectFactories: s.opt({ not: {} }),
2413
+ sessionBehaviors: s.opt({ not: {} }),
2414
+ preparationHooks: s.opt(s.arr(s.obj({
2415
+ ...PreparationHookMetadataProperties,
2416
+ around: s.unknown()
2417
+ }, { open: true }))),
2418
+ inputTransforms: s.opt(s.arr(s.obj({
2419
+ contributionId: s.str({ minLength: 1 }),
2420
+ transform: s.unknown()
2421
+ }, { open: true }))),
2422
+ prefixes: s.opt(s.arr(PluginPrefixContributionSchema)),
2423
+ namedStates: s.opt(s.arr(s.obj({
2424
+ ...NamedStateMetadataProperties,
2425
+ read: s.unknown()
2426
+ }, { open: true }))),
2427
+ hooks: s.opt(s.arr({
2428
+ ...s.obj({
2429
+ ...ToolHookMetadataProperties,
2430
+ ...ToolHookCallbacksProperties
2431
+ }, { open: true }),
2432
+ anyOf: [{ required: ["prepare"] }, { required: ["feedback"] }]
2433
+ })),
2434
+ tools: s.arr(s.union([HostToolReference, s.obj({
2435
+ ...ModelToolMetadataProperties,
2436
+ recovery: s.opt(s.union([s.lit("unsafe"), s.lit("safe")])),
2437
+ prepareArguments: s.opt(s.unknown()),
2438
+ execute: s.unknown()
2439
+ }, { open: true })]))
2440
+ }, { open: true });
2441
+ /**
2442
+ * Trusted in-process ESM, not a sandbox. Node owns module evaluation and its
2443
+ * process-lifetime cache; close deregisters resolution, not that cache or active
2444
+ * code. Close borrowing Platforms first. Each loader has its own module cache
2445
+ * namespace, with one module instance per Package/path inside that loader.
2446
+ */
2447
+ var NodePluginPackageLoader = class {
2448
+ #authority;
2449
+ #namespace = `sorbet-plugin:${randomUUID()}/`;
2450
+ #modules = /* @__PURE__ */ new Map();
2451
+ #hooks;
2452
+ #hostTools;
2453
+ #profiles;
2454
+ #effectModuleUrl;
2455
+ #closed = false;
2456
+ constructor(authority, hostTools = [], profiles = [], effectModuleUrl = resolveEffectModuleUrl()) {
2457
+ this.#authority = authority;
2458
+ this.#effectModuleUrl = effectModuleUrl;
2459
+ const abis = /* @__PURE__ */ new Set();
2460
+ this.#profiles = profiles.map((profile) => {
2461
+ if (check(NativePluginPackageAbiSchema, profile.abi) || abis.has(profile.abi)) throw new TypeError("Duplicate Plugin Package ABI");
2462
+ abis.add(profile.abi);
2463
+ return {
2464
+ abi: profile.abi,
2465
+ sourceProfile: profile.sourceProfile,
2466
+ inspect: profile.inspect.bind(profile),
2467
+ load: profile.load.bind(profile)
2468
+ };
2469
+ });
2470
+ const keys = /* @__PURE__ */ new Set();
2471
+ this.#hostTools = hostTools.map((binding) => {
2472
+ const packageId = decode(PluginPackageIdSchema, binding.packageId);
2473
+ const entryId = decode(s.str({
2474
+ minLength: 1,
2475
+ maxLength: 200
2476
+ }), binding.entryId);
2477
+ const bindingId = decode(HostToolReferenceProperties.hostBinding, binding.bindingId);
2478
+ const key = JSON.stringify([
2479
+ packageId,
2480
+ entryId,
2481
+ bindingId
2482
+ ]);
2483
+ if (keys.has(key)) throw new TypeError("Duplicate Plugin Host Tool binding");
2484
+ keys.add(key);
2485
+ return {
2486
+ packageId,
2487
+ entryId,
2488
+ bindingId,
2489
+ tool: {
2490
+ ...structuredClone(captureModelToolMetadata(binding.tool)),
2491
+ recovery: binding.tool.recovery,
2492
+ execute: binding.tool.execute.bind(binding.tool),
2493
+ prepareArguments: binding.tool.prepareArguments?.bind(binding.tool)
2494
+ }
2495
+ };
2496
+ });
2497
+ this.#hooks = registerHooks({
2498
+ resolve: (specifier, context, next) => {
2499
+ const parent = this.#modules.get(context.parentURL ?? "");
2500
+ if (parent) {
2501
+ this.#assertAdmission(parent.packageId);
2502
+ const target = parent.imports.get(specifier);
2503
+ if (!target) throw new TypeError("Plugin import is outside its module graph");
2504
+ return {
2505
+ url: target,
2506
+ shortCircuit: true
2507
+ };
2508
+ }
2509
+ if (!specifier.startsWith(this.#namespace)) return next(specifier, context);
2510
+ const source = this.#modules.get(specifier);
2511
+ if (!source) throw new TypeError("Plugin module is outside its module graph");
2512
+ this.#assertAdmission(source.packageId);
2513
+ return {
2514
+ url: specifier,
2515
+ shortCircuit: true
2516
+ };
2517
+ },
2518
+ load: (url, context, next) => {
2519
+ if (!url.startsWith(this.#namespace)) return next(url, context);
2520
+ const source = this.#modules.get(url);
2521
+ if (!source) throw new TypeError("Plugin module is outside its module graph");
2522
+ this.#assertAdmission(source.packageId);
2523
+ return {
2524
+ format: "module",
2525
+ source: source.source,
2526
+ shortCircuit: true
2527
+ };
2528
+ }
2529
+ });
2530
+ }
2531
+ /** Captures current desired provenance now; reconstruction and evaluation run under Activation readiness. */
2532
+ component(entryId) {
2533
+ return this.componentAt(this.#authority.executionReference(entryId));
2534
+ }
2535
+ /** Captures current Desired inputs without evaluating code; stale references reject on load. */
2536
+ componentAt(reference) {
2537
+ return this.#component(reference);
2538
+ }
2539
+ #component(reference) {
2540
+ const captured = structuredClone(reference);
2541
+ this.#assertAdmission(captured.packageId);
2542
+ const resolved = this.#authority.resolveExecution(captured);
2543
+ resolved.catch(() => {});
2544
+ let executionProfile;
2545
+ const load = async (context) => {
2546
+ context.lifetime.signal.throwIfAborted();
2547
+ this.#assertAdmission(captured.packageId);
2548
+ const input = await resolved;
2549
+ const loaded = await this.#load(input.package, input.details, this.#lifetime(input.package.packageId, context.lifetime));
2550
+ executionProfile = loaded.kind === "context" ? loaded.definition.apply.executionProfile : loaded.component.executionProfile;
2551
+ if (loaded.kind === "context") {
2552
+ const packageId = input.package.packageId;
2553
+ const component = contextComponent([captured.entryId], loaded.definition.apply, captureJsonValue(input.entry.config), {
2554
+ lifetime: (lifetime) => this.#lifetime(packageId, lifetime),
2555
+ capturePolicy: () => this.#capturePolicy(packageId, captured.entryId, context.lifetime.assertAvailable),
2556
+ assertReady: () => this.#assertAdmission(packageId)
2557
+ });
2558
+ this.#assertAdmission(packageId);
2559
+ return {
2560
+ ...loaded.definition,
2561
+ assertAvailable: () => this.#assertAdmission(packageId),
2562
+ activate: component.activate
2563
+ };
2564
+ }
2565
+ return {
2566
+ assertAvailable: () => this.#assertAdmission(input.package.packageId),
2567
+ activate: async (activationContext) => {
2568
+ const activate = loaded.component.activate;
2569
+ this.#assertAdmission(input.package.packageId);
2570
+ const output = await activate({
2571
+ ...activationContext,
2572
+ lifetime: this.#lifetime(input.package.packageId, context.lifetime),
2573
+ config: captureJsonValue(input.entry.config)
2574
+ });
2575
+ context.lifetime.signal.throwIfAborted();
2576
+ this.#assertAdmission(input.package.packageId);
2577
+ if (!check(ActivatedExport, output)) throw new TypeError("Plugin activation returned incompatible Tool contributions");
2578
+ const admission = contributionAdmission(() => this.#assertAdmission(input.package.packageId));
2579
+ const deferredAdmission = contributionAdmission(context.lifetime.assertAvailable, () => this.#assertAdmission(input.package.packageId));
2580
+ return capturePluginContributions({
2581
+ tools: output.tools.map((declaration) => {
2582
+ const tool = check(HostToolReference, declaration) ? this.#hostTools.find((binding) => binding.packageId === captured.packageId && binding.entryId === captured.entryId && binding.bindingId === declaration.hostBinding)?.tool : declaration;
2583
+ if (tool === void 0) throw new TypeError("Missing exact Plugin Host Tool binding");
2584
+ const metadata = captureModelToolMetadata(tool);
2585
+ const execute = decodeCallback(tool.execute).bind(tool);
2586
+ const prepareArguments = tool.prepareArguments === void 0 ? void 0 : decodeCallback(tool.prepareArguments).bind(tool);
2587
+ return {
2588
+ ...metadata,
2589
+ recovery: tool.recovery,
2590
+ prepareArguments: prepareArguments === void 0 ? void 0 : admission.call(prepareArguments),
2591
+ execute: (inputValue, toolContext) => {
2592
+ admission.assert();
2593
+ return execute(inputValue, admission.toolContext(toolContext, deferredAdmission));
2594
+ }
2595
+ };
2596
+ }),
2597
+ hooks: (output.hooks ?? []).map((hook) => {
2598
+ const prepare = hook.prepare === void 0 ? void 0 : decodeCallback(hook.prepare).bind(hook);
2599
+ const feedback = hook.feedback === void 0 ? void 0 : decodeCallback(hook.feedback).bind(hook);
2600
+ const prepared = async (inputValue, hookContext) => await prepare?.(inputValue, hookContext) ?? { input: inputValue };
2601
+ const received = async (result, state, hookContext) => await feedback?.(result, state, hookContext) ?? result;
2602
+ return {
2603
+ ...captureToolHookMetadata(hook),
2604
+ prepare: admission.call(prepared),
2605
+ feedback: admission.call(received)
2606
+ };
2607
+ }),
2608
+ namedStates: (output.namedStates ?? []).map((state) => ({
2609
+ ...captureNamedStateMetadata(state),
2610
+ read: admission.call(decodeCallback(state.read).bind(state))
2611
+ })),
2612
+ prefixes: capturePluginPrefixes(output.prefixes ?? []),
2613
+ inputTransforms: (output.inputTransforms ?? []).map((handler) => ({
2614
+ contributionId: handler.contributionId,
2615
+ transform: admission.call(decodeCallback(handler.transform).bind(handler))
2616
+ })),
2617
+ preparationHooks: (output.preparationHooks ?? []).map((hook) => ({
2618
+ hookId: hook.hookId,
2619
+ around: admission.call(decodeCallback(hook.around).bind(hook))
2620
+ }))
2621
+ });
2622
+ }
2623
+ };
2624
+ };
2625
+ return {
2626
+ componentId: captured.entryId,
2627
+ get executionProfile() {
2628
+ return executionProfile;
2629
+ },
2630
+ load,
2631
+ activate: async (context) => (await load(context)).activate(context)
2632
+ };
2633
+ }
2634
+ close() {
2635
+ if (this.#closed) return;
2636
+ this.#closed = true;
2637
+ this.#hooks.deregister();
2638
+ this.#modules.clear();
2639
+ }
2640
+ async #load(record, details, lifetime, componentId) {
2641
+ const signal = lifetime.signal;
2642
+ const { document, graph, sourceProfile } = details;
2643
+ if (componentId !== void 0 && document.manifest.componentId !== componentId) throw new PluginAuthorityError("invalid-data");
2644
+ if (!check(NativePluginPackageAbiSchema, document.manifest.abi)) {
2645
+ const profile = this.#profiles.find((candidate) => candidate.abi === document.manifest.abi);
2646
+ if (!profile) throw new TypeError("Missing Plugin Package execution profile");
2647
+ if (profile.sourceProfile !== sourceProfile) throw new TypeError("Missing registered Plugin source profile");
2648
+ signal.throwIfAborted();
2649
+ this.#assertAdmission(record.packageId);
2650
+ const definition = await profile.load(record, lifetime, document);
2651
+ signal.throwIfAborted();
2652
+ this.#assertAdmission(record.packageId);
2653
+ return {
2654
+ kind: "context",
2655
+ definition: captureDefinition(definition)
2656
+ };
2657
+ }
2658
+ if (graph === void 0) throw new TypeError("Missing registered Plugin module graph");
2659
+ signal.throwIfAborted();
2660
+ this.#assertAdmission(record.packageId);
2661
+ const prefix = `${this.#namespace}${record.packageId}/`;
2662
+ const files = new Map(document.files.map((file) => [file.path, file.content]));
2663
+ for (const module of graph.modules) {
2664
+ const source = files.get(module.path);
2665
+ if (source === void 0) throw new PluginAuthorityError("invalid-data");
2666
+ this.#modules.set(`${prefix}${module.path}`, {
2667
+ packageId: record.packageId,
2668
+ source,
2669
+ imports: new Map(module.imports.map((item) => {
2670
+ let url = `${prefix}${item.target}`;
2671
+ if (item.specifier === "effect") url = this.#effectModuleUrl;
2672
+ else if (item.specifier.startsWith("effect/")) url = this.#effectModuleUrl.startsWith("sorbet-worker:") ? `${this.#effectModuleUrl}/${item.specifier.slice(7)}` : pathToFileURL(createRequire(this.#effectModuleUrl).resolve(item.specifier)).href;
2673
+ return [item.specifier, url];
2674
+ }))
2675
+ });
2676
+ }
2677
+ const namespace = await import(`${prefix}${graph.entrypoint}`);
2678
+ signal.throwIfAborted();
2679
+ this.#assertAdmission(record.packageId);
2680
+ if (document.manifest.abi === "sorbet.context-plugin/v1") {
2681
+ if (!check(ApplyExport, namespace)) throw new TypeError("Plugin Package exports an incompatible apply entry");
2682
+ return {
2683
+ kind: "context",
2684
+ definition: captureDefinition(namespace.default)
2685
+ };
2686
+ }
2687
+ const exported = decode(ApplyExport, namespace).default;
2688
+ if (!isObject(exported)) throw new TypeError("Plugin Package exports an incompatible Tool Component");
2689
+ const metadata = decode(ComponentMetadata, {
2690
+ componentId: Reflect.get(exported, "componentId"),
2691
+ executionProfile: Reflect.get(exported, "executionProfile")
2692
+ });
2693
+ if (metadata.componentId !== document.manifest.componentId) throw new TypeError("Plugin Package exports an incompatible Tool Component");
2694
+ const activate = decodeCallback(Reflect.get(exported, "activate")).bind(exported);
2695
+ return {
2696
+ kind: "legacy",
2697
+ component: {
2698
+ ...metadata,
2699
+ activate
2700
+ }
2701
+ };
2702
+ }
2703
+ #capturePolicy(packageId, entryId, assertOwnerAvailable) {
2704
+ const admission = contributionAdmission(() => this.#assertAdmission(packageId));
2705
+ const toolAdmission = contributionAdmission(assertOwnerAvailable, () => this.#assertAdmission(packageId));
2706
+ return {
2707
+ entryId,
2708
+ objectFactory: (factory) => ({
2709
+ ...factory,
2710
+ assertAvailable: () => admission.assert(),
2711
+ create: (key, self) => this.#authorizedEffect(packageId, factory.create(key, self))
2712
+ }),
2713
+ sessionBehavior: (behavior) => ({
2714
+ ...behavior,
2715
+ reduce: (state, command, scope) => {
2716
+ admission.assert();
2717
+ return behavior.reduce(state, command, scope);
2718
+ },
2719
+ project: (state) => {
2720
+ admission.assert();
2721
+ return behavior.project(state);
2722
+ }
2723
+ }),
2724
+ assertRegistration: () => admission.assert(),
2725
+ resolveHostTool: (bindingId) => this.#hostTools.find((binding) => binding.packageId === packageId && binding.entryId === entryId && binding.bindingId === bindingId)?.tool,
2726
+ tool: (tool) => {
2727
+ const execute = tool.execute;
2728
+ const prepareArguments = tool.prepareArguments;
2729
+ return {
2730
+ ...tool,
2731
+ prepareArguments: prepareArguments === void 0 ? void 0 : admission.call(prepareArguments),
2732
+ execute: (input, toolContext) => {
2733
+ toolAdmission.assert();
2734
+ return execute(input, toolAdmission.toolContext(toolContext));
2735
+ }
2736
+ };
2737
+ },
2738
+ hook: (hook) => {
2739
+ const prepare = hook.prepare;
2740
+ const feedback = hook.feedback;
2741
+ const prepared = async (input, hookContext) => decode(ToolHookPreparationSchema, await prepare?.(input, hookContext) ?? { input });
2742
+ const received = async (result, state, hookContext) => decode(ToolHookFeedbackSchema, await feedback?.(result, state, hookContext) ?? result);
2743
+ return {
2744
+ ...hook,
2745
+ prepare: admission.call(prepared),
2746
+ feedback: admission.call(received)
2747
+ };
2748
+ },
2749
+ namedState: (state) => {
2750
+ const read = state.read;
2751
+ return {
2752
+ ...state,
2753
+ read: admission.call(read)
2754
+ };
2755
+ },
2756
+ runYield: (hook) => ({
2757
+ ...hook,
2758
+ onYield: admission.call(hook.onYield)
2759
+ }),
2760
+ compactionPolicy: (compactionPolicy) => ({
2761
+ ...compactionPolicy,
2762
+ shouldCompact: admission.call(compactionPolicy.shouldCompact)
2763
+ }),
2764
+ compactionObserver: (observer) => ({
2765
+ ...observer,
2766
+ before: observer.before === void 0 ? void 0 : admission.call(observer.before)
2767
+ }),
2768
+ compactionCompiler: (compactionCompiler) => ({
2769
+ ...compactionCompiler,
2770
+ compile: admission.call(compactionCompiler.compile)
2771
+ }),
2772
+ inputTransform: (handler) => {
2773
+ const transform = admission.call(handler.transform);
2774
+ return {
2775
+ ...handler,
2776
+ transform: async (input, inputContext) => decode(PluginInputSchema, await transform(input, inputContext))
2777
+ };
2778
+ },
2779
+ preparationHook: (hook) => {
2780
+ const around = hook.around;
2781
+ return {
2782
+ ...hook,
2783
+ around: admission.call(around)
2784
+ };
2785
+ },
2786
+ historySelector: (selector) => {
2787
+ const select = selector.select;
2788
+ return {
2789
+ ...selector,
2790
+ select: admission.call(select)
2791
+ };
2792
+ }
2793
+ };
2794
+ }
2795
+ #assertAdmission(packageId) {
2796
+ if (this.#closed) throw new PluginAuthorityError("closed");
2797
+ this.#authority.assertPackageExecution(packageId);
2798
+ }
2799
+ #authorizedEffect(packageId, effect) {
2800
+ const admission = Effect.sync(() => this.#assertAdmission(packageId));
2801
+ return Effect.gen(function* () {
2802
+ yield* admission;
2803
+ const scope = yield* Effect.acquireRelease(Scope.make(), (owned) => admission.pipe(Effect.andThen(Scope.close(owned, Exit.void))));
2804
+ return yield* Scope.provide(effect, scope);
2805
+ });
2806
+ }
2807
+ #lifetime(packageId, lifetime) {
2808
+ return {
2809
+ signal: lifetime.signal,
2810
+ assertAvailable: () => {
2811
+ this.#assertAdmission(packageId);
2812
+ lifetime.assertAvailable();
2813
+ },
2814
+ run: (effect) => lifetime.run(this.#authorizedEffect(packageId, effect)),
2815
+ acquire: (acquire, release) => {
2816
+ this.#assertAdmission(packageId);
2817
+ return lifetime.acquire(async (signal) => {
2818
+ this.#assertAdmission(packageId);
2819
+ return acquire(signal);
2820
+ }, async (resource) => {
2821
+ this.#assertAdmission(packageId);
2822
+ return release(resource);
2823
+ });
2824
+ },
2825
+ addFinalizer: (finalizer) => {
2826
+ this.#assertAdmission(packageId);
2827
+ lifetime.addFinalizer(async () => {
2828
+ this.#assertAdmission(packageId);
2829
+ await finalizer();
2830
+ });
2831
+ },
2832
+ supervise: (task) => {
2833
+ this.#assertAdmission(packageId);
2834
+ return lifetime.supervise(async (signal) => {
2835
+ this.#assertAdmission(packageId);
2836
+ await task(signal);
2837
+ });
2838
+ }
2839
+ };
2840
+ }
2841
+ };
2842
+
2843
+ //#endregion
2844
+ export { NodePluginDirectory, NodePluginPackageLoader, NodePluginProcessLoader, PluginDiagnosticCapture, PluginProcessError, SqlitePluginStore, objectFacetTransport, serveObjectFacet };