@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.
@@ -0,0 +1,4667 @@
1
+ import { B as ModelToolMetadataProperties, E as PluginPrefixContributionSchema, H as JsonValueSchema, M as InputTransformMetadataSchema, U as captureJsonValue, V as captureModelToolMetadata, a as capturePluginContributions, b as decodeCallback, i as captureCallbackRetention, k as PreparationHookMetadataSchema, m as captureToolHookMetadata, o as retainPluginCallbacks, p as captureToolHookCallbacks, t as bindObjectRefPort, w as captureNamedStateMetadata, z as captureSessionBehaviors } from "./object-borrow-C81Gj5tq.js";
2
+ import { n as RunYieldMetadataSchema } from "./run-yield-B1AE7-PN.js";
3
+ import { n as captureObjectFactory, r as defineObject, t as captureObjectAddress } from "./objects-DdioT9PR.js";
4
+ import * as s from "@earendil-works/pi-schema";
5
+ import { check, decode } from "@sorbetai/schema";
6
+ import * as Context from "effect/Context";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Layer from "effect/Layer";
9
+ import * as PubSub from "effect/PubSub";
10
+ import ensureError from "ensure-error";
11
+ import { cloneDeep, isEqual, isError, isFunction, isPromise, isString, maxBy, sortBy } from "es-toolkit";
12
+ import * as Predicate from "effect/Predicate";
13
+ import * as Exit from "effect/Exit";
14
+ import * as FiberSet from "effect/FiberSet";
15
+ import * as Ref from "effect/Ref";
16
+ import * as Scope from "effect/Scope";
17
+ import * as Cause from "effect/Cause";
18
+ import * as Deferred from "effect/Deferred";
19
+ import * as Duration from "effect/Duration";
20
+ import * as Fiber from "effect/Fiber";
21
+ import * as Option from "effect/Option";
22
+ import * as Queue from "effect/Queue";
23
+ import * as Semaphore from "effect/Semaphore";
24
+ import * as Stream from "effect/Stream";
25
+ import * as EffectNamespaces from "effect";
26
+ import { parse } from "acorn";
27
+ import { simple } from "acorn-walk";
28
+
29
+ //#region src/composition/lifecycle-error.ts
30
+ /** Preserve author errors and all failure reasons; formatting belongs to diagnostics. */
31
+ function pluginFailure(cause) {
32
+ const errors = cause.reasons.flatMap((reason) => {
33
+ if (Cause.isFailReason(reason)) return [reason.error];
34
+ if (Cause.isDieReason(reason)) return [ensureError(reason.defect)];
35
+ return [];
36
+ });
37
+ if (errors.length > 1) return new AggregateError(errors, "Plugin operation failed");
38
+ return errors[0] ?? ensureError(Cause.squash(cause));
39
+ }
40
+ var PluginLifecycleError = class extends Error {
41
+ constructor(phase, message) {
42
+ super(message);
43
+ this.phase = phase;
44
+ this.name = "PluginLifecycleError";
45
+ }
46
+ };
47
+ /** Admission failed before any Plugin work; reconciliation may retry after capacity returns. */
48
+ var PluginAdmissionError = class extends Error {
49
+ name = "PluginAdmissionError";
50
+ code = "capacity";
51
+ constructor(message = "Plugin execution capacity exceeded") {
52
+ super(message);
53
+ }
54
+ };
55
+ var PluginLeaseDeadlineError = class extends Error {
56
+ name = "PluginLeaseDeadlineError";
57
+ code = "deadline";
58
+ constructor(message = "Model Tool lease deadline has expired") {
59
+ super(message);
60
+ }
61
+ };
62
+ const PluginLeaseDeadlineErrorSchema = s.obj({
63
+ name: s.lit("PluginLeaseDeadlineError"),
64
+ code: s.lit("deadline")
65
+ }, { open: true });
66
+
67
+ //#endregion
68
+ //#region src/composition/sessions.ts
69
+ function makeActivationSessions(access, activationId, signal, retirementSignal, assertAvailable) {
70
+ const assertAdmission = () => {
71
+ assertAvailable?.();
72
+ if (retirementSignal.aborted) throw new PluginLifecycleError("admission", "Plugin Session access is retired");
73
+ };
74
+ const source = access.resolver({
75
+ entryId: access.entryId,
76
+ activationId,
77
+ signal
78
+ });
79
+ const discover = source.discover?.bind(source);
80
+ const create = source.create?.bind(source);
81
+ const invoke = async (requestSignal, execute) => {
82
+ assertAdmission();
83
+ requestSignal.throwIfAborted();
84
+ const release = access.retain();
85
+ try {
86
+ return await execute(requestSignal);
87
+ } finally {
88
+ release();
89
+ }
90
+ };
91
+ const bind = (scope) => {
92
+ assertAdmission();
93
+ scope.signal.throwIfAborted();
94
+ const scopeSignal = AbortSignal.any([scope.signal, retirementSignal]);
95
+ const requestSignal = (requested) => AbortSignal.any([
96
+ scope.signal,
97
+ signal,
98
+ ...requested === void 0 ? [] : [requested]
99
+ ]);
100
+ const { facts, records, request, model, work, control } = scope;
101
+ const forkModel = model?.fork?.bind(model);
102
+ return Object.freeze({
103
+ sessionId: scope.sessionId,
104
+ signal: scopeSignal,
105
+ facts: facts === void 0 ? void 0 : {
106
+ read: (input, options) => invoke(requestSignal(options?.signal), (current) => facts.read(input, { signal: current })),
107
+ follow: (input, options) => ({ [Symbol.asyncIterator]: () => {
108
+ assertAdmission();
109
+ const current = AbortSignal.any([scopeSignal, requestSignal(options?.signal)]);
110
+ current.throwIfAborted();
111
+ const iterator = facts.follow(input, { signal: current })[Symbol.asyncIterator]();
112
+ let closing;
113
+ const close = () => {
114
+ if (closing !== void 0) return closing;
115
+ const release = access.retain();
116
+ closing = Promise.resolve().then(() => iterator.return?.() ?? {
117
+ done: true,
118
+ value: void 0
119
+ }).finally(release);
120
+ return closing;
121
+ };
122
+ const aborted = () => {
123
+ close().catch(() => {});
124
+ };
125
+ current.addEventListener("abort", aborted, { once: true });
126
+ if (current.aborted) aborted();
127
+ return {
128
+ next: () => invoke(current, async () => {
129
+ if (closing !== void 0) return closing;
130
+ const result = await iterator.next();
131
+ current.throwIfAborted();
132
+ if (result.done) {
133
+ current.removeEventListener("abort", aborted);
134
+ closing = Promise.resolve(result);
135
+ }
136
+ return result;
137
+ }),
138
+ return: () => {
139
+ current.removeEventListener("abort", aborted);
140
+ return close();
141
+ }
142
+ };
143
+ } })
144
+ },
145
+ records: records === void 0 ? void 0 : {
146
+ read: (input, options) => invoke(requestSignal(options?.signal), (current) => records.read(input, { signal: current })),
147
+ append: (input, options) => invoke(requestSignal(options?.signal), (current) => records.append(input, { signal: current }))
148
+ },
149
+ model: model === void 0 ? void 0 : {
150
+ complete: (input, options) => invoke(requestSignal(options?.signal), (current) => model.complete(input, {
151
+ signal: current,
152
+ provider: options?.provider
153
+ })),
154
+ fork: forkModel === void 0 ? void 0 : (input, options) => invoke(requestSignal(options?.signal), (current) => forkModel(input, { signal: current }))
155
+ },
156
+ request: request === void 0 ? void 0 : { current: (options) => invoke(requestSignal(options?.signal), (current) => request.current({ signal: current })) },
157
+ work: work === void 0 ? void 0 : { spawn: (task) => {
158
+ assertAdmission();
159
+ scopeSignal.throwIfAborted();
160
+ const release = access.retain();
161
+ try {
162
+ const handle = work.spawn((current) => task(AbortSignal.any([current, scopeSignal])));
163
+ const cancel = () => handle.cancel();
164
+ scopeSignal.addEventListener("abort", cancel, { once: true });
165
+ const settled = handle.settled.catch((cause) => ({
166
+ status: scopeSignal.aborted ? "cancelled" : "failed",
167
+ error: ensureError(cause)
168
+ })).finally(() => {
169
+ scopeSignal.removeEventListener("abort", cancel);
170
+ release();
171
+ });
172
+ if (scopeSignal.aborted) cancel();
173
+ return {
174
+ settled,
175
+ cancel
176
+ };
177
+ } catch (error) {
178
+ release();
179
+ throw error;
180
+ }
181
+ } },
182
+ control: control === void 0 ? void 0 : {
183
+ send: (input, options) => invoke(requestSignal(options?.signal), (current) => control.send(input, { signal: current })),
184
+ write: (() => {
185
+ const writeControl = control.write;
186
+ return writeControl === void 0 ? void 0 : (input, options) => invoke(requestSignal(options?.signal), (current) => writeControl(input, { signal: current }));
187
+ })(),
188
+ cancel: control.cancel === void 0 ? void 0 : (options) => invoke(requestSignal(options?.signal), (current) => control.cancel?.({ signal: current }) ?? Promise.resolve())
189
+ }
190
+ });
191
+ };
192
+ const directory = {
193
+ bind: (sessionId, options) => {
194
+ const current = AbortSignal.any([retirementSignal, ...options?.signal === void 0 ? [] : [options.signal]]);
195
+ return invoke(current, () => source.bind(sessionId, { signal: current })).then(bind);
196
+ },
197
+ discover: discover === void 0 ? void 0 : () => invoke(signal, () => discover()),
198
+ create: create === void 0 ? void 0 : (input) => invoke(signal, async () => bind(await create(input)))
199
+ };
200
+ return Object.freeze(directory);
201
+ }
202
+
203
+ //#endregion
204
+ //#region src/composition/activation.ts
205
+ const AdmittingPhases = new Set([
206
+ "loading",
207
+ "pending",
208
+ "active"
209
+ ]);
210
+ const LivePhases = new Set(["pending", "active"]);
211
+ /** Child scopes and task sets belong to the Platform root, never to a new runtime. */
212
+ const makePluginActivation = Effect.fn("Plugin.makeActivation")(function* (activationId, component, onFailure, observation, sessionAccess, objectAccess) {
213
+ const parent = yield* Effect.scope;
214
+ const scope = yield* Scope.fork(parent, "sequential");
215
+ const memoMap = yield* Layer.makeMemoMap;
216
+ const acquisitions = yield* Scope.provide(FiberSet.make(), scope);
217
+ const tasks = yield* Scope.provide(FiberSet.make(), scope);
218
+ const runAcquisition = yield* FiberSet.runtimePromise(acquisitions)();
219
+ const runTask = yield* FiberSet.runtimePromise(tasks)();
220
+ const phase = yield* Ref.make("loading");
221
+ const failures = yield* Ref.make([]);
222
+ const cleanupFailures = yield* Ref.make([]);
223
+ const controller = new AbortController();
224
+ const retirement = new AbortController();
225
+ const retirementSignal = AbortSignal.any([controller.signal, retirement.signal]);
226
+ const assertAvailable = () => {
227
+ if (controller.signal.aborted) throw new PluginLifecycleError("admission", "Plugin resource is unavailable");
228
+ };
229
+ let admitsFinalizers = true;
230
+ let poisoned = false;
231
+ const assertAdmission = Effect.gen(function* () {
232
+ const current = yield* Ref.get(phase);
233
+ if (!AdmittingPhases.has(current)) return yield* Effect.fail(/* @__PURE__ */ new Error(`Activation ${activationId} is ${current}`));
234
+ if (controller.signal.aborted) return yield* Effect.fail(/* @__PURE__ */ new Error(`Activation ${activationId} was cancelled`));
235
+ });
236
+ const recordFailure = (error) => Ref.update(failures, (all) => [...all, error]);
237
+ const release = (finalizer) => Effect.tryPromise({
238
+ try: finalizer,
239
+ catch: (cause) => isError(cause) ? cause : new Error(String(cause))
240
+ }).pipe(Effect.catch((error) => Ref.update(cleanupFailures, (all) => [...all, error])));
241
+ const lifetime = {
242
+ signal: controller.signal,
243
+ assertAvailable,
244
+ run: (effect) => runAcquisition(assertAdmission.pipe(Effect.andThen(Scope.provide(Effect.provideService(effect, Layer.CurrentMemoMap, memoMap), scope)), Effect.tapError(recordFailure)), { signal: controller.signal }),
245
+ acquire: (acquire, dispose) => {
246
+ const promise = runAcquisition(Effect.uninterruptible(Effect.gen(function* () {
247
+ yield* assertAdmission;
248
+ const resource = yield* Effect.tryPromise({
249
+ try: () => acquire(controller.signal),
250
+ catch: (cause) => isError(cause) ? cause : new Error(String(cause))
251
+ });
252
+ if (controller.signal.aborted) {
253
+ yield* release(() => dispose(resource));
254
+ return yield* Effect.fail(/* @__PURE__ */ new Error(`Activation ${activationId} acquired after cancellation`));
255
+ }
256
+ yield* Scope.addFinalizer(scope, release(() => dispose(resource)));
257
+ return resource;
258
+ })).pipe(Effect.tapError(recordFailure)));
259
+ promise.catch(() => {});
260
+ return promise;
261
+ },
262
+ addFinalizer: (finalizer) => {
263
+ if (!admitsFinalizers || Predicate.isTagged(scope.state, "Closed")) throw new PluginLifecycleError("admission", `Activation ${activationId} no longer accepts finalizers`);
264
+ Effect.runSync(Scope.addFinalizer(scope, release(finalizer)));
265
+ },
266
+ supervise: (task) => {
267
+ const settled = runTask(Effect.uninterruptible(assertAdmission.pipe(Effect.andThen(Effect.tryPromise({
268
+ try: () => task(controller.signal),
269
+ catch: (cause) => isError(cause) ? cause : new Error(String(cause))
270
+ })), Effect.tapError((error) => Effect.gen(function* () {
271
+ if (controller.signal.aborted) return;
272
+ yield* recordFailure(error);
273
+ controller.abort(error);
274
+ if (AdmittingPhases.has(yield* Ref.get(phase))) {
275
+ yield* Ref.set(phase, "failed");
276
+ yield* onFailure(error);
277
+ }
278
+ })))));
279
+ settled.catch(() => {});
280
+ return { settled };
281
+ }
282
+ };
283
+ const stop = Effect.gen(function* () {
284
+ yield* Ref.set(phase, "retiring");
285
+ controller.abort(/* @__PURE__ */ new Error(`Activation ${activationId} is closing`));
286
+ });
287
+ const close = Effect.uninterruptible(Effect.gen(function* () {
288
+ yield* stop;
289
+ yield* FiberSet.awaitEmpty(acquisitions);
290
+ yield* FiberSet.awaitEmpty(tasks);
291
+ admitsFinalizers = false;
292
+ yield* Scope.close(scope, Exit.void);
293
+ const errors = yield* Ref.get(cleanupFailures);
294
+ if (errors.length > 0) {
295
+ poisoned = true;
296
+ return yield* Effect.fail(new AggregateError(errors, `Activation ${activationId} cleanup failed`));
297
+ }
298
+ poisoned = false;
299
+ yield* Ref.set(phase, "closed");
300
+ }));
301
+ let definition;
302
+ const load = Effect.uninterruptible(Effect.gen(function* () {
303
+ yield* assertAdmission;
304
+ if (definition !== void 0) return definition;
305
+ definition = yield* Effect.tryPromise({
306
+ try: () => component.load?.({
307
+ activationId,
308
+ lifetime
309
+ }) ?? Promise.resolve({ activate: component.activate.bind(component) }),
310
+ catch: (cause) => isError(cause) ? cause : new Error(String(cause))
311
+ });
312
+ yield* FiberSet.awaitEmpty(acquisitions);
313
+ yield* assertAdmission;
314
+ const errors = yield* Ref.get(failures);
315
+ if (errors.length > 0) return yield* Effect.fail(new AggregateError(errors, "Plugin declaration loading failed"));
316
+ return definition;
317
+ }));
318
+ const prepare = (services = Context.makeUnsafe(/* @__PURE__ */ new Map())) => Effect.uninterruptible(Effect.gen(function* () {
319
+ const loaded = yield* load;
320
+ yield* assertAdmission;
321
+ const result = yield* Effect.exit(Effect.tryPromise({
322
+ try: () => loaded.activate({
323
+ activationId,
324
+ lifetime,
325
+ services,
326
+ observation,
327
+ objects: objectAccess,
328
+ sessions: sessionAccess === void 0 ? void 0 : makeActivationSessions(sessionAccess, activationId, controller.signal, retirementSignal, loaded.assertAvailable)
329
+ }),
330
+ catch: (cause) => isError(cause) ? cause : new Error(String(cause))
331
+ }));
332
+ if (Exit.isFailure(result)) {
333
+ yield* stop;
334
+ return yield* Effect.failCause(result.cause);
335
+ }
336
+ yield* FiberSet.awaitEmpty(acquisitions);
337
+ if (result.value.assertReady !== void 0) yield* Effect.tryPromise({
338
+ try: () => Promise.resolve(result.value.assertReady?.()),
339
+ catch: (cause) => isError(cause) ? cause : new Error(String(cause))
340
+ });
341
+ yield* assertAdmission;
342
+ const errors = yield* Ref.get(failures);
343
+ if (errors.length > 0) return yield* Effect.fail(new AggregateError(errors, "Plugin preparation failed"));
344
+ return result.value;
345
+ }));
346
+ return {
347
+ scope,
348
+ signal: controller.signal,
349
+ retirementSignal,
350
+ canBorrow: () => Ref.getUnsafe(phase) === "active" && !controller.signal.aborted,
351
+ assertAvailable,
352
+ activationId,
353
+ componentId: component.componentId,
354
+ load,
355
+ prepare,
356
+ close,
357
+ stop,
358
+ fence: Ref.update(phase, (current) => LivePhases.has(current) ? "retiring" : current).pipe(Effect.andThen(Effect.sync(() => retirement.abort(/* @__PURE__ */ new Error(`Activation ${activationId} is retiring`))))),
359
+ awaitServices: assertAdmission.pipe(Effect.andThen(Ref.set(phase, "pending"))),
360
+ serve: assertAdmission.pipe(Effect.andThen(Ref.set(phase, "active"))),
361
+ poison: Effect.sync(() => {
362
+ if (Ref.getUnsafe(phase) === "closed") return;
363
+ poisoned = true;
364
+ controller.abort(/* @__PURE__ */ new Error("Plugin cleanup uncertainty"));
365
+ }),
366
+ snapshot: () => ({
367
+ activationId,
368
+ componentId: component.componentId,
369
+ profile: component.executionProfile ?? "in_process",
370
+ phase: Ref.getUnsafe(phase),
371
+ residualResources: poisoned,
372
+ failures: [...Ref.getUnsafe(failures), ...Ref.getUnsafe(cleanupFailures)].map((error) => error.message)
373
+ })
374
+ };
375
+ });
376
+
377
+ //#endregion
378
+ //#region src/contributions/admission.ts
379
+ function contributionAdmission(...checks) {
380
+ const assert = () => {
381
+ for (const check$1 of checks) check$1();
382
+ };
383
+ const admission = {
384
+ assert,
385
+ call: (callback) => (...args) => {
386
+ assert();
387
+ return callback(...args);
388
+ },
389
+ toolContext: (context, deferred = admission) => {
390
+ const { ownTask } = context;
391
+ return {
392
+ ...context,
393
+ assertAvailable: () => {
394
+ context.assertAvailable?.();
395
+ deferred.assert();
396
+ },
397
+ ownTask: ownTask === void 0 ? void 0 : (execute) => ownTask(async () => {
398
+ deferred.assert();
399
+ await execute();
400
+ })
401
+ };
402
+ }
403
+ };
404
+ return admission;
405
+ }
406
+
407
+ //#endregion
408
+ //#region src/contributions/context.ts
409
+ async function runPluginApply(result, lifetime) {
410
+ if (Effect.isEffect(result)) await lifetime.run(result);
411
+ else {
412
+ const registration = await result;
413
+ if (registration !== void 0) {
414
+ const dispose = registration.dispose.bind(registration);
415
+ lifetime.addFinalizer(async () => {
416
+ await dispose();
417
+ });
418
+ }
419
+ }
420
+ }
421
+ const HostToolRegistrationSchema = s.obj({
422
+ key: s.opt(s.str({ minLength: 1 })),
423
+ hostBinding: s.str({
424
+ minLength: 1,
425
+ maxLength: 200
426
+ })
427
+ }, { open: false });
428
+ const ToolRegistrationSchema = s.obj({
429
+ key: s.opt(s.str({ minLength: 1 })),
430
+ name: ModelToolMetadataProperties.name,
431
+ label: ModelToolMetadataProperties.label,
432
+ description: ModelToolMetadataProperties.description,
433
+ parameters: ModelToolMetadataProperties.parameters,
434
+ outputSchema: ModelToolMetadataProperties.outputSchema,
435
+ prepareArguments: s.opt(s.unknown()),
436
+ execute: s.unknown()
437
+ }, { open: true });
438
+ const CommandInputSchema = s.obj({ arguments: s.str() }, { open: false });
439
+ const CommandResultProperties = {
440
+ text: s.str(),
441
+ details: s.opt(JsonValueSchema)
442
+ };
443
+ const CommandResultSchema = s.obj(CommandResultProperties, { open: false });
444
+ const MAX_MODEL_TOOL_NAME_CHARS = 64;
445
+ /** Creates an Activation-owned registration view; it owns no lifecycle state of its own. */
446
+ function createPluginContext(instancePath, lifetime, policy = {}, ownCleanup = lifetime.addFinalizer) {
447
+ const instanceKey = instancePath.join("/");
448
+ let open = true;
449
+ let version = 0;
450
+ const listeners = /* @__PURE__ */ new Set();
451
+ const changed = () => {
452
+ version += 1;
453
+ for (const listener of listeners) listener();
454
+ };
455
+ const keys = /* @__PURE__ */ new Map();
456
+ /** Model-facing Tool names in use, so a derived command name cannot shadow one. */
457
+ const toolNameUses = /* @__PURE__ */ new Map();
458
+ const releaseToolName = (name) => {
459
+ const uses = (toolNameUses.get(name) ?? 1) - 1;
460
+ if (uses === 0) toolNameUses.delete(name);
461
+ else toolNameUses.set(name, uses);
462
+ };
463
+ const contributions = {
464
+ objectFactories: [],
465
+ sessionBehaviors: [],
466
+ tools: [],
467
+ hooks: [],
468
+ namedStates: [],
469
+ prefixes: [],
470
+ runYield: [],
471
+ compactionPolicies: [],
472
+ compactionCompilers: [],
473
+ compactionObservers: [],
474
+ inputTransforms: [],
475
+ preparationHooks: [],
476
+ historySelectors: []
477
+ };
478
+ const identity = (domain, key) => {
479
+ policy.assertRegistration?.();
480
+ lifetime.signal.throwIfAborted();
481
+ if (!open) throw new Error(`Plugin ${instanceKey} registration is sealed`);
482
+ if (key.length === 0) throw new TypeError("Plugin registration key must not be empty");
483
+ if ((keys.get(domain) ?? /* @__PURE__ */ new Set()).has(key)) throw new TypeError(`Duplicate Plugin ${domain} registration: ${key}`);
484
+ return registrationId(instancePath, domain, key);
485
+ };
486
+ const register = (domain, key, entries, value) => {
487
+ const domainKeys = keys.get(domain) ?? /* @__PURE__ */ new Set();
488
+ domainKeys.add(key);
489
+ keys.set(domain, domainKeys);
490
+ entries.push(value);
491
+ changed();
492
+ return { dispose: () => {
493
+ const index = entries.indexOf(value);
494
+ if (index === -1 || lifetime.signal.aborted) return;
495
+ if (!open) throw new Error(`Plugin ${instanceKey} registration is sealed`);
496
+ entries.splice(index, 1);
497
+ domainKeys.delete(key);
498
+ changed();
499
+ } };
500
+ };
501
+ const registerTool = (registration) => {
502
+ let tool;
503
+ let localKey;
504
+ if (check(HostToolRegistrationSchema, registration)) {
505
+ const host = decode(HostToolRegistrationSchema, registration);
506
+ const resolved = policy.resolveHostTool?.(host.hostBinding);
507
+ if (resolved === void 0) throw new TypeError("Missing exact Plugin Host Tool binding");
508
+ tool = resolved;
509
+ localKey = host.key ?? host.hostBinding;
510
+ } else {
511
+ const author = decode(ToolRegistrationSchema, registration);
512
+ tool = captureCallbackRetention({
513
+ ...author,
514
+ contributionId: "",
515
+ execute: decodeCallback(author.execute).bind(registration),
516
+ prepareArguments: author.prepareArguments === void 0 ? void 0 : decodeCallback(author.prepareArguments).bind(registration)
517
+ }, registration);
518
+ localKey = author.key ?? author.name;
519
+ }
520
+ const contributionId = identity("tool", localKey);
521
+ const metadata = captureModelToolMetadata({
522
+ ...tool,
523
+ contributionId
524
+ });
525
+ const captured = captureCallbackRetention({
526
+ ...metadata,
527
+ recovery: tool.recovery,
528
+ execute: tool.execute.bind(tool),
529
+ prepareArguments: tool.prepareArguments?.bind(tool)
530
+ }, tool);
531
+ const configured = captureCallbackRetention(policy.tool?.(captured) ?? captured, captured);
532
+ toolNameUses.set(metadata.name, (toolNameUses.get(metadata.name) ?? 0) + 1);
533
+ const claimed = register("tool", localKey, contributions.tools, configured);
534
+ let released = false;
535
+ return { dispose: () => {
536
+ if (released) return;
537
+ released = true;
538
+ claimed.dispose();
539
+ releaseToolName(metadata.name);
540
+ } };
541
+ };
542
+ const commandToolName = (name, toolIdentity) => {
543
+ const toolName = `command_${name.replace(/[^A-Za-z0-9_-]/g, "_") || "command"}_${btoa(Array.from(new TextEncoder().encode(toolIdentity), (byte) => String.fromCharCode(byte)).join("")).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")}`;
544
+ if (toolName.length > MAX_MODEL_TOOL_NAME_CHARS) throw new TypeError(`Command Tool name exceeds ${MAX_MODEL_TOOL_NAME_CHARS} characters: ${toolName}`);
545
+ return toolName;
546
+ };
547
+ const context = {
548
+ objects: {
549
+ define: (id, definition) => defineObject(id, definition),
550
+ serve: (type, factory) => {
551
+ identity("object-factory", type.id);
552
+ const captured = captureObjectFactory(type, factory);
553
+ return register("object-factory", type.id, contributions.objectFactories, policy.objectFactory?.(captured) ?? captured);
554
+ },
555
+ acquire: (type, key) => {
556
+ const acquisition = policy.objects;
557
+ if (acquisition === void 0) return Effect.fail(/* @__PURE__ */ new Error("Object acquisition requires a programmatic composition root"));
558
+ return acquisition.acquire(type, key);
559
+ }
560
+ },
561
+ entryId: policy.entryId,
562
+ activationId: policy.activationId,
563
+ observation: policy.observation,
564
+ provide: (service, value) => {
565
+ policy.assertRegistration?.();
566
+ lifetime.signal.throwIfAborted();
567
+ if (!open) throw new Error(`Plugin ${instanceKey} registration is sealed`);
568
+ if (policy.provide === void 0) throw new Error("Service providers require programmatic configuration");
569
+ return policy.provide(service, value);
570
+ },
571
+ mount: (key, apply, config) => {
572
+ policy.assertRegistration?.();
573
+ lifetime.signal.throwIfAborted();
574
+ if (!open) throw new Error(`Plugin ${instanceKey} registration is sealed`);
575
+ if (policy.mount === void 0) throw new Error("Dynamic child Plugins require programmatic configuration");
576
+ if (isFunction(apply)) return policy.mount(key, apply, config);
577
+ return policy.mount(key, apply, config);
578
+ },
579
+ session: {
580
+ bind: async (sessionId, options) => {
581
+ if (policy.sessions === void 0) throw new Error("Plugin Session access is unavailable");
582
+ return policy.sessions.bind(sessionId, options);
583
+ },
584
+ discover: async () => {
585
+ if (policy.sessions?.discover === void 0) throw new Error("Plugin Session discovery is unavailable");
586
+ return policy.sessions.discover();
587
+ },
588
+ create: async (input) => {
589
+ if (policy.sessions?.create === void 0) throw new Error("Plugin Session creation is unavailable");
590
+ return policy.sessions.create(input);
591
+ },
592
+ behavior: (behavior) => {
593
+ const [captured] = captureSessionBehaviors([{
594
+ ...behavior,
595
+ contributionId: identity("session-behavior", behavior.name)
596
+ }]);
597
+ if (captured === void 0) throw new Error("Missing Session behavior");
598
+ return register("session-behavior", behavior.name, contributions.sessionBehaviors, policy.sessionBehavior?.(captured) ?? captured);
599
+ }
600
+ },
601
+ signal: lifetime.signal,
602
+ assertAvailable: lifetime.assertAvailable,
603
+ acquire: lifetime.acquire,
604
+ supervise: lifetime.supervise,
605
+ tools: {
606
+ register: registerTool,
607
+ hook: (hook) => {
608
+ captureToolHookCallbacks(hook);
609
+ const captured = {
610
+ ...captureToolHookMetadata({
611
+ contributionId: identity("tool-hook", hook.key),
612
+ version: hook.version,
613
+ before: hook.before?.map((reference) => referencedRegistrationId(instancePath, "tool-hook", reference)),
614
+ after: hook.after?.map((reference) => referencedRegistrationId(instancePath, "tool-hook", reference))
615
+ }),
616
+ prepare: hook.prepare?.bind(hook),
617
+ feedback: hook.feedback?.bind(hook)
618
+ };
619
+ return register("tool-hook", hook.key, contributions.hooks, policy.hook?.(captured) ?? captured);
620
+ }
621
+ },
622
+ commands: { register: (command) => {
623
+ if (command.name.length === 0 || /[\s/]/.test(command.name)) throw new TypeError("Command name must not contain whitespace or slash");
624
+ if (!isFunction(command.execute)) throw new TypeError("Command execute must be a function");
625
+ const argumentHint = command.argumentHint;
626
+ const toolName = commandToolName(command.name, `${instanceKey}/${command.key ?? command.name}`);
627
+ if (toolNameUses.has(toolName)) throw new TypeError(`Command Tool name is already registered: ${toolName}`);
628
+ return registerTool({
629
+ key: `command:${command.key ?? command.name}`,
630
+ name: toolName,
631
+ label: `/${command.name}`,
632
+ description: command.description,
633
+ parameters: s.obj({ arguments: s.str() }, { open: false }),
634
+ discovery: { exposure: "hidden" },
635
+ metadata: { "sorbet.dev/slash-command": {
636
+ name: command.name,
637
+ description: command.description,
638
+ ...argumentHint === void 0 ? {} : { argumentHint }
639
+ } },
640
+ execute: async (input, execution) => {
641
+ const parsed = decode(CommandInputSchema, input);
642
+ const result = decode(CommandResultSchema, await command.execute({
643
+ arguments: parsed.arguments,
644
+ ...execution.source === void 0 ? {} : { source: execution.source }
645
+ }, {
646
+ sessionId: execution.sessionId,
647
+ signal: execution.signal,
648
+ ...execution.commandBehavior === void 0 ? {} : { commandBehavior: execution.commandBehavior }
649
+ }));
650
+ return {
651
+ content: [{
652
+ type: "text",
653
+ text: result.text
654
+ }],
655
+ details: result.details ?? {}
656
+ };
657
+ }
658
+ });
659
+ } },
660
+ runYield: { register: (key, hook) => {
661
+ decodeCallback(hook.onYield);
662
+ const captured = {
663
+ ...decode(RunYieldMetadataSchema, {
664
+ contributionId: identity("run-yield", key),
665
+ behavior: hook.behavior
666
+ }),
667
+ onYield: hook.onYield.bind(hook)
668
+ };
669
+ return register("run-yield", key, contributions.runYield, policy.runYield?.(captured) ?? captured);
670
+ } },
671
+ compaction: {
672
+ policy: (registration) => {
673
+ if (!isFunction(registration.shouldCompact)) throw new TypeError("Compaction policy must define shouldCompact");
674
+ const registeredVersion = registration.version ?? 1;
675
+ if (!Number.isInteger(registeredVersion) || registeredVersion < 1) throw new TypeError("Compaction policy version must be a positive integer");
676
+ const captured = {
677
+ ...registration,
678
+ contributionId: identity("compaction-policy", registration.key),
679
+ version: registeredVersion,
680
+ shouldCompact: registration.shouldCompact.bind(registration)
681
+ };
682
+ return register("compaction-policy", registration.key, contributions.compactionPolicies, policy.compactionPolicy?.(captured) ?? captured);
683
+ },
684
+ compiler: (registration) => {
685
+ if (!isFunction(registration.compile)) throw new TypeError("Compaction compiler must define compile");
686
+ const registeredVersion = registration.version ?? 1;
687
+ if (!Number.isInteger(registeredVersion) || registeredVersion < 1) throw new TypeError("Compaction compiler version must be a positive integer");
688
+ const captured = {
689
+ ...registration,
690
+ contributionId: identity("compaction-compiler", registration.key),
691
+ version: registeredVersion,
692
+ compile: registration.compile.bind(registration)
693
+ };
694
+ return register("compaction-compiler", registration.key, contributions.compactionCompilers, policy.compactionCompiler?.(captured) ?? captured);
695
+ },
696
+ observe: (registration) => {
697
+ if (!isFunction(registration.before)) throw new TypeError("Compaction observer must define before");
698
+ const registeredVersion = registration.version ?? 1;
699
+ if (!Number.isInteger(registeredVersion) || registeredVersion < 1) throw new TypeError("Compaction observer version must be a positive integer");
700
+ const captured = {
701
+ ...registration,
702
+ contributionId: identity("compaction-observer", registration.key),
703
+ version: registeredVersion,
704
+ before: registration.before.bind(registration)
705
+ };
706
+ return register("compaction-observer", registration.key, contributions.compactionObservers, policy.compactionObserver?.(captured) ?? captured);
707
+ }
708
+ },
709
+ input: { transform: (key, transform) => {
710
+ decodeCallback(transform);
711
+ const contributionId = identity("input", key);
712
+ decode(InputTransformMetadataSchema, { contributionId });
713
+ const captured = {
714
+ contributionId,
715
+ transform
716
+ };
717
+ return register("input", key, contributions.inputTransforms, policy.inputTransform?.(captured) ?? captured);
718
+ } },
719
+ context: {
720
+ state: (state) => {
721
+ const captured = {
722
+ ...captureNamedStateMetadata({
723
+ contributionId: identity("named-state", state.key ?? state.stateName),
724
+ stateName: state.stateName,
725
+ schema: state.schema
726
+ }),
727
+ read: state.read.bind(state)
728
+ };
729
+ return register("named-state", state.key ?? state.stateName, contributions.namedStates, policy.namedState?.(captured) ?? captured);
730
+ },
731
+ prefix: (key, content) => {
732
+ return register("prefix", key, contributions.prefixes, decode(PluginPrefixContributionSchema, {
733
+ contributionId: identity("prefix", key),
734
+ content
735
+ }));
736
+ },
737
+ around: (key, around) => {
738
+ decodeCallback(around);
739
+ const hookId = identity("context-around", key);
740
+ decode(PreparationHookMetadataSchema, { hookId });
741
+ const captured = {
742
+ hookId,
743
+ around
744
+ };
745
+ return register("context-around", key, contributions.preparationHooks, policy.preparationHook?.(captured) ?? captured);
746
+ },
747
+ selectHistory: (key, select) => {
748
+ decodeCallback(select);
749
+ const selectorId = identity("history-selector", key);
750
+ decode(s.str({ minLength: 1 }), selectorId);
751
+ const captured = {
752
+ selectorId,
753
+ select
754
+ };
755
+ return register("history-selector", key, contributions.historySelectors, policy.historySelector?.(captured) ?? captured);
756
+ }
757
+ }
758
+ };
759
+ ownCleanup(async () => {
760
+ open = false;
761
+ policy.close?.();
762
+ listeners.clear();
763
+ for (const entries of Object.values(contributions)) entries.length = 0;
764
+ keys.clear();
765
+ toolNameUses.clear();
766
+ changed();
767
+ });
768
+ return {
769
+ live: {
770
+ get version() {
771
+ return version;
772
+ },
773
+ snapshot: () => contributions,
774
+ subscribe: (listener) => {
775
+ listeners.add(listener);
776
+ return () => {
777
+ listeners.delete(listener);
778
+ };
779
+ }
780
+ },
781
+ contributions,
782
+ context,
783
+ seal: () => {
784
+ open = false;
785
+ }
786
+ };
787
+ }
788
+ function registrationId(instancePath, domain, key) {
789
+ return `sorbet:plugin/${instancePath.map(encodeURIComponent).join("/")}/${domain}/${encodeURIComponent(key)}`;
790
+ }
791
+ function referencedRegistrationId(instancePath, domain, reference) {
792
+ if (isString(reference)) return registrationId(instancePath, domain, reference);
793
+ return registrationId([reference.entry], domain, reference.key);
794
+ }
795
+
796
+ //#endregion
797
+ //#region src/composition/reconciliation.ts
798
+ function sameServiceBindings(left, right) {
799
+ return left.length === right.length && left.every((binding, index) => binding.provider === right[index]?.provider && binding.registration === right[index]?.registration);
800
+ }
801
+ function sameEntryIdentity(left, right) {
802
+ if (left?.kind !== right.kind || left.entryId !== right.entryId) return false;
803
+ if (left.kind === "package" && right.kind === "package") return left.packageId === right.packageId && isEqual(left.config, right.config);
804
+ if (left.kind === "programmatic" && right.kind === "programmatic") return left.apply === right.apply && left.realm === right.realm && left.replacement === right.replacement && isEqual(left.requires, right.requires) && isEqual(left.provides ?? [], right.provides ?? []) && isEqual(left.config, right.config);
805
+ if (left.kind === "child" && right.kind === "child") return left.component === right.component;
806
+ return false;
807
+ }
808
+ const AdmissionCapacityErrorSchema = s.obj({
809
+ name: s.lit("PluginAdmissionError"),
810
+ code: s.lit("capacity")
811
+ }, { open: true });
812
+ function makeMountReconciliation(input) {
813
+ const options = { ...input };
814
+ const created = [];
815
+ const staged = [];
816
+ const owners = [];
817
+ const waitingExclusive = /* @__PURE__ */ new Set();
818
+ const waitingAdmission = /* @__PURE__ */ new Set();
819
+ const rootRealm = {
820
+ path: [],
821
+ providers: /* @__PURE__ */ new Map(),
822
+ reverseRequires: /* @__PURE__ */ new Map()
823
+ };
824
+ const realms = new Set([rootRealm]);
825
+ const offered = /* @__PURE__ */ new Map();
826
+ const dirty = /* @__PURE__ */ new Set();
827
+ const childVersions = /* @__PURE__ */ new Map();
828
+ const serviceVersions = /* @__PURE__ */ new Map();
829
+ let roots = [];
830
+ const sourcesChanged = () => [...childVersions].some(([entry, version]) => entry.children?.version !== version) || [...serviceVersions].some(([entry, version]) => entry.services?.version !== version);
831
+ const notifyKey = (realm, key) => {
832
+ for (const target of realm.reverseRequires.get(key) ?? []) dirty.add(target);
833
+ };
834
+ const resolve = (target) => {
835
+ const bindings = [];
836
+ const missing = [];
837
+ const conflicting = [];
838
+ for (const requirement of target.member.requires ?? []) {
839
+ const key = isString(requirement) ? requirement : requirement.key;
840
+ let available = [];
841
+ for (let realm = target.realm; realm !== void 0; realm = realm.parent) {
842
+ available = [...realm.providers.get(key) ?? []];
843
+ if (available.length > 0) break;
844
+ }
845
+ const [binding] = available;
846
+ if (available.length > 1) conflicting.push(key);
847
+ else if (binding === void 0) {
848
+ if (isString(requirement) || !Context.isReference(requirement)) missing.push(key);
849
+ } else bindings.push(binding);
850
+ }
851
+ return {
852
+ bindings,
853
+ missing,
854
+ conflicting
855
+ };
856
+ };
857
+ const track = (member, parent, collision) => {
858
+ const path = [...parent?.path ?? [], member.identity?.entryId ?? member.component.componentId];
859
+ const key = path.map(encodeURIComponent).join("/");
860
+ let realm = parent?.realm ?? rootRealm;
861
+ if (member.realm !== void 0) {
862
+ realm = {
863
+ path,
864
+ parent: member.realm === "inherit" ? realm : void 0,
865
+ providers: /* @__PURE__ */ new Map(),
866
+ reverseRequires: /* @__PURE__ */ new Map()
867
+ };
868
+ realms.add(realm);
869
+ }
870
+ const target = {
871
+ key,
872
+ path,
873
+ realm,
874
+ member,
875
+ parent,
876
+ children: [],
877
+ collision
878
+ };
879
+ if (collision !== void 0) return target;
880
+ for (const requirement of member.requires ?? []) {
881
+ const serviceKey = isString(requirement) ? requirement : requirement.key;
882
+ for (let visible = realm; visible !== void 0; visible = visible.parent) {
883
+ const consumers = visible.reverseRequires.get(serviceKey) ?? /* @__PURE__ */ new Set();
884
+ consumers.add(target);
885
+ visible.reverseRequires.set(serviceKey, consumers);
886
+ }
887
+ }
888
+ return target;
889
+ };
890
+ const deactivate = (target, untrack = false) => {
891
+ for (const child of target.children) deactivate(child, true);
892
+ target.children.length = 0;
893
+ const entry = target.entry;
894
+ if (entry !== void 0) {
895
+ target.entry = void 0;
896
+ owners.splice(owners.indexOf(entry), 1);
897
+ for (const binding of offered.get(entry) ?? []) {
898
+ target.realm.providers.get(binding.registration.key)?.delete(binding);
899
+ notifyKey(target.realm, binding.registration.key);
900
+ }
901
+ offered.delete(entry);
902
+ }
903
+ if (untrack) {
904
+ for (const requirement of target.member.requires ?? []) {
905
+ const key = isString(requirement) ? requirement : requirement.key;
906
+ for (let realm = target.realm; realm !== void 0; realm = realm.parent) realm.reverseRequires.get(key)?.delete(target);
907
+ }
908
+ dirty.delete(target);
909
+ } else dirty.add(target);
910
+ };
911
+ const attach = (target, entry) => {
912
+ entry.rootRealm = target.realm === rootRealm;
913
+ target.entry = entry;
914
+ owners.push(entry);
915
+ const bindings = (entry.services?.snapshot() ?? []).map((registration) => ({
916
+ provider: entry,
917
+ registration
918
+ }));
919
+ offered.set(entry, bindings);
920
+ for (const binding of bindings) {
921
+ const available = target.realm.providers.get(binding.registration.key) ?? /* @__PURE__ */ new Set();
922
+ available.add(binding);
923
+ target.realm.providers.set(binding.registration.key, available);
924
+ notifyKey(target.realm, binding.registration.key);
925
+ }
926
+ if (entry.services !== void 0) serviceVersions.set(entry, entry.services.version);
927
+ if (entry.children !== void 0) childVersions.set(entry, entry.children.version);
928
+ };
929
+ const stage = (member, path, parent, bindings = []) => Effect.gen(function* () {
930
+ let entry;
931
+ const owner = yield* Scope.provide(makePluginActivation(options.createId(), member.component, (error) => Effect.sync(() => {
932
+ entry.failure = error;
933
+ options.failures.set(member.component, {
934
+ error,
935
+ bindings: entry.bindings,
936
+ terminal: true
937
+ });
938
+ options.notify();
939
+ }), options.observation, options.sessions === void 0 ? void 0 : {
940
+ resolver: options.sessions,
941
+ entryId: `sorbet:plugin/${encodeURIComponent(options.scopeId)}/${member.identity?.kind === "package" ? encodeURIComponent(member.identity.entryId) : path.map(encodeURIComponent).join("/")}`,
942
+ retain: () => {
943
+ const drained = Deferred.makeUnsafe();
944
+ entry.drains.add(drained);
945
+ options.borrowed?.(1);
946
+ return () => {
947
+ if (entry.drains.delete(drained)) {
948
+ options.borrowed?.(-1);
949
+ Effect.runSync(Deferred.succeed(drained, void 0));
950
+ }
951
+ };
952
+ }
953
+ }, options.objects), parent?.owner.scope ?? options.scope);
954
+ entry = {
955
+ owner,
956
+ identity: member.identity,
957
+ parent,
958
+ path,
959
+ rootRealm: false,
960
+ bindings,
961
+ prepared: false,
962
+ ownedChildren: /* @__PURE__ */ new Set(),
963
+ consumers: /* @__PURE__ */ new Set(),
964
+ requires: member.requires ?? [],
965
+ replacement: member.replacement,
966
+ contributions: { tools: [] },
967
+ behaviorRegistrations: [],
968
+ drains: /* @__PURE__ */ new Set()
969
+ };
970
+ staged.push(entry);
971
+ created.push(owner);
972
+ parent?.ownedChildren.add(entry);
973
+ yield* options.preparing(entry);
974
+ return entry;
975
+ });
976
+ const acquire = (entry, work) => Effect.gen(function* () {
977
+ const fiber = yield* Effect.forkIn(Effect.exit(work), options.scope);
978
+ entry.preparation = Fiber.await(fiber).pipe(Effect.asVoid);
979
+ const result = yield* Fiber.join(fiber).pipe(Effect.timeoutOption(options.preparationTimeoutMs ?? Duration.infinity));
980
+ if (Option.isNone(result)) {
981
+ yield* entry.owner.stop;
982
+ return yield* Effect.fail(new PluginLifecycleError("preparation", "Plugin preparation timed out"));
983
+ }
984
+ return yield* result.value;
985
+ });
986
+ const retireFailed = (entry) => options.retire([entry]).pipe(Effect.catch((error) => entry.identity === void 0 ? Effect.fail(error) : Effect.void));
987
+ const deferAdmission = (target) => {
988
+ const admission = target.member.component.admission;
989
+ if (admission === void 0 || admission.available()) return false;
990
+ target.pendingReason = "admission";
991
+ return true;
992
+ };
993
+ const isCapacityFailure = (member, error) => member.component.admission !== void 0 && check(AdmissionCapacityErrorSchema, error);
994
+ const discardStaged = Effect.fn("MountReconciliation.discardStaged")(function* (entry) {
995
+ const stagedIndex = staged.indexOf(entry);
996
+ if (stagedIndex >= 0) staged.splice(stagedIndex, 1);
997
+ const createdIndex = created.indexOf(entry.owner);
998
+ if (createdIndex >= 0) created.splice(createdIndex, 1);
999
+ yield* retireFailed(entry);
1000
+ });
1001
+ const prepareTarget = (target) => Effect.gen(function* () {
1002
+ if (options.isClosing()) return yield* Effect.fail(new PluginLifecycleError("preparation", "Plugin preparation cancelled"));
1003
+ dirty.delete(target);
1004
+ const previousFailure = options.failures.get(target.member.component);
1005
+ if (previousFailure?.terminal) {
1006
+ target.error = previousFailure.error;
1007
+ return;
1008
+ }
1009
+ const resolved = resolve(target);
1010
+ if (resolved.missing.length > 0 || resolved.conflicting.length > 0) return;
1011
+ target.pendingReason = void 0;
1012
+ const { member } = target;
1013
+ const parent = target.parent?.entry;
1014
+ const identity = member.identity;
1015
+ let entry = identity === void 0 ? void 0 : [...staged, ...options.existing].find((candidate) => candidate.failure === void 0 && candidate.prepared && candidate.parent === parent && sameEntryIdentity(candidate.identity, identity) && sameServiceBindings(candidate.bindings, resolved.bindings));
1016
+ if (entry === void 0) {
1017
+ const previous = [
1018
+ ...staged,
1019
+ ...options.existing,
1020
+ ...options.retiring
1021
+ ].filter((candidate) => candidate.prepared && isEqual(candidate.path, target.path) && (candidate.replacement === "exclusive" || member.replacement === "exclusive"));
1022
+ if (previous.length > 0) {
1023
+ for (const candidate of previous) waitingExclusive.add(candidate);
1024
+ target.pendingReason = "retiring";
1025
+ return;
1026
+ }
1027
+ }
1028
+ target.error = previousFailure !== void 0 && sameServiceBindings(previousFailure.bindings, resolved.bindings) ? previousFailure.error : void 0;
1029
+ if (entry === void 0 && target.error === void 0) {
1030
+ if ((target.waitingEntry === void 0 || !staged.includes(target.waitingEntry)) && deferAdmission(target)) {
1031
+ target.waitingEntry = void 0;
1032
+ return;
1033
+ }
1034
+ const services = resolved.bindings.reduce((context, binding) => Context.merge(context, binding.registration.context), Context.makeUnsafe(/* @__PURE__ */ new Map()));
1035
+ entry = target.waitingEntry !== void 0 && staged.includes(target.waitingEntry) ? target.waitingEntry : yield* stage(member, target.path, parent, resolved.bindings);
1036
+ target.waitingEntry = void 0;
1037
+ const owner = entry.owner;
1038
+ entry.bindings = resolved.bindings;
1039
+ entry.requires = member.requires ?? [];
1040
+ entry.replacement = member.replacement;
1041
+ for (const binding of entry.bindings) binding.provider.consumers.add(entry);
1042
+ if (member.component.load !== void 0) {
1043
+ const loaded = yield* Effect.exit(acquire(entry, owner.load));
1044
+ if (Exit.isFailure(loaded)) {
1045
+ const error = pluginFailure(loaded.cause);
1046
+ if (!isCapacityFailure(member, error)) return yield* Effect.fail(error);
1047
+ yield* discardStaged(entry);
1048
+ target.pendingReason = "admission";
1049
+ return;
1050
+ }
1051
+ const definition = loaded.value;
1052
+ if (!isEqual(definition.requires ?? [], member.requires ?? []) || !isEqual(definition.provides ?? [], member.provides ?? []) || definition.realm !== member.realm || definition.replacement !== member.replacement) return yield* Effect.fail(/* @__PURE__ */ new Error("Plugin declaration changed for the same component identity"));
1053
+ entry.definition = definition;
1054
+ }
1055
+ const prepared = yield* Effect.exit(acquire(entry, owner.prepare(services)));
1056
+ if (Exit.isFailure(prepared)) {
1057
+ target.error = pluginFailure(prepared.cause);
1058
+ if (isCapacityFailure(member, target.error)) {
1059
+ yield* discardStaged(entry);
1060
+ target.error = void 0;
1061
+ target.pendingReason = "admission";
1062
+ return;
1063
+ }
1064
+ if (parent === void 0 && entry.requires.length === 0 && member.replacement !== "exclusive" && member.identity?.kind !== "package") return yield* Effect.fail(target.error);
1065
+ yield* discardStaged(entry);
1066
+ options.failures.set(member.component, {
1067
+ error: target.error,
1068
+ bindings: resolved.bindings
1069
+ });
1070
+ entry = void 0;
1071
+ } else {
1072
+ entry.prepared = true;
1073
+ entry.contributions = capturePluginContributions(prepared.value);
1074
+ entry.live = prepared.value.live;
1075
+ entry.behaviorRegistrations = [...entry.live?.snapshot().sessionBehaviors ?? prepared.value.sessionBehaviors ?? []];
1076
+ entry.version = prepared.value.live?.version;
1077
+ entry.unsubscribeLive = entry.live?.subscribe(options.notify);
1078
+ entry.children = prepared.value.children;
1079
+ entry.unsubscribeChildren = entry.children?.subscribe(options.notify);
1080
+ entry.services = prepared.value.services;
1081
+ entry.unsubscribeServices = entry.services?.subscribe(options.notify);
1082
+ }
1083
+ }
1084
+ if (target.error !== void 0) entry = options.existing.find((candidate) => candidate.failure === void 0 && candidate.prepared && candidate.parent === parent && candidate.identity?.entryId === identity?.entryId && sameServiceBindings(candidate.bindings, resolved.bindings));
1085
+ if (entry === void 0) return;
1086
+ attach(target, entry);
1087
+ const children = [...member.children ?? [], ...(entry.children?.snapshot() ?? []).map((child) => ({
1088
+ component: child.component,
1089
+ report: child.report,
1090
+ requires: child.requires,
1091
+ provides: child.provides,
1092
+ realm: child.realm,
1093
+ replacement: child.replacement,
1094
+ identity: {
1095
+ kind: "child",
1096
+ entryId: child.key,
1097
+ component: child.component
1098
+ }
1099
+ }))];
1100
+ const siblings = /* @__PURE__ */ new Map();
1101
+ for (const child of children) {
1102
+ const key = child.identity?.entryId ?? child.component.componentId;
1103
+ const group = siblings.get(key) ?? [];
1104
+ group.push(child);
1105
+ siblings.set(key, group);
1106
+ }
1107
+ for (const [key, group] of siblings) {
1108
+ const child = group[0];
1109
+ if (group.length > 1) target.children.push(track({
1110
+ ...child,
1111
+ report: (status) => {
1112
+ for (const sibling of group) sibling.report?.(status);
1113
+ }
1114
+ }, target, /* @__PURE__ */ new Error(`Duplicate child Mount path: ${[...target.path, key].join("/")}`)));
1115
+ else target.children.push(yield* prepareMember(child, target));
1116
+ }
1117
+ });
1118
+ const ordered = () => {
1119
+ const visit = (target) => [target, ...target.children.flatMap(visit)];
1120
+ return roots.flatMap(visit);
1121
+ };
1122
+ /**
1123
+ * Canonical, index-addressable identity of the prepared graph plus the next target.
1124
+ * Oscillation is detected by set membership on this key instead of deep-comparing
1125
+ * every earlier graph, so a pass costs one linear walk to build it.
1126
+ */
1127
+ const signature = (next) => JSON.stringify([next.key, ...ordered().flatMap((target) => target.entry === void 0 ? [] : [[
1128
+ target.key,
1129
+ target.entry.bindings.map((binding) => [binding.registration.key, binding.provider.path]),
1130
+ (offered.get(target.entry) ?? []).map((binding) => binding.registration.key),
1131
+ serviceVersions.get(target.entry) ?? null,
1132
+ childVersions.get(target.entry) ?? null
1133
+ ]])]);
1134
+ function* prepareMember(member, parent) {
1135
+ if (options.isClosing()) return yield* Effect.fail(new PluginLifecycleError("preparation", "Plugin preparation cancelled"));
1136
+ if (member.component.load === void 0 || options.failures.get(member.component)?.terminal) {
1137
+ const target$1 = track(member, parent);
1138
+ yield* prepareTarget(target$1);
1139
+ return target$1;
1140
+ }
1141
+ const identity = member.identity;
1142
+ const existing = [...staged, ...options.existing].find((entry$1) => entry$1.parent === parent?.entry && identity !== void 0 && sameEntryIdentity(entry$1.identity, identity));
1143
+ if (existing === void 0 && member.component.admission?.available() === false) {
1144
+ const target$1 = track(member, parent);
1145
+ target$1.pendingReason = "admission";
1146
+ return target$1;
1147
+ }
1148
+ const entry = existing ?? (yield* stage(member, [...parent?.path ?? [], identity?.entryId ?? member.component.componentId], parent?.entry));
1149
+ const loaded = yield* Effect.exit(entry.definition === void 0 ? acquire(entry, entry.owner.load) : Effect.succeed(entry.definition));
1150
+ if (Exit.isFailure(loaded)) {
1151
+ const error = pluginFailure(loaded.cause);
1152
+ if (isCapacityFailure(member, error)) {
1153
+ yield* discardStaged(entry);
1154
+ const target$2 = track(member, parent);
1155
+ target$2.pendingReason = "admission";
1156
+ return target$2;
1157
+ }
1158
+ if (member.identity?.kind !== "package") return yield* Effect.fail(error);
1159
+ options.failures.set(member.component, {
1160
+ error,
1161
+ bindings: [],
1162
+ terminal: true
1163
+ });
1164
+ const target$1 = track(member, parent);
1165
+ target$1.error = error;
1166
+ yield* discardStaged(entry);
1167
+ return target$1;
1168
+ }
1169
+ const definition = loaded.value;
1170
+ entry.definition = definition;
1171
+ entry.requires = definition.requires ?? [];
1172
+ entry.replacement = definition.replacement;
1173
+ const target = track({
1174
+ ...member,
1175
+ requires: definition.requires,
1176
+ provides: definition.provides,
1177
+ realm: definition.realm,
1178
+ replacement: definition.replacement
1179
+ }, parent);
1180
+ if (!entry.prepared && entry.failure === void 0) target.waitingEntry = entry;
1181
+ yield* prepareTarget(target);
1182
+ return target;
1183
+ }
1184
+ const prepare = Effect.gen(function* () {
1185
+ rootRealm.reverseRequires.clear();
1186
+ rootRealm.providers.clear();
1187
+ realms.clear();
1188
+ realms.add(rootRealm);
1189
+ offered.clear();
1190
+ dirty.clear();
1191
+ childVersions.clear();
1192
+ serviceVersions.clear();
1193
+ owners.length = 0;
1194
+ waitingExclusive.clear();
1195
+ waitingAdmission.clear();
1196
+ roots = [];
1197
+ for (const member of options.members) roots.push(yield* prepareMember(member));
1198
+ const seen = /* @__PURE__ */ new Set();
1199
+ let waiting = [];
1200
+ while (dirty.size > 0) {
1201
+ const active = [...dirty].find((target$1) => target$1.entry !== void 0);
1202
+ if (active !== void 0) {
1203
+ dirty.delete(active);
1204
+ const resolved$1 = resolve(active);
1205
+ if (active.entry !== void 0 && (resolved$1.missing.length > 0 || resolved$1.conflicting.length > 0 || !sameServiceBindings(active.entry.bindings, resolved$1.bindings))) deactivate(active);
1206
+ continue;
1207
+ }
1208
+ if (waiting.length === 0) waiting = ordered().filter((candidate) => dirty.has(candidate));
1209
+ const target = waiting.shift();
1210
+ if (target === void 0) break;
1211
+ if (!dirty.delete(target)) continue;
1212
+ const resolved = resolve(target);
1213
+ if (resolved.missing.length > 0 || resolved.conflicting.length > 0) continue;
1214
+ const current = signature(target);
1215
+ if (seen.has(current)) {
1216
+ target.error = /* @__PURE__ */ new Error(`Service dependency resolution oscillates at ${target.path.join("/")}`);
1217
+ options.failures.set(target.member.component, {
1218
+ error: target.error,
1219
+ bindings: resolved.bindings
1220
+ });
1221
+ continue;
1222
+ }
1223
+ seen.add(current);
1224
+ yield* prepareTarget(target);
1225
+ }
1226
+ for (const target of ordered()) {
1227
+ if (target.waitingEntry !== void 0 && !owners.includes(target.waitingEntry)) owners.push(target.waitingEntry);
1228
+ const admission = target.member.component.admission;
1229
+ if (target.pendingReason === "admission" && admission !== void 0) waitingAdmission.add(admission);
1230
+ }
1231
+ }).pipe(Effect.repeat({ while: sourcesChanged }));
1232
+ const coldCycles = () => {
1233
+ const targets = ordered();
1234
+ const declarations = /* @__PURE__ */ new Map();
1235
+ for (const target of targets) {
1236
+ if (target.collision !== void 0 || target.error !== void 0) continue;
1237
+ const services = declarations.get(target.realm) ?? /* @__PURE__ */ new Map();
1238
+ declarations.set(target.realm, services);
1239
+ for (const provided of target.member.provides ?? []) {
1240
+ const key = isString(provided) ? provided : provided.key;
1241
+ const providers = services.get(key) ?? [];
1242
+ if (!providers.includes(target)) providers.push(target);
1243
+ services.set(key, providers);
1244
+ }
1245
+ }
1246
+ const waits = /* @__PURE__ */ new Map();
1247
+ for (const target of targets) {
1248
+ if (target.entry !== void 0 || target.error !== void 0 || target.pendingReason !== void 0) continue;
1249
+ const edges = [];
1250
+ for (const key of resolve(target).missing) for (let realm = target.realm; realm !== void 0; realm = realm.parent) {
1251
+ const providers = declarations.get(realm)?.get(key) ?? [];
1252
+ if (providers.length === 0) continue;
1253
+ for (const provider of providers) edges.push({
1254
+ provider,
1255
+ service: key
1256
+ });
1257
+ break;
1258
+ }
1259
+ waits.set(target, edges);
1260
+ }
1261
+ const cycles = /* @__PURE__ */ new Map();
1262
+ for (const start of waits.keys()) {
1263
+ const visited = /* @__PURE__ */ new Set();
1264
+ const find = (target) => {
1265
+ if (visited.has(target)) return;
1266
+ visited.add(target);
1267
+ for (const edge of waits.get(target) ?? []) {
1268
+ const step = {
1269
+ path: target.path,
1270
+ service: edge.service
1271
+ };
1272
+ if (edge.provider === start) return [step];
1273
+ const suffix = find(edge.provider);
1274
+ if (suffix !== void 0) return [step, ...suffix];
1275
+ }
1276
+ };
1277
+ const cycle = find(start);
1278
+ if (cycle !== void 0) cycles.set(start, cycle);
1279
+ }
1280
+ return cycles;
1281
+ };
1282
+ const observations = () => {
1283
+ const cycles = coldCycles();
1284
+ return ordered().map((target) => {
1285
+ const resolved = resolve(target);
1286
+ const error = target.collision ?? target.entry?.failure ?? target.error;
1287
+ if (error !== void 0 && (target.collision !== void 0 || options.failures.get(target.member.component)?.terminal || resolved.missing.length === 0 && resolved.conflicting.length === 0)) return {
1288
+ path: target.path,
1289
+ phase: "failed",
1290
+ profile: target.member.component.executionProfile,
1291
+ activationId: target.entry?.owner.activationId,
1292
+ error: error.message
1293
+ };
1294
+ if (target.entry !== void 0) return {
1295
+ path: target.path,
1296
+ phase: "active",
1297
+ profile: target.entry.owner.snapshot().profile,
1298
+ activationId: target.entry.owner.activationId
1299
+ };
1300
+ return {
1301
+ path: target.path,
1302
+ phase: "pending",
1303
+ profile: target.member.component.executionProfile,
1304
+ pendingReason: target.pendingReason ?? (cycles.has(target) ? "dependency-cycle" : void 0),
1305
+ dependencyCycle: cycles.get(target),
1306
+ missingServices: resolved.missing,
1307
+ conflictingServices: resolved.conflicting
1308
+ };
1309
+ });
1310
+ };
1311
+ return {
1312
+ created,
1313
+ staged,
1314
+ owners,
1315
+ waitingExclusive,
1316
+ waitingAdmission,
1317
+ prepare,
1318
+ commitSourceVersions: () => {
1319
+ for (const [entry, version] of childVersions) entry.childrenVersion = version;
1320
+ for (const [entry, version] of serviceVersions) entry.servicesVersion = version;
1321
+ options.existing = [];
1322
+ options.retiring = [];
1323
+ },
1324
+ observations,
1325
+ report: () => {
1326
+ const statuses = observations();
1327
+ ordered().forEach((target, index) => {
1328
+ const status = statuses[index];
1329
+ if (status !== void 0) target.member.report?.(status);
1330
+ });
1331
+ return statuses;
1332
+ },
1333
+ conflicts: () => [...realms].flatMap((realm) => [...realm.providers].filter(([, available]) => available.size > 1).map(([key, available]) => ({
1334
+ key,
1335
+ realmPath: realm.path,
1336
+ providers: [...available].map(({ provider }) => ({
1337
+ path: provider.path,
1338
+ activationId: provider.owner.activationId
1339
+ }))
1340
+ })))
1341
+ };
1342
+ }
1343
+
1344
+ //#endregion
1345
+ //#region src/composition/cleanup.ts
1346
+ /** Every Object, resource slot and Activation deadline reports the same way. */
1347
+ function cleanupTimeoutError(label) {
1348
+ return new PluginLifecycleError("cleanup", `${label} cleanup timed out; resources remain resident`);
1349
+ }
1350
+ /**
1351
+ * Records that a cleanup deadline left resources resident. `first` reports whether
1352
+ * this is the first deadline for the owner, so callers publish one lifecycle failure
1353
+ * instead of one per repeated deadline.
1354
+ */
1355
+ function residentCleanupFailure(owner, label, changed) {
1356
+ const error = cleanupTimeoutError(label);
1357
+ if (owner.residualResources) return {
1358
+ error,
1359
+ first: false
1360
+ };
1361
+ owner.failure = error;
1362
+ owner.residualResources = true;
1363
+ changed();
1364
+ return {
1365
+ error,
1366
+ first: true
1367
+ };
1368
+ }
1369
+ /**
1370
+ * Cleanup either settles completely or fails: one failure keeps its own identity,
1371
+ * several become one aggregate, and none returns undefined. Deduplicating failures is
1372
+ * a per-host decision because it changes whether one repeated failure stays singular.
1373
+ */
1374
+ function aggregateCleanupFailure(errors, message) {
1375
+ const [first] = errors;
1376
+ if (errors.length === 0) return void 0;
1377
+ if (errors.length === 1 && first !== void 0) return first;
1378
+ return new AggregateError(errors, message);
1379
+ }
1380
+
1381
+ //#endregion
1382
+ //#region src/contributions/object-resource.ts
1383
+ const ResourceIdentitySchema = s.obj({
1384
+ name: s.str({ minLength: 1 }),
1385
+ key: s.str({ minLength: 1 }),
1386
+ version: s.int({ minimum: 1 }),
1387
+ replacement: s.opt(s.union([s.lit("staged"), s.lit("exclusive")]))
1388
+ }, { open: false });
1389
+ const OwnerServiceKeys = new Set([Scope.Scope.key, Layer.CurrentMemoMap.key]);
1390
+ function createObjectResourceAccess(host) {
1391
+ const declare = host.resource.bind(host);
1392
+ return { resource(name, key, definition) {
1393
+ return Effect.gen(function* () {
1394
+ const captured = yield* Effect.try({
1395
+ try: () => {
1396
+ const metadata = decode(ResourceIdentitySchema, {
1397
+ name,
1398
+ key: key.key,
1399
+ version: definition.version,
1400
+ replacement: definition.replacement
1401
+ });
1402
+ if (OwnerServiceKeys.has(metadata.key)) throw new TypeError("Object Scope and Layer memoization are supplied by its owner");
1403
+ const acquire = definition.acquire;
1404
+ const token = Context.Service(metadata.key);
1405
+ return {
1406
+ token,
1407
+ declaration: {
1408
+ ...metadata,
1409
+ identity: cloneDeep(definition.identity),
1410
+ acquire: Effect.map(acquire, (resource) => Context.make(token, resource))
1411
+ }
1412
+ };
1413
+ },
1414
+ catch: ensureError
1415
+ });
1416
+ const context = yield* Effect.try({
1417
+ try: () => declare(captured.declaration),
1418
+ catch: ensureError
1419
+ }).pipe(Effect.flatten);
1420
+ return yield* Effect.try({
1421
+ try: () => Context.get(context, captured.token),
1422
+ catch: ensureError
1423
+ });
1424
+ });
1425
+ } };
1426
+ }
1427
+
1428
+ //#endregion
1429
+ //#region src/contributions/object-state.ts
1430
+ const ObjectStateIdentitySchema = s.obj({
1431
+ name: s.str({ minLength: 1 }),
1432
+ version: s.int({ minimum: 1 })
1433
+ }, { open: false });
1434
+ function createObjectStateAccess(host) {
1435
+ const declare = host.state.bind(host);
1436
+ return { state(name, definition) {
1437
+ return Effect.gen(function* () {
1438
+ const captured = yield* Effect.try({
1439
+ try: () => {
1440
+ const identity = decode(ObjectStateIdentitySchema, {
1441
+ name,
1442
+ version: definition.version
1443
+ });
1444
+ const schema = cloneDeep(definition.schema);
1445
+ const migration = definition.migrate;
1446
+ const declaration = {
1447
+ ...identity,
1448
+ schema: captureJsonValue(schema),
1449
+ initial: captureJsonValue(decode(schema, definition.initial))
1450
+ };
1451
+ if (migration === void 0) return {
1452
+ schema,
1453
+ declaration
1454
+ };
1455
+ const from = decode(ObjectStateIdentitySchema, {
1456
+ name,
1457
+ version: migration.from.version
1458
+ });
1459
+ if (identity.version <= from.version) throw new TypeError("Object state migration must increase its version");
1460
+ const previousSchema = cloneDeep(migration.from.schema);
1461
+ const transform = migration.transform;
1462
+ return {
1463
+ schema,
1464
+ declaration: {
1465
+ ...declaration,
1466
+ migrate: {
1467
+ schema: captureJsonValue(previousSchema),
1468
+ version: from.version,
1469
+ transform: (previous) => Effect.try({
1470
+ try: () => captureJsonValue(decode(schema, transform(decode(previousSchema, previous)))),
1471
+ catch: ensureError
1472
+ })
1473
+ }
1474
+ }
1475
+ };
1476
+ },
1477
+ catch: ensureError
1478
+ });
1479
+ const port = yield* Effect.try({
1480
+ try: () => declare(captured.declaration),
1481
+ catch: ensureError
1482
+ }).pipe(Effect.flatten);
1483
+ const readFrame = (frame) => Effect.try({
1484
+ try: () => {
1485
+ return {
1486
+ name: frame.name,
1487
+ version: frame.version,
1488
+ revision: frame.revision,
1489
+ value: decode(captured.schema, frame.value)
1490
+ };
1491
+ },
1492
+ catch: ensureError
1493
+ });
1494
+ return {
1495
+ get: port.read.pipe(Effect.flatMap(readFrame), Effect.map((frame) => frame.value)),
1496
+ set: (value) => port.modify(() => Effect.try({
1497
+ try: () => captureJsonValue(decode(captured.schema, value)),
1498
+ catch: ensureError
1499
+ })),
1500
+ update: (change) => port.modify((current) => Effect.try({
1501
+ try: () => {
1502
+ const value = decode(captured.schema, current);
1503
+ return captureJsonValue(decode(captured.schema, change(value)));
1504
+ },
1505
+ catch: ensureError
1506
+ })),
1507
+ changes: port.changes.pipe(Stream.mapEffect(readFrame))
1508
+ };
1509
+ });
1510
+ } };
1511
+ }
1512
+
1513
+ //#endregion
1514
+ //#region src/contributions/object-self.ts
1515
+ const stateHosts = /* @__PURE__ */ new WeakMap();
1516
+ function createObjectSelf(host) {
1517
+ const self = Object.freeze({
1518
+ ...createObjectStateAccess(host),
1519
+ ...createObjectResourceAccess(host)
1520
+ });
1521
+ stateHosts.set(self, host);
1522
+ return self;
1523
+ }
1524
+ /** Execution profiles borrow the owning state port; no state registry crosses the boundary. */
1525
+ function objectSelfStateHost(self) {
1526
+ const host = stateHosts.get(self);
1527
+ if (host === void 0) throw new TypeError("Object state requires a native composition owner");
1528
+ return host;
1529
+ }
1530
+
1531
+ //#endregion
1532
+ //#region src/composition/object-slots.ts
1533
+ function compatible$1(slot, declaration) {
1534
+ return slot.declaration.version === declaration.version && isEqual(slot.declaration.schema, declaration.schema);
1535
+ }
1536
+ function assertCompatible(slot, declaration) {
1537
+ if (!compatible$1(slot, declaration)) throw new TypeError(`Incompatible Object state slot: ${declaration.name}`);
1538
+ }
1539
+ /** The logical instance owns slots; generations only hold validated access handles. */
1540
+ const makeObjectSlots = Effect.fn("Object.slots")(function* () {
1541
+ const owner = yield* Effect.scope;
1542
+ const slots = /* @__PURE__ */ new Map();
1543
+ const views = /* @__PURE__ */ new Set();
1544
+ let epoch = 0;
1545
+ let pausedBy;
1546
+ const snapshot = (slot) => ({
1547
+ ...slot.frame,
1548
+ schema: slot.declaration.schema
1549
+ });
1550
+ const makeSlot = (declaration, initial) => Effect.gen(function* () {
1551
+ const scope = yield* Scope.fork(owner, "sequential");
1552
+ const lane = yield* Semaphore.make(1);
1553
+ const updates = yield* PubSub.sliding({
1554
+ capacity: 1,
1555
+ replay: 1
1556
+ });
1557
+ yield* Scope.addFinalizer(scope, PubSub.shutdown(updates));
1558
+ const slot = {
1559
+ declaration,
1560
+ scope,
1561
+ frame: initial,
1562
+ lane,
1563
+ updates,
1564
+ committed: false
1565
+ };
1566
+ yield* PubSub.publish(updates, snapshot(slot));
1567
+ return slot;
1568
+ });
1569
+ return {
1570
+ drainWriters: Effect.suspend(() => Effect.forEach(slots.values(), (slot) => Semaphore.withPermit(slot.lane, Effect.void), { discard: true })),
1571
+ states: () => sortBy([...slots.values()], [(slot) => slot.declaration.name]).map(snapshot),
1572
+ watchState: (name) => Stream.unwrap(Effect.try({
1573
+ try: () => {
1574
+ const slot = slots.get(name);
1575
+ if (slot === void 0) throw new TypeError(`Unknown Object state slot: ${name}`);
1576
+ return Stream.fromPubSub(slot.updates);
1577
+ },
1578
+ catch: ensureError
1579
+ })),
1580
+ candidate: (assertAvailable, transition) => Effect.gen(function* () {
1581
+ const generation = yield* Effect.scope;
1582
+ const declarations = /* @__PURE__ */ new Map();
1583
+ const declaring = yield* Semaphore.make(1);
1584
+ const stopped = yield* Deferred.make();
1585
+ const superseded = yield* Deferred.make();
1586
+ const adopted = yield* Deferred.make();
1587
+ const token = {};
1588
+ let viewEpoch = epoch;
1589
+ let sealed = false;
1590
+ let active = false;
1591
+ let closed = false;
1592
+ let aborted = false;
1593
+ let migrating = false;
1594
+ views.add(superseded);
1595
+ const rollback = () => {
1596
+ if (!active) aborted = true;
1597
+ if (pausedBy === token) pausedBy = void 0;
1598
+ transition.rollback();
1599
+ };
1600
+ const assertRead = () => {
1601
+ if (aborted) throw new PluginLifecycleError("admission", "Object state candidate was aborted");
1602
+ if (closed) throw new PluginLifecycleError("admission", "Object state generation is closed");
1603
+ if (viewEpoch !== epoch) throw new PluginLifecycleError("admission", "Object state generation is superseded");
1604
+ if (active) assertAvailable();
1605
+ };
1606
+ const assertWrite = () => {
1607
+ assertRead();
1608
+ if (!active) throw new PluginLifecycleError("admission", "Object state is not adopted");
1609
+ if (pausedBy && pausedBy !== token) throw new PluginLifecycleError("admission", "Object state transition is pending");
1610
+ };
1611
+ yield* Scope.addFinalizer(generation, Effect.gen(function* () {
1612
+ closed = true;
1613
+ rollback();
1614
+ views.delete(superseded);
1615
+ yield* Deferred.succeed(stopped, void 0);
1616
+ yield* Effect.forEach(declarations.values(), ({ slot }) => slot.committed ? Effect.void : Scope.close(slot.scope, Exit.void), { discard: true });
1617
+ }));
1618
+ const host = { state: (declaration) => Semaphore.withPermit(declaring, Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
1619
+ yield* Effect.try({
1620
+ try: () => {
1621
+ assertRead();
1622
+ if (sealed) throw new PluginLifecycleError("admission", "Object state declarations are sealed");
1623
+ if (declarations.has(declaration.name)) throw new TypeError(`Duplicate Object state slot: ${declaration.name}`);
1624
+ },
1625
+ catch: ensureError
1626
+ });
1627
+ const previous = slots.get(declaration.name);
1628
+ let selected;
1629
+ if (previous !== void 0 && !compatible$1(previous, declaration)) {
1630
+ const migration = yield* Effect.try({
1631
+ try: () => {
1632
+ const requested = declaration.migrate;
1633
+ if (requested === void 0 || declaration.version <= requested.version || requested.version !== previous.declaration.version || !isEqual(requested.schema, previous.declaration.schema)) throw new TypeError(`Incompatible Object state slot: ${declaration.name}`);
1634
+ return requested;
1635
+ },
1636
+ catch: ensureError
1637
+ });
1638
+ yield* restore(transition.quiesce);
1639
+ yield* Effect.try({
1640
+ try: assertRead,
1641
+ catch: ensureError
1642
+ });
1643
+ pausedBy = token;
1644
+ yield* restore(Effect.forEach(slots.values(), (slot) => Semaphore.withPermit(slot.lane, Effect.void), { discard: true }));
1645
+ const from = previous.frame;
1646
+ const value = yield* restore(Effect.try({
1647
+ try: () => {
1648
+ assertRead();
1649
+ assertAvailable();
1650
+ return migration.transform(from.value);
1651
+ },
1652
+ catch: ensureError
1653
+ }).pipe(Effect.flatten));
1654
+ yield* Effect.try({
1655
+ try: assertRead,
1656
+ catch: ensureError
1657
+ });
1658
+ const frame = {
1659
+ name: declaration.name,
1660
+ version: declaration.version,
1661
+ revision: from.revision + 1,
1662
+ value
1663
+ };
1664
+ selected = {
1665
+ declaration,
1666
+ previous: {
1667
+ slot: previous,
1668
+ frame: from
1669
+ },
1670
+ slot: yield* makeSlot(declaration, frame)
1671
+ };
1672
+ migrating = true;
1673
+ } else selected = {
1674
+ declaration,
1675
+ slot: previous ?? (yield* makeSlot(declaration, {
1676
+ name: declaration.name,
1677
+ version: declaration.version,
1678
+ revision: 0,
1679
+ value: declaration.initial
1680
+ }))
1681
+ };
1682
+ yield* Effect.try({
1683
+ try: () => {
1684
+ assertRead();
1685
+ if (sealed) throw new PluginLifecycleError("admission", "Object state declarations are sealed");
1686
+ declarations.set(declaration.name, selected);
1687
+ },
1688
+ catch: ensureError
1689
+ }).pipe(Effect.onError(() => selected.slot.committed ? Effect.void : Scope.close(selected.slot.scope, Exit.void)));
1690
+ return {
1691
+ read: Effect.try({
1692
+ try: () => {
1693
+ assertRead();
1694
+ return selected.slot.frame;
1695
+ },
1696
+ catch: ensureError
1697
+ }),
1698
+ modify: (change) => Effect.try({
1699
+ try: assertWrite,
1700
+ catch: ensureError
1701
+ }).pipe(Effect.andThen(Effect.suspend(() => Semaphore.withPermit(selected.slot.lane, Effect.uninterruptibleMask((restoreChange) => Effect.gen(function* () {
1702
+ yield* Effect.try({
1703
+ try: assertWrite,
1704
+ catch: ensureError
1705
+ });
1706
+ const current = selected.slot.frame;
1707
+ const value = yield* restoreChange(Effect.suspend(() => change(current.value)));
1708
+ yield* Effect.try({
1709
+ try: assertWrite,
1710
+ catch: ensureError
1711
+ });
1712
+ if (isEqual(value, current.value)) return;
1713
+ selected.slot.frame = {
1714
+ ...current,
1715
+ revision: current.revision + 1,
1716
+ value
1717
+ };
1718
+ yield* PubSub.publish(selected.slot.updates, snapshot(selected.slot));
1719
+ })))))),
1720
+ changes: Stream.unwrap(Deferred.await(adopted).pipe(Effect.andThen(Effect.try({
1721
+ try: () => {
1722
+ assertRead();
1723
+ return Stream.fromPubSub(selected.slot.updates).pipe(Stream.takeWhile(() => viewEpoch === epoch), Stream.map((frame) => ({
1724
+ name: frame.name,
1725
+ version: frame.version,
1726
+ revision: frame.revision,
1727
+ value: frame.value
1728
+ })));
1729
+ },
1730
+ catch: ensureError
1731
+ })))).pipe(Stream.interruptWhen(Effect.race(Deferred.await(stopped), Deferred.await(superseded))))
1732
+ };
1733
+ }))) };
1734
+ const validate = () => {
1735
+ assertRead();
1736
+ if (pausedBy && pausedBy !== token) throw new PluginLifecycleError("admission", "Object state transition is pending");
1737
+ for (const selected of declarations.values()) {
1738
+ const installed = slots.get(selected.declaration.name);
1739
+ if (selected.previous !== void 0) {
1740
+ if (installed !== selected.previous.slot || installed.frame !== selected.previous.frame) throw new PluginLifecycleError("admission", "Object state migration source changed");
1741
+ } else if (installed !== void 0) assertCompatible(installed, selected.declaration);
1742
+ }
1743
+ };
1744
+ return {
1745
+ host,
1746
+ validate,
1747
+ rollback,
1748
+ seal: () => {
1749
+ sealed = true;
1750
+ },
1751
+ adopt: () => {
1752
+ validate();
1753
+ const cleanup = [];
1754
+ if (migrating) {
1755
+ epoch += 1;
1756
+ viewEpoch = epoch;
1757
+ for (const view of views) if (view !== superseded) cleanup.push(Deferred.succeed(view, void 0).pipe(Effect.asVoid));
1758
+ }
1759
+ for (const selected of declarations.values()) {
1760
+ const installed = slots.get(selected.declaration.name);
1761
+ if (installed === void 0) {
1762
+ selected.slot.committed = true;
1763
+ slots.set(selected.declaration.name, selected.slot);
1764
+ } else if (selected.slot !== installed) {
1765
+ cleanup.push(Scope.close(selected.slot.scope, Exit.void));
1766
+ if (selected.previous !== void 0) {
1767
+ installed.declaration = selected.declaration;
1768
+ installed.frame = selected.slot.frame;
1769
+ const frame = snapshot(installed);
1770
+ const migrated = installed.frame;
1771
+ cleanup.push(Semaphore.withPermit(installed.lane, Effect.suspend(() => installed.frame === migrated ? PubSub.publish(installed.updates, frame).pipe(Effect.asVoid) : Effect.void)));
1772
+ }
1773
+ selected.slot = installed;
1774
+ }
1775
+ }
1776
+ active = true;
1777
+ if (migrating) {
1778
+ pausedBy = void 0;
1779
+ transition.commit();
1780
+ }
1781
+ cleanup.push(Deferred.succeed(adopted, void 0).pipe(Effect.asVoid));
1782
+ return cleanup;
1783
+ }
1784
+ };
1785
+ })
1786
+ };
1787
+ });
1788
+
1789
+ //#endregion
1790
+ //#region src/composition/object-resources.ts
1791
+ function compatible(slot, declaration, origin) {
1792
+ return slot.declaration.key === declaration.key && slot.declaration.version === declaration.version && isEqual(slot.declaration.identity, declaration.identity) && slot.bindings.length === origin.source.bindings.length && slot.bindings.every((binding, index) => binding.provider === origin.source.bindings[index]?.provider && binding.registration === origin.source.bindings[index]?.registration);
1793
+ }
1794
+ /** Stable slots own acquisition and origin retention before any constructor receives the value. */
1795
+ const makeObjectResources = Effect.fn("Object.resources")(function* (root, options) {
1796
+ const owner = yield* Effect.scope;
1797
+ const lane = yield* Semaphore.make(1);
1798
+ const slots = /* @__PURE__ */ new Map();
1799
+ const owned = /* @__PURE__ */ new Set();
1800
+ let closing = false;
1801
+ const makeSlot = (declaration, origin) => Effect.gen(function* () {
1802
+ const releaseOrigin = yield* origin.borrow.retain();
1803
+ const scope = yield* Scope.fork(owner, "sequential");
1804
+ const author = yield* Scope.make();
1805
+ const memoMap = yield* Layer.makeMemoMap;
1806
+ const ready = yield* Deferred.make();
1807
+ const retirementStarted = yield* Deferred.make();
1808
+ const acquisition = yield* Effect.forkIn(Effect.exit(Effect.sync(() => {
1809
+ origin.assertAvailable();
1810
+ origin.assertDeclaration();
1811
+ }).pipe(Effect.andThen(Scope.provide(Effect.provideService(declaration.acquire, Layer.CurrentMemoMap, memoMap), author)))).pipe(Effect.interruptible), root);
1812
+ const slot = {
1813
+ declaration,
1814
+ origin,
1815
+ bindings: [...origin.source.bindings],
1816
+ scope,
1817
+ ready,
1818
+ acquisition,
1819
+ retirementStarted,
1820
+ holders: 0,
1821
+ committed: false,
1822
+ retirementRequested: false,
1823
+ residualResources: false,
1824
+ phase: "acquiring"
1825
+ };
1826
+ yield* Effect.forkIn(Effect.gen(function* () {
1827
+ const result = yield* Fiber.join(acquisition);
1828
+ if (Exit.isFailure(result)) {
1829
+ const error = pluginFailure(result.cause);
1830
+ slot.failure = error;
1831
+ if (slot.phase === "acquiring") slot.phase = "failed";
1832
+ yield* Deferred.fail(ready, error);
1833
+ } else {
1834
+ if (slot.phase === "acquiring") slot.phase = "ready";
1835
+ yield* Deferred.succeed(ready, result.value);
1836
+ }
1837
+ }), root);
1838
+ yield* Scope.addFinalizer(scope, Effect.gen(function* () {
1839
+ yield* Fiber.interrupt(acquisition);
1840
+ yield* Effect.sync(origin.assertAuthorized);
1841
+ yield* Scope.close(author, Exit.void);
1842
+ yield* releaseOrigin;
1843
+ }));
1844
+ return slot;
1845
+ });
1846
+ const retire = (slot) => Effect.uninterruptible(Effect.gen(function* () {
1847
+ slot.retirementRequested = true;
1848
+ if (slot.phase === "retiring") yield* Deferred.await(slot.retirementStarted);
1849
+ if (slot.retirement === void 0) {
1850
+ slot.phase = "retiring";
1851
+ options.changed();
1852
+ slot.retirement = yield* Effect.forkIn(Scope.close(slot.scope, Exit.void).pipe(Effect.catchCause((cause) => {
1853
+ const error = pluginFailure(cause);
1854
+ slot.failure = error;
1855
+ slot.residualResources = true;
1856
+ options.changed();
1857
+ return Effect.fail(error);
1858
+ }), Effect.tap(() => Effect.sync(() => {
1859
+ slot.phase = "closed";
1860
+ if (slots.get(slot.declaration.name) === slot) slots.delete(slot.declaration.name);
1861
+ owned.delete(slot);
1862
+ options.changed();
1863
+ }))), root);
1864
+ yield* Deferred.succeed(slot.retirementStarted, void 0);
1865
+ yield* Effect.forkIn(Fiber.join(slot.retirement).pipe(Effect.timeoutOption(options.cleanupTimeoutMs ?? Duration.infinity), Effect.flatMap((result) => {
1866
+ if (Option.isSome(result)) return Effect.void;
1867
+ const { error, first } = residentCleanupFailure(slot, `Object resource ${slot.declaration.name}`, options.changed);
1868
+ return first ? options.onFailure(error) : Effect.void;
1869
+ }), Effect.catch(() => Effect.void)), root);
1870
+ }
1871
+ return yield* Fiber.join(slot.retirement);
1872
+ }));
1873
+ const closeSlots = (selected) => Effect.gen(function* () {
1874
+ const errors = (yield* Effect.forEach([...selected].reverse(), (slot) => Effect.exit(retire(slot)))).flatMap((outcome) => Exit.isFailure(outcome) ? [pluginFailure(outcome.cause)] : []);
1875
+ const first = errors[0];
1876
+ if (errors.length === 1 && first !== void 0) return yield* Effect.fail(first);
1877
+ if (errors.length > 0) return yield* Effect.fail(new AggregateError(errors, "Object resource cleanup failed"));
1878
+ });
1879
+ return {
1880
+ candidate: (origin, transition) => Effect.gen(function* () {
1881
+ const declarations = /* @__PURE__ */ new Map();
1882
+ let sealed = false;
1883
+ let closed = false;
1884
+ yield* Effect.addFinalizer(() => Effect.gen(function* () {
1885
+ closed = true;
1886
+ yield* closeSlots([...declarations.values()].filter((slot) => {
1887
+ slot.holders -= 1;
1888
+ return slot.holders === 0 && !slot.committed;
1889
+ })).pipe(Effect.orDie);
1890
+ }));
1891
+ return {
1892
+ host: { resource: (declaration) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
1893
+ if ((yield* Semaphore.withPermit(lane, Effect.try({
1894
+ try: () => {
1895
+ origin.assertAvailable();
1896
+ origin.assertDeclaration();
1897
+ if (closing || closed || sealed) throw new PluginLifecycleError("admission", "Object resource declarations are sealed");
1898
+ if (declarations.has(declaration.name)) throw new TypeError(`Duplicate Object resource slot: ${declaration.name}`);
1899
+ const current = slots.get(declaration.name);
1900
+ return current !== void 0 && !compatible(current, declaration, origin) && declaration.replacement === "exclusive" ? current : void 0;
1901
+ },
1902
+ catch: ensureError
1903
+ }))) !== void 0) {
1904
+ yield* restore(transition.quiesce);
1905
+ yield* restore(transition.retirePrevious);
1906
+ yield* Effect.try({
1907
+ try: origin.assertAvailable,
1908
+ catch: ensureError
1909
+ });
1910
+ const previous = yield* Semaphore.withPermit(lane, Effect.sync(() => [...owned].filter((entry) => entry.declaration.name === declaration.name)));
1911
+ const retirement = yield* Effect.forkIn(closeSlots(previous), root);
1912
+ yield* restore(Fiber.join(retirement).pipe(Effect.timeoutOrElse({
1913
+ duration: options.cleanupTimeoutMs ?? Duration.infinity,
1914
+ orElse: () => Effect.fail(new PluginLifecycleError("cleanup", `Object resource ${declaration.name} cleanup is still pending`))
1915
+ })));
1916
+ }
1917
+ const slot = yield* Semaphore.withPermit(lane, Effect.gen(function* () {
1918
+ yield* Effect.try({
1919
+ try: () => {
1920
+ origin.assertAvailable();
1921
+ origin.assertDeclaration();
1922
+ if (closing || closed || sealed) throw new PluginLifecycleError("admission", "Object resource declarations are sealed");
1923
+ if (declarations.has(declaration.name)) throw new TypeError(`Duplicate Object resource slot: ${declaration.name}`);
1924
+ },
1925
+ catch: ensureError
1926
+ });
1927
+ const current = slots.get(declaration.name);
1928
+ if (current !== void 0 && !compatible(current, declaration, origin)) yield* Effect.try({
1929
+ try: () => {
1930
+ if (declaration.replacement !== "staged") throw new TypeError(`Incompatible Object resource slot: ${declaration.name}`);
1931
+ },
1932
+ catch: ensureError
1933
+ });
1934
+ const previous = [...owned].find((entry) => entry.declaration.name === declaration.name && !entry.retirementRequested && compatible(entry, declaration, origin));
1935
+ if (previous !== void 0) yield* Effect.try({
1936
+ try: () => {
1937
+ previous.origin.assertAvailable();
1938
+ if (previous.phase === "retiring") throw new PluginLifecycleError("admission", "Object resource cleanup is pending");
1939
+ },
1940
+ catch: ensureError
1941
+ });
1942
+ const selected = previous ?? (yield* makeSlot(declaration, origin));
1943
+ owned.add(selected);
1944
+ yield* Effect.try({
1945
+ try: () => {
1946
+ origin.assertDeclaration();
1947
+ if (closed || sealed) throw new PluginLifecycleError("admission", "Object resource declarations are sealed");
1948
+ },
1949
+ catch: ensureError
1950
+ }).pipe(Effect.onError(() => previous === void 0 ? Effect.forkIn(retire(selected).pipe(Effect.catch(() => Effect.void)), root).pipe(Effect.asVoid) : Effect.void));
1951
+ selected.holders += 1;
1952
+ declarations.set(declaration.name, selected);
1953
+ return selected;
1954
+ }));
1955
+ return yield* restore(Deferred.await(slot.ready));
1956
+ })) },
1957
+ seal: () => {
1958
+ sealed = true;
1959
+ },
1960
+ assertAvailable: () => {
1961
+ if (closed) throw new PluginLifecycleError("admission", "Object resource generation is closed");
1962
+ for (const slot of declarations.values()) slot.origin.assertAvailable();
1963
+ },
1964
+ validate: () => {
1965
+ if (closed) throw new PluginLifecycleError("admission", "Object resource generation is closed");
1966
+ for (const slot of declarations.values()) {
1967
+ slot.origin.assertAvailable();
1968
+ if (slot.phase !== "ready") throw new PluginLifecycleError("preparation", "Object resource is not ready");
1969
+ }
1970
+ },
1971
+ adopt: (current) => {
1972
+ const cleanup = [];
1973
+ if (!current) return cleanup;
1974
+ for (const slot of declarations.values()) {
1975
+ const previous = slots.get(slot.declaration.name);
1976
+ if (previous && previous !== slot) {
1977
+ previous.committed = false;
1978
+ if (previous.holders === 0) {
1979
+ previous.retirementRequested = true;
1980
+ cleanup.push(retire(previous));
1981
+ }
1982
+ }
1983
+ slot.committed = true;
1984
+ slots.set(slot.declaration.name, slot);
1985
+ }
1986
+ return cleanup;
1987
+ }
1988
+ };
1989
+ }),
1990
+ close: Semaphore.withPermit(lane, Effect.sync(() => {
1991
+ closing = true;
1992
+ return [...owned];
1993
+ })).pipe(Effect.flatMap(closeSlots)),
1994
+ closeUnborrowed: Semaphore.withPermit(lane, Effect.sync(() => {
1995
+ closing = true;
1996
+ return [...owned].filter((slot) => slot.holders === 0);
1997
+ })).pipe(Effect.flatMap(closeSlots)),
1998
+ status: () => [...owned].map((slot) => ({
1999
+ name: slot.declaration.name,
2000
+ key: slot.declaration.key,
2001
+ version: slot.declaration.version,
2002
+ identity: slot.declaration.identity,
2003
+ originActivationId: slot.origin.source.owner.activationId,
2004
+ phase: slot.phase,
2005
+ committed: slot.committed,
2006
+ holders: slot.holders,
2007
+ residualResources: slot.residualResources,
2008
+ error: slot.failure?.message
2009
+ }))
2010
+ };
2011
+ });
2012
+
2013
+ //#endregion
2014
+ //#region src/composition/source-borrow.ts
2015
+ /** Shares an already captured graph borrow, including after its source retires. */
2016
+ function makeSourceBorrow(releaseSource) {
2017
+ let holders = 1;
2018
+ const makeRelease = () => {
2019
+ let released = false;
2020
+ return Effect.uninterruptible(Effect.suspend(() => {
2021
+ if (released) return Effect.void;
2022
+ released = true;
2023
+ holders -= 1;
2024
+ return holders === 0 ? releaseSource : Effect.void;
2025
+ }));
2026
+ };
2027
+ return {
2028
+ release: makeRelease(),
2029
+ retain: () => Effect.suspend(() => {
2030
+ if (holders === 0) return Effect.fail(new PluginLifecycleError("admission", "Plugin source borrow is released"));
2031
+ holders += 1;
2032
+ return Effect.succeed(makeRelease());
2033
+ })
2034
+ };
2035
+ }
2036
+
2037
+ //#endregion
2038
+ //#region src/composition/objects.ts
2039
+ /** Instances share Composition's admission lane and retain its existing dependency owners. */
2040
+ const makeCompositionObjects = Effect.fn("Composition.objects")(function* (options) {
2041
+ const scope = yield* Effect.scope;
2042
+ const stopped = yield* Deferred.make();
2043
+ const instances = /* @__PURE__ */ new Map();
2044
+ let closing = false;
2045
+ const reportFailure = (error) => options.onFailure?.(error) ?? Effect.void;
2046
+ const all = () => [...instances.values()].flatMap((instance) => [...instance.generations]);
2047
+ const assertOpen = () => {
2048
+ if (closing) throw new PluginLifecycleError("admission", "Object composition is closing");
2049
+ };
2050
+ const visible = () => options.sample()?.samples.flatMap(({ entry, contributions }) => entry.rootRealm ? (contributions.objectFactories ?? []).map((factory) => ({
2051
+ entry,
2052
+ factory
2053
+ })) : []) ?? [];
2054
+ const assertOwnerAvailable = (generation) => {
2055
+ assertOpen();
2056
+ generation.source.owner.assertAvailable();
2057
+ generation.factory.assertAvailable?.();
2058
+ generation.assertResourcesAvailable();
2059
+ };
2060
+ const assertAvailable = (generation) => {
2061
+ assertOwnerAvailable(generation);
2062
+ if (!visible().some(({ factory }) => factory.typeId === generation.factory.typeId && factory.version === generation.factory.version)) throw new PluginLifecycleError("admission", "Object factory is unavailable");
2063
+ };
2064
+ const assertCallAdmission = (generation) => {
2065
+ if (generation.superseded) throw new PluginLifecycleError("admission", "Object implementation is superseded");
2066
+ if (generation.instance.transition && generation.instance.transition !== generation) throw new PluginLifecycleError("admission", "Object transition is pending");
2067
+ };
2068
+ const instanceCleanupTimeout = (instance) => Effect.gen(function* () {
2069
+ const { error, first } = residentCleanupFailure(instance, `Object ${instance.id}`, options.changed);
2070
+ if (first) yield* reportFailure(error);
2071
+ yield* Deferred.fail(instance.closed, error);
2072
+ return error;
2073
+ });
2074
+ const retireInstance = (instance) => Effect.uninterruptible(Effect.gen(function* () {
2075
+ if (instance.retiring) return yield* Deferred.await(instance.retirementStarted);
2076
+ instance.retiring = true;
2077
+ instance.closing = true;
2078
+ const work = instance.resources.close.pipe(Effect.andThen(Scope.close(instance.scope, Exit.void)), Effect.tap(() => Effect.sync(() => {
2079
+ instances.delete(instance.indexKey);
2080
+ instance.residualResources = false;
2081
+ options.changed();
2082
+ })), Effect.tap(() => Deferred.succeed(instance.closed, void 0)), Effect.catchCause((cause) => {
2083
+ const error = pluginFailure(cause);
2084
+ instance.failure = error;
2085
+ instance.residualResources = true;
2086
+ options.changed();
2087
+ return Deferred.fail(instance.closed, error).pipe(Effect.andThen(reportFailure(error)), Effect.andThen(Effect.fail(error)));
2088
+ }));
2089
+ instance.retirement = yield* Effect.forkIn(work, scope);
2090
+ yield* Deferred.succeed(instance.retirementStarted, void 0);
2091
+ yield* Effect.forkIn(Fiber.join(instance.retirement).pipe(Effect.timeoutOption(options.cleanupTimeoutMs ?? Duration.infinity), Effect.flatMap((result) => Option.isSome(result) ? Effect.void : instanceCleanupTimeout(instance).pipe(Effect.asVoid)), Effect.catch(() => Effect.void)), scope);
2092
+ }));
2093
+ const cleanupTimeout = (generation) => Effect.gen(function* () {
2094
+ const { error, first } = residentCleanupFailure(generation, `Object ${generation.id}`, options.changed);
2095
+ if (first) yield* reportFailure(error);
2096
+ yield* Deferred.fail(generation.retired, error);
2097
+ if (generation.instance.closing) yield* Deferred.fail(generation.instance.closed, error);
2098
+ return error;
2099
+ });
2100
+ const retire = (generation) => Effect.uninterruptible(Effect.gen(function* () {
2101
+ if (generation.phase === "retiring") return yield* Deferred.await(generation.retirementStarted);
2102
+ generation.phase = "retiring";
2103
+ const retired = generation.retired;
2104
+ const cleanup = Effect.gen(function* () {
2105
+ yield* Fiber.interrupt(generation.preparation);
2106
+ yield* Effect.forEach(generation.invocations, Deferred.await, { discard: true });
2107
+ if (generation.superseded) yield* generation.instance.slots.drainWriters;
2108
+ yield* Scope.close(generation.scope, Exit.void);
2109
+ yield* generation.releaseSource;
2110
+ const instance = generation.instance;
2111
+ instance.generations.delete(generation);
2112
+ if (instance.current === generation) instance.current = maxBy([...instance.generations].filter((entry) => entry.phase === "active"), (entry) => entry.ordinal);
2113
+ if (instance.generations.size === 0) {
2114
+ yield* retireInstance(instance);
2115
+ yield* Deferred.await(instance.closed);
2116
+ }
2117
+ generation.residualResources = false;
2118
+ yield* Deferred.succeed(retired, void 0);
2119
+ options.changed();
2120
+ }).pipe(Effect.catchCause((cause) => {
2121
+ const error = pluginFailure(cause);
2122
+ generation.failure = error;
2123
+ generation.residualResources = true;
2124
+ if (generation.instance.closing) Effect.runSync(Deferred.fail(generation.instance.closed, error));
2125
+ return Deferred.fail(retired, error).pipe(Effect.andThen(reportFailure(error)), Effect.andThen(Effect.fail(error)));
2126
+ }));
2127
+ generation.retirement = yield* Effect.forkIn(cleanup, scope);
2128
+ yield* Deferred.succeed(generation.retirementStarted, void 0);
2129
+ yield* Effect.forkIn(Fiber.join(generation.retirement).pipe(Effect.timeoutOption(options.cleanupTimeoutMs ?? Duration.infinity), Effect.flatMap((outcome) => {
2130
+ if (Option.isSome(outcome)) return Effect.void;
2131
+ return cleanupTimeout(generation).pipe(Effect.asVoid);
2132
+ }), Effect.catch(() => Effect.void)), scope);
2133
+ }));
2134
+ const releaseIfIdle = (generation) => Effect.suspend(() => {
2135
+ if (generation.holders !== 0 || generation.invocations.size !== 0) return Effect.void;
2136
+ if (generation.phase !== "active") generation.rollbackTransition();
2137
+ if (generation.instance.transition && generation.instance.transition !== generation) return Effect.void;
2138
+ if ([...generation.instance.generations].every((entry) => entry.holders === 0 && entry.invocations.size === 0)) generation.instance.closing = true;
2139
+ return retire(generation);
2140
+ });
2141
+ const settleIdle = (generation) => releaseIfIdle(generation).pipe(Effect.andThen(Effect.suspend(() => generation.phase === "retiring" ? Deferred.await(generation.retired).pipe(Effect.catch(() => Effect.void)) : Effect.void)));
2142
+ const invoke = (generation, binding, name, input, admit) => Effect.uninterruptibleMask((restoreCall) => Effect.gen(function* () {
2143
+ const drained = yield* Deferred.make();
2144
+ yield* Effect.try({
2145
+ try: () => {
2146
+ assertAvailable(generation);
2147
+ assertCallAdmission(generation);
2148
+ admit();
2149
+ generation.invocations.add(drained);
2150
+ },
2151
+ catch: ensureError
2152
+ });
2153
+ const invocation = yield* Effect.forkIn(restoreCall(Effect.suspend(() => binding.call(name, input))).pipe(Effect.ensuring(Effect.sync(() => generation.invocations.delete(drained)).pipe(Effect.andThen(Deferred.succeed(drained, void 0)), Effect.andThen(releaseIfIdle(generation))))), scope);
2154
+ generation.calls.add(invocation);
2155
+ return yield* restoreCall(Fiber.join(invocation)).pipe(Effect.onInterrupt(() => Fiber.interrupt(invocation).pipe(Effect.andThen(Fiber.await(invocation)), Effect.flatMap((exit) => Exit.isFailure(exit) ? Effect.failCause(exit.cause) : Effect.void))), Effect.ensuring(Effect.sync(() => generation.calls.delete(invocation))));
2156
+ }));
2157
+ const catalog = () => Effect.try({
2158
+ try: () => {
2159
+ assertOpen();
2160
+ if (options.namespace === void 0) throw new PluginLifecycleError("admission", "Object namespace is not configured");
2161
+ const factories = visible();
2162
+ for (const { entry, factory } of factories) {
2163
+ entry.owner.assertAvailable();
2164
+ factory.assertAvailable?.();
2165
+ }
2166
+ const ordered = sortBy(factories, [
2167
+ ({ factory }) => factory.typeId,
2168
+ ({ factory }) => factory.version,
2169
+ ({ entry }) => entry.path.join("/")
2170
+ ]);
2171
+ return {
2172
+ namespace: options.namespace,
2173
+ types: ordered.map(({ factory }) => ({
2174
+ contract: factory.descriptor,
2175
+ availability: factories.filter(({ factory: candidate }) => candidate.typeId === factory.typeId && candidate.version === factory.version).length > 1 ? "ambiguous" : "available"
2176
+ })),
2177
+ instances: sortBy([...instances.values()].filter((instance) => factories.some(({ factory }) => factory.typeId === instance.address.typeId && factory.version === instance.address.version)), [(instance) => instance.indexKey]).map((instance) => instance.address)
2178
+ };
2179
+ },
2180
+ catch: ensureError
2181
+ });
2182
+ const acquire = (type, key) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
2183
+ const captured = yield* Effect.try({
2184
+ try: () => {
2185
+ assertOpen();
2186
+ if (options.namespace === void 0) throw new PluginLifecycleError("admission", "Object namespace is not configured");
2187
+ return captureObjectAddress(type, key, options.namespace);
2188
+ },
2189
+ catch: ensureError
2190
+ });
2191
+ let releaseSelection;
2192
+ const obtained = yield* Semaphore.withPermit(options.lane, Effect.gen(function* () {
2193
+ const selected = yield* Effect.try({
2194
+ try: () => {
2195
+ assertOpen();
2196
+ const factories = visible().filter(({ factory }) => factory.typeId === captured.address.typeId && factory.version === captured.address.version);
2197
+ const first = factories[0];
2198
+ if (first === void 0) throw new PluginLifecycleError("admission", "Object factory is unavailable");
2199
+ if (factories.length > 1) throw new PluginLifecycleError("admission", "Object factory is ambiguous");
2200
+ first.factory.assertAvailable?.();
2201
+ releaseSelection = retainPluginCallbacks({
2202
+ tools: [],
2203
+ objectFactories: [first.factory]
2204
+ });
2205
+ return first;
2206
+ },
2207
+ catch: ensureError
2208
+ });
2209
+ const resident = instances.get(captured.indexKey);
2210
+ if (resident?.closing) return {
2211
+ kind: "closing",
2212
+ instance: resident
2213
+ };
2214
+ if (resident?.transition && (resident.transition.factory !== selected.factory || resident.transition.phase !== "activating")) return yield* Effect.fail(new PluginLifecycleError("admission", "Object transition is pending"));
2215
+ const existing = [...resident?.generations ?? []].find((entry) => entry.factory === selected.factory && entry.source === selected.entry);
2216
+ if (existing !== void 0) {
2217
+ if (existing.phase !== "retiring") existing.holders += 1;
2218
+ return {
2219
+ kind: "generation",
2220
+ generation: existing
2221
+ };
2222
+ }
2223
+ const snapshot = options.sample();
2224
+ if (snapshot === void 0) return yield* Effect.fail(new PluginLifecycleError("admission", "Object composition is not initialized"));
2225
+ const sourceBorrow = makeSourceBorrow(yield* snapshot.borrow([selected.entry]));
2226
+ const instance = resident ?? (yield* Effect.gen(function* () {
2227
+ const owner = yield* Scope.fork(scope, "sequential");
2228
+ const slots = yield* Scope.provide(makeObjectSlots(), owner);
2229
+ const resources$1 = yield* Scope.provide(makeObjectResources(scope, {
2230
+ cleanupTimeoutMs: options.cleanupTimeoutMs,
2231
+ changed: options.changed,
2232
+ onFailure: reportFailure
2233
+ }), owner);
2234
+ const closed = yield* Deferred.make();
2235
+ const retirementStarted$1 = yield* Deferred.make();
2236
+ const created = {
2237
+ id: options.createId(),
2238
+ indexKey: captured.indexKey,
2239
+ address: captured.address,
2240
+ scope: owner,
2241
+ slots,
2242
+ resources: resources$1,
2243
+ closed,
2244
+ retirementStarted: retirementStarted$1,
2245
+ generations: /* @__PURE__ */ new Set(),
2246
+ nextGeneration: 0,
2247
+ lastAdoptedOrdinal: 0,
2248
+ closing: false,
2249
+ retiring: false,
2250
+ residualResources: false
2251
+ };
2252
+ instances.set(captured.indexKey, created);
2253
+ return created;
2254
+ }));
2255
+ const generationScope = yield* Scope.fork(instance.scope, "sequential");
2256
+ const releaseFactory = releaseSelection;
2257
+ yield* Scope.addFinalizer(generationScope, Effect.sync(() => releaseFactory?.()));
2258
+ releaseSelection = void 0;
2259
+ const memoMap = yield* Layer.makeMemoMap;
2260
+ const ready = yield* Deferred.make();
2261
+ const retired = yield* Deferred.make();
2262
+ const retirementStarted = yield* Deferred.make();
2263
+ const registered = yield* Deferred.make();
2264
+ let generation$1;
2265
+ let irreversible = false;
2266
+ const transition = {
2267
+ quiesce: Effect.gen(function* () {
2268
+ const calls = yield* Effect.try({
2269
+ try: () => {
2270
+ assertAvailable(generation$1);
2271
+ if (generation$1.phase !== "activating" || generation$1.superseded) throw new PluginLifecycleError("admission", "Object transition was cancelled");
2272
+ if (instance.transition && instance.transition !== generation$1) throw new PluginLifecycleError("admission", "Object transition is pending");
2273
+ instance.transition = generation$1;
2274
+ return [...instance.generations].filter((entry) => entry !== generation$1).flatMap((entry) => [...entry.invocations]);
2275
+ },
2276
+ catch: ensureError
2277
+ });
2278
+ yield* Effect.forEach(calls, Deferred.await, { discard: true });
2279
+ }),
2280
+ retirePrevious: Effect.uninterruptibleMask((restoreCleanup) => Effect.gen(function* () {
2281
+ const previous = yield* Effect.try({
2282
+ try: () => {
2283
+ assertAvailable(generation$1);
2284
+ if (instance.transition !== generation$1 || generation$1.phase !== "activating" || generation$1.superseded || !visible().some(({ entry, factory }) => entry === generation$1.source && factory === generation$1.factory)) throw new PluginLifecycleError("admission", "Object exclusive transition was superseded");
2285
+ irreversible = true;
2286
+ const previousGenerations = [...instance.generations].filter((entry) => entry !== generation$1);
2287
+ for (const entry of previousGenerations) entry.superseded = true;
2288
+ return previousGenerations;
2289
+ },
2290
+ catch: ensureError
2291
+ });
2292
+ const cleanup = yield* Effect.forkIn(Effect.gen(function* () {
2293
+ const errors = (yield* Effect.forEach(previous, (entry) => retire(entry).pipe(Effect.andThen(Deferred.await(entry.retired)), Effect.exit), { concurrency: "unbounded" })).flatMap((outcome) => Exit.isFailure(outcome) ? [pluginFailure(outcome.cause)] : []);
2294
+ const first = errors[0];
2295
+ if (errors.length === 1 && first !== void 0) return yield* Effect.fail(first);
2296
+ if (errors.length > 0) return yield* Effect.fail(new AggregateError(errors, "Object exclusive generation cleanup failed"));
2297
+ }), scope);
2298
+ yield* restoreCleanup(Fiber.join(cleanup));
2299
+ })),
2300
+ commit: () => {
2301
+ for (const previous of instance.generations) if (previous !== generation$1) previous.superseded = true;
2302
+ instance.transition = void 0;
2303
+ },
2304
+ rollback: () => {
2305
+ if (instance.transition === generation$1 && !irreversible) {
2306
+ instance.transition = void 0;
2307
+ Effect.runSync(Effect.forkIn(Effect.forEach([...instance.generations].filter((entry) => entry !== generation$1), releaseIfIdle, { discard: true }), scope));
2308
+ }
2309
+ }
2310
+ };
2311
+ const candidate = yield* Scope.provide(instance.slots.candidate(() => {
2312
+ generation$1.source.owner.assertAvailable();
2313
+ generation$1.factory.assertAvailable?.();
2314
+ generation$1.assertResourcesAvailable();
2315
+ if (generation$1.superseded) throw new PluginLifecycleError("admission", "Object state generation is superseded");
2316
+ }, transition), generationScope);
2317
+ const resources = yield* Scope.provide(instance.resources.candidate({
2318
+ source: selected.entry,
2319
+ borrow: sourceBorrow,
2320
+ assertAuthorized: () => selected.factory.assertAvailable?.(),
2321
+ assertAvailable: () => {
2322
+ selected.entry.owner.assertAvailable();
2323
+ selected.factory.assertAvailable?.();
2324
+ },
2325
+ assertDeclaration: () => {
2326
+ assertOpen();
2327
+ assertCallAdmission(generation$1);
2328
+ if (generation$1.phase !== "activating" || instance.closing) throw new PluginLifecycleError("admission", "Object resource preparation was cancelled");
2329
+ if (instance.transition === generation$1 && !visible().some(({ entry, factory }) => entry === generation$1.source && factory === generation$1.factory)) throw new PluginLifecycleError("admission", "Object transition factory is superseded");
2330
+ }
2331
+ }, transition), generationScope);
2332
+ const self = createObjectSelf({
2333
+ ...candidate.host,
2334
+ ...resources.host
2335
+ });
2336
+ const preparation = yield* Effect.forkIn(Deferred.await(registered).pipe(Effect.andThen(Effect.exit(restore(Scope.provide(Effect.provideService(Effect.suspend(() => selected.factory.create(captured.address.key, self)).pipe(Effect.ensuring(Effect.sync(() => {
2337
+ candidate.seal();
2338
+ resources.seal();
2339
+ }))), Layer.CurrentMemoMap, memoMap), generationScope))))), scope);
2340
+ instance.nextGeneration += 1;
2341
+ generation$1 = {
2342
+ id: options.createId(),
2343
+ instance,
2344
+ ordinal: instance.nextGeneration,
2345
+ factory: selected.factory,
2346
+ source: selected.entry,
2347
+ scope: generationScope,
2348
+ releaseSource: sourceBorrow.release,
2349
+ assertResourcesAvailable: resources.assertAvailable,
2350
+ ready,
2351
+ retired,
2352
+ retirementStarted,
2353
+ preparation,
2354
+ rollbackTransition: candidate.rollback,
2355
+ invocations: /* @__PURE__ */ new Set(),
2356
+ calls: /* @__PURE__ */ new Set(),
2357
+ holders: 1,
2358
+ phase: "activating",
2359
+ superseded: false,
2360
+ residualResources: false
2361
+ };
2362
+ instance.generations.add(generation$1);
2363
+ yield* Deferred.succeed(registered, void 0);
2364
+ yield* Effect.forkIn(Effect.gen(function* () {
2365
+ const result = yield* Fiber.join(preparation).pipe(Effect.catchCause((cause) => Effect.succeed(Exit.fail(pluginFailure(cause)))), Effect.timeoutOption(options.preparationTimeoutMs ?? Duration.infinity));
2366
+ if (closing || generation$1.phase === "retiring") {
2367
+ candidate.rollback();
2368
+ yield* Deferred.fail(ready, new PluginLifecycleError("admission", "Object preparation was cancelled"));
2369
+ } else if (Option.isNone(result)) {
2370
+ candidate.rollback();
2371
+ const error = new PluginLifecycleError("preparation", "Object preparation timed out");
2372
+ generation$1.failure = error;
2373
+ generation$1.phase = "failed";
2374
+ yield* Deferred.fail(ready, error);
2375
+ } else if (Exit.isFailure(result.value)) {
2376
+ candidate.rollback();
2377
+ const error = pluginFailure(result.value.cause);
2378
+ generation$1.failure = error;
2379
+ generation$1.phase = "failed";
2380
+ yield* Deferred.fail(ready, error);
2381
+ } else {
2382
+ const adopted = yield* Semaphore.withPermit(options.lane, Effect.try({
2383
+ try: () => {
2384
+ assertAvailable(generation$1);
2385
+ assertCallAdmission(generation$1);
2386
+ if (instance.transition === generation$1 && !visible().some(({ entry, factory }) => entry === generation$1.source && factory === generation$1.factory)) throw new PluginLifecycleError("admission", "Object transition factory is superseded");
2387
+ if (generation$1.phase !== "activating" || instance.closing) throw new PluginLifecycleError("admission", "Object adoption was cancelled");
2388
+ candidate.validate();
2389
+ resources.validate();
2390
+ const cleanup = candidate.adopt();
2391
+ const current = instance.lastAdoptedOrdinal < generation$1.ordinal;
2392
+ const retiredResources = resources.adopt(current);
2393
+ if (instance.transition === generation$1) transition.commit();
2394
+ generation$1.phase = "active";
2395
+ if (current) {
2396
+ instance.current = generation$1;
2397
+ instance.lastAdoptedOrdinal = generation$1.ordinal;
2398
+ }
2399
+ return {
2400
+ cleanup,
2401
+ retiredResources
2402
+ };
2403
+ },
2404
+ catch: ensureError
2405
+ })).pipe(Effect.exit);
2406
+ if (Exit.isFailure(adopted)) {
2407
+ candidate.rollback();
2408
+ const error = pluginFailure(adopted.cause);
2409
+ generation$1.failure = error;
2410
+ yield* Effect.sync(() => {
2411
+ if (generation$1.phase !== "retiring") generation$1.phase = "failed";
2412
+ });
2413
+ yield* Deferred.fail(ready, error);
2414
+ } else {
2415
+ yield* Effect.forEach(adopted.value.cleanup, (cleanup) => cleanup, { discard: true });
2416
+ yield* Effect.forEach(adopted.value.retiredResources, (cleanup) => Effect.forkIn(cleanup.pipe(Effect.tapError(reportFailure), Effect.ensuring(Effect.sync(options.changed))), scope), { discard: true });
2417
+ yield* Deferred.succeed(ready, result.value.value);
2418
+ }
2419
+ }
2420
+ yield* Effect.forEach(instance.generations, releaseIfIdle, { discard: true });
2421
+ options.changed();
2422
+ }), scope);
2423
+ options.changed();
2424
+ return {
2425
+ kind: "generation",
2426
+ generation: generation$1
2427
+ };
2428
+ })).pipe(Effect.ensuring(Effect.sync(() => releaseSelection?.())));
2429
+ if (obtained.kind === "closing") {
2430
+ yield* restore(Deferred.await(obtained.instance.closed));
2431
+ return yield* restore(acquire(type, key));
2432
+ }
2433
+ const generation = obtained.generation;
2434
+ if (generation.phase === "retiring") {
2435
+ yield* restore(Deferred.await(generation.retired));
2436
+ return yield* restore(acquire(type, key));
2437
+ }
2438
+ let released = false;
2439
+ const refStopped = yield* Deferred.make();
2440
+ const release = Effect.suspend(() => {
2441
+ if (released) return Effect.void;
2442
+ released = true;
2443
+ generation.holders -= 1;
2444
+ return Deferred.succeed(refStopped, void 0).pipe(Effect.andThen(settleIdle(generation)));
2445
+ });
2446
+ yield* Effect.addFinalizer(() => release);
2447
+ const binding = yield* restore(Effect.raceFirst(Deferred.await(generation.ready), Deferred.await(refStopped).pipe(Effect.andThen(Effect.fail(new PluginLifecycleError("admission", "Object acquisition Scope is closed")))))).pipe(Effect.onError(() => release));
2448
+ yield* Effect.try({
2449
+ try: () => {
2450
+ assertAvailable(generation);
2451
+ if (released) throw new PluginLifecycleError("admission", "Object acquisition Scope is closed");
2452
+ },
2453
+ catch: ensureError
2454
+ }).pipe(Effect.onError(() => release));
2455
+ const assertRef = () => {
2456
+ if (released) throw new PluginLifecycleError("admission", "Object Ref is released");
2457
+ };
2458
+ const assertObservation = () => {
2459
+ assertRef();
2460
+ assertAvailable(generation);
2461
+ };
2462
+ return bindObjectRefPort(captured.createRef({ call: (name, input) => invoke(generation, binding, name, input, assertRef) }, {
2463
+ states: () => Effect.try({
2464
+ try: () => {
2465
+ assertObservation();
2466
+ return generation.instance.slots.states();
2467
+ },
2468
+ catch: ensureError
2469
+ }),
2470
+ watchState: (name) => Stream.unwrap(Effect.try({
2471
+ try: () => {
2472
+ assertObservation();
2473
+ return generation.instance.slots.watchState(name).pipe(Stream.filterEffect(() => Effect.try({
2474
+ try: () => {
2475
+ if (released || closing) return false;
2476
+ assertAvailable(generation);
2477
+ return true;
2478
+ },
2479
+ catch: ensureError
2480
+ })), Stream.interruptWhen(Effect.race(Deferred.await(refStopped), Deferred.await(stopped))));
2481
+ },
2482
+ catch: ensureError
2483
+ }))
2484
+ }), { capture: (name) => {
2485
+ assertRef();
2486
+ assertAvailable(generation);
2487
+ assertCallAdmission(generation);
2488
+ const method = captured.methods[name];
2489
+ if (method === void 0) throw new TypeError("Unknown Object method");
2490
+ let pins = 0;
2491
+ let expired = false;
2492
+ const assertProjection = () => {
2493
+ if (expired) throw new PluginLifecycleError("admission", "Object method binding is released");
2494
+ assertOwnerAvailable(generation);
2495
+ };
2496
+ return {
2497
+ address: captured.address,
2498
+ input: method.input,
2499
+ output: method.output,
2500
+ settle: settleIdle(generation),
2501
+ assertAvailable: () => {
2502
+ assertProjection();
2503
+ assertAvailable(generation);
2504
+ },
2505
+ retain: () => {
2506
+ assertProjection();
2507
+ assertCallAdmission(generation);
2508
+ if (pins === 0) assertRef();
2509
+ if (generation.phase !== "active" || generation.instance.closing) throw new PluginLifecycleError("admission", "Object no longer accepts bindings");
2510
+ pins += 1;
2511
+ generation.holders += 1;
2512
+ let held = true;
2513
+ return () => {
2514
+ if (!held) return;
2515
+ held = false;
2516
+ pins -= 1;
2517
+ if (pins === 0) expired = true;
2518
+ generation.holders -= 1;
2519
+ Effect.runSync(Effect.forkIn(releaseIfIdle(generation), scope));
2520
+ };
2521
+ },
2522
+ invoke: (input) => invoke(generation, binding, name, input, () => {
2523
+ assertProjection();
2524
+ if (pins === 0) throw new PluginLifecycleError("admission", "Object method binding is not retained");
2525
+ })
2526
+ };
2527
+ } });
2528
+ }));
2529
+ const stop = Effect.gen(function* () {
2530
+ closing = true;
2531
+ yield* Deferred.succeed(stopped, void 0);
2532
+ for (const generation of all()) generation.rollbackTransition();
2533
+ for (const generation of all()) yield* Deferred.fail(generation.ready, new PluginLifecycleError("admission", "Object composition is closing"));
2534
+ });
2535
+ return {
2536
+ acquire,
2537
+ acquireAddress: (address) => Effect.gen(function* () {
2538
+ return yield* acquire(yield* Effect.try({
2539
+ try: () => {
2540
+ assertOpen();
2541
+ if (address.namespace !== options.namespace) throw new PluginLifecycleError("admission", "Object namespace is unavailable");
2542
+ const factories = visible().filter(({ factory }) => factory.typeId === address.typeId && factory.version === address.version);
2543
+ const selected = factories[0];
2544
+ if (selected === void 0) throw new PluginLifecycleError("admission", "Object factory is unavailable");
2545
+ if (factories.length !== 1) throw new PluginLifecycleError("admission", "Object factory is ambiguous");
2546
+ const contract = selected.factory.descriptor;
2547
+ return {
2548
+ id: contract.id,
2549
+ version: contract.version,
2550
+ key: contract.key,
2551
+ methods: Object.fromEntries(Object.entries(contract.methods).map(([name, method]) => [name, {
2552
+ input: method.input,
2553
+ output: method.output
2554
+ }]))
2555
+ };
2556
+ },
2557
+ catch: ensureError
2558
+ }), address.key);
2559
+ }),
2560
+ catalog,
2561
+ stop,
2562
+ close: Effect.gen(function* () {
2563
+ yield* stop;
2564
+ const residents = all();
2565
+ for (const instance of instances.values()) instance.closing = true;
2566
+ const generations = yield* Effect.forEach(residents, (generation) => Effect.gen(function* () {
2567
+ yield* Effect.forkIn(Fiber.interruptAll(generation.calls), scope);
2568
+ yield* retire(generation);
2569
+ if (generation.retirement !== void 0) yield* Fiber.join(generation.retirement).pipe(Effect.timeoutOrElse({
2570
+ duration: options.cleanupTimeoutMs ?? Duration.infinity,
2571
+ orElse: () => cleanupTimeout(generation).pipe(Effect.flatMap(Effect.fail))
2572
+ }));
2573
+ }).pipe(Effect.exit), { concurrency: "unbounded" });
2574
+ const owners = yield* Effect.forEach(instances.values(), (instance) => Effect.gen(function* () {
2575
+ if (instance.generations.size === 0) yield* retireInstance(instance);
2576
+ else {
2577
+ const cleanup = yield* Effect.forkIn(instance.resources.closeUnborrowed, scope);
2578
+ yield* Fiber.join(cleanup).pipe(Effect.timeoutOrElse({
2579
+ duration: options.cleanupTimeoutMs ?? Duration.infinity,
2580
+ orElse: () => instanceCleanupTimeout(instance).pipe(Effect.flatMap(Effect.fail))
2581
+ }));
2582
+ }
2583
+ if (instance.retirement !== void 0) yield* Fiber.join(instance.retirement).pipe(Effect.timeoutOrElse({
2584
+ duration: options.cleanupTimeoutMs ?? Duration.infinity,
2585
+ orElse: () => instanceCleanupTimeout(instance).pipe(Effect.flatMap(Effect.fail))
2586
+ }));
2587
+ }).pipe(Effect.exit), { concurrency: "unbounded" });
2588
+ const failure = aggregateCleanupFailure([...new Set([...generations, ...owners].flatMap((outcome) => Exit.isFailure(outcome) ? [pluginFailure(outcome.cause)] : []))], "Object cleanup failed");
2589
+ if (failure !== void 0) return yield* Effect.fail(failure);
2590
+ }),
2591
+ status: () => [...instances.values()].flatMap((instance) => instance.generations.size === 0 ? [{
2592
+ instanceId: instance.id,
2593
+ generationId: void 0,
2594
+ current: false,
2595
+ address: instance.address,
2596
+ activationId: void 0,
2597
+ phase: "retiring",
2598
+ holders: 0,
2599
+ invocations: 0,
2600
+ residualResources: instance.residualResources,
2601
+ error: instance.failure?.message,
2602
+ resources: instance.resources.status()
2603
+ }] : [...instance.generations].map((generation) => ({
2604
+ instanceId: generation.instance.id,
2605
+ generationId: generation.id,
2606
+ current: generation.instance.current === generation,
2607
+ address: generation.instance.address,
2608
+ activationId: generation.source.owner.activationId,
2609
+ phase: generation.phase,
2610
+ holders: generation.holders,
2611
+ invocations: generation.invocations.size,
2612
+ residualResources: generation.residualResources,
2613
+ error: generation.failure?.message,
2614
+ resources: instance.resources.status()
2615
+ })))
2616
+ };
2617
+ });
2618
+
2619
+ //#endregion
2620
+ //#region src/composition/observation.ts
2621
+ function observePlugin(callback, failed = () => {}) {
2622
+ try {
2623
+ const result = callback();
2624
+ if (isPromise(result)) result.catch(failed);
2625
+ } catch {
2626
+ failed();
2627
+ }
2628
+ }
2629
+
2630
+ //#endregion
2631
+ //#region src/composition/live.ts
2632
+ /** Resource ownership and graph convergence do not require a model consumer or durable archive. */
2633
+ const makeLiveComposition = Effect.fn("LiveComposition.make")(function* (options) {
2634
+ const scope = yield* Effect.scope;
2635
+ const lane = yield* Semaphore.make(1);
2636
+ const residents = /* @__PURE__ */ new Set();
2637
+ const pending = yield* Ref.make(void 0);
2638
+ const retirements = yield* FiberSet.make();
2639
+ const retiringEntries = /* @__PURE__ */ new Set();
2640
+ const failedPreparations = /* @__PURE__ */ new WeakMap();
2641
+ const changes = yield* Queue.make({
2642
+ capacity: 1,
2643
+ strategy: "sliding"
2644
+ });
2645
+ const publications = yield* Queue.make({
2646
+ capacity: 1,
2647
+ strategy: "sliding"
2648
+ });
2649
+ let roots;
2650
+ let closing = false;
2651
+ let observationDetached = false;
2652
+ let observerFailures = 0;
2653
+ let borrowTotal = 0;
2654
+ let observedMounts = [];
2655
+ const activationStarts = /* @__PURE__ */ new WeakMap();
2656
+ const retirementStarts = /* @__PURE__ */ new WeakMap();
2657
+ const activationReported = /* @__PURE__ */ new WeakSet();
2658
+ const retirementUncertain = /* @__PURE__ */ new WeakSet();
2659
+ const retirementFinished = /* @__PURE__ */ new WeakSet();
2660
+ let current;
2661
+ let changePending = false;
2662
+ const health = () => {
2663
+ const entries = [...new Set([...current?.owners ?? [], ...retiringEntries])];
2664
+ const borrows = new Map(entries.map((entry) => [entry.owner, entry.drains.size]));
2665
+ const currentPaths = new Set(observedMounts.map((mount) => JSON.stringify(mount.path)));
2666
+ const removed = [...retiringEntries].filter((entry) => !currentPaths.has(JSON.stringify(entry.path))).map((entry) => ({
2667
+ path: [...entry.path],
2668
+ phase: "removed",
2669
+ activationId: entry.owner.activationId,
2670
+ profile: entry.owner.snapshot().profile
2671
+ }));
2672
+ return {
2673
+ scopeId: options.scopeId,
2674
+ admissionClosed: closing,
2675
+ closed: observationDetached,
2676
+ mounts: [...observedMounts.map((mount) => ({
2677
+ path: [...mount.path],
2678
+ phase: closing ? "removed" : mount.phase,
2679
+ pendingReason: mount.pendingReason ?? (mount.conflictingServices?.length ? "service-conflict" : void 0) ?? (mount.missingServices?.length ? "missing-service" : void 0),
2680
+ activationId: mount.activationId,
2681
+ profile: mount.profile
2682
+ })), ...removed],
2683
+ activations: [...residents].map((owner) => {
2684
+ const snapshot = owner.snapshot();
2685
+ return {
2686
+ activationId: snapshot.activationId,
2687
+ componentId: snapshot.componentId,
2688
+ profile: snapshot.profile,
2689
+ phase: snapshot.phase,
2690
+ cleanupUncertain: snapshot.residualResources,
2691
+ borrows: borrows.get(owner) ?? 0
2692
+ };
2693
+ }),
2694
+ observerFailures,
2695
+ borrowTotal
2696
+ };
2697
+ };
2698
+ const failedObservation = () => {
2699
+ observerFailures += 1;
2700
+ };
2701
+ const publishHealth = () => {
2702
+ if (options.observation?.compositionChanged !== void 0) observePlugin(() => options.observation?.compositionChanged?.(health()), failedObservation);
2703
+ };
2704
+ const lifecycle = (owner, kind, outcome) => {
2705
+ if (kind === "retirement" && outcome !== "timeout") {
2706
+ if (retirementFinished.has(owner)) return;
2707
+ retirementFinished.add(owner);
2708
+ }
2709
+ const observe = kind === "activation" ? options.observation?.activationSettled : options.observation?.retirementSettled;
2710
+ const start = (kind === "activation" ? activationStarts : retirementStarts).get(owner);
2711
+ if (observe === void 0 || start === void 0) return;
2712
+ const snapshot = owner.snapshot();
2713
+ observePlugin(() => observe({
2714
+ scopeId: options.scopeId,
2715
+ activationId: owner.activationId,
2716
+ componentId: snapshot.componentId,
2717
+ profile: snapshot.profile,
2718
+ outcome,
2719
+ durationMs: performance.now() - start.monotonic,
2720
+ startedAtUnixMs: start.wall,
2721
+ endedAtUnixMs: Date.now()
2722
+ }), failedObservation);
2723
+ };
2724
+ const observeBorrows = (delta) => {
2725
+ borrowTotal += delta;
2726
+ if (options.observation?.borrowsChanged === void 0) return;
2727
+ observePlugin(() => options.observation?.borrowsChanged?.({
2728
+ scopeId: options.scopeId,
2729
+ borrowTotal
2730
+ }), failedObservation);
2731
+ };
2732
+ const publishChange = () => {
2733
+ publishHealth();
2734
+ changePending = false;
2735
+ try {
2736
+ options.changed?.();
2737
+ } catch (cause) {
2738
+ Effect.runSync(Effect.forkIn(Effect.suspend(() => options.onFailure?.(ensureError(cause)) ?? Effect.void), scope));
2739
+ }
2740
+ };
2741
+ const publishPendingChange = () => {
2742
+ if (changePending) publishChange();
2743
+ };
2744
+ const notify = () => {
2745
+ changePending = true;
2746
+ Queue.offerUnsafe(publications, void 0);
2747
+ Queue.offerUnsafe(changes, void 0);
2748
+ };
2749
+ const objects = yield* makeCompositionObjects({
2750
+ namespace: options.objectNamespace,
2751
+ lane,
2752
+ createId: options.createId,
2753
+ preparationTimeoutMs: options.preparationTimeoutMs,
2754
+ cleanupTimeoutMs: options.cleanupTimeoutMs,
2755
+ sample: () => checkpoint(),
2756
+ changed: publishChange,
2757
+ onFailure: options.onFailure
2758
+ });
2759
+ const superviseCleanup = Effect.fn("LiveComposition.cleanup")(function* (owner, work) {
2760
+ const fiber = yield* Effect.forkIn(work, scope);
2761
+ const observed = yield* Effect.exit(Fiber.join(fiber).pipe(Effect.timeoutOption(options.cleanupTimeoutMs ?? Duration.infinity)));
2762
+ if (Exit.isFailure(observed)) {
2763
+ const error = pluginFailure(observed.cause);
2764
+ yield* owner.poison;
2765
+ retirementUncertain.add(owner);
2766
+ lifecycle(owner, "retirement", "failed");
2767
+ publishHealth();
2768
+ yield* options.onFailure?.(error) ?? Effect.void;
2769
+ return yield* Effect.fail(error);
2770
+ }
2771
+ if (Option.isNone(observed.value)) {
2772
+ const error = cleanupTimeoutError(`Activation ${owner.activationId}`);
2773
+ yield* owner.poison;
2774
+ if (!retirementUncertain.has(owner)) lifecycle(owner, "retirement", "timeout");
2775
+ retirementUncertain.add(owner);
2776
+ publishHealth();
2777
+ yield* options.onFailure?.(error) ?? Effect.void;
2778
+ return yield* Effect.fail(error);
2779
+ }
2780
+ });
2781
+ const cleanup = (owner, work) => superviseCleanup(owner, work).pipe(Effect.forkIn(scope), Effect.flatMap(Fiber.join));
2782
+ const settleCleanups = Effect.fn("LiveComposition.settleCleanups")(function* (cleanups) {
2783
+ const failure = aggregateCleanupFailure((yield* Effect.all(cleanups.map(Effect.exit), { concurrency: "unbounded" })).flatMap((outcome) => Exit.isFailure(outcome) ? [pluginFailure(outcome.cause)] : []), "Plugin cleanup failed");
2784
+ if (failure !== void 0) return yield* Effect.fail(failure);
2785
+ });
2786
+ const retire = (owners, preparation) => {
2787
+ const startEntry = (entry) => Effect.gen(function* () {
2788
+ if (entry.retirement !== void 0) return entry.retirement;
2789
+ const observation = yield* Deferred.make();
2790
+ entry.retirementObservation = observation;
2791
+ retiringEntries.add(entry);
2792
+ if (options.observation?.retirementSettled !== void 0) retirementStarts.set(entry.owner, {
2793
+ monotonic: performance.now(),
2794
+ wall: Date.now()
2795
+ });
2796
+ if (!activationReported.has(entry.owner) && entry.failure !== void 0) {
2797
+ activationReported.add(entry.owner);
2798
+ lifecycle(entry.owner, "activation", "failed");
2799
+ }
2800
+ publishHealth();
2801
+ entry.releaseCallbacks?.();
2802
+ entry.releaseCallbacks = void 0;
2803
+ const joinCleanup = (work$1) => Effect.gen(function* () {
2804
+ const fiber = yield* Effect.forkIn(work$1, scope);
2805
+ const observer = yield* superviseCleanup(entry.owner, Fiber.join(fiber)).pipe(Effect.catch((error) => Deferred.fail(observation, error)), Effect.forkIn(scope));
2806
+ yield* Fiber.join(fiber);
2807
+ yield* Fiber.join(observer);
2808
+ });
2809
+ const work = Effect.all([
2810
+ (preparation ?? entry.preparation) === void 0 ? Effect.void : joinCleanup(preparation ?? entry.preparation ?? Effect.void),
2811
+ settleCleanups([
2812
+ entry.unsubscribeLive,
2813
+ entry.unsubscribeChildren,
2814
+ entry.unsubscribeServices
2815
+ ].map((unsubscribe) => Effect.try({
2816
+ try: () => unsubscribe?.(),
2817
+ catch: (cause) => ensureError(cause)
2818
+ }))),
2819
+ settleCleanups([...new Set([...entry.ownedChildren, ...entry.consumers])].map((child) => Effect.gen(function* () {
2820
+ const retirement = yield* startEntry(child);
2821
+ if (child.retirementObservation !== void 0) yield* Deferred.await(child.retirementObservation).pipe(Effect.catch((error) => Deferred.fail(observation, error)), Effect.forkIn(scope));
2822
+ yield* Fiber.join(retirement);
2823
+ })))
2824
+ ], { concurrency: "unbounded" }).pipe(Effect.andThen(Effect.suspend(() => Effect.forEach(entry.drains, Deferred.await, { discard: true }))), Effect.andThen(joinCleanup(entry.owner.close)), Effect.tap(() => Effect.sync(() => {
2825
+ lifecycle(entry.owner, "retirement", retirementUncertain.has(entry.owner) ? "late_succeeded" : "succeeded");
2826
+ residents.delete(entry.owner);
2827
+ retiringEntries.delete(entry);
2828
+ entry.parent?.ownedChildren.delete(entry);
2829
+ for (const binding of entry.bindings) binding.provider.consumers.delete(entry);
2830
+ notify();
2831
+ })), Effect.tap(() => Deferred.succeed(observation, void 0)), Effect.tapError((error) => entry.owner.poison.pipe(Effect.andThen(Effect.sync(() => {
2832
+ lifecycle(entry.owner, "retirement", "failed");
2833
+ publishHealth();
2834
+ })), Effect.andThen(Deferred.fail(observation, error)), Effect.andThen(options.onFailure?.(error) ?? Effect.void))));
2835
+ entry.retirement = yield* Effect.forkIn(Effect.uninterruptible(work), scope);
2836
+ return entry.retirement;
2837
+ });
2838
+ const closeEntry = (entry) => Effect.gen(function* () {
2839
+ if (closing && entry.retirement !== void 0) return yield* cleanup(entry.owner, Fiber.join(entry.retirement));
2840
+ yield* startEntry(entry);
2841
+ if (entry.retirementObservation !== void 0) yield* Deferred.await(entry.retirementObservation);
2842
+ });
2843
+ const retiringOwners = new Set(owners);
2844
+ return settleCleanups(owners.filter((entry) => entry.parent === void 0 || !retiringOwners.has(entry.parent)).map(closeEntry));
2845
+ };
2846
+ const updateInLane = (components) => Effect.gen(function* () {
2847
+ if (closing) return yield* Effect.fail(new PluginLifecycleError("admission", "Live Composition is not admitting changes"));
2848
+ const reconciliation = makeMountReconciliation({
2849
+ scopeId: options.scopeId,
2850
+ sessions: options.sessions,
2851
+ objects: { acquire: objects.acquire },
2852
+ borrowed: observeBorrows,
2853
+ preparationTimeoutMs: options.preparationTimeoutMs,
2854
+ members: components,
2855
+ existing: current?.owners ?? [],
2856
+ retiring: [...retiringEntries],
2857
+ scope,
2858
+ createId: options.createId,
2859
+ isClosing: () => closing,
2860
+ notify,
2861
+ observation: options.observation,
2862
+ failures: failedPreparations,
2863
+ retire,
2864
+ preparing: (entry) => Effect.sync(() => {
2865
+ residents.add(entry.owner);
2866
+ }).pipe(Effect.andThen(Ref.set(pending, entry.owner)), Effect.andThen(Effect.sync(() => {
2867
+ if (options.observation?.activationSettled !== void 0) activationStarts.set(entry.owner, {
2868
+ monotonic: performance.now(),
2869
+ wall: Date.now()
2870
+ });
2871
+ })))
2872
+ });
2873
+ const { created, staged, owners } = reconciliation;
2874
+ const cleanupCreated = Effect.suspend(() => retire(staged));
2875
+ const prepared = yield* Effect.exit(reconciliation.prepare);
2876
+ if (Exit.isFailure(prepared)) {
2877
+ yield* cleanupCreated;
2878
+ return yield* Effect.fail(pluginFailure(prepared.cause));
2879
+ }
2880
+ const superseded = staged.filter((entry) => !owners.includes(entry));
2881
+ yield* retire(superseded);
2882
+ for (const entry of superseded) {
2883
+ staged.splice(staged.indexOf(entry), 1);
2884
+ created.splice(created.indexOf(entry.owner), 1);
2885
+ }
2886
+ const admissionScope = yield* Scope.fork(scope, "sequential");
2887
+ const subscriptions = yield* Effect.exit(Scope.provide(Effect.forEach(reconciliation.waitingAdmission, (admission) => Effect.acquireRelease(Effect.try({
2888
+ try: () => admission.subscribe(notify),
2889
+ catch: ensureError
2890
+ }), (unsubscribe) => Effect.try({
2891
+ try: unsubscribe,
2892
+ catch: ensureError
2893
+ }).pipe(Effect.catch((error) => options.onFailure?.(error) ?? Effect.void))), { discard: true }), admissionScope));
2894
+ const discardCandidate = settleCleanups([Scope.close(admissionScope, Exit.void), cleanupCreated]);
2895
+ if (Exit.isFailure(subscriptions)) {
2896
+ yield* discardCandidate;
2897
+ return yield* Effect.fail(pluginFailure(subscriptions.cause));
2898
+ }
2899
+ const previousAdmissionScope = current?.admissionScope;
2900
+ const adopted = yield* Effect.exit(Effect.try({
2901
+ try: () => {
2902
+ if (closing) throw new PluginLifecycleError("admission", "Composition closed during preparation");
2903
+ for (const entry of staged) if (entry.failure === void 0) Effect.runSync(entry.prepared ? entry.owner.serve : entry.owner.awaitServices);
2904
+ const removed = (current?.owners ?? []).filter((entry) => !owners.includes(entry));
2905
+ for (const entry of removed) Effect.runSync(entry.owner.fence);
2906
+ const snapshot = sampleEntries(owners, observeBorrows);
2907
+ commitSamples(snapshot);
2908
+ releaseRemovedCallbacks(current?.snapshot, snapshot);
2909
+ reconciliation.commitSourceVersions();
2910
+ observedMounts = reconciliation.report();
2911
+ current = {
2912
+ owners: [...owners],
2913
+ snapshot,
2914
+ reconciliation,
2915
+ admissionScope
2916
+ };
2917
+ roots = components;
2918
+ for (const entry of staged) if (entry.prepared && entry.failure === void 0 && !activationReported.has(entry.owner)) {
2919
+ activationReported.add(entry.owner);
2920
+ lifecycle(entry.owner, "activation", "succeeded");
2921
+ }
2922
+ publishChange();
2923
+ return removed;
2924
+ },
2925
+ catch: ensureError
2926
+ }));
2927
+ if (Exit.isFailure(adopted)) {
2928
+ yield* discardCandidate;
2929
+ return yield* Effect.fail(pluginFailure(adopted.cause));
2930
+ }
2931
+ if (previousAdmissionScope !== void 0) yield* Scope.close(previousAdmissionScope, Exit.void);
2932
+ if ([...reconciliation.waitingAdmission].some((admission) => admission.available())) notify();
2933
+ yield* FiberSet.run(retirements, retire(adopted.value).pipe(Effect.catch(() => Effect.void)));
2934
+ }).pipe(Effect.ensuring(Ref.set(pending, void 0)));
2935
+ const needsReconciliation = () => current?.owners.some((entry) => entry.failure !== void 0 || entry.children?.version !== entry.childrenVersion || entry.services?.version !== entry.servicesVersion) || [...current?.reconciliation.waitingExclusive ?? []].some((entry) => !retiringEntries.has(entry)) || [...current?.reconciliation.waitingAdmission ?? []].some((admission) => admission.available());
2936
+ function checkpoint() {
2937
+ if (current?.snapshot.samples.some(({ entry }) => entry.failure !== void 0)) {
2938
+ const snapshot$1 = sampleEntries(current.owners, observeBorrows);
2939
+ observedMounts = current.reconciliation.observations();
2940
+ commitSamples(snapshot$1);
2941
+ releaseRemovedCallbacks(current.snapshot, snapshot$1);
2942
+ current = {
2943
+ ...current,
2944
+ snapshot: snapshot$1
2945
+ };
2946
+ publishChange();
2947
+ }
2948
+ if (needsReconciliation()) return current?.snapshot;
2949
+ if (current === void 0 || !current.owners.some((entry) => entry.live?.version !== entry.version)) return current?.snapshot;
2950
+ if (closing) throw new PluginLifecycleError("admission", "Live Composition is not admitting changes");
2951
+ const snapshot = sampleEntries(current.owners, observeBorrows);
2952
+ commitSamples(snapshot);
2953
+ current = {
2954
+ ...current,
2955
+ snapshot
2956
+ };
2957
+ publishChange();
2958
+ return snapshot;
2959
+ }
2960
+ const reconcile = Effect.suspend(() => {
2961
+ if (closing) return Effect.void;
2962
+ if (roots !== void 0 && needsReconciliation()) return updateInLane(roots);
2963
+ return Effect.try({
2964
+ try: () => {
2965
+ checkpoint();
2966
+ },
2967
+ catch: (cause) => ensureError(cause)
2968
+ });
2969
+ });
2970
+ const flush = Semaphore.withPermit(lane, reconcile).pipe(Effect.ensuring(Effect.sync(publishPendingChange)));
2971
+ yield* Effect.forever(Queue.take(publications).pipe(Effect.andThen(Effect.yieldNow), Effect.andThen(Effect.sync(publishPendingChange)))).pipe(Effect.forkScoped);
2972
+ yield* Effect.forever(Queue.take(changes).pipe(Effect.andThen(Effect.yieldNow), Effect.andThen(flush), Effect.catch((error) => options.onFailure?.(error) ?? Effect.void))).pipe(Effect.forkScoped);
2973
+ const stop = Effect.gen(function* () {
2974
+ closing = true;
2975
+ publishHealth();
2976
+ yield* objects.stop;
2977
+ if (current !== void 0) yield* Scope.close(current.admissionScope, Exit.void);
2978
+ const preparing = yield* Ref.get(pending);
2979
+ if (preparing !== void 0) yield* preparing.stop;
2980
+ });
2981
+ return {
2982
+ scope,
2983
+ lane,
2984
+ checkpoint,
2985
+ close: Effect.gen(function* () {
2986
+ closing = true;
2987
+ yield* objects.close;
2988
+ if (current !== void 0) yield* Scope.close(current.admissionScope, Exit.void);
2989
+ const preparing = yield* Ref.get(pending);
2990
+ if (preparing !== void 0) yield* preparing.stop;
2991
+ yield* Effect.forEach(current?.owners ?? [], (entry) => entry.owner.fence);
2992
+ yield* retire([...new Set([...current?.owners ?? [], ...retiringEntries])]);
2993
+ yield* FiberSet.awaitEmpty(retirements);
2994
+ if ([...residents].some((owner) => owner.snapshot().residualResources)) return yield* Effect.fail(new PluginLifecycleError("cleanup", "Live Composition retains poisoned residency"));
2995
+ }).pipe(Effect.ensuring(Effect.sync(publishChange))),
2996
+ stop,
2997
+ flush,
2998
+ detachObservation: () => {
2999
+ observationDetached = true;
3000
+ publishHealth();
3001
+ },
3002
+ objects,
3003
+ update: (members) => Semaphore.withPermit(lane, updateInLane(members)),
3004
+ snapshot: () => current?.snapshot,
3005
+ status: () => ({
3006
+ objects: objects.status(),
3007
+ observation: health(),
3008
+ activations: [...residents].map((owner) => owner.snapshot()),
3009
+ mounts: structuredClone(current?.reconciliation.observations() ?? []),
3010
+ serviceConflicts: structuredClone(current?.reconciliation.conflicts() ?? [])
3011
+ })
3012
+ };
3013
+ });
3014
+ function sampleEntries(entries, borrowed) {
3015
+ const unavailable = /* @__PURE__ */ new Set();
3016
+ const exclude = (entry) => {
3017
+ if (unavailable.has(entry)) return;
3018
+ unavailable.add(entry);
3019
+ for (const child of entry.ownedChildren) exclude(child);
3020
+ for (const consumer of entry.consumers) exclude(consumer);
3021
+ };
3022
+ for (const entry of entries) if (entry.failure !== void 0) exclude(entry);
3023
+ return {
3024
+ samples: entries.filter((entry) => !unavailable.has(entry)).map((entry) => {
3025
+ const source = entry.live === void 0 || entry.live.version === entry.version ? void 0 : entry.live.snapshot();
3026
+ return {
3027
+ entry,
3028
+ version: entry.live?.version,
3029
+ contributions: source === void 0 ? entry.contributions : capturePluginContributions(source, entry.contributions),
3030
+ behaviorRegistrations: source === void 0 ? entry.behaviorRegistrations : [...source.sessionBehaviors ?? []]
3031
+ };
3032
+ }),
3033
+ borrow: Effect.fn("LiveComposition.borrow")(function* (owners) {
3034
+ const retained = /* @__PURE__ */ new Set();
3035
+ const include = (entry) => {
3036
+ if (retained.has(entry)) return;
3037
+ retained.add(entry);
3038
+ if (entry.parent !== void 0) include(entry.parent);
3039
+ for (const binding of entry.bindings) include(binding.provider);
3040
+ };
3041
+ for (const entry of owners) include(entry);
3042
+ for (const entry of retained) if (!entry.owner.canBorrow()) return yield* Effect.fail(new PluginLifecycleError("admission", "Plugin no longer accepts new borrows"));
3043
+ const drained = yield* Deferred.make();
3044
+ for (const entry of retained) entry.drains.add(drained);
3045
+ if (retained.size > 0) borrowed(retained.size);
3046
+ return Effect.sync(() => {
3047
+ let released = 0;
3048
+ for (const entry of retained) if (entry.drains.delete(drained)) released += 1;
3049
+ if (released > 0) borrowed(-released);
3050
+ }).pipe(Effect.andThen(Deferred.succeed(drained, void 0)));
3051
+ })
3052
+ };
3053
+ }
3054
+ function commitSamples(samples) {
3055
+ for (const sample of samples.samples) {
3056
+ const release = retainPluginCallbacks(sample.contributions);
3057
+ sample.entry.releaseCallbacks?.();
3058
+ sample.entry.releaseCallbacks = release;
3059
+ sample.entry.version = sample.version;
3060
+ sample.entry.contributions = sample.contributions;
3061
+ sample.entry.behaviorRegistrations = sample.behaviorRegistrations;
3062
+ }
3063
+ }
3064
+ function releaseRemovedCallbacks(before, after) {
3065
+ const retained = new Set(after.samples.map((sample) => sample.entry));
3066
+ for (const sample of before?.samples ?? []) {
3067
+ if (retained.has(sample.entry)) continue;
3068
+ sample.entry.releaseCallbacks?.();
3069
+ sample.entry.releaseCallbacks = void 0;
3070
+ }
3071
+ }
3072
+
3073
+ //#endregion
3074
+ //#region src/composition/programmatic.ts
3075
+ const ActivationServiceKeys = new Set([Scope.Scope.key, Layer.CurrentMemoMap.key]);
3076
+ const DefinitionSchema = s.obj({
3077
+ apply: s.unknown(),
3078
+ requires: s.opt(s.arr(s.unknown())),
3079
+ provides: s.opt(s.arr(s.unknown())),
3080
+ realm: s.opt(s.oneOf(["inherit", "isolate"])),
3081
+ replacement: s.opt(s.oneOf(["staged", "exclusive"]))
3082
+ }, { open: true });
3083
+ const EntrySchema = s.obj({
3084
+ key: s.str({
3085
+ minLength: 1,
3086
+ maxLength: 200
3087
+ }),
3088
+ apply: s.unknown(),
3089
+ config: JsonValueSchema
3090
+ }, { open: false });
3091
+ function captureDefinition(input) {
3092
+ if (isFunction(input)) return {
3093
+ apply: decodeCallback(input),
3094
+ requires: [],
3095
+ provides: [],
3096
+ realm: void 0,
3097
+ replacement: void 0
3098
+ };
3099
+ const definition = decode(DefinitionSchema, input);
3100
+ const apply = decodeCallback(definition.apply);
3101
+ const declarations = {
3102
+ requires: definition.requires ?? [],
3103
+ provides: definition.provides ?? []
3104
+ };
3105
+ const validated = {
3106
+ requires: [],
3107
+ provides: []
3108
+ };
3109
+ for (const name of ["requires", "provides"]) {
3110
+ const services = declarations[name];
3111
+ for (const service of services) {
3112
+ if (!Context.isKey(service)) throw new TypeError("Plugin Service declarations must contain Effect Context keys");
3113
+ validated[name].push(service);
3114
+ const key = decode(s.str({ minLength: 1 }), service.key);
3115
+ if (ActivationServiceKeys.has(key)) throw new TypeError("Plugin Scope and Layer memoization are supplied by its Activation");
3116
+ }
3117
+ }
3118
+ return {
3119
+ apply,
3120
+ requires: [...new Set(validated.requires)],
3121
+ provides: [...new Set(validated.provides)],
3122
+ realm: definition.realm,
3123
+ replacement: definition.replacement
3124
+ };
3125
+ }
3126
+ /** Boundary decoder for the public const-tuple API. */
3127
+ function captureProgrammaticEntries(entries) {
3128
+ const keys = /* @__PURE__ */ new Set();
3129
+ return entries.map((input) => {
3130
+ const entry = decode(EntrySchema, input);
3131
+ if (keys.has(entry.key)) throw new TypeError(`Duplicate Plugin entry key: ${entry.key}`);
3132
+ keys.add(entry.key);
3133
+ const { apply, requires, provides, realm, replacement } = captureDefinition(entry.apply);
3134
+ const config = captureJsonValue(entry.config);
3135
+ if (!isEqual(entry.config, config)) throw new TypeError(`Plugin ${entry.key} config must be lossless JSON data`);
3136
+ const component = contextComponent([entry.key], apply, config);
3137
+ return {
3138
+ key: entry.key,
3139
+ apply,
3140
+ requires,
3141
+ provides,
3142
+ realm,
3143
+ replacement,
3144
+ config,
3145
+ component
3146
+ };
3147
+ });
3148
+ }
3149
+ function contextComponent(path, apply, config, options = {}) {
3150
+ return {
3151
+ componentId: path.join("/"),
3152
+ executionProfile: apply.executionProfile,
3153
+ activate: async ({ activationId, observation, sessions, objects, lifetime: ownerLifetime, services = Context.makeUnsafe(/* @__PURE__ */ new Map()) }) => {
3154
+ const lifetime = options.lifetime?.(ownerLifetime) ?? ownerLifetime;
3155
+ const policy = options.capturePolicy?.(path);
3156
+ const provided = /* @__PURE__ */ new Map();
3157
+ const children = /* @__PURE__ */ new Map();
3158
+ const listeners = /* @__PURE__ */ new Set();
3159
+ let version = 0;
3160
+ const changed = () => {
3161
+ version += 1;
3162
+ for (const listener of listeners) listener();
3163
+ };
3164
+ const mount = (key, childApply, childConfig) => {
3165
+ decode(s.str({
3166
+ minLength: 1,
3167
+ maxLength: 200
3168
+ }), key);
3169
+ if (children.has(key)) throw new TypeError(`Duplicate child Plugin key: ${key}`);
3170
+ const { apply: capturedApply, requires: childRequires, provides: childProvides, realm, replacement } = captureDefinition(childApply);
3171
+ let capturedConfig = decodeChildConfig(childConfig);
3172
+ let generation = 0;
3173
+ let status = {
3174
+ path: [...path, key],
3175
+ phase: "pending"
3176
+ };
3177
+ const reportFor = (expected) => (next) => {
3178
+ if (expected === generation) status = structuredClone(next);
3179
+ };
3180
+ let child = {
3181
+ report: reportFor(generation),
3182
+ key,
3183
+ requires: childRequires,
3184
+ provides: childProvides,
3185
+ realm,
3186
+ replacement,
3187
+ component: contextComponent([...path, key], capturedApply, capturedConfig, options)
3188
+ };
3189
+ children.set(key, child);
3190
+ changed();
3191
+ return {
3192
+ status: () => structuredClone(status),
3193
+ update: (nextConfig) => {
3194
+ policy?.assertRegistration?.();
3195
+ lifetime.signal.throwIfAborted();
3196
+ if (children.get(key) !== child) throw new Error(`Child Plugin ${key} was removed`);
3197
+ const next = decodeChildConfig(nextConfig);
3198
+ if (isEqual(capturedConfig, next)) return;
3199
+ capturedConfig = next;
3200
+ generation += 1;
3201
+ status = {
3202
+ path: [...path, key],
3203
+ phase: "pending"
3204
+ };
3205
+ child = {
3206
+ report: reportFor(generation),
3207
+ key,
3208
+ requires: childRequires,
3209
+ provides: childProvides,
3210
+ realm,
3211
+ replacement,
3212
+ component: contextComponent([...path, key], capturedApply, next, options)
3213
+ };
3214
+ children.set(key, child);
3215
+ changed();
3216
+ },
3217
+ dispose: () => {
3218
+ if (children.get(key) !== child || lifetime.signal.aborted) return;
3219
+ generation += 1;
3220
+ status = {
3221
+ path: [...path, key],
3222
+ phase: "removed"
3223
+ };
3224
+ children.delete(key);
3225
+ changed();
3226
+ }
3227
+ };
3228
+ };
3229
+ const close = () => {
3230
+ listeners.clear();
3231
+ for (const child of children.values()) child.report?.({
3232
+ path: [...path, child.key],
3233
+ phase: "removed"
3234
+ });
3235
+ children.clear();
3236
+ provided.clear();
3237
+ };
3238
+ const provide = (service, value) => {
3239
+ if (!Context.isKey(service)) throw new TypeError("Plugin provide requires an Effect Context key");
3240
+ const key = decode(s.str({ minLength: 1 }), service.key);
3241
+ if (ActivationServiceKeys.has(key)) throw new TypeError("Plugin Scope and Layer memoization are supplied by its Activation");
3242
+ if (provided.has(key)) throw new TypeError(`Duplicate Plugin Service: ${service.key}`);
3243
+ const registration = {
3244
+ key,
3245
+ context: Context.make(service, value)
3246
+ };
3247
+ provided.set(key, registration);
3248
+ changed();
3249
+ return { dispose: () => {
3250
+ if (lifetime.signal.aborted || provided.get(key) !== registration) return;
3251
+ provided.delete(key);
3252
+ changed();
3253
+ } };
3254
+ };
3255
+ const registry = createPluginContext(path, lifetime, {
3256
+ ...policy,
3257
+ mount,
3258
+ provide,
3259
+ close,
3260
+ activationId,
3261
+ observation,
3262
+ sessions,
3263
+ objects
3264
+ }, ownerLifetime.addFinalizer);
3265
+ try {
3266
+ const result = apply(registry.context, structuredClone(config));
3267
+ await runPluginApply(Effect.isEffect(result) ? Effect.provideContext(result, services) : result, lifetime);
3268
+ } catch (error) {
3269
+ registry.seal();
3270
+ throw error;
3271
+ }
3272
+ return {
3273
+ ...registry.contributions,
3274
+ live: registry.live,
3275
+ assertReady: options.assertReady,
3276
+ services: {
3277
+ get version() {
3278
+ return version;
3279
+ },
3280
+ snapshot: () => [...provided.values()],
3281
+ subscribe: (listener) => {
3282
+ listeners.add(listener);
3283
+ return () => {
3284
+ listeners.delete(listener);
3285
+ };
3286
+ }
3287
+ },
3288
+ children: {
3289
+ get version() {
3290
+ return version;
3291
+ },
3292
+ snapshot: () => [...children.values()],
3293
+ subscribe: (listener) => {
3294
+ listeners.add(listener);
3295
+ return () => {
3296
+ listeners.delete(listener);
3297
+ };
3298
+ }
3299
+ }
3300
+ };
3301
+ }
3302
+ };
3303
+ }
3304
+ /** JSON boundary for runtime child configuration, matching Host configure capture. */
3305
+ function decodeChildConfig(input) {
3306
+ const config = captureJsonValue(decode(JsonValueSchema, input));
3307
+ if (!isEqual(input, config)) throw new TypeError("Child Plugin config must be lossless JSON data");
3308
+ return config;
3309
+ }
3310
+
3311
+ //#endregion
3312
+ //#region src/package/config.ts
3313
+ const MAX_CONFIG_BYTES = 65536;
3314
+ const PropertyName = s.str({ pattern: `^(?!(?:${[
3315
+ "__proto__",
3316
+ "constructor",
3317
+ "prototype",
3318
+ "__defineGetter__",
3319
+ "__defineSetter__",
3320
+ "__lookupGetter__",
3321
+ "__lookupSetter__",
3322
+ "hasOwnProperty",
3323
+ "isPrototypeOf",
3324
+ "propertyIsEnumerable",
3325
+ "toLocaleString",
3326
+ "toString",
3327
+ "valueOf"
3328
+ ].join("|")})$)[A-Za-z_][A-Za-z0-9_.-]{0,127}$` });
3329
+ const Annotations = {
3330
+ title: s.opt(s.str({ maxLength: 200 })),
3331
+ description: s.opt(s.str({ maxLength: 2e3 })),
3332
+ default: s.opt(JsonValueSchema),
3333
+ enum: s.opt(s.arr(JsonValueSchema, {
3334
+ minItems: 1,
3335
+ uniqueItems: true
3336
+ }))
3337
+ };
3338
+ const Size = s.int({ minimum: 0 });
3339
+ const ConfigReference = { $ref: "urn:sorbet:plugin-config" };
3340
+ const ConfigSchema = {
3341
+ $id: "urn:sorbet:plugin-config",
3342
+ ...s.union([
3343
+ s.obj({
3344
+ ...Annotations,
3345
+ type: s.lit("string"),
3346
+ minLength: s.opt(Size),
3347
+ maxLength: s.opt(Size)
3348
+ }, { open: false }),
3349
+ s.obj({
3350
+ ...Annotations,
3351
+ type: s.union([s.lit("number"), s.lit("integer")]),
3352
+ minimum: s.opt(s.num()),
3353
+ maximum: s.opt(s.num())
3354
+ }, { open: false }),
3355
+ s.obj({
3356
+ ...Annotations,
3357
+ type: s.union([s.lit("boolean"), s.lit("null")])
3358
+ }, { open: false }),
3359
+ s.obj({
3360
+ ...Annotations,
3361
+ type: s.lit("array"),
3362
+ items: ConfigReference,
3363
+ minItems: s.opt(Size),
3364
+ maxItems: s.opt(Size)
3365
+ }, { open: false }),
3366
+ s.obj({
3367
+ ...Annotations,
3368
+ type: s.lit("object"),
3369
+ properties: {
3370
+ ...s.map(ConfigReference),
3371
+ propertyNames: PropertyName
3372
+ },
3373
+ required: s.opt(s.arr(PropertyName, { uniqueItems: true })),
3374
+ additionalProperties: s.lit(false)
3375
+ }, { open: false })
3376
+ ])
3377
+ };
3378
+ var PluginConfigError = class extends Error {
3379
+ constructor(code) {
3380
+ super(`Plugin configuration: ${code}`);
3381
+ this.code = code;
3382
+ this.name = "PluginConfigError";
3383
+ }
3384
+ };
3385
+ /** Data-only schema profile. No external references, custom validators, or executable defaults. */
3386
+ function validatePluginConfigSchema(input) {
3387
+ if (!check(ConfigSchema, input)) throw new PluginConfigError("invalid-schema");
3388
+ const encoded = JSON.stringify(input);
3389
+ if (encoded === void 0 || new TextEncoder().encode(encoded).byteLength > 262144) throw new PluginConfigError("invalid-schema");
3390
+ const schema = decode(ConfigSchema, JSON.parse(encoded));
3391
+ const pending = [schema];
3392
+ for (const current of pending) {
3393
+ switch (current.type) {
3394
+ case "number":
3395
+ case "integer":
3396
+ if ((current.minimum ?? -Infinity) > (current.maximum ?? Infinity)) throw new PluginConfigError("invalid-schema");
3397
+ break;
3398
+ }
3399
+ if (current.type === "string" && (current.minLength ?? 0) > (current.maxLength ?? Infinity)) throw new PluginConfigError("invalid-schema");
3400
+ if (current.type === "array" && (current.minItems ?? 0) > (current.maxItems ?? Infinity)) throw new PluginConfigError("invalid-schema");
3401
+ if (current.type === "object") {
3402
+ const properties = new Set(Object.keys(current.properties));
3403
+ for (const name of current.required ?? []) if (!properties.has(name)) throw new PluginConfigError("invalid-schema");
3404
+ pending.push(...Object.values(current.properties));
3405
+ }
3406
+ if (current.type === "array") pending.push(current.items);
3407
+ }
3408
+ for (const current of pending) {
3409
+ if (current.enum !== void 0) {
3410
+ const { enum: values,...valueSchema } = current;
3411
+ if (values.some((value) => !check(valueSchema, value))) throw new PluginConfigError("invalid-schema");
3412
+ }
3413
+ if (current.default !== void 0) {
3414
+ if (new TextEncoder().encode(JSON.stringify(current.default)).byteLength > MAX_CONFIG_BYTES) throw new PluginConfigError("invalid-default");
3415
+ const value = boundedConfigDefaults(current);
3416
+ const serialized = JSON.stringify(value);
3417
+ if (!check(current, value) || serialized === void 0 || new TextEncoder().encode(serialized).byteLength > MAX_CONFIG_BYTES) throw new PluginConfigError("invalid-default");
3418
+ }
3419
+ }
3420
+ return schema;
3421
+ }
3422
+ /**
3423
+ * Applies only declared defaults to a detached JSON snapshot; never coerces or removes
3424
+ * input fields. Missing objects are not invented. Explicit null is not absence.
3425
+ * Returns deterministic data for admission and recovery without invoking author code.
3426
+ */
3427
+ function materializePluginConfig(schema, input) {
3428
+ const capturedSchema = validatePluginConfigSchema(schema);
3429
+ if (input !== void 0 && !check(JsonValueSchema, input)) throw new PluginConfigError("invalid-config");
3430
+ const serialized = input === void 0 ? void 0 : JSON.stringify(input);
3431
+ if (serialized !== void 0 && new TextEncoder().encode(serialized).byteLength > MAX_CONFIG_BYTES) throw new PluginConfigError("invalid-config");
3432
+ const result = boundedConfigDefaults(capturedSchema, serialized === void 0 ? void 0 : decode(JsonValueSchema, JSON.parse(serialized)));
3433
+ if (!check(capturedSchema, result) || !check(JsonValueSchema, result)) throw new PluginConfigError("invalid-config");
3434
+ const encoded = JSON.stringify(result);
3435
+ if (encoded === void 0 || new TextEncoder().encode(encoded).byteLength > MAX_CONFIG_BYTES) throw new PluginConfigError("invalid-config");
3436
+ return decode(JsonValueSchema, JSON.parse(encoded));
3437
+ }
3438
+ function boundedConfigDefaults(schema, input) {
3439
+ let bytes = input === void 0 ? 0 : new TextEncoder().encode(JSON.stringify(input)).byteLength;
3440
+ const apply = (current, value, propertyBytes = 0) => {
3441
+ if (value === void 0 && current.default !== void 0) {
3442
+ bytes += new TextEncoder().encode(JSON.stringify(current.default)).byteLength + propertyBytes;
3443
+ if (bytes > MAX_CONFIG_BYTES) throw new PluginConfigError("expansion-limit");
3444
+ value = decode(JsonValueSchema, structuredClone(current.default));
3445
+ }
3446
+ if (current.type === "array" && check(s.arr(JsonValueSchema), value)) return value.map((item) => apply(current.items, item) ?? item);
3447
+ if (current.type === "object" && check(s.map(JsonValueSchema), value)) for (const [name, child] of Object.entries(current.properties)) {
3448
+ const next = apply(child, value[name], JSON.stringify(name).length + 2);
3449
+ if (next !== void 0) value[name] = next;
3450
+ }
3451
+ return value;
3452
+ };
3453
+ return apply(schema, input);
3454
+ }
3455
+
3456
+ //#endregion
3457
+ //#region src/package/identity.ts
3458
+ const PluginPackageIdSchema = s.str({ minLength: 1 });
3459
+
3460
+ //#endregion
3461
+ //#region src/package/format.ts
3462
+ const MAX_PLUGIN_PACKAGE_BYTES = 16 * 1024 * 1024;
3463
+ const NativePluginPackageAbiSchema = s.union([s.lit("sorbet.context-plugin/v1"), s.lit("sorbet.tool-component/v1")]);
3464
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
3465
+ const MAX_CONTENT_BYTES = 8 * 1024 * 1024;
3466
+ const Segment = "[A-Za-z0-9_-](?:[A-Za-z0-9._-]*[A-Za-z0-9_-])?";
3467
+ const PackagePath = s.str({
3468
+ pattern: `^(?:${Segment}/)*${Segment}$`,
3469
+ maxLength: 240
3470
+ });
3471
+ const Identity$2 = s.str({
3472
+ minLength: 1,
3473
+ maxLength: 200
3474
+ });
3475
+ const PluginPackageDocumentProperties = {
3476
+ formatVersion: s.lit(1),
3477
+ manifest: s.obj({
3478
+ name: Identity$2,
3479
+ version: Identity$2,
3480
+ abi: Identity$2,
3481
+ componentId: Identity$2,
3482
+ entrypoint: PackagePath,
3483
+ configSchema: ConfigSchema
3484
+ }, { open: false }),
3485
+ files: s.arr(s.obj({
3486
+ path: PackagePath,
3487
+ content: s.str()
3488
+ }, { open: false }), { minItems: 1 })
3489
+ };
3490
+ const PluginPackageDocumentSchema = s.obj(PluginPackageDocumentProperties, { open: false });
3491
+ var PluginPackageFormatError = class extends Error {
3492
+ /** `quota` reports a bounded Host resource limit, `format` reports the package bytes themselves. */
3493
+ constructor(message, code = "format") {
3494
+ super(message);
3495
+ this.code = code;
3496
+ this.name = "PluginPackageFormatError";
3497
+ }
3498
+ };
3499
+ /** Creates an installation identity and its UTF-8 container without evaluating code. */
3500
+ async function encodePluginPackage(input) {
3501
+ const document = normalizePackage(input);
3502
+ const text = JSON.stringify(document);
3503
+ if (text === void 0) throw new PluginPackageFormatError("Package cannot be serialized");
3504
+ const bytes = new TextEncoder().encode(text);
3505
+ if (bytes.byteLength > MAX_PLUGIN_PACKAGE_BYTES) throw new PluginPackageFormatError("Package exceeds its encoded byte limit", "quota");
3506
+ return {
3507
+ packageId: crypto.randomUUID(),
3508
+ bytes
3509
+ };
3510
+ }
3511
+ /** Decodes the package representation and its supported module/configuration profile. */
3512
+ async function decodePluginPackage(input) {
3513
+ if (input.bytes.byteLength > MAX_PLUGIN_PACKAGE_BYTES) throw new PluginPackageFormatError("Package exceeds its encoded byte limit", "quota");
3514
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(input.bytes);
3515
+ return normalizePackage(JSON.parse(text));
3516
+ }
3517
+ function normalizePackage(input) {
3518
+ const document = decode(PluginPackageDocumentSchema, input);
3519
+ const paths = /* @__PURE__ */ new Set();
3520
+ const spellings = /* @__PURE__ */ new Map();
3521
+ let contentBytes = 0;
3522
+ for (const file of document.files) {
3523
+ if (paths.has(file.path)) throw new PluginPackageFormatError("Duplicate Package file");
3524
+ paths.add(file.path);
3525
+ const segments = file.path.split("/");
3526
+ for (let index = 0; index < segments.length; index += 1) {
3527
+ const prefix = segments.slice(0, index + 1).join("/");
3528
+ const folded = prefix.toLowerCase();
3529
+ if ((spellings.get(folded) ?? prefix) !== prefix) throw new PluginPackageFormatError("Case-conflicting Package paths");
3530
+ if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(segments[index] ?? "")) throw new PluginPackageFormatError("Reserved Package path segment");
3531
+ spellings.set(folded, prefix);
3532
+ }
3533
+ const encoded = new TextEncoder().encode(file.content);
3534
+ if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(encoded) !== file.content) throw new PluginPackageFormatError("Package content contains an unpaired surrogate");
3535
+ const length = encoded.byteLength;
3536
+ if (length > MAX_FILE_BYTES) throw new PluginPackageFormatError("Package file exceeds its byte limit", "quota");
3537
+ contentBytes += length;
3538
+ if (contentBytes > MAX_CONTENT_BYTES) throw new PluginPackageFormatError("Package content exceeds its byte limit", "quota");
3539
+ }
3540
+ for (const path of paths) {
3541
+ const segments = path.split("/");
3542
+ for (let index = 1; index < segments.length; index += 1) if (paths.has(segments.slice(0, index).join("/"))) throw new PluginPackageFormatError("Package file conflicts with a directory");
3543
+ }
3544
+ if (!paths.has(document.manifest.entrypoint)) throw new PluginPackageFormatError("Package entrypoint is missing");
3545
+ return {
3546
+ formatVersion: 1,
3547
+ manifest: {
3548
+ ...document.manifest,
3549
+ configSchema: validatePluginConfigSchema(document.manifest.configSchema)
3550
+ },
3551
+ files: sortBy(document.files, ["path"]).map((file) => ({ ...file }))
3552
+ };
3553
+ }
3554
+
3555
+ //#endregion
3556
+ //#region src/package/modules.ts
3557
+ const EffectEntrySchema = s.oneOf(["effect", "effect/http"]);
3558
+ var PluginModuleError = class extends Error {
3559
+ constructor(code, modulePath) {
3560
+ super(`Plugin module ${modulePath}: ${code}`);
3561
+ this.code = code;
3562
+ this.modulePath = modulePath;
3563
+ this.name = "PluginModuleError";
3564
+ }
3565
+ };
3566
+ /**
3567
+ * Inspects the decoded package without evaluating code or resolving Host paths.
3568
+ * The result describes explicit ESM imports for managed module resolution.
3569
+ */
3570
+ async function inspectPluginModules(input, document) {
3571
+ const packageId = input.packageId;
3572
+ document ??= await decodePluginPackage(input);
3573
+ if (!check(NativePluginPackageAbiSchema, document.manifest.abi)) throw new PluginModuleError("unsupported-module", document.manifest.entrypoint);
3574
+ const files = new Map(document.files.map((file) => [file.path, file.content]));
3575
+ const pending = new Set([document.manifest.entrypoint]);
3576
+ const modules = [];
3577
+ for (const path of pending) {
3578
+ if (!/\.m?js$/.test(path)) throw new PluginModuleError("unsupported-module", path);
3579
+ const source = files.get(path);
3580
+ if (source === void 0) throw new PluginModuleError("missing-module", path);
3581
+ let program;
3582
+ try {
3583
+ program = parse(source, {
3584
+ ecmaVersion: 2022,
3585
+ sourceType: "module"
3586
+ });
3587
+ } catch {
3588
+ throw new PluginModuleError("invalid-syntax", path);
3589
+ }
3590
+ const imports = [];
3591
+ let hasDefault = false;
3592
+ const addImport = (literal, kind) => {
3593
+ const specifier = literal.value;
3594
+ if (!check(s.str(), specifier)) throw new PluginModuleError("unsupported-import", path);
3595
+ if (document.manifest.abi === "sorbet.context-plugin/v1" && (check(EffectEntrySchema, specifier) || /^effect\/[A-Z][A-Za-z0-9]*$/.test(specifier) && Object.keys(EffectNamespaces).includes(specifier.slice(7)))) {
3596
+ imports.push({
3597
+ specifier,
3598
+ target: specifier,
3599
+ kind
3600
+ });
3601
+ return;
3602
+ }
3603
+ const target = resolveModuleSpecifier(path, specifier);
3604
+ imports.push({
3605
+ specifier,
3606
+ target,
3607
+ kind
3608
+ });
3609
+ pending.add(target);
3610
+ };
3611
+ simple(program, {
3612
+ ImportDeclaration(node) {
3613
+ addImport(node.source, "static");
3614
+ },
3615
+ ExportNamedDeclaration(node) {
3616
+ if (node.source) addImport(node.source, "static");
3617
+ hasDefault ||= node.specifiers.some((specifier) => specifier.exported.type === "Identifier" ? specifier.exported.name === "default" : specifier.exported.value === "default");
3618
+ },
3619
+ ExportAllDeclaration(node) {
3620
+ addImport(node.source, "static");
3621
+ if (node.exported?.type === "Identifier") hasDefault ||= node.exported.name === "default";
3622
+ if (node.exported?.type === "Literal") hasDefault ||= node.exported.value === "default";
3623
+ },
3624
+ ExportDefaultDeclaration() {
3625
+ hasDefault = true;
3626
+ },
3627
+ ImportExpression(node) {
3628
+ if (node.source.type !== "Literal") throw new PluginModuleError("unsupported-import", path);
3629
+ addImport(node.source, "dynamic");
3630
+ },
3631
+ MetaProperty(node) {
3632
+ if (node.meta.name === "import") throw new PluginModuleError("unsupported-import", path);
3633
+ }
3634
+ });
3635
+ if (path === document.manifest.entrypoint && !hasDefault) throw new PluginModuleError("missing-default-export", path);
3636
+ modules.push({
3637
+ path,
3638
+ imports
3639
+ });
3640
+ }
3641
+ return {
3642
+ packageId,
3643
+ profile: "sorbet.esm2022/v1",
3644
+ entrypoint: document.manifest.entrypoint,
3645
+ modules: sortBy(modules, ["path"])
3646
+ };
3647
+ }
3648
+ function resolveModuleSpecifier(importer, specifier) {
3649
+ if (!/^\.{1,2}\/[A-Za-z0-9_./-]+$/.test(specifier)) throw new PluginModuleError("unsupported-import", importer);
3650
+ const segments = importer.split("/").slice(0, -1);
3651
+ for (const segment of specifier.split("/")) {
3652
+ if (segment === ".") continue;
3653
+ if (segment === "..") {
3654
+ if (segments.length === 0) throw new PluginModuleError("unsupported-import", importer);
3655
+ segments.pop();
3656
+ } else {
3657
+ if (segment.length === 0) throw new PluginModuleError("unsupported-import", importer);
3658
+ segments.push(segment);
3659
+ }
3660
+ }
3661
+ return segments.join("/");
3662
+ }
3663
+
3664
+ //#endregion
3665
+ //#region src/authority/desired.ts
3666
+ const Identity$1 = s.str({
3667
+ minLength: 1,
3668
+ maxLength: 200
3669
+ });
3670
+ const Position = {
3671
+ parentId: s.union([Identity$1, s.nul()]),
3672
+ order: s.int({
3673
+ minimum: 0,
3674
+ maximum: Number.MAX_SAFE_INTEGER
3675
+ })
3676
+ };
3677
+ const AuthoredPluginEntrySchema = s.obj({
3678
+ entryId: Identity$1,
3679
+ packageId: PluginPackageIdSchema,
3680
+ ...Position,
3681
+ enabled: s.bool(),
3682
+ config: s.opt(JsonValueSchema)
3683
+ }, { open: false });
3684
+ const CompositionMutationSchema = s.union([
3685
+ s.obj({
3686
+ kind: s.lit("add"),
3687
+ entry: AuthoredPluginEntrySchema
3688
+ }, { open: false }),
3689
+ s.obj({
3690
+ kind: s.lit("configure"),
3691
+ entryId: Identity$1,
3692
+ config: s.opt(JsonValueSchema)
3693
+ }, { open: false }),
3694
+ s.obj({
3695
+ kind: s.lit("replace"),
3696
+ entryId: Identity$1,
3697
+ packageId: PluginPackageIdSchema
3698
+ }, { open: false }),
3699
+ s.obj({
3700
+ kind: s.lit("move"),
3701
+ entryId: Identity$1,
3702
+ ...Position
3703
+ }, { open: false }),
3704
+ s.obj({
3705
+ kind: s.lit("set-enabled"),
3706
+ entryId: Identity$1,
3707
+ enabled: s.bool()
3708
+ }, { open: false }),
3709
+ s.obj({
3710
+ kind: s.lit("remove"),
3711
+ entryId: Identity$1
3712
+ }, { open: false })
3713
+ ]);
3714
+ const DesiredPluginPatchSchema = s.obj({
3715
+ commandId: s.str({
3716
+ minLength: 1,
3717
+ maxLength: 180
3718
+ }),
3719
+ baseGeneration: s.int({
3720
+ minimum: 0,
3721
+ maximum: Number.MAX_SAFE_INTEGER
3722
+ }),
3723
+ mutations: s.arr(CompositionMutationSchema, { minItems: 1 })
3724
+ }, { open: false });
3725
+ const AuthoredPluginCompositionSchema = s.obj({
3726
+ sequence: s.int({
3727
+ minimum: 0,
3728
+ maximum: Number.MAX_SAFE_INTEGER
3729
+ }),
3730
+ entries: s.arr(AuthoredPluginEntrySchema)
3731
+ }, { open: false });
3732
+ var PluginCompositionError = class extends Error {
3733
+ constructor(code) {
3734
+ super(`Plugin composition: ${code}`);
3735
+ this.code = code;
3736
+ this.name = "PluginCompositionError";
3737
+ }
3738
+ };
3739
+ /**
3740
+ * Replays detached inputs without IO or author evaluation. Each batch must leave a
3741
+ * valid tree; references/configuration are checked after its last mutation. This
3742
+ * does not register Packages, authorize commands, or publish executable revisions.
3743
+ */
3744
+ async function projectPluginComposition(packages, history) {
3745
+ return (await replayPluginComposition(packages, history)).desired;
3746
+ }
3747
+ var PluginCompositionProjection = class {
3748
+ #authored;
3749
+ #catalog;
3750
+ #desired = {
3751
+ sequence: 0,
3752
+ entries: []
3753
+ };
3754
+ constructor(catalog, previous) {
3755
+ this.#catalog = catalog;
3756
+ this.#authored = new Map(previous === void 0 ? [] : [...previous.#authored].map(([id, entry]) => [id, { ...entry }]));
3757
+ if (previous !== void 0) this.#desired = previous.#desired;
3758
+ }
3759
+ apply(batch) {
3760
+ for (const mutation of batch.mutations) applyMutation(this.#authored, mutation);
3761
+ this.#desired = {
3762
+ sequence: batch.sequence,
3763
+ entries: sortBy(materializeEntries(this.#authored, this.#catalog), ["order", "entryId"])
3764
+ };
3765
+ return this.#desired;
3766
+ }
3767
+ get desired() {
3768
+ return this.#desired;
3769
+ }
3770
+ capture() {
3771
+ return {
3772
+ sequence: this.#desired.sequence,
3773
+ entries: [...this.#authored.values()].map((entry) => ({
3774
+ ...entry,
3775
+ config: entry.config === void 0 ? void 0 : structuredClone(entry.config)
3776
+ }))
3777
+ };
3778
+ }
3779
+ restore(snapshot) {
3780
+ const restored = new Map(snapshot.entries.map((entry) => [entry.entryId, { ...entry }]));
3781
+ if (restored.size !== snapshot.entries.length) throw new PluginCompositionError("duplicate-entry");
3782
+ const entries = sortBy(materializeEntries(restored, this.#catalog), ["order", "entryId"]);
3783
+ this.#authored.clear();
3784
+ for (const [id, entry] of restored) this.#authored.set(id, entry);
3785
+ this.#desired = {
3786
+ sequence: snapshot.sequence,
3787
+ entries
3788
+ };
3789
+ return this.#desired;
3790
+ }
3791
+ };
3792
+ async function replayPluginComposition(packages, history) {
3793
+ const projection = new PluginCompositionProjection(new Map(await Promise.all(packages.map(async (record) => [record.packageId, await decodePluginPackage(record)]))));
3794
+ for (const batch of history) projection.apply(batch);
3795
+ return { desired: projection.desired };
3796
+ }
3797
+ function applyMutation(entries, mutation) {
3798
+ if (mutation.kind === "add") {
3799
+ if (entries.has(mutation.entry.entryId)) throw new PluginCompositionError("duplicate-entry");
3800
+ entries.set(mutation.entry.entryId, { ...mutation.entry });
3801
+ return;
3802
+ }
3803
+ const entry = entries.get(mutation.entryId);
3804
+ if (!entry) throw new PluginCompositionError("missing-entry");
3805
+ switch (mutation.kind) {
3806
+ case "configure":
3807
+ if (mutation.config === void 0) delete entry.config;
3808
+ else entry.config = mutation.config;
3809
+ break;
3810
+ case "replace":
3811
+ entry.packageId = mutation.packageId;
3812
+ break;
3813
+ case "move":
3814
+ entry.parentId = mutation.parentId;
3815
+ entry.order = mutation.order;
3816
+ break;
3817
+ case "set-enabled":
3818
+ entry.enabled = mutation.enabled;
3819
+ break;
3820
+ case "remove":
3821
+ entries.delete(mutation.entryId);
3822
+ break;
3823
+ }
3824
+ }
3825
+ function materializeEntries(authored, catalog) {
3826
+ return [...authored.values()].map((entry) => {
3827
+ const document = catalog.get(entry.packageId);
3828
+ if (!document) throw new PluginCompositionError("missing-package");
3829
+ let effectiveEnabled = entry.enabled;
3830
+ const ancestors = new Set([entry.entryId]);
3831
+ let parentId = entry.parentId;
3832
+ while (parentId !== null) {
3833
+ if (ancestors.has(parentId)) throw new PluginCompositionError("parent-cycle");
3834
+ ancestors.add(parentId);
3835
+ const parent = authored.get(parentId);
3836
+ if (!parent) throw new PluginCompositionError("missing-parent");
3837
+ effectiveEnabled = effectiveEnabled && parent.enabled;
3838
+ parentId = parent.parentId;
3839
+ }
3840
+ return {
3841
+ ...entry,
3842
+ effectiveEnabled,
3843
+ config: materializePluginConfig(document.manifest.configSchema, entry.config)
3844
+ };
3845
+ });
3846
+ }
3847
+
3848
+ //#endregion
3849
+ //#region src/authority/commands.ts
3850
+ const Identity = s.str({
3851
+ minLength: 1,
3852
+ maxLength: 200
3853
+ });
3854
+ const MAX_PLUGIN_AUTHORITY_BYTES = 64 * 1024 * 1024;
3855
+ const MAX_PLUGIN_RETRY_COMMANDS = 64;
3856
+ const Sequence = s.int({
3857
+ minimum: 0,
3858
+ maximum: Number.MAX_SAFE_INTEGER
3859
+ });
3860
+ const PackageDeny = {
3861
+ packageId: PluginPackageIdSchema,
3862
+ issuerId: Identity,
3863
+ reason: s.union([
3864
+ s.lit("operator"),
3865
+ s.lit("policy"),
3866
+ s.lit("compromised")
3867
+ ]),
3868
+ policyVersion: s.lit(1)
3869
+ };
3870
+ const PluginAuthorityCheckpointSchema = s.obj({
3871
+ schemaVersion: s.lit(1),
3872
+ authorityId: Identity,
3873
+ sequence: Sequence,
3874
+ composition: AuthoredPluginCompositionSchema,
3875
+ registrations: s.arr(s.obj({
3876
+ packageId: PluginPackageIdSchema,
3877
+ sourceProfile: Identity,
3878
+ retired: s.bool()
3879
+ }, { open: false })),
3880
+ revocations: s.arr(s.obj(PackageDeny, { open: false }))
3881
+ }, { open: false });
3882
+ const CompositionCommandSchema = s.obj({
3883
+ commandId: Identity,
3884
+ idempotencyKey: Identity,
3885
+ baseSequence: Sequence,
3886
+ action: s.union([
3887
+ s.obj({
3888
+ kind: s.lit("revoke-package"),
3889
+ ...PackageDeny
3890
+ }, { open: false }),
3891
+ s.obj({
3892
+ kind: s.lit("register"),
3893
+ packageId: PluginPackageIdSchema
3894
+ }, { open: false }),
3895
+ s.obj({
3896
+ kind: s.lit("apply"),
3897
+ mutations: s.arr(CompositionMutationSchema, { minItems: 1 })
3898
+ }, { open: false })
3899
+ ])
3900
+ }, { open: false });
3901
+ const Header = {
3902
+ entryId: Identity,
3903
+ authorityId: Identity,
3904
+ commandId: Identity,
3905
+ sequence: Sequence,
3906
+ timestamp: Sequence,
3907
+ schemaVersion: s.lit(2)
3908
+ };
3909
+ const AcceptedSchema = s.obj({
3910
+ ...Header,
3911
+ kind: s.union([
3912
+ s.lit("package.registration.accepted"),
3913
+ s.lit("composition.command.accepted"),
3914
+ s.lit("security.revocation.command.accepted")
3915
+ ]),
3916
+ payload: CompositionCommandSchema
3917
+ }, { open: false });
3918
+ const ResultSchema = s.union([
3919
+ s.obj({
3920
+ ...Header,
3921
+ kind: s.lit("security.revocation.committed"),
3922
+ payload: s.obj(PackageDeny, { open: false })
3923
+ }, { open: false }),
3924
+ s.obj({
3925
+ ...Header,
3926
+ kind: s.lit("package.registered"),
3927
+ payload: s.obj({
3928
+ packageId: PluginPackageIdSchema,
3929
+ sourceProfile: Identity
3930
+ }, { open: false })
3931
+ }, { open: false }),
3932
+ s.obj({
3933
+ ...Header,
3934
+ kind: s.lit("composition.changed"),
3935
+ payload: s.obj({}, { open: false })
3936
+ }, { open: false })
3937
+ ]);
3938
+ const CompositionJournalBatchSchema = s.tuple([AcceptedSchema, ResultSchema]);
3939
+ const AuthorityBatchSchema = CompositionJournalBatchSchema;
3940
+ var PluginAuthorityError = class extends Error {
3941
+ constructor(code) {
3942
+ super(`Plugin authority: ${code}`);
3943
+ this.code = code;
3944
+ this.name = "PluginAuthorityError";
3945
+ }
3946
+ };
3947
+ /** Decodes caller-owned or immutable persisted facts without cloning their data. */
3948
+ function decodeAuthorityBatch(input, authorityId) {
3949
+ try {
3950
+ const batch = decode(AuthorityBatchSchema, input);
3951
+ assertCompositionBatch(batch, authorityId);
3952
+ return batch;
3953
+ } catch {
3954
+ throw new PluginAuthorityError("invalid-data");
3955
+ }
3956
+ }
3957
+ function captureCompositionData(schema, input) {
3958
+ try {
3959
+ return decode(schema, JSON.parse(JSON.stringify(decode(schema, input))));
3960
+ } catch {
3961
+ throw new PluginAuthorityError("invalid-data");
3962
+ }
3963
+ }
3964
+ function assertCompositionBatch(batch, authorityId) {
3965
+ const [accepted, result] = batch;
3966
+ const command = accepted.payload;
3967
+ const action = command.action;
3968
+ if (accepted.authorityId !== authorityId || result.authorityId !== authorityId || accepted.commandId !== command.commandId || result.commandId !== command.commandId || accepted.entryId === result.entryId || accepted.sequence !== command.baseSequence + 1 || result.sequence !== accepted.sequence + 1) throw new PluginAuthorityError("invalid-data");
3969
+ switch (action.kind) {
3970
+ case "register":
3971
+ if (accepted.kind !== "package.registration.accepted" || result.kind !== "package.registered" || result.payload.packageId !== action.packageId) throw new PluginAuthorityError("invalid-data");
3972
+ break;
3973
+ case "apply":
3974
+ if (accepted.kind !== "composition.command.accepted" || result.kind !== "composition.changed") throw new PluginAuthorityError("invalid-data");
3975
+ break;
3976
+ case "revoke-package": {
3977
+ const { kind: _kind,...denial } = action;
3978
+ if (accepted.kind !== "security.revocation.command.accepted" || result.kind !== "security.revocation.committed" || !isEqual(result.payload, denial)) throw new PluginAuthorityError("invalid-data");
3979
+ break;
3980
+ }
3981
+ }
3982
+ }
3983
+
3984
+ //#endregion
3985
+ //#region src/authority/authority.ts
3986
+ const liveAuthorities = /* @__PURE__ */ new WeakSet();
3987
+ const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
3988
+ /** Trusted Host command owner; author evaluation and executable residency belong to the Platform. */
3989
+ var PluginCompositionAuthority = class PluginCompositionAuthority {
3990
+ #observers = /* @__PURE__ */ new Set();
3991
+ #notificationPending = false;
3992
+ /** Coalesced hints, including failed writes and close; reread status in the callback.
3993
+ * Delivery is asynchronous. Unsubscribe suppresses queued delivery; observer throws cannot
3994
+ * change command results. This port owns no executable Plugin or Effect resources. */
3995
+ subscribeInvalidation(observer) {
3996
+ if (this.#closing !== void 0) throw new PluginAuthorityError("closed");
3997
+ this.#observers.add(observer);
3998
+ this.#notifyChanges();
3999
+ return () => {
4000
+ this.#observers.delete(observer);
4001
+ };
4002
+ }
4003
+ #notifyChanges() {
4004
+ if (this.#notificationPending) return;
4005
+ this.#notificationPending = true;
4006
+ queueMicrotask(() => {
4007
+ this.#notificationPending = false;
4008
+ for (const observer of [...this.#observers]) {
4009
+ if (!this.#observers.has(observer)) continue;
4010
+ try {
4011
+ observer();
4012
+ } catch {}
4013
+ }
4014
+ if (this.#closing !== void 0) this.#observers.clear();
4015
+ });
4016
+ }
4017
+ #options;
4018
+ #receipts = [];
4019
+ #commands = /* @__PURE__ */ new Map();
4020
+ #keys = /* @__PURE__ */ new Map();
4021
+ #revocations = /* @__PURE__ */ new Map();
4022
+ #registrations = /* @__PURE__ */ new Map();
4023
+ #retirementCandidates = /* @__PURE__ */ new Set();
4024
+ #head = 0;
4025
+ #checkpointSequence = 0;
4026
+ #metadataBytes = 0;
4027
+ #compositionBytes = new TextEncoder().encode(JSON.stringify({
4028
+ sequence: 0,
4029
+ entries: []
4030
+ })).byteLength;
4031
+ #checkpointHeaderBytes;
4032
+ #receiptBytes = 0;
4033
+ #catalogBytes = 0;
4034
+ #packages = /* @__PURE__ */ new Map();
4035
+ #documents = /* @__PURE__ */ new Map();
4036
+ #composition = new PluginCompositionProjection(this.#documents);
4037
+ #details = /* @__PURE__ */ new Map();
4038
+ #desired;
4039
+ #fence;
4040
+ #pendingDenial;
4041
+ #closing;
4042
+ #lane = Promise.resolve();
4043
+ constructor(options, empty) {
4044
+ const profiles = (options.packageProfiles ?? []).map((profile) => ({
4045
+ abi: profile.abi,
4046
+ sourceProfile: profile.sourceProfile,
4047
+ inspect: profile.inspect.bind(profile)
4048
+ }));
4049
+ const names = /* @__PURE__ */ new Set();
4050
+ for (const profile of profiles) {
4051
+ if (check(NativePluginPackageAbiSchema, profile.abi) || names.has(profile.abi)) throw new TypeError("Duplicate Plugin Package ABI");
4052
+ names.add(profile.abi);
4053
+ }
4054
+ this.#options = {
4055
+ ...options,
4056
+ packageProfiles: profiles
4057
+ };
4058
+ this.#desired = freezeSnapshot(empty);
4059
+ this.#checkpointHeaderBytes = new TextEncoder().encode(JSON.stringify({
4060
+ schemaVersion: 1,
4061
+ authorityId: options.store.authorityId,
4062
+ sequence: Number.MAX_SAFE_INTEGER,
4063
+ composition: null,
4064
+ registrations: [],
4065
+ revocations: []
4066
+ })).byteLength - 4;
4067
+ }
4068
+ static async open(options) {
4069
+ const captured = { ...options };
4070
+ if (liveAuthorities.has(captured.store)) throw new PluginAuthorityError("conflict");
4071
+ liveAuthorities.add(captured.store);
4072
+ try {
4073
+ const authority = new PluginCompositionAuthority(captured, {
4074
+ sequence: 0,
4075
+ entries: []
4076
+ });
4077
+ await authority.#reload();
4078
+ return authority;
4079
+ } catch (error) {
4080
+ liveAuthorities.delete(captured.store);
4081
+ throw error;
4082
+ }
4083
+ }
4084
+ get #sequence() {
4085
+ return this.#head;
4086
+ }
4087
+ /** Shares deeply frozen Desired; a fenced owner must not authorize execution from it. */
4088
+ status() {
4089
+ return {
4090
+ sequence: this.#sequence,
4091
+ desired: this.#desired,
4092
+ fenced: this.#fence !== void 0,
4093
+ closed: this.#closing !== void 0
4094
+ };
4095
+ }
4096
+ /** Shared deeply frozen Package metadata, including the inspected module graph. */
4097
+ packageDetails(packageId) {
4098
+ const details = this.#details.get(packageId);
4099
+ if (details === void 0) throw this.#missingPackage(packageId);
4100
+ return details;
4101
+ }
4102
+ /** Revocation changes admission independently of Desired and executor residency. */
4103
+ async revokePackage(command) {
4104
+ const captured = captureCompositionData(CompositionCommandSchema, command);
4105
+ if (captured.action.kind !== "revoke-package") throw new PluginAuthorityError("invalid-data");
4106
+ const { kind: _kind,...denial } = captured.action;
4107
+ return this.#enqueue(async () => {
4108
+ this.#assertMutable();
4109
+ const previous = this.#checkCommand(captured);
4110
+ if (previous) return previous;
4111
+ await this.#prepareWrite();
4112
+ const batch = this.#batch(captured, {
4113
+ kind: "security.revocation.committed",
4114
+ payload: denial
4115
+ });
4116
+ await this.#append(batch, this.#desired);
4117
+ await this.#maybeCompact();
4118
+ return batch;
4119
+ });
4120
+ }
4121
+ /** Current policy gate for captured code; residency and new loading are checked separately. */
4122
+ assertPackageExecution(packageId) {
4123
+ this.#assertMutable();
4124
+ if (!this.#registrations.has(packageId)) throw new PluginAuthorityError("unregistered-package");
4125
+ if (this.#revocations.has(packageId) || this.#pendingDenial === packageId) throw new PluginAuthorityError("revoked-package");
4126
+ }
4127
+ /** Captures the latest enabled Entry's provenance before suspension, without evaluating author code. */
4128
+ executionReference(entryId) {
4129
+ this.#assertMutable();
4130
+ const entry = this.#desired.entries.find((candidate) => candidate.entryId === entryId);
4131
+ if (!entry?.effectiveEnabled) throw new PluginAuthorityError("disabled-entry");
4132
+ this.assertPackageExecution(entry.packageId);
4133
+ return {
4134
+ schemaVersion: 1,
4135
+ authorityId: this.#options.store.authorityId,
4136
+ compositionSequence: this.#desired.sequence,
4137
+ entryId,
4138
+ packageId: entry.packageId
4139
+ };
4140
+ }
4141
+ /** Resolves current Desired under deny/fence checks; stale references cannot reconstruct historical executors. */
4142
+ async resolveExecution(reference) {
4143
+ this.assertPackageExecution(reference.packageId);
4144
+ if (reference.authorityId !== this.#options.store.authorityId) throw new PluginAuthorityError("invalid-data");
4145
+ const record = this.#packages.get(reference.packageId);
4146
+ if (!record) throw this.#missingPackage(reference.packageId);
4147
+ if (reference.compositionSequence !== this.#desired.sequence) throw new PluginAuthorityError("stale-command");
4148
+ const entry = this.#desired.entries.find((candidate) => candidate.entryId === reference.entryId);
4149
+ if (!entry?.effectiveEnabled) throw new PluginAuthorityError("disabled-entry");
4150
+ if (entry.packageId !== reference.packageId) throw new PluginAuthorityError("invalid-data");
4151
+ return {
4152
+ entry,
4153
+ package: {
4154
+ packageId: record.packageId,
4155
+ bytes: record.bytes.slice()
4156
+ },
4157
+ details: this.packageDetails(record.packageId)
4158
+ };
4159
+ }
4160
+ async register(command, input) {
4161
+ const captured = captureCompositionData(CompositionCommandSchema, command);
4162
+ if (captured.action.kind !== "register" || captured.action.packageId !== input.packageId) throw new PluginAuthorityError("invalid-data");
4163
+ if (input.bytes.byteLength > MAX_PLUGIN_PACKAGE_BYTES) throw new PluginAuthorityError("quota");
4164
+ const record = {
4165
+ packageId: input.packageId,
4166
+ bytes: new Uint8Array(input.bytes)
4167
+ };
4168
+ return this.#enqueue(async () => {
4169
+ this.#assertMutable();
4170
+ if (this.#registrations.get(record.packageId)?.retired) throw new PluginAuthorityError("expired-package");
4171
+ const installed = this.#packages.get(record.packageId);
4172
+ if (installed !== void 0 && !isEqual(installed.bytes, record.bytes)) throw new PluginAuthorityError("conflict");
4173
+ const previous = this.#checkCommand(captured);
4174
+ if (previous) return previous;
4175
+ await this.#prepareWrite();
4176
+ if (this.#registrations.get(record.packageId)?.retired) throw new PluginAuthorityError("expired-package");
4177
+ if (installed === void 0) {
4178
+ if (this.#catalogBytes + record.bytes.byteLength > MAX_CATALOG_BYTES) await this.#compact();
4179
+ if (this.#catalogBytes + record.bytes.byteLength > MAX_CATALOG_BYTES) throw new PluginAuthorityError("quota");
4180
+ }
4181
+ const details = installed === void 0 ? await this.#inspect(record) : this.packageDetails(record.packageId);
4182
+ const batch = this.#batch(captured, {
4183
+ kind: "package.registered",
4184
+ payload: {
4185
+ packageId: record.packageId,
4186
+ sourceProfile: details.sourceProfile
4187
+ }
4188
+ });
4189
+ await this.#append(batch, this.#desired, { package: installed ?? record }, details);
4190
+ await this.#maybeCompact();
4191
+ return batch;
4192
+ });
4193
+ }
4194
+ async apply(command) {
4195
+ const captured = captureCompositionData(CompositionCommandSchema, command);
4196
+ if (captured.action.kind !== "apply") throw new PluginAuthorityError("invalid-data");
4197
+ const { mutations } = captured.action;
4198
+ return this.#enqueue(async () => {
4199
+ this.#assertMutable();
4200
+ const previous = this.#checkCommand(captured);
4201
+ if (previous) return previous;
4202
+ await this.#prepareWrite();
4203
+ return this.#commitDesired(captured, mutations);
4204
+ });
4205
+ }
4206
+ /** Authorizes the materialized target under the authority lane, before writing or loading code.
4207
+ * The authorizer must not issue commands on this authority. Generations track Desired only. */
4208
+ applyDesired(patch, authorize) {
4209
+ const captured = captureCompositionData(DesiredPluginPatchSchema, patch);
4210
+ return this.#enqueue(async () => {
4211
+ this.#assertMutable();
4212
+ const command = {
4213
+ commandId: captured.commandId,
4214
+ idempotencyKey: captured.commandId,
4215
+ baseSequence: this.#sequence,
4216
+ action: {
4217
+ kind: "apply",
4218
+ mutations: captured.mutations
4219
+ }
4220
+ };
4221
+ const previous = this.#checkCommand(command);
4222
+ if (previous) {
4223
+ await authorize(structuredClone(this.#desired));
4224
+ return previous;
4225
+ }
4226
+ if (captured.baseGeneration !== this.#desired.sequence) throw new PluginAuthorityError("stale-command");
4227
+ await this.#prepareWrite();
4228
+ return this.#commitDesired(command, captured.mutations, authorize);
4229
+ });
4230
+ }
4231
+ async #commitDesired(command, mutations, authorize) {
4232
+ for (const mutation of mutations) {
4233
+ const packageId = mutation.kind === "add" ? mutation.entry.packageId : void 0;
4234
+ const replacement = mutation.kind === "replace" ? mutation.packageId : packageId;
4235
+ if (replacement !== void 0 && !this.#packages.has(replacement)) throw this.#missingPackage(replacement);
4236
+ }
4237
+ const projection = new PluginCompositionProjection(this.#documents, this.#composition);
4238
+ const desired = projection.apply({
4239
+ sequence: command.baseSequence + 2,
4240
+ mutations
4241
+ });
4242
+ if (authorize !== void 0) {
4243
+ await authorize(structuredClone(desired));
4244
+ this.#assertMutable();
4245
+ }
4246
+ const batch = this.#batch(command, {
4247
+ kind: "composition.changed",
4248
+ payload: {}
4249
+ });
4250
+ const previous = this.#desired;
4251
+ const authoredBytes = new TextEncoder().encode(JSON.stringify(projection.capture())).byteLength;
4252
+ await this.#append(batch, desired, {}, void 0, authoredBytes);
4253
+ this.#markRetirements(previous, desired);
4254
+ this.#composition = projection;
4255
+ await this.#maybeCompact();
4256
+ return batch;
4257
+ }
4258
+ /** Resolve an uncertain exact write and reload authority; never retries a command or Package put. */
4259
+ recover() {
4260
+ return this.#enqueue(async () => {
4261
+ if (this.#closing !== void 0) throw new PluginAuthorityError("closed");
4262
+ const fence = this.#fence;
4263
+ if (fence?.kind === "journal" && await this.#options.store.reconcile(fence.batch) === "unknown") throw new PluginAuthorityError("fenced");
4264
+ await this.#reload();
4265
+ this.#fence = void 0;
4266
+ });
4267
+ }
4268
+ /** Fences queued commands and waits for the in-flight store call; borrowed stores remain open. */
4269
+ close() {
4270
+ this.#closing ??= this.#lane.then(() => {
4271
+ liveAuthorities.delete(this.#options.store);
4272
+ this.#notifyChanges();
4273
+ });
4274
+ return this.#closing;
4275
+ }
4276
+ #assertMutable() {
4277
+ if (this.#closing !== void 0) throw new PluginAuthorityError("closed");
4278
+ if (this.#fence) throw new PluginAuthorityError("fenced");
4279
+ }
4280
+ #checkCommand(command) {
4281
+ const byId = this.#commands.get(command.commandId);
4282
+ if (byId && byId[0].payload.idempotencyKey !== command.idempotencyKey) throw new PluginAuthorityError("conflict");
4283
+ const existing = this.#keys.get(command.idempotencyKey);
4284
+ if (existing) {
4285
+ if (!isEqual(existing[0].payload.action, command.action)) throw new PluginAuthorityError("conflict");
4286
+ return existing;
4287
+ }
4288
+ if (command.baseSequence !== this.#sequence) throw new PluginAuthorityError("stale-command");
4289
+ }
4290
+ #batch(command, result) {
4291
+ const kind = {
4292
+ register: "package.registration.accepted",
4293
+ apply: "composition.command.accepted",
4294
+ "revoke-package": "security.revocation.command.accepted"
4295
+ }[command.action.kind];
4296
+ const header = {
4297
+ authorityId: this.#options.store.authorityId,
4298
+ commandId: command.commandId,
4299
+ schemaVersion: 2,
4300
+ timestamp: this.#options.now()
4301
+ };
4302
+ return freezeSnapshot(decodeAuthorityBatch([{
4303
+ ...header,
4304
+ entryId: this.#options.createId(),
4305
+ sequence: command.baseSequence + 1,
4306
+ kind,
4307
+ payload: command
4308
+ }, {
4309
+ ...header,
4310
+ entryId: this.#options.createId(),
4311
+ sequence: command.baseSequence + 2,
4312
+ ...result
4313
+ }], this.#options.store.authorityId));
4314
+ }
4315
+ async #append(batch, desired, data = {}, details, compositionBytes = this.#compositionBytes) {
4316
+ const bytes = new TextEncoder().encode(JSON.stringify(batch)).byteLength;
4317
+ const expired = this.#receipts.length === MAX_PLUGIN_RETRY_COMMANDS ? this.#receipts[0]?.bytes ?? 0 : 0;
4318
+ if (this.#receiptBytes - expired + bytes > MAX_PLUGIN_AUTHORITY_BYTES) throw new PluginAuthorityError("quota");
4319
+ const metadataDelta = this.#metadataDelta(batch);
4320
+ if (this.#checkpointHeaderBytes + this.#metadataBytes + metadataDelta + compositionBytes > MAX_PLUGIN_AUTHORITY_BYTES) throw new PluginAuthorityError("quota");
4321
+ this.#pendingDenial = batch[0].payload.action.kind === "revoke-package" ? batch[0].payload.action.packageId : void 0;
4322
+ let result;
4323
+ try {
4324
+ result = await this.#options.store.append(batch, data);
4325
+ } catch {
4326
+ this.#fence = {
4327
+ kind: "journal",
4328
+ batch
4329
+ };
4330
+ throw new PluginAuthorityError("fenced");
4331
+ } finally {
4332
+ this.#pendingDenial = void 0;
4333
+ }
4334
+ if (result === "unknown") {
4335
+ this.#fence = {
4336
+ kind: "journal",
4337
+ batch
4338
+ };
4339
+ throw new PluginAuthorityError("fenced");
4340
+ }
4341
+ if (result === "conflict") {
4342
+ this.#fence = { kind: "failed" };
4343
+ throw new PluginAuthorityError("conflict");
4344
+ }
4345
+ if (result === "not-committed") {
4346
+ this.#fence = void 0;
4347
+ throw new PluginAuthorityError("not-committed");
4348
+ }
4349
+ this.#fence = {
4350
+ kind: "journal",
4351
+ batch
4352
+ };
4353
+ this.#head = batch[1].sequence;
4354
+ this.#compositionBytes = compositionBytes;
4355
+ this.#retainReceipt(batch, bytes);
4356
+ this.#applyRegistration(batch);
4357
+ if (data.package !== void 0 && !this.#packages.has(data.package.packageId)) {
4358
+ this.#catalogBytes += data.package.bytes.byteLength;
4359
+ this.#packages.set(data.package.packageId, data.package);
4360
+ }
4361
+ if (data.package !== void 0 && details !== void 0) {
4362
+ this.#details.set(data.package.packageId, details);
4363
+ this.#documents.set(data.package.packageId, details.document);
4364
+ }
4365
+ if (desired !== this.#desired) this.#desired = freezeSnapshot(desired);
4366
+ this.#fence = void 0;
4367
+ }
4368
+ async #reload() {
4369
+ this.#fence = { kind: "failed" };
4370
+ const persisted = await this.#options.store.readCheckpoint();
4371
+ const checkpoint = persisted === void 0 ? void 0 : freezeSnapshot(captureCompositionData(PluginAuthorityCheckpointSchema, persisted));
4372
+ if (checkpoint !== void 0 && (checkpoint.authorityId !== this.#options.store.authorityId || checkpoint.sequence % 2 !== 0 || checkpoint.composition.sequence % 2 !== 0 || checkpoint.composition.sequence > checkpoint.sequence)) throw new PluginAuthorityError("invalid-data");
4373
+ const batches = (await this.#options.store.read()).map((batch) => freezeSnapshot(decodeAuthorityBatch(batch, this.#options.store.authorityId)));
4374
+ let sequence = batches[0]?.[0].sequence === void 0 ? 0 : batches[0][0].sequence - 1;
4375
+ if (checkpoint === void 0 && sequence !== 0) throw new PluginAuthorityError("invalid-data");
4376
+ const entryIds = /* @__PURE__ */ new Set();
4377
+ for (const batch of batches) for (const entry of batch) {
4378
+ if (entry.sequence !== ++sequence || entryIds.has(entry.entryId)) throw new PluginAuthorityError("invalid-data");
4379
+ entryIds.add(entry.entryId);
4380
+ }
4381
+ if (sequence < (checkpoint?.sequence ?? 0)) throw new PluginAuthorityError("invalid-data");
4382
+ const last = batches.at(-1);
4383
+ if (last && await this.#options.store.reconcile(last) !== "committed") throw new PluginAuthorityError("fenced");
4384
+ const registrations = new Map(checkpoint?.registrations.map((record) => [record.packageId, record]) ?? []);
4385
+ if (registrations.size !== checkpoint?.registrations.length && checkpoint !== void 0) throw new PluginAuthorityError("invalid-data");
4386
+ const tail = batches.filter((batch) => batch[0].sequence > (checkpoint?.sequence ?? 0));
4387
+ let tailSequence = checkpoint?.sequence ?? 0;
4388
+ for (const batch of tail) {
4389
+ if (batch[0].sequence !== tailSequence + 1) throw new PluginAuthorityError("invalid-data");
4390
+ tailSequence = batch[1].sequence;
4391
+ const result = batch[1];
4392
+ if (result.kind === "package.registered") {
4393
+ const existing = registrations.get(result.payload.packageId);
4394
+ if (existing?.retired || existing !== void 0 && existing.sourceProfile !== result.payload.sourceProfile) throw new PluginAuthorityError("invalid-data");
4395
+ registrations.set(result.payload.packageId, {
4396
+ ...result.payload,
4397
+ retired: false
4398
+ });
4399
+ }
4400
+ }
4401
+ const catalog = [];
4402
+ let catalogBytes = 0;
4403
+ const details = /* @__PURE__ */ new Map();
4404
+ const documents = /* @__PURE__ */ new Map();
4405
+ for (const { packageId, sourceProfile, retired } of registrations.values()) {
4406
+ if (retired) continue;
4407
+ const input = await this.#options.store.readPackage(packageId);
4408
+ if (!input || input.packageId !== packageId) throw new PluginAuthorityError("invalid-data");
4409
+ if (input.bytes.byteLength > MAX_PLUGIN_PACKAGE_BYTES) throw new PluginAuthorityError("quota");
4410
+ catalogBytes += input.bytes.byteLength;
4411
+ if (catalogBytes > MAX_CATALOG_BYTES) throw new PluginAuthorityError("quota");
4412
+ const record = {
4413
+ packageId,
4414
+ bytes: new Uint8Array(input.bytes)
4415
+ };
4416
+ const inspected = await this.#inspect(record, sourceProfile);
4417
+ details.set(packageId, inspected);
4418
+ documents.set(packageId, inspected.document);
4419
+ catalog.push(record);
4420
+ }
4421
+ const composition = new PluginCompositionProjection(documents);
4422
+ if (checkpoint !== void 0) composition.restore(checkpoint.composition);
4423
+ this.#retirementCandidates.clear();
4424
+ for (const batch of tail) if (batch[0].payload.action.kind === "apply") {
4425
+ const previous = composition.desired;
4426
+ const next = composition.apply({
4427
+ sequence: batch[1].sequence,
4428
+ mutations: batch[0].payload.action.mutations
4429
+ });
4430
+ this.#markRetirements(previous, next);
4431
+ }
4432
+ const desired = composition.desired;
4433
+ this.#head = tailSequence;
4434
+ this.#checkpointSequence = checkpoint?.sequence ?? 0;
4435
+ this.#receipts = [];
4436
+ this.#receiptBytes = 0;
4437
+ this.#commands.clear();
4438
+ this.#keys.clear();
4439
+ this.#registrations.clear();
4440
+ this.#metadataBytes = 0;
4441
+ for (const registration of registrations.values()) this.#setRegistration(registration);
4442
+ this.#revocations.clear();
4443
+ for (const denial of checkpoint?.revocations ?? []) {
4444
+ if (this.#revocations.has(denial.packageId)) throw new PluginAuthorityError("invalid-data");
4445
+ this.#setRevocation(denial);
4446
+ }
4447
+ for (const batch of tail) this.#applyRegistration(batch);
4448
+ for (const batch of batches.slice(-MAX_PLUGIN_RETRY_COMMANDS)) this.#retainReceipt(batch, new TextEncoder().encode(JSON.stringify(batch)).byteLength);
4449
+ if (this.#receiptBytes > MAX_PLUGIN_AUTHORITY_BYTES) throw new PluginAuthorityError("quota");
4450
+ this.#catalogBytes = catalogBytes;
4451
+ this.#packages.clear();
4452
+ for (const record of catalog) this.#packages.set(record.packageId, record);
4453
+ this.#documents.clear();
4454
+ this.#details.clear();
4455
+ for (const [id, detail] of details) {
4456
+ this.#documents.set(id, detail.document);
4457
+ this.#details.set(id, detail);
4458
+ }
4459
+ this.#composition = new PluginCompositionProjection(this.#documents, composition);
4460
+ this.#compositionBytes = new TextEncoder().encode(JSON.stringify(this.#composition.capture())).byteLength;
4461
+ if (this.#checkpointHeaderBytes + this.#metadataBytes + this.#compositionBytes > MAX_PLUGIN_AUTHORITY_BYTES) throw new PluginAuthorityError("invalid-data");
4462
+ this.#desired = freezeSnapshot(desired);
4463
+ this.#fence = void 0;
4464
+ }
4465
+ /** The loader must use the exact source profile accepted by registration. */
4466
+ assertPackageProfile(packageId, sourceProfile) {
4467
+ this.assertPackageExecution(packageId);
4468
+ if (this.#registrations.get(packageId)?.sourceProfile !== sourceProfile) throw new PluginAuthorityError("invalid-data");
4469
+ }
4470
+ async #inspect(record, sourceProfile) {
4471
+ const document = freezeSnapshot(await decodePluginPackage(record));
4472
+ if (check(NativePluginPackageAbiSchema, document.manifest.abi)) {
4473
+ const graph = freezeSnapshot(await inspectPluginModules(record, document));
4474
+ if (sourceProfile !== void 0 && graph.profile !== sourceProfile) throw new PluginAuthorityError("invalid-data");
4475
+ return Object.freeze({
4476
+ document,
4477
+ graph,
4478
+ sourceProfile: graph.profile
4479
+ });
4480
+ }
4481
+ const profile = this.#options.packageProfiles?.find((candidate) => candidate.abi === document.manifest.abi && (sourceProfile === void 0 || candidate.sourceProfile === sourceProfile));
4482
+ if (!profile) throw new PluginAuthorityError("invalid-data");
4483
+ await profile.inspect(record, document);
4484
+ return Object.freeze({
4485
+ document,
4486
+ graph: void 0,
4487
+ sourceProfile: profile.sourceProfile
4488
+ });
4489
+ }
4490
+ #retainReceipt(batch, bytes) {
4491
+ this.#receipts.push({
4492
+ batch,
4493
+ bytes
4494
+ });
4495
+ this.#receiptBytes += bytes;
4496
+ if (this.#receipts.length > MAX_PLUGIN_RETRY_COMMANDS) {
4497
+ const expired = this.#receipts.shift();
4498
+ if (expired !== void 0) {
4499
+ this.#receiptBytes -= expired.bytes;
4500
+ this.#commands.delete(expired.batch[0].commandId);
4501
+ this.#keys.delete(expired.batch[0].payload.idempotencyKey);
4502
+ }
4503
+ }
4504
+ this.#commands.set(batch[0].commandId, batch);
4505
+ this.#keys.set(batch[0].payload.idempotencyKey, batch);
4506
+ }
4507
+ #applyRegistration(batch) {
4508
+ const result = batch[1];
4509
+ if (result.kind === "security.revocation.committed") this.#setRevocation(result.payload);
4510
+ if (result.kind === "package.registered") this.#setRegistration({
4511
+ ...result.payload,
4512
+ retired: false
4513
+ });
4514
+ }
4515
+ #metadataSize(record) {
4516
+ return record === void 0 ? 0 : new TextEncoder().encode(JSON.stringify(record)).byteLength + 1;
4517
+ }
4518
+ #metadataDelta(batch) {
4519
+ const result = batch[1];
4520
+ if (result.kind === "package.registered") return this.#metadataSize({
4521
+ ...result.payload,
4522
+ retired: false
4523
+ }) - this.#metadataSize(this.#registrations.get(result.payload.packageId));
4524
+ if (result.kind === "security.revocation.committed") return this.#metadataSize(result.payload) - this.#metadataSize(this.#revocations.get(result.payload.packageId));
4525
+ return 0;
4526
+ }
4527
+ #setRegistration(registration) {
4528
+ this.#metadataBytes += this.#metadataSize(registration) - this.#metadataSize(this.#registrations.get(registration.packageId));
4529
+ this.#registrations.set(registration.packageId, registration);
4530
+ }
4531
+ #setRevocation(denial) {
4532
+ this.#metadataBytes += this.#metadataSize(denial) - this.#metadataSize(this.#revocations.get(denial.packageId));
4533
+ this.#revocations.set(denial.packageId, denial);
4534
+ }
4535
+ #missingPackage(packageId) {
4536
+ return new PluginAuthorityError(this.#registrations.get(packageId)?.retired ? "expired-package" : "unregistered-package");
4537
+ }
4538
+ #markRetirements(previous, desired) {
4539
+ const current = new Set(desired.entries.map((entry) => entry.packageId));
4540
+ for (const entry of previous.entries) if (!current.has(entry.packageId)) this.#retirementCandidates.add(entry.packageId);
4541
+ for (const packageId of current) this.#retirementCandidates.delete(packageId);
4542
+ }
4543
+ async #maybeCompact() {
4544
+ if (this.#sequence - this.#checkpointSequence >= MAX_PLUGIN_RETRY_COMMANDS * 2) await this.#compact();
4545
+ }
4546
+ async #prepareWrite() {
4547
+ await this.#maybeCompact();
4548
+ if (this.#sequence - this.#checkpointSequence >= MAX_PLUGIN_RETRY_COMMANDS * 2) throw new PluginAuthorityError("not-committed");
4549
+ }
4550
+ async #compact() {
4551
+ const checkpoint = freezeSnapshot(captureCompositionData(PluginAuthorityCheckpointSchema, {
4552
+ schemaVersion: 1,
4553
+ authorityId: this.#options.store.authorityId,
4554
+ sequence: this.#sequence,
4555
+ composition: this.#composition.capture(),
4556
+ registrations: [...this.#registrations.values()].map((registration) => ({
4557
+ ...registration,
4558
+ retired: registration.retired || this.#retirementCandidates.has(registration.packageId)
4559
+ })),
4560
+ revocations: [...this.#revocations.values()]
4561
+ }));
4562
+ if (new TextEncoder().encode(JSON.stringify(checkpoint)).byteLength > MAX_PLUGIN_AUTHORITY_BYTES) throw new PluginAuthorityError("invalid-data");
4563
+ let result;
4564
+ try {
4565
+ result = await this.#options.store.compact(checkpoint);
4566
+ } catch {
4567
+ this.#fence = { kind: "failed" };
4568
+ throw new PluginAuthorityError("fenced");
4569
+ }
4570
+ if (result === "not-committed") return;
4571
+ if (result !== "committed") {
4572
+ this.#fence = { kind: "failed" };
4573
+ throw new PluginAuthorityError("fenced");
4574
+ }
4575
+ this.#checkpointSequence = checkpoint.sequence;
4576
+ for (const registration of checkpoint.registrations) {
4577
+ this.#setRegistration(registration);
4578
+ if (!registration.retired) continue;
4579
+ const record = this.#packages.get(registration.packageId);
4580
+ if (record !== void 0) this.#catalogBytes -= record.bytes.byteLength;
4581
+ this.#packages.delete(registration.packageId);
4582
+ this.#documents.delete(registration.packageId);
4583
+ this.#details.delete(registration.packageId);
4584
+ this.#retirementCandidates.delete(registration.packageId);
4585
+ }
4586
+ }
4587
+ #enqueue(work) {
4588
+ const result = this.#lane.then(work).finally(() => {
4589
+ this.#notifyChanges();
4590
+ });
4591
+ this.#lane = result.then(() => void 0, () => void 0);
4592
+ return result;
4593
+ }
4594
+ };
4595
+ function freezeSnapshot(value) {
4596
+ const pending = new Set([value]);
4597
+ for (const current of pending) {
4598
+ Object.freeze(current);
4599
+ for (const child of Object.values(current)) if (Predicate.isObjectOrArray(child)) pending.add(child);
4600
+ }
4601
+ return value;
4602
+ }
4603
+
4604
+ //#endregion
4605
+ //#region src/authority/store.ts
4606
+ /** Process-lifetime implementation with the same atomic visibility as durable adapters. */
4607
+ var MemoryPluginStore = class {
4608
+ #batches = [];
4609
+ #commits = /* @__PURE__ */ new Set();
4610
+ #packages = /* @__PURE__ */ new Map();
4611
+ #sequence = 0;
4612
+ #checkpoint;
4613
+ constructor(authorityId) {
4614
+ this.authorityId = authorityId;
4615
+ }
4616
+ async read() {
4617
+ return [...this.#batches];
4618
+ }
4619
+ async readCheckpoint() {
4620
+ return structuredClone(this.#checkpoint);
4621
+ }
4622
+ async readPackage(packageId) {
4623
+ const bytes = this.#packages.get(packageId);
4624
+ if (bytes) return {
4625
+ packageId,
4626
+ bytes: bytes.slice()
4627
+ };
4628
+ }
4629
+ async append(batch, data = {}) {
4630
+ if (this.#commits.has(batch[0].entryId)) return "committed";
4631
+ if (batch[0].sequence !== this.#sequence + 1) return "conflict";
4632
+ const snapshot = structuredClone(batch);
4633
+ if (data.package) this.#packages.set(data.package.packageId, data.package.bytes.slice());
4634
+ this.#batches.push(snapshot);
4635
+ this.#commits.add(batch[0].entryId);
4636
+ this.#sequence += batch.length;
4637
+ this.#trimReceipts();
4638
+ return "committed";
4639
+ }
4640
+ async reconcile(batch) {
4641
+ if (this.#commits.has(batch[0].entryId)) return "committed";
4642
+ if (batch[0].sequence <= (this.#checkpoint?.sequence ?? 0)) throw new PluginAuthorityError("stale-command");
4643
+ return "absent";
4644
+ }
4645
+ async compact(checkpoint) {
4646
+ const snapshot = captureCompositionData(PluginAuthorityCheckpointSchema, checkpoint);
4647
+ if (snapshot.authorityId !== this.authorityId) throw new PluginAuthorityError("invalid-data");
4648
+ if (snapshot.sequence !== this.#sequence) return "conflict";
4649
+ for (const registration of snapshot.registrations) if (registration.retired) this.#packages.delete(registration.packageId);
4650
+ this.#checkpoint = snapshot;
4651
+ this.#trimReceipts();
4652
+ return "committed";
4653
+ }
4654
+ #trimReceipts() {
4655
+ let expired = 0;
4656
+ const sequence = this.#checkpoint?.sequence ?? 0;
4657
+ for (const batch of this.#batches.slice(0, -MAX_PLUGIN_RETRY_COMMANDS)) {
4658
+ if (batch[1].sequence > sequence) break;
4659
+ this.#commits.delete(batch[0].entryId);
4660
+ expired += 1;
4661
+ }
4662
+ this.#batches.splice(0, expired);
4663
+ }
4664
+ };
4665
+
4666
+ //#endregion
4667
+ export { PluginAdmissionError as A, contextComponent as C, aggregateCleanupFailure as D, objectSelfStateHost as E, PluginLeaseDeadlineErrorSchema as M, PluginLifecycleError as N, sameEntryIdentity as O, pluginFailure as P, captureProgrammaticEntries as S, makeSourceBorrow as T, encodePluginPackage as _, PluginAuthorityCheckpointSchema as a, materializePluginConfig as b, DesiredPluginPatchSchema as c, PluginModuleError as d, inspectPluginModules as f, decodePluginPackage as g, PluginPackageFormatError as h, MAX_PLUGIN_RETRY_COMMANDS as i, PluginLeaseDeadlineError as j, contributionAdmission as k, PluginCompositionError as l, PluginPackageDocumentProperties as m, PluginCompositionAuthority as n, PluginAuthorityError as o, NativePluginPackageAbiSchema as p, AuthorityBatchSchema as r, captureCompositionData as s, MemoryPluginStore as t, projectPluginComposition as u, PluginPackageIdSchema as v, makeLiveComposition as w, captureDefinition as x, PluginConfigError as y };