@sorbetai/plugins 0.0.0-stage → 0.1.0-alpha.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1179 -2
- package/dist/LICENSE.worker.acorn +21 -0
- package/dist/LICENSE.worker.acorn-walk +21 -0
- package/dist/LICENSE.worker.effect +21 -0
- package/dist/LICENSE.worker.ensure-error +9 -0
- package/dist/LICENSE.worker.es-toolkit +21 -0
- package/dist/LICENSE.worker.pi-schema.typebox +23 -0
- package/dist/authority-Ci--C1Np.js +4667 -0
- package/dist/authority-DGNilDTs.d.ts +547 -0
- package/dist/context-VD8Q9ax-.d.ts +1326 -0
- package/dist/data-schema-CHZWAtoX.js +185 -0
- package/dist/facet-DnC_pqrd.d.ts +178 -0
- package/dist/index-S_uGJe46.d.ts +610 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +1400 -0
- package/dist/isolate-worker.d.mts +1 -0
- package/dist/isolate-worker.mjs +180791 -0
- package/dist/model.d.ts +27 -0
- package/dist/model.js +274 -0
- package/dist/node.d.ts +273 -0
- package/dist/node.js +2844 -0
- package/dist/object-borrow-C81Gj5tq.js +488 -0
- package/dist/object-invocation-DC6PCiFY.js +15 -0
- package/dist/object-invocation-DMnRagqW.d.ts +13 -0
- package/dist/object-method-Bs7hYSjS.js +69 -0
- package/dist/objects-DdioT9PR.js +113 -0
- package/dist/remote.d.ts +39 -0
- package/dist/remote.js +899 -0
- package/dist/run-yield-B1AE7-PN.js +16 -0
- package/dist/source-Dlv8HG5K.d.ts +214 -0
- package/dist/view-Cn9jz2Wx.js +73 -0
- package/package.json +53 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1400 @@
|
|
|
1
|
+
import { A as capturePreparationHooks, D as capturePluginPrefixes, F as SessionBehaviorCommandSchema, H as JsonValueSchema, I as SessionBehaviorMetadataSchema, L as SessionBehaviorViewSchema, P as captureInputTransforms, R as captureSessionBehaviorMetadata, T as orderNamedStates, U as captureJsonValue, V as captureModelToolMetadata, _ as prepareToolHooks, g as orderToolHooks, h as finishToolHooks, m as captureToolHookMetadata, o as retainPluginCallbacks, v as runToolHooks, w as captureNamedStateMetadata, y as ToolResultSchema, z as captureSessionBehaviors } from "./object-borrow-C81Gj5tq.js";
|
|
2
|
+
import { n as RunYieldMetadataSchema, r as YieldDecisionSchema } from "./run-yield-B1AE7-PN.js";
|
|
3
|
+
import { i as runHistorySelectors, n as freezeModelEvidence, r as captureHistorySelectorMetadata, t as ModelViewSchema } from "./view-Cn9jz2Wx.js";
|
|
4
|
+
import { n as makeObjectMethodBinding } from "./object-method-Bs7hYSjS.js";
|
|
5
|
+
import { N as PluginLifecycleError, O as sameEntryIdentity, P as pluginFailure, S as captureProgrammaticEntries, T as makeSourceBorrow, _ as encodePluginPackage, b as materializePluginConfig, c as DesiredPluginPatchSchema, d as PluginModuleError, f as inspectPluginModules, g as decodePluginPackage, h as PluginPackageFormatError, j as PluginLeaseDeadlineError, k as contributionAdmission, l as PluginCompositionError, n as PluginCompositionAuthority, o as PluginAuthorityError, s as captureCompositionData, t as MemoryPluginStore, u as projectPluginComposition, w as makeLiveComposition, y as PluginConfigError } from "./authority-Ci--C1Np.js";
|
|
6
|
+
import { r as defineObject } from "./objects-DdioT9PR.js";
|
|
7
|
+
import * as s from "@earendil-works/pi-schema";
|
|
8
|
+
import { check, compile, decode, validationErrors } from "@sorbetai/schema";
|
|
9
|
+
import { runContextPreparation } from "@sorbetai/context";
|
|
10
|
+
import * as Context from "effect/Context";
|
|
11
|
+
import * as Effect from "effect/Effect";
|
|
12
|
+
import * as Layer from "effect/Layer";
|
|
13
|
+
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
14
|
+
import * as PubSub from "effect/PubSub";
|
|
15
|
+
import ensureError from "ensure-error";
|
|
16
|
+
import { isEqual, isError, isPromise, omitBy, sortBy } from "es-toolkit";
|
|
17
|
+
import * as Exit from "effect/Exit";
|
|
18
|
+
import * as FiberSet from "effect/FiberSet";
|
|
19
|
+
import * as Ref from "effect/Ref";
|
|
20
|
+
import * as Scope from "effect/Scope";
|
|
21
|
+
import * as Cause from "effect/Cause";
|
|
22
|
+
import * as Deferred from "effect/Deferred";
|
|
23
|
+
|
|
24
|
+
//#region src/contributions/session.ts
|
|
25
|
+
/** Host-decoded shape for Plugin `ctx.session.control.send`. */
|
|
26
|
+
const PluginSessionSendInputSchema = s.obj({
|
|
27
|
+
text: s.str({ minLength: 1 }),
|
|
28
|
+
images: s.opt(s.arr(s.obj({
|
|
29
|
+
type: s.lit("image"),
|
|
30
|
+
data: s.str({ minLength: 1 }),
|
|
31
|
+
mimeType: s.str({ minLength: 1 })
|
|
32
|
+
}, { open: false }))),
|
|
33
|
+
deliverAs: s.opt(s.union([s.lit("steer"), s.lit("followUp")]))
|
|
34
|
+
}, { open: false });
|
|
35
|
+
const PluginSessionWriteInputSchema = s.obj({ text: s.str({ minLength: 1 }) }, { open: false });
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/composition-control.ts
|
|
39
|
+
var PluginCompositionAccessError = class extends Error {
|
|
40
|
+
name = "PluginCompositionAccessError";
|
|
41
|
+
constructor(code) {
|
|
42
|
+
super(`Plugin composition access: ${code}`);
|
|
43
|
+
this.code = code;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const ControlErrorSchema = s.obj({
|
|
47
|
+
name: s.union([
|
|
48
|
+
s.lit("PluginAuthorityError"),
|
|
49
|
+
s.lit("PluginCompositionError"),
|
|
50
|
+
s.lit("PluginConfigError"),
|
|
51
|
+
s.lit("PluginCompositionAccessError")
|
|
52
|
+
]),
|
|
53
|
+
code: s.str()
|
|
54
|
+
}, { open: true });
|
|
55
|
+
/** Creates an object capability, not a typed view of the Platform. Never pass the source to a client. */
|
|
56
|
+
function makeCompositionControl(source, policy) {
|
|
57
|
+
const authorize = policy.authorize.bind(policy);
|
|
58
|
+
const visibleEntry = policy.visibleEntry.bind(policy);
|
|
59
|
+
const readConfig = policy.readConfig?.bind(policy);
|
|
60
|
+
const check$1 = async (action, snapshot, signal, patch) => {
|
|
61
|
+
signal.throwIfAborted();
|
|
62
|
+
const granted = await authorize({
|
|
63
|
+
action,
|
|
64
|
+
scopeId: snapshot.scopeId,
|
|
65
|
+
desired: structuredClone(snapshot.desired),
|
|
66
|
+
patch: structuredClone(patch),
|
|
67
|
+
signal
|
|
68
|
+
});
|
|
69
|
+
signal.throwIfAborted();
|
|
70
|
+
if (!granted) throw new PluginCompositionAccessError("not-authorized");
|
|
71
|
+
};
|
|
72
|
+
const project = (snapshot) => {
|
|
73
|
+
const entries = snapshot.desired.filter((entry) => visibleEntry(structuredClone(entry)));
|
|
74
|
+
const ids = new Set(entries.map((entry) => entry.entryId));
|
|
75
|
+
const hidden = new Set(snapshot.desired.filter((entry) => !ids.has(entry.entryId)).map((entry) => entry.entryId));
|
|
76
|
+
return {
|
|
77
|
+
scopeId: snapshot.scopeId,
|
|
78
|
+
generation: snapshot.generation,
|
|
79
|
+
authority: { ...snapshot.authority },
|
|
80
|
+
desired: entries.map((entry) => ({
|
|
81
|
+
entryId: entry.entryId,
|
|
82
|
+
packageId: entry.packageId,
|
|
83
|
+
parentId: entry.parentId !== null && ids.has(entry.parentId) ? entry.parentId : null,
|
|
84
|
+
order: entry.order,
|
|
85
|
+
enabled: entry.enabled,
|
|
86
|
+
effectiveEnabled: entry.effectiveEnabled,
|
|
87
|
+
config: readConfig === void 0 ? void 0 : structuredClone(readConfig(structuredClone(entry)))
|
|
88
|
+
})),
|
|
89
|
+
observed: {
|
|
90
|
+
phase: snapshot.observed.phase,
|
|
91
|
+
mounts: snapshot.observed.mounts.filter((mount) => ids.has(mount.path[0] ?? "") && mount.path.every((part) => !hidden.has(part))).map((mount) => ({
|
|
92
|
+
path: [...mount.path],
|
|
93
|
+
phase: mount.phase,
|
|
94
|
+
activationId: mount.activationId,
|
|
95
|
+
pendingReason: mount.pendingReason
|
|
96
|
+
}))
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
const guarded = async (work) => {
|
|
101
|
+
try {
|
|
102
|
+
return await work();
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
throw new PluginCompositionAccessError(check(ControlErrorSchema, cause) ? cause.code : "unavailable");
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
return Object.freeze({
|
|
108
|
+
queryComposition: (signal = new AbortController().signal) => guarded(async () => {
|
|
109
|
+
const snapshot = await source.queryComposition();
|
|
110
|
+
await check$1("query", snapshot, signal);
|
|
111
|
+
return project(snapshot);
|
|
112
|
+
}),
|
|
113
|
+
applyComposition: (patch, signal = new AbortController().signal) => guarded(async () => {
|
|
114
|
+
const captured = structuredClone(patch);
|
|
115
|
+
const before = await source.queryComposition();
|
|
116
|
+
await check$1("apply", before, signal, captured);
|
|
117
|
+
await check$1("query", before, signal);
|
|
118
|
+
const result = await source.applyComposition(captured, async (desired) => {
|
|
119
|
+
for (const oldEntry of before.desired) if (!isEqual(oldEntry, desired.entries.find((entry) => entry.entryId === oldEntry.entryId)) && !visibleEntry(structuredClone(oldEntry))) throw new PluginCompositionAccessError("not-authorized");
|
|
120
|
+
for (const mutation of captured.mutations) {
|
|
121
|
+
const id = mutation.kind === "add" ? mutation.entry.entryId : mutation.entryId;
|
|
122
|
+
const entry = desired.entries.find((item) => item.entryId === id) ?? before.desired.find((item) => item.entryId === id);
|
|
123
|
+
if (entry === void 0 || !visibleEntry(structuredClone(entry))) throw new PluginCompositionAccessError("not-authorized");
|
|
124
|
+
if (entry.parentId !== null) {
|
|
125
|
+
const parent = desired.entries.find((item) => item.entryId === entry.parentId);
|
|
126
|
+
if (parent === void 0 || !visibleEntry(structuredClone(parent))) throw new PluginCompositionAccessError("not-authorized");
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
await check$1("apply", {
|
|
130
|
+
scopeId: before.scopeId,
|
|
131
|
+
desired: desired.entries
|
|
132
|
+
}, signal, captured);
|
|
133
|
+
});
|
|
134
|
+
await check$1("query", result.snapshot, signal);
|
|
135
|
+
return {
|
|
136
|
+
accepted: result.accepted,
|
|
137
|
+
generation: result.generation,
|
|
138
|
+
reconciliation: result.reconciliation,
|
|
139
|
+
snapshot: project(result.snapshot)
|
|
140
|
+
};
|
|
141
|
+
}),
|
|
142
|
+
watchComposition: (observe, signal) => guarded(() => source.watchComposition(async (snapshot, observerSignal) => {
|
|
143
|
+
await check$1("watch", snapshot, observerSignal);
|
|
144
|
+
observerSignal.throwIfAborted();
|
|
145
|
+
await observe(project(snapshot), observerSignal);
|
|
146
|
+
}, signal))
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
//#endregion
|
|
151
|
+
//#region src/model/object-capabilities.ts
|
|
152
|
+
function makeObjectCapabilitySource(objects) {
|
|
153
|
+
return Object.freeze({
|
|
154
|
+
catalog: () => objects.catalog(),
|
|
155
|
+
bind: (address, method, metadata) => Effect.gen(function* () {
|
|
156
|
+
return yield* makeObjectMethodBinding(yield* objects.acquireAddress(address), method, metadata);
|
|
157
|
+
})
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/model/schema-diagnostic.ts
|
|
163
|
+
const ObjectFields = s.obj({ properties: s.map(s.unknown()) }, { open: true });
|
|
164
|
+
const LimitKeywords = new Set([
|
|
165
|
+
"minimum",
|
|
166
|
+
"maximum",
|
|
167
|
+
"exclusiveMinimum",
|
|
168
|
+
"exclusiveMaximum",
|
|
169
|
+
"minLength",
|
|
170
|
+
"maxLength",
|
|
171
|
+
"minItems",
|
|
172
|
+
"maxItems",
|
|
173
|
+
"minProperties",
|
|
174
|
+
"maxProperties"
|
|
175
|
+
]);
|
|
176
|
+
function schemaDiagnostic(schema, value) {
|
|
177
|
+
const fields = new Set(check(ObjectFields, schema) ? Object.keys(schema.properties) : []);
|
|
178
|
+
const shown = validationErrors(schema, value).slice(0, 5).map((error) => {
|
|
179
|
+
const segment = error.path.slice(1).split("/")[0] ?? "";
|
|
180
|
+
const field = segment.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
181
|
+
const path = fields.has(field) ? `#/properties/${segment}` : "#";
|
|
182
|
+
const limit = LimitKeywords.has(error.keyword) ? error.message.match(/-?\d+(?:\.\d+)?(?:e[+-]?\d+)?/i)?.[0] : void 0;
|
|
183
|
+
const constraint = limit === void 0 ? error.keyword : `${error.keyword} ${limit}`;
|
|
184
|
+
return `${path.slice(0, 120).replace(/[\r\n\t]/g, " ")}: ${constraint}`;
|
|
185
|
+
});
|
|
186
|
+
return shown.length === 0 ? "schema validation failed" : shown.join("; ");
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region src/model/invocation.ts
|
|
191
|
+
const toolResultValidator = compile(ToolResultSchema);
|
|
192
|
+
/** Interrupt notifies Promise code, then joins it before Scope can release its owner. */
|
|
193
|
+
const invocationPromise = (signal, operation) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
194
|
+
const controller = new AbortController();
|
|
195
|
+
const effective = AbortSignal.any([signal, controller.signal]);
|
|
196
|
+
const pending = Promise.resolve().then(() => operation(effective));
|
|
197
|
+
const settled = Effect.tryPromise({
|
|
198
|
+
try: () => pending,
|
|
199
|
+
catch: (cause) => isError(cause) ? cause : new Error(String(cause))
|
|
200
|
+
});
|
|
201
|
+
return yield* restore(settled).pipe(Effect.onInterrupt(() => Effect.sync(() => controller.abort(/* @__PURE__ */ new Error("Plugin invocation interrupted"))).pipe(Effect.andThen(settled), Effect.ignore)));
|
|
202
|
+
}));
|
|
203
|
+
const makeInvocationLifetime = Effect.fn("Plugin.makeInvocationLifetime")(function* (parent) {
|
|
204
|
+
const scope = yield* Scope.fork(parent, "sequential");
|
|
205
|
+
const tasks = yield* Scope.provide(FiberSet.make(), scope);
|
|
206
|
+
const runTask = yield* FiberSet.runtimePromise(tasks)();
|
|
207
|
+
let open = true;
|
|
208
|
+
yield* Scope.addFinalizer(scope, Effect.sync(() => {
|
|
209
|
+
open = false;
|
|
210
|
+
}));
|
|
211
|
+
return {
|
|
212
|
+
isOpen: () => open,
|
|
213
|
+
run: async (operation) => {
|
|
214
|
+
if (!open) throw new Error("Model Tool lease is released");
|
|
215
|
+
const result = await runTask(Effect.exit(Effect.interruptible(operation)));
|
|
216
|
+
if (Exit.isFailure(result)) throw Cause.squash(result.cause);
|
|
217
|
+
return result.value;
|
|
218
|
+
},
|
|
219
|
+
close: Effect.uninterruptible(Effect.gen(function* () {
|
|
220
|
+
open = false;
|
|
221
|
+
yield* FiberSet.awaitEmpty(tasks);
|
|
222
|
+
yield* Scope.close(scope, Exit.void);
|
|
223
|
+
}))
|
|
224
|
+
};
|
|
225
|
+
});
|
|
226
|
+
const invokeTool = Effect.fn("Plugin.invokeTool")((options) => Effect.scoped(Effect.gen(function* () {
|
|
227
|
+
const tasks = yield* FiberSet.make();
|
|
228
|
+
const runTask = yield* FiberSet.runtimePromise(tasks)();
|
|
229
|
+
let open = true;
|
|
230
|
+
const outcomes = [Exit.void];
|
|
231
|
+
const submit = (signal, operation, index = outcomes.length) => {
|
|
232
|
+
outcomes[index] = Exit.void;
|
|
233
|
+
const pending = runTask(Effect.exit(Effect.interruptible(invocationPromise(signal, operation))).pipe(Effect.tap((exit) => Effect.sync(() => {
|
|
234
|
+
outcomes[index] = exit;
|
|
235
|
+
})))).then((exit) => {
|
|
236
|
+
if (Exit.isFailure(exit)) throw Cause.squash(exit.cause);
|
|
237
|
+
return exit.value;
|
|
238
|
+
});
|
|
239
|
+
pending.catch(() => {});
|
|
240
|
+
return pending;
|
|
241
|
+
};
|
|
242
|
+
let reading;
|
|
243
|
+
const read = options.readToolResults;
|
|
244
|
+
const command = options.commandBehavior;
|
|
245
|
+
const ownTask = options.context.ownTask;
|
|
246
|
+
const author = yield* Effect.exit(invocationPromise(options.context.signal, async (signal) => {
|
|
247
|
+
const assertHandle = (expiry) => {
|
|
248
|
+
if (!open) throw new Error(expiry);
|
|
249
|
+
signal.throwIfAborted();
|
|
250
|
+
};
|
|
251
|
+
try {
|
|
252
|
+
const readToolResults = read === void 0 ? void 0 : (cancellation) => {
|
|
253
|
+
if (!open) return Promise.reject(/* @__PURE__ */ new Error("Tool observation handle has expired"));
|
|
254
|
+
reading ??= submit(cancellation === void 0 ? signal : AbortSignal.any([signal, cancellation]), async (readSignal) => {
|
|
255
|
+
readSignal.throwIfAborted();
|
|
256
|
+
const snapshot = await read(readSignal);
|
|
257
|
+
readSignal.throwIfAborted();
|
|
258
|
+
return structuredClone(snapshot);
|
|
259
|
+
}, 0);
|
|
260
|
+
return reading;
|
|
261
|
+
};
|
|
262
|
+
const commandBehavior = command === void 0 ? void 0 : (name, input, cancellation) => {
|
|
263
|
+
if (!open) return Promise.reject(/* @__PURE__ */ new Error("Session behavior command handle expired"));
|
|
264
|
+
const effective = cancellation === void 0 ? signal : AbortSignal.any([signal, cancellation]);
|
|
265
|
+
effective.throwIfAborted();
|
|
266
|
+
const captured = structuredClone(input);
|
|
267
|
+
return submit(effective, async (commandSignal) => command(name, captured, commandSignal));
|
|
268
|
+
};
|
|
269
|
+
const result = await options.tool.execute(options.parameters, {
|
|
270
|
+
...options.context,
|
|
271
|
+
signal,
|
|
272
|
+
ownTask: ownTask === void 0 ? void 0 : (execute) => {
|
|
273
|
+
assertHandle("Tool task ownership handle has expired");
|
|
274
|
+
return ownTask(execute);
|
|
275
|
+
},
|
|
276
|
+
readToolResults,
|
|
277
|
+
commandBehavior,
|
|
278
|
+
onUpdate: options.context.onUpdate === void 0 ? void 0 : (update) => {
|
|
279
|
+
assertHandle("Tool update handle has expired");
|
|
280
|
+
if (!toolResultValidator.check(update)) throw new TypeError(`Invalid Plugin Tool update: ${schemaDiagnostic(ToolResultSchema, update)}`);
|
|
281
|
+
options.context.onUpdate?.(structuredClone(update));
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
if (!toolResultValidator.check(result)) throw new TypeError(`Invalid Plugin Tool result: ${schemaDiagnostic(ToolResultSchema, result)}`);
|
|
285
|
+
return structuredClone(result);
|
|
286
|
+
} finally {
|
|
287
|
+
open = false;
|
|
288
|
+
}
|
|
289
|
+
}));
|
|
290
|
+
yield* FiberSet.awaitEmpty(tasks);
|
|
291
|
+
if (Exit.isFailure(author)) return yield* author;
|
|
292
|
+
for (const exit of outcomes) if (Exit.isFailure(exit)) return yield* Effect.failCause(exit.cause);
|
|
293
|
+
return author.value;
|
|
294
|
+
})));
|
|
295
|
+
|
|
296
|
+
//#endregion
|
|
297
|
+
//#region src/contributions/tool-observation.ts
|
|
298
|
+
const ToolResultObservationSchema = s.obj({
|
|
299
|
+
factId: s.str({ minLength: 1 }),
|
|
300
|
+
sequence: s.int({ minimum: 1 }),
|
|
301
|
+
runId: s.str({ minLength: 1 }),
|
|
302
|
+
toolCallId: s.str({ minLength: 1 }),
|
|
303
|
+
toolName: s.str({ minLength: 1 }),
|
|
304
|
+
isError: s.bool(),
|
|
305
|
+
details: JsonValueSchema
|
|
306
|
+
}, { open: false });
|
|
307
|
+
const PluginToolResultSnapshotSchema = s.obj({
|
|
308
|
+
sessionId: s.str({ minLength: 1 }),
|
|
309
|
+
throughSequence: s.int({ minimum: 0 }),
|
|
310
|
+
cursor: s.opt(s.str()),
|
|
311
|
+
results: s.arr(ToolResultObservationSchema)
|
|
312
|
+
}, { open: false });
|
|
313
|
+
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region src/model/consumer.ts
|
|
316
|
+
const IdentitySchema = s.str({ minLength: 1 });
|
|
317
|
+
const DurationSchema = s.int({
|
|
318
|
+
minimum: 1,
|
|
319
|
+
maximum: Number.MAX_SAFE_INTEGER
|
|
320
|
+
});
|
|
321
|
+
const VisibleToolNamesSchema = s.arr(s.str({ minLength: 1 }), { uniqueItems: true });
|
|
322
|
+
/** Each lease owns its borrows; cached declarations never authorize execution. */
|
|
323
|
+
const makeModelConsumer = Effect.fn("ModelConsumer.make")(function* (options, sample) {
|
|
324
|
+
const requestRoot = yield* Effect.scope;
|
|
325
|
+
yield* Effect.try({
|
|
326
|
+
try: () => options.maxLeaseDurationMs === void 0 ? void 0 : decode(DurationSchema, options.maxLeaseDurationMs),
|
|
327
|
+
catch: ensureError
|
|
328
|
+
});
|
|
329
|
+
const requests = /* @__PURE__ */ new Set();
|
|
330
|
+
const views = /* @__PURE__ */ new WeakMap();
|
|
331
|
+
let closed = false;
|
|
332
|
+
const cleanupTasks = yield* FiberSet.make();
|
|
333
|
+
const runCleanup = yield* FiberSet.runtimePromise(cleanupTasks)();
|
|
334
|
+
const assertOpen = Effect.sync(() => {
|
|
335
|
+
if (closed) throw new Error("Model consumer is closed");
|
|
336
|
+
});
|
|
337
|
+
return {
|
|
338
|
+
acquire: Effect.fn("ModelConsumer.acquire")(function* (input) {
|
|
339
|
+
yield* assertOpen;
|
|
340
|
+
const captured = yield* Effect.try({
|
|
341
|
+
try: () => {
|
|
342
|
+
input.signal.throwIfAborted();
|
|
343
|
+
const sessionId = decode(IdentitySchema, input.sessionId);
|
|
344
|
+
const runId = input.runId === void 0 ? void 0 : decode(IdentitySchema, input.runId);
|
|
345
|
+
const operationId = input.operationId === void 0 ? void 0 : decode(IdentitySchema, input.operationId);
|
|
346
|
+
if (runId === void 0 === (operationId === void 0)) throw new Error("Plugin request requires exactly one Run or operation identity");
|
|
347
|
+
const source = input.source === void 0 ? void 0 : captureJsonValue(input.source);
|
|
348
|
+
const now = options.now();
|
|
349
|
+
let deadline = input.deadline === void 0 ? void 0 : decode(s.num(), input.deadline);
|
|
350
|
+
if (options.maxLeaseDurationMs !== void 0) deadline = Math.min(deadline ?? Number.POSITIVE_INFINITY, now + options.maxLeaseDurationMs);
|
|
351
|
+
if (deadline !== void 0 && deadline <= now) throw new PluginLeaseDeadlineError();
|
|
352
|
+
const toolNames = input.toolNames === void 0 ? void 0 : new Set(decode(VisibleToolNamesSchema, input.toolNames));
|
|
353
|
+
return {
|
|
354
|
+
subject: {
|
|
355
|
+
sessionId,
|
|
356
|
+
runId,
|
|
357
|
+
operationId,
|
|
358
|
+
source
|
|
359
|
+
},
|
|
360
|
+
deadline,
|
|
361
|
+
toolNames,
|
|
362
|
+
signal: input.signal
|
|
363
|
+
};
|
|
364
|
+
},
|
|
365
|
+
catch: ensureError
|
|
366
|
+
});
|
|
367
|
+
const leaseId = options.createId();
|
|
368
|
+
yield* assertOpen;
|
|
369
|
+
const model = yield* Effect.try({
|
|
370
|
+
try: sample,
|
|
371
|
+
catch: ensureError
|
|
372
|
+
});
|
|
373
|
+
const view = yield* Effect.try({
|
|
374
|
+
try: () => {
|
|
375
|
+
const previous = views.get(model);
|
|
376
|
+
const includeHidden = captured.subject.operationId !== void 0;
|
|
377
|
+
if (previous !== void 0 && previous.includeHidden === includeHidden && isEqual(previous.names, captured.toolNames)) return previous.view;
|
|
378
|
+
const catalog = previous?.catalog ?? requestCatalog(model);
|
|
379
|
+
const selected = captureRequest(catalog, captured.toolNames, includeHidden);
|
|
380
|
+
views.set(model, {
|
|
381
|
+
names: captured.toolNames,
|
|
382
|
+
includeHidden,
|
|
383
|
+
view: selected,
|
|
384
|
+
catalog
|
|
385
|
+
});
|
|
386
|
+
return selected;
|
|
387
|
+
},
|
|
388
|
+
catch: ensureError
|
|
389
|
+
});
|
|
390
|
+
const leaseScope = yield* Scope.fork(requestRoot, "sequential");
|
|
391
|
+
const released = yield* Ref.make(false);
|
|
392
|
+
const leaseDrained = yield* Deferred.make();
|
|
393
|
+
const grant = Effect.gen(function* () {
|
|
394
|
+
const { subject, deadline, toolNames } = captured;
|
|
395
|
+
yield* Effect.acquireRelease(Effect.sync(() => requests.add(leaseDrained)), () => Effect.gen(function* () {
|
|
396
|
+
requests.delete(leaseDrained);
|
|
397
|
+
yield* Ref.set(released, true);
|
|
398
|
+
yield* Deferred.succeed(leaseDrained, void 0);
|
|
399
|
+
}));
|
|
400
|
+
const sourceBorrow = yield* Effect.acquireRelease(Effect.map(model.borrow(new Set(view.metadata.tools.map((tool) => tool.name))), makeSourceBorrow), (borrow) => borrow.release);
|
|
401
|
+
yield* assertOpen;
|
|
402
|
+
yield* Effect.try({
|
|
403
|
+
try: () => captured.signal.throwIfAborted(),
|
|
404
|
+
catch: ensureError
|
|
405
|
+
});
|
|
406
|
+
const deadlineController = new AbortController();
|
|
407
|
+
const signal = AbortSignal.any([captured.signal, deadlineController.signal]);
|
|
408
|
+
if (deadline !== void 0) yield* Effect.forkIn(Effect.sleep(deadline - options.now()).pipe(Effect.andThen(Effect.sync(() => deadlineController.abort(new PluginLeaseDeadlineError())))), leaseScope);
|
|
409
|
+
const lifetime = yield* makeInvocationLifetime(leaseScope);
|
|
410
|
+
const close = yield* Effect.cached(Effect.uninterruptible(lifetime.close.pipe(Effect.andThen(Effect.sync(() => deadlineController.abort(/* @__PURE__ */ new Error("Model Tool lease is released")))), Effect.andThen(Scope.close(leaseScope, Exit.void)), Effect.andThen(Deferred.await(leaseDrained)))));
|
|
411
|
+
const historySelectors = view.historySelectors;
|
|
412
|
+
const assertExecution = (invocationSignal) => {
|
|
413
|
+
if (!lifetime.isOpen()) throw new Error("Model Tool lease is released");
|
|
414
|
+
const effective = invocationSignal === void 0 ? signal : AbortSignal.any([signal, invocationSignal]);
|
|
415
|
+
effective.throwIfAborted();
|
|
416
|
+
if (deadline !== void 0 && options.now() >= deadline) throw new PluginLeaseDeadlineError();
|
|
417
|
+
return effective;
|
|
418
|
+
};
|
|
419
|
+
const runSubject = () => {
|
|
420
|
+
if (subject.runId === void 0) throw new Error("Operation Tool leases have no model callback scope");
|
|
421
|
+
return {
|
|
422
|
+
sessionId: subject.sessionId,
|
|
423
|
+
runId: subject.runId
|
|
424
|
+
};
|
|
425
|
+
};
|
|
426
|
+
let disposal;
|
|
427
|
+
const dispose = async () => {
|
|
428
|
+
if (Ref.getUnsafe(released)) return;
|
|
429
|
+
const outcome = await runCleanup(Effect.exit(close));
|
|
430
|
+
if (Exit.isFailure(outcome)) throw pluginFailure(outcome.cause);
|
|
431
|
+
};
|
|
432
|
+
const behaviorSignals = /* @__PURE__ */ new Map();
|
|
433
|
+
return {
|
|
434
|
+
toolRecovery: (bindingId) => {
|
|
435
|
+
assertExecution();
|
|
436
|
+
const tool = view.tools.get(bindingId);
|
|
437
|
+
if (tool === void 0 || toolNames !== void 0 && !toolNames.has(tool.name)) throw new Error("Tool binding does not belong to this lease");
|
|
438
|
+
return tool.recovery ?? "unsafe";
|
|
439
|
+
},
|
|
440
|
+
behaviorSignal: (name) => {
|
|
441
|
+
assertExecution();
|
|
442
|
+
let behaviorSignal = behaviorSignals.get(name);
|
|
443
|
+
if (behaviorSignal === void 0) {
|
|
444
|
+
behaviorSignal = Effect.runSync(Scope.provide(model.behaviorSignal(name), leaseScope));
|
|
445
|
+
behaviorSignals.set(name, behaviorSignal);
|
|
446
|
+
}
|
|
447
|
+
return behaviorSignal;
|
|
448
|
+
},
|
|
449
|
+
prepareToolArguments: (bindingId, argumentsValue) => {
|
|
450
|
+
assertExecution();
|
|
451
|
+
const tool = view.tools.get(bindingId);
|
|
452
|
+
if (tool === void 0 || toolNames !== void 0 && !toolNames.has(tool.name)) throw new Error(`Tool binding ${bindingId} does not belong to this lease`);
|
|
453
|
+
const parameters = captureJsonValue(argumentsValue);
|
|
454
|
+
return tool.prepareArguments === void 0 ? parameters : captureJsonValue(structuredClone(tool.prepareArguments(parameters)));
|
|
455
|
+
},
|
|
456
|
+
reduceBehavior: (name, state, command, scope) => {
|
|
457
|
+
assertExecution();
|
|
458
|
+
const behavior = view.sessionBehaviors.find((entry) => entry.name === name);
|
|
459
|
+
if (behavior === void 0) throw new Error(`Session behavior ${name} is unavailable`);
|
|
460
|
+
const next = captureJsonValue(structuredClone(behavior.reduce(structuredClone(state), structuredClone(command), {
|
|
461
|
+
...scope,
|
|
462
|
+
sessionId: subject.sessionId
|
|
463
|
+
})));
|
|
464
|
+
if (!check(behavior.stateSchema, next)) throw new TypeError("Invalid Session behavior state");
|
|
465
|
+
return {
|
|
466
|
+
state: next,
|
|
467
|
+
view: structuredClone(decode(SessionBehaviorViewSchema, behavior.project(structuredClone(next))))
|
|
468
|
+
};
|
|
469
|
+
},
|
|
470
|
+
leaseId,
|
|
471
|
+
view: view.metadata,
|
|
472
|
+
deadline,
|
|
473
|
+
signal,
|
|
474
|
+
assertExecution,
|
|
475
|
+
selectHistory: historySelectors.length === 0 ? void 0 : async (history, requestScopeId, invocationSignal) => {
|
|
476
|
+
const executionSignal = assertExecution(invocationSignal);
|
|
477
|
+
decode(IdentitySchema, requestScopeId);
|
|
478
|
+
return lifetime.run(invocationPromise(executionSignal, async (callbackSignal) => {
|
|
479
|
+
return await runHistorySelectors(historySelectors, history, {
|
|
480
|
+
...runSubject(),
|
|
481
|
+
requestScopeId
|
|
482
|
+
}, callbackSignal);
|
|
483
|
+
}));
|
|
484
|
+
},
|
|
485
|
+
prepareContext: async (draft, scope) => {
|
|
486
|
+
const executionSignal = assertExecution(scope.signal);
|
|
487
|
+
const visibleToolNames = scope.visibleToolNames === void 0 ? void 0 : [...decode(VisibleToolNamesSchema, scope.visibleToolNames)];
|
|
488
|
+
return lifetime.run(invocationPromise(executionSignal, async (callbackSignal) => {
|
|
489
|
+
return await runContextPreparation(view.preparationHooks.map((hook) => ({
|
|
490
|
+
hookId: hook.hookId,
|
|
491
|
+
around: (preparedDraft, context, next) => hook.around(preparedDraft, {
|
|
492
|
+
...context,
|
|
493
|
+
...runSubject(),
|
|
494
|
+
visibleToolNames,
|
|
495
|
+
leaseId
|
|
496
|
+
}, next)
|
|
497
|
+
})), draft, {
|
|
498
|
+
turnScopeId: scope.turnScopeId,
|
|
499
|
+
requestScopeId: scope.requestScopeId,
|
|
500
|
+
signal: callbackSignal
|
|
501
|
+
});
|
|
502
|
+
}));
|
|
503
|
+
},
|
|
504
|
+
transformInput: async (prompt, source, mode = "initial") => {
|
|
505
|
+
assertExecution();
|
|
506
|
+
let effective = prompt;
|
|
507
|
+
const context = {
|
|
508
|
+
...runSubject(),
|
|
509
|
+
signal,
|
|
510
|
+
source,
|
|
511
|
+
mode
|
|
512
|
+
};
|
|
513
|
+
return lifetime.run(invocationPromise(signal, async (callbackSignal) => {
|
|
514
|
+
for (const handler of view.inputTransforms) {
|
|
515
|
+
callbackSignal.throwIfAborted();
|
|
516
|
+
effective = await handler.transform(effective, {
|
|
517
|
+
...context,
|
|
518
|
+
signal: callbackSignal
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
callbackSignal.throwIfAborted();
|
|
522
|
+
return effective;
|
|
523
|
+
}));
|
|
524
|
+
},
|
|
525
|
+
yieldRun: async (contributionId, answer, context) => {
|
|
526
|
+
const executionSignal = assertExecution(context.signal);
|
|
527
|
+
const hook = view.runYield.find((entry) => entry.contributionId === contributionId);
|
|
528
|
+
if (hook === void 0) throw new Error("Yield hook does not belong to this lease");
|
|
529
|
+
return lifetime.run(invocationPromise(executionSignal, async (hookSignal) => decode(YieldDecisionSchema, await hook.onYield(structuredClone(answer), {
|
|
530
|
+
...context,
|
|
531
|
+
usage: structuredClone(context.usage),
|
|
532
|
+
behaviorState: structuredClone(context.behaviorState),
|
|
533
|
+
signal: hookSignal
|
|
534
|
+
}))));
|
|
535
|
+
},
|
|
536
|
+
readNamedState: async (contributionId, invocationSignal, toolResults, toolCatalog) => {
|
|
537
|
+
const executionSignal = assertExecution(invocationSignal);
|
|
538
|
+
const state = view.namedStates.get(contributionId);
|
|
539
|
+
if (state === void 0) throw new Error("Named state does not belong to this lease");
|
|
540
|
+
return lifetime.run(invocationPromise(executionSignal, async (callbackSignal) => {
|
|
541
|
+
const result = await state.read({
|
|
542
|
+
...runSubject(),
|
|
543
|
+
signal: callbackSignal,
|
|
544
|
+
toolResults,
|
|
545
|
+
toolCatalog: toolCatalog === void 0 ? void 0 : structuredClone(toolCatalog)
|
|
546
|
+
});
|
|
547
|
+
callbackSignal.throwIfAborted();
|
|
548
|
+
return result;
|
|
549
|
+
}));
|
|
550
|
+
},
|
|
551
|
+
prepareToolHooks: async (argumentsValue, context) => {
|
|
552
|
+
const executionSignal = assertExecution(context.signal);
|
|
553
|
+
return lifetime.run(invocationPromise(executionSignal, (callbackSignal) => prepareToolHooks(view.hooks, argumentsValue, {
|
|
554
|
+
...context,
|
|
555
|
+
...subject,
|
|
556
|
+
signal: callbackSignal
|
|
557
|
+
})));
|
|
558
|
+
},
|
|
559
|
+
finishToolHooks: async (prepared, result, context) => {
|
|
560
|
+
const executionSignal = assertExecution(context.signal);
|
|
561
|
+
return lifetime.run(invocationPromise(executionSignal, (callbackSignal) => finishToolHooks(view.hooks, prepared, result, {
|
|
562
|
+
...context,
|
|
563
|
+
...subject,
|
|
564
|
+
signal: callbackSignal
|
|
565
|
+
})));
|
|
566
|
+
},
|
|
567
|
+
runToolHooks: async (argumentsValue, context, continuation) => {
|
|
568
|
+
const executionSignal = assertExecution(context.signal);
|
|
569
|
+
return lifetime.run(invocationPromise(executionSignal, async (callbackSignal) => {
|
|
570
|
+
return await runToolHooks(view.hooks, argumentsValue, {
|
|
571
|
+
...context,
|
|
572
|
+
...subject,
|
|
573
|
+
signal: callbackSignal
|
|
574
|
+
}, continuation);
|
|
575
|
+
}));
|
|
576
|
+
},
|
|
577
|
+
invoke: async (bindingId, argumentsValue, invocationSignal, toolCallId, readToolResults, commandBehavior, onUpdate, traceContext, executeTool, approval, steeringSignal, toolCatalog) => {
|
|
578
|
+
const executionSignal = assertExecution(invocationSignal);
|
|
579
|
+
if (toolCallId !== void 0) decode(IdentitySchema, toolCallId);
|
|
580
|
+
const tool = view.tools.get(bindingId);
|
|
581
|
+
if (tool === void 0 || toolNames !== void 0 && !toolNames.has(tool.name)) throw new Error(`Tool binding ${bindingId} does not belong to this lease`);
|
|
582
|
+
const parameters = argumentsValue;
|
|
583
|
+
if (!check(tool.parameters, parameters)) throw new TypeError(`Invalid input for Tool ${tool.name}: ${schemaDiagnostic(tool.parameters, parameters)}`);
|
|
584
|
+
return lifetime.run(invokeTool({
|
|
585
|
+
tool,
|
|
586
|
+
parameters,
|
|
587
|
+
context: {
|
|
588
|
+
...subject,
|
|
589
|
+
approval: approval ?? "not-required",
|
|
590
|
+
steeringSignal,
|
|
591
|
+
toolCatalog: toolCatalog === void 0 ? void 0 : structuredClone(toolCatalog),
|
|
592
|
+
leaseId,
|
|
593
|
+
signal: executionSignal,
|
|
594
|
+
toolCallId,
|
|
595
|
+
traceContext,
|
|
596
|
+
onUpdate,
|
|
597
|
+
executeTool,
|
|
598
|
+
ownTask: (execute) => {
|
|
599
|
+
assertExecution();
|
|
600
|
+
if (closed) throw new Error("Model consumer is closed");
|
|
601
|
+
const release = Effect.runSync(sourceBorrow.retain());
|
|
602
|
+
const settled = Promise.resolve().then(execute).finally(async () => {
|
|
603
|
+
const result = await runCleanup(Effect.exit(release));
|
|
604
|
+
if (Exit.isFailure(result)) throw pluginFailure(result.cause);
|
|
605
|
+
});
|
|
606
|
+
settled.catch(() => {});
|
|
607
|
+
return settled;
|
|
608
|
+
}
|
|
609
|
+
},
|
|
610
|
+
readToolResults,
|
|
611
|
+
commandBehavior
|
|
612
|
+
}));
|
|
613
|
+
},
|
|
614
|
+
[Symbol.asyncDispose]: () => disposal ??= dispose()
|
|
615
|
+
};
|
|
616
|
+
});
|
|
617
|
+
return yield* Scope.provide(grant, leaseScope).pipe(Effect.onError((cause) => Scope.close(leaseScope, Exit.failCause(cause))));
|
|
618
|
+
}),
|
|
619
|
+
close: Effect.gen(function* () {
|
|
620
|
+
closed = true;
|
|
621
|
+
yield* Effect.forEach([...requests], Deferred.await, { discard: true });
|
|
622
|
+
}),
|
|
623
|
+
requestCount: () => requests.size
|
|
624
|
+
};
|
|
625
|
+
});
|
|
626
|
+
function requestCatalog(model) {
|
|
627
|
+
const hooks = orderToolHooks(model.hooks);
|
|
628
|
+
const runYield = sortBy(model.runYield, ["contributionId"]);
|
|
629
|
+
for (const hook of runYield) if (hook.behavior !== void 0 && !model.sessionBehaviors.some((behavior) => behavior.name === hook.behavior && behavior.contributionId === `${hook.contributionId.slice(0, hook.contributionId.lastIndexOf("/run-yield/"))}/session-behavior/${encodeURIComponent(hook.behavior)}`)) throw new Error("Yield hook must use a behavior owned by the same plugin");
|
|
630
|
+
const states = orderNamedStates(model.namedStates);
|
|
631
|
+
const inputs = sortBy(model.inputTransforms, ["contributionId"]);
|
|
632
|
+
const sessionBehaviors = captureSessionBehaviors(model.sessionBehaviors);
|
|
633
|
+
const metadata = decode(ModelViewSchema, {
|
|
634
|
+
schemaVersion: 1,
|
|
635
|
+
tools: [],
|
|
636
|
+
...omitBy({
|
|
637
|
+
runYield: runYield.map(({ contributionId, behavior, entryId, activationId }) => ({
|
|
638
|
+
...decode(RunYieldMetadataSchema, {
|
|
639
|
+
contributionId,
|
|
640
|
+
behavior
|
|
641
|
+
}),
|
|
642
|
+
bindingId: model.yieldBindings.get(contributionId),
|
|
643
|
+
...entryId === void 0 ? {} : { entryId },
|
|
644
|
+
...activationId === void 0 ? {} : { activationId }
|
|
645
|
+
})),
|
|
646
|
+
hooks: hooks.map(captureToolHookMetadata),
|
|
647
|
+
namedStates: states.map(captureNamedStateMetadata),
|
|
648
|
+
prefixes: capturePluginPrefixes(model.prefixes),
|
|
649
|
+
inputTransforms: captureInputTransforms(inputs),
|
|
650
|
+
preparationHooks: capturePreparationHooks(model.preparationHooks),
|
|
651
|
+
historySelectors: captureHistorySelectorMetadata(model.historySelectors),
|
|
652
|
+
sessionBehaviors: sessionBehaviors.map(captureSessionBehaviorMetadata)
|
|
653
|
+
}, (entries) => entries.length === 0)
|
|
654
|
+
});
|
|
655
|
+
freezeModelEvidence(metadata);
|
|
656
|
+
const tools = sortBy(model.tools, ["name"]);
|
|
657
|
+
const byName = /* @__PURE__ */ new Map();
|
|
658
|
+
for (const tool of tools) {
|
|
659
|
+
const group = byName.get(tool.name);
|
|
660
|
+
if (group === void 0) byName.set(tool.name, [tool]);
|
|
661
|
+
else group.push(tool);
|
|
662
|
+
}
|
|
663
|
+
return {
|
|
664
|
+
model,
|
|
665
|
+
metadata,
|
|
666
|
+
tools,
|
|
667
|
+
byName,
|
|
668
|
+
declarations: /* @__PURE__ */ new Map(),
|
|
669
|
+
hooks,
|
|
670
|
+
namedStates: new Map(states.map((state) => [state.contributionId, state])),
|
|
671
|
+
runYield,
|
|
672
|
+
inputTransforms: inputs,
|
|
673
|
+
preparationHooks: model.preparationHooks,
|
|
674
|
+
historySelectors: model.historySelectors,
|
|
675
|
+
sessionBehaviors
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
function captureRequest(catalog, toolNames, includeHidden) {
|
|
679
|
+
const selected = toolNames === void 0 ? catalog.tools : [...toolNames].sort().flatMap((name) => catalog.byName.get(name) ?? []);
|
|
680
|
+
const names = /* @__PURE__ */ new Set();
|
|
681
|
+
const contributions = /* @__PURE__ */ new Set();
|
|
682
|
+
const tools = /* @__PURE__ */ new Map();
|
|
683
|
+
const declarations = selected.filter((tool) => includeHidden || tool.discovery?.exposure !== "hidden").map((tool) => {
|
|
684
|
+
if (names.has(tool.name)) throw new TypeError(`Duplicate Plugin Tool name: ${tool.name}`);
|
|
685
|
+
if (contributions.has(tool.contributionId)) throw new TypeError(`Duplicate Plugin contribution: ${tool.contributionId}`);
|
|
686
|
+
names.add(tool.name);
|
|
687
|
+
contributions.add(tool.contributionId);
|
|
688
|
+
let declaration = catalog.declarations.get(tool);
|
|
689
|
+
if (declaration === void 0) {
|
|
690
|
+
const bindingId = catalog.model.bindings.get(tool.contributionId);
|
|
691
|
+
if (bindingId === void 0) throw new Error("Missing live Tool binding");
|
|
692
|
+
declaration = {
|
|
693
|
+
...captureModelToolMetadata(tool),
|
|
694
|
+
bindingId
|
|
695
|
+
};
|
|
696
|
+
freezeModelEvidence(declaration);
|
|
697
|
+
catalog.declarations.set(tool, declaration);
|
|
698
|
+
}
|
|
699
|
+
tools.set(declaration.bindingId, tool);
|
|
700
|
+
return declaration;
|
|
701
|
+
});
|
|
702
|
+
const metadata = {
|
|
703
|
+
...catalog.metadata,
|
|
704
|
+
tools: declarations
|
|
705
|
+
};
|
|
706
|
+
freezeModelEvidence(metadata);
|
|
707
|
+
return {
|
|
708
|
+
...catalog,
|
|
709
|
+
metadata,
|
|
710
|
+
tools
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
//#endregion
|
|
715
|
+
//#region src/model/projection.ts
|
|
716
|
+
const toolBindings = /* @__PURE__ */ new WeakMap();
|
|
717
|
+
const projections = /* @__PURE__ */ new WeakMap();
|
|
718
|
+
function modelContributions(snapshot, policy = "strict") {
|
|
719
|
+
let policies = projections.get(snapshot);
|
|
720
|
+
if (policies === void 0) {
|
|
721
|
+
policies = /* @__PURE__ */ new Map();
|
|
722
|
+
projections.set(snapshot, policies);
|
|
723
|
+
}
|
|
724
|
+
let projection = policies.get(policy);
|
|
725
|
+
if (projection === void 0) {
|
|
726
|
+
projection = buildModelContributions(snapshot, policy);
|
|
727
|
+
policies.set(policy, projection);
|
|
728
|
+
}
|
|
729
|
+
return projection;
|
|
730
|
+
}
|
|
731
|
+
/** Model consumers choose their callable resource owners; the graph retains dependency closure. */
|
|
732
|
+
function buildModelContributions(snapshot, policy = "strict") {
|
|
733
|
+
const samples = snapshot.samples.map(({ entry, contributions, behaviorRegistrations }) => {
|
|
734
|
+
const closure = /* @__PURE__ */ new Set();
|
|
735
|
+
const include = (owner) => {
|
|
736
|
+
if (closure.has(owner)) return;
|
|
737
|
+
closure.add(owner);
|
|
738
|
+
if (owner.parent !== void 0) include(owner.parent);
|
|
739
|
+
for (const binding of owner.bindings) include(binding.provider);
|
|
740
|
+
};
|
|
741
|
+
include(entry);
|
|
742
|
+
const signal = AbortSignal.any([...closure].map((owner) => owner.owner.signal));
|
|
743
|
+
const admission = contributionAdmission(() => {
|
|
744
|
+
for (const owner of closure) owner.owner.assertAvailable();
|
|
745
|
+
});
|
|
746
|
+
const merged = (cancellation) => AbortSignal.any(cancellation === void 0 ? [signal] : [signal, cancellation]);
|
|
747
|
+
return {
|
|
748
|
+
entry,
|
|
749
|
+
contributions: {
|
|
750
|
+
...contributions,
|
|
751
|
+
tools: contributions.tools.map((tool) => {
|
|
752
|
+
const prepare = tool.prepareArguments;
|
|
753
|
+
return {
|
|
754
|
+
...tool,
|
|
755
|
+
prepareArguments: prepare === void 0 ? void 0 : admission.call(prepare),
|
|
756
|
+
execute: (input, context) => {
|
|
757
|
+
admission.assert();
|
|
758
|
+
return tool.execute(input, {
|
|
759
|
+
...admission.toolContext(context),
|
|
760
|
+
signal: merged(context.signal)
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
}),
|
|
765
|
+
hooks: contributions.hooks?.map((hook) => {
|
|
766
|
+
const prepare = hook.prepare;
|
|
767
|
+
const feedback = hook.feedback;
|
|
768
|
+
const prepared = async (input, context) => await prepare?.(input, {
|
|
769
|
+
...context,
|
|
770
|
+
signal: merged(context.signal)
|
|
771
|
+
}) ?? { input };
|
|
772
|
+
const received = async (result, state, context) => await feedback?.(result, state, {
|
|
773
|
+
...context,
|
|
774
|
+
signal: merged(context.signal)
|
|
775
|
+
}) ?? result;
|
|
776
|
+
return {
|
|
777
|
+
...hook,
|
|
778
|
+
prepare: admission.call(prepared),
|
|
779
|
+
feedback: admission.call(received)
|
|
780
|
+
};
|
|
781
|
+
}),
|
|
782
|
+
namedStates: contributions.namedStates?.map((state) => {
|
|
783
|
+
const read = admission.call(state.read);
|
|
784
|
+
return {
|
|
785
|
+
...state,
|
|
786
|
+
read: (context) => read({
|
|
787
|
+
...context,
|
|
788
|
+
signal: merged(context.signal)
|
|
789
|
+
})
|
|
790
|
+
};
|
|
791
|
+
}),
|
|
792
|
+
runYield: contributions.runYield?.map((hook) => {
|
|
793
|
+
const onYield = admission.call(hook.onYield);
|
|
794
|
+
return {
|
|
795
|
+
...hook,
|
|
796
|
+
entryId: entry.identity?.entryId ?? entry.path.join("/"),
|
|
797
|
+
activationId: entry.owner.activationId,
|
|
798
|
+
onYield: (answer, context) => onYield(answer, {
|
|
799
|
+
...context,
|
|
800
|
+
signal: merged(context.signal)
|
|
801
|
+
})
|
|
802
|
+
};
|
|
803
|
+
}),
|
|
804
|
+
compactionPolicies: contributions.compactionPolicies?.map((registration) => {
|
|
805
|
+
const shouldCompact = admission.call(registration.shouldCompact);
|
|
806
|
+
return {
|
|
807
|
+
...registration,
|
|
808
|
+
entryId: entry.identity?.entryId ?? entry.path.join("/"),
|
|
809
|
+
activationId: entry.owner.activationId,
|
|
810
|
+
shouldCompact: (input) => shouldCompact({
|
|
811
|
+
...input,
|
|
812
|
+
signal: merged(input.signal)
|
|
813
|
+
})
|
|
814
|
+
};
|
|
815
|
+
}),
|
|
816
|
+
compactionCompilers: contributions.compactionCompilers?.map((compiler) => {
|
|
817
|
+
const compile$1 = admission.call(compiler.compile);
|
|
818
|
+
return {
|
|
819
|
+
...compiler,
|
|
820
|
+
entryId: entry.identity?.entryId ?? entry.path.join("/"),
|
|
821
|
+
activationId: entry.owner.activationId,
|
|
822
|
+
compile: (input) => compile$1({
|
|
823
|
+
...input,
|
|
824
|
+
signal: merged(input.signal)
|
|
825
|
+
})
|
|
826
|
+
};
|
|
827
|
+
}),
|
|
828
|
+
compactionObservers: contributions.compactionObservers?.map((observer) => {
|
|
829
|
+
const before = observer.before === void 0 ? void 0 : admission.call(observer.before);
|
|
830
|
+
return {
|
|
831
|
+
...observer,
|
|
832
|
+
entryId: entry.identity?.entryId ?? entry.path.join("/"),
|
|
833
|
+
activationId: entry.owner.activationId,
|
|
834
|
+
before: before === void 0 ? void 0 : (input) => before({
|
|
835
|
+
...input,
|
|
836
|
+
signal: merged(input.signal)
|
|
837
|
+
})
|
|
838
|
+
};
|
|
839
|
+
}),
|
|
840
|
+
inputTransforms: contributions.inputTransforms?.map((handler) => {
|
|
841
|
+
const transform = admission.call(handler.transform);
|
|
842
|
+
return {
|
|
843
|
+
...handler,
|
|
844
|
+
transform: (input, context) => transform(input, {
|
|
845
|
+
...context,
|
|
846
|
+
signal: merged(context.signal)
|
|
847
|
+
})
|
|
848
|
+
};
|
|
849
|
+
}),
|
|
850
|
+
preparationHooks: contributions.preparationHooks?.map((hook) => {
|
|
851
|
+
const around = admission.call(hook.around);
|
|
852
|
+
return {
|
|
853
|
+
...hook,
|
|
854
|
+
around: (draft, context, next) => around(draft, {
|
|
855
|
+
...context,
|
|
856
|
+
signal: merged(context.signal)
|
|
857
|
+
}, next)
|
|
858
|
+
};
|
|
859
|
+
}),
|
|
860
|
+
historySelectors: contributions.historySelectors?.map((selector) => {
|
|
861
|
+
const select = admission.call(selector.select);
|
|
862
|
+
return {
|
|
863
|
+
...selector,
|
|
864
|
+
select: (context) => select({
|
|
865
|
+
...context,
|
|
866
|
+
signal: merged(context.signal)
|
|
867
|
+
})
|
|
868
|
+
};
|
|
869
|
+
}),
|
|
870
|
+
sessionBehaviors: contributions.sessionBehaviors?.map((behavior) => ({
|
|
871
|
+
...behavior,
|
|
872
|
+
reduce: (...args) => {
|
|
873
|
+
admission.assert();
|
|
874
|
+
return behavior.reduce(...args);
|
|
875
|
+
},
|
|
876
|
+
project: (...args) => {
|
|
877
|
+
admission.assert();
|
|
878
|
+
return behavior.project(...args);
|
|
879
|
+
}
|
|
880
|
+
}))
|
|
881
|
+
},
|
|
882
|
+
behaviorSignal: Effect.fn("ModelComposition.behaviorSignal")(function* (name) {
|
|
883
|
+
const behavior = behaviorRegistrations.find((item) => item.name === name);
|
|
884
|
+
if (behavior === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Missing Session behavior"));
|
|
885
|
+
const changed = new AbortController();
|
|
886
|
+
const check$1 = () => {
|
|
887
|
+
const current = entry.live?.snapshot().sessionBehaviors?.find((item) => item.name === name);
|
|
888
|
+
if (!isEqual(behavior, current)) changed.abort(/* @__PURE__ */ new Error(`Session behavior ${name} changed`));
|
|
889
|
+
};
|
|
890
|
+
if (entry.live !== void 0) {
|
|
891
|
+
const live = entry.live;
|
|
892
|
+
yield* Effect.acquireRelease(Effect.sync(() => live.subscribe(check$1)), (unsubscribe) => Effect.sync(unsubscribe));
|
|
893
|
+
check$1();
|
|
894
|
+
}
|
|
895
|
+
return AbortSignal.any([changed.signal, ...[...closure].map((owner) => owner.owner.retirementSignal)]);
|
|
896
|
+
})
|
|
897
|
+
};
|
|
898
|
+
});
|
|
899
|
+
const declared = samples.flatMap(({ contributions }) => contributions.tools);
|
|
900
|
+
const names = /* @__PURE__ */ new Map();
|
|
901
|
+
const identities = /* @__PURE__ */ new Map();
|
|
902
|
+
for (const tool of declared) {
|
|
903
|
+
names.set(tool.name, (names.get(tool.name) ?? 0) + 1);
|
|
904
|
+
identities.set(tool.contributionId, (identities.get(tool.contributionId) ?? 0) + 1);
|
|
905
|
+
}
|
|
906
|
+
const isolated = new Set(policy === "strict" ? [] : declared.filter((tool) => (names.get(tool.name) ?? 0) > 1 || (identities.get(tool.contributionId) ?? 0) > 1));
|
|
907
|
+
const isolatedNames = new Set([...isolated].map((tool) => tool.name));
|
|
908
|
+
const isolatedIdentities = new Set([...isolated].map((tool) => tool.contributionId));
|
|
909
|
+
const tools = declared.filter((tool) => !isolated.has(tool));
|
|
910
|
+
const callbackOwners = samples.filter(({ contributions }) => [
|
|
911
|
+
contributions.hooks,
|
|
912
|
+
contributions.namedStates,
|
|
913
|
+
contributions.inputTransforms,
|
|
914
|
+
contributions.runYield,
|
|
915
|
+
contributions.preparationHooks,
|
|
916
|
+
contributions.historySelectors,
|
|
917
|
+
contributions.sessionBehaviors
|
|
918
|
+
].some((domain) => (domain?.length ?? 0) > 0)).map(({ entry }) => entry);
|
|
919
|
+
const toolOwners = /* @__PURE__ */ new Map();
|
|
920
|
+
for (const { entry, contributions } of samples) for (const tool of contributions.tools) {
|
|
921
|
+
if (isolatedNames.has(tool.name) || isolatedIdentities.has(tool.contributionId)) continue;
|
|
922
|
+
const owners = toolOwners.get(tool.name);
|
|
923
|
+
if (owners === void 0) toolOwners.set(tool.name, [entry]);
|
|
924
|
+
else owners.push(entry);
|
|
925
|
+
}
|
|
926
|
+
return {
|
|
927
|
+
tools,
|
|
928
|
+
bindings: new Map(snapshot.samples.flatMap(({ entry, version, contributions }) => contributions.tools.map((tool) => {
|
|
929
|
+
let binding = toolBindings.get(tool);
|
|
930
|
+
if (binding === void 0) {
|
|
931
|
+
binding = JSON.stringify([
|
|
932
|
+
entry.owner.activationId,
|
|
933
|
+
version ?? 0,
|
|
934
|
+
tool.contributionId
|
|
935
|
+
]);
|
|
936
|
+
toolBindings.set(tool, binding);
|
|
937
|
+
}
|
|
938
|
+
return [tool.contributionId, binding];
|
|
939
|
+
}))),
|
|
940
|
+
yieldBindings: new Map(snapshot.samples.flatMap(({ entry, version, contributions }) => (contributions.runYield ?? []).map((hook) => [hook.contributionId, JSON.stringify([
|
|
941
|
+
entry.owner.activationId,
|
|
942
|
+
version ?? 0,
|
|
943
|
+
hook.contributionId
|
|
944
|
+
])]))),
|
|
945
|
+
behaviorSignal: (name) => {
|
|
946
|
+
const owner = samples.find(({ contributions }) => contributions.sessionBehaviors?.some((behavior) => behavior.name === name));
|
|
947
|
+
if (owner === void 0) return Effect.die(/* @__PURE__ */ new Error(`Session behavior ${name} is unavailable`));
|
|
948
|
+
return owner.behaviorSignal(name);
|
|
949
|
+
},
|
|
950
|
+
isolatedTools: [...new Set([...isolated].map((tool) => tool.name))].sort(),
|
|
951
|
+
hooks: samples.flatMap(({ contributions }) => contributions.hooks ?? []),
|
|
952
|
+
namedStates: samples.flatMap(({ contributions }) => contributions.namedStates ?? []),
|
|
953
|
+
prefixes: samples.flatMap(({ contributions }) => contributions.prefixes ?? []),
|
|
954
|
+
runYield: samples.flatMap(({ contributions }) => contributions.runYield ?? []),
|
|
955
|
+
compactionPolicies: samples.flatMap(({ contributions }) => contributions.compactionPolicies ?? []),
|
|
956
|
+
compactionCompilers: samples.flatMap(({ contributions }) => contributions.compactionCompilers ?? []),
|
|
957
|
+
compactionObservers: samples.flatMap(({ contributions }) => contributions.compactionObservers ?? []),
|
|
958
|
+
inputTransforms: samples.flatMap(({ contributions }) => contributions.inputTransforms ?? []),
|
|
959
|
+
preparationHooks: samples.flatMap(({ contributions }) => contributions.preparationHooks ?? []),
|
|
960
|
+
historySelectors: samples.flatMap(({ contributions }) => contributions.historySelectors ?? []),
|
|
961
|
+
sessionBehaviors: samples.flatMap(({ contributions }) => contributions.sessionBehaviors ?? []),
|
|
962
|
+
borrow: (toolNames) => Effect.gen(function* () {
|
|
963
|
+
const releaseOwners = yield* snapshot.borrow([...callbackOwners, ...toolNames === void 0 ? [...toolOwners.values()].flat() : [...toolNames].flatMap((name) => toolOwners.get(name) ?? [])]);
|
|
964
|
+
const releaseCallbacks = yield* Effect.try({
|
|
965
|
+
try: () => {
|
|
966
|
+
const retained = [];
|
|
967
|
+
try {
|
|
968
|
+
const selected = new Set(tools.filter((tool) => toolNames === void 0 || toolNames.has(tool.name)).map((tool) => tool.name));
|
|
969
|
+
for (const sample of snapshot.samples) retained.push(retainPluginCallbacks(sample.contributions, selected));
|
|
970
|
+
} catch (cause) {
|
|
971
|
+
for (const release of retained) release();
|
|
972
|
+
throw cause;
|
|
973
|
+
}
|
|
974
|
+
return () => {
|
|
975
|
+
for (const release of retained) release();
|
|
976
|
+
};
|
|
977
|
+
},
|
|
978
|
+
catch: ensureError
|
|
979
|
+
}).pipe(Effect.onError(() => releaseOwners));
|
|
980
|
+
return Effect.sync(releaseCallbacks).pipe(Effect.andThen(releaseOwners));
|
|
981
|
+
})
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
//#endregion
|
|
986
|
+
//#region src/platform.ts
|
|
987
|
+
const makeRoot = Effect.fn("PluginRoot.make")(function* (options) {
|
|
988
|
+
const changes = yield* PubSub.sliding(1);
|
|
989
|
+
const failures = [];
|
|
990
|
+
const commandListeners = /* @__PURE__ */ new Set();
|
|
991
|
+
let commandDirectory = [];
|
|
992
|
+
let commandBehaviors = [];
|
|
993
|
+
let readSnapshot = () => void 0;
|
|
994
|
+
let closing = false;
|
|
995
|
+
const changed = () => {
|
|
996
|
+
PubSub.publishUnsafe(changes, void 0);
|
|
997
|
+
const snapshot = readSnapshot();
|
|
998
|
+
if (snapshot === void 0 || closing) return;
|
|
999
|
+
const projection = modelContributions(snapshot, options.modelToolConflictPolicy);
|
|
1000
|
+
const next = projection.tools.flatMap((tool) => {
|
|
1001
|
+
if (tool.metadata?.["sorbet.dev/slash-command"] === void 0) return [];
|
|
1002
|
+
const bindingId = projection.bindings.get(tool.contributionId);
|
|
1003
|
+
if (bindingId === void 0) throw new Error("Missing live Tool binding");
|
|
1004
|
+
return [{
|
|
1005
|
+
...captureModelToolMetadata(tool),
|
|
1006
|
+
bindingId
|
|
1007
|
+
}];
|
|
1008
|
+
});
|
|
1009
|
+
const behaviors = projection.sessionBehaviors.map(captureSessionBehaviorMetadata);
|
|
1010
|
+
if (isEqual(commandDirectory, next) && isEqual(commandBehaviors, behaviors)) return;
|
|
1011
|
+
freezeModelEvidence(next);
|
|
1012
|
+
freezeModelEvidence(behaviors);
|
|
1013
|
+
commandDirectory = next;
|
|
1014
|
+
commandBehaviors = behaviors;
|
|
1015
|
+
for (const listener of commandListeners) try {
|
|
1016
|
+
const result = listener();
|
|
1017
|
+
if (isPromise(result)) result.catch(() => {});
|
|
1018
|
+
} catch {}
|
|
1019
|
+
};
|
|
1020
|
+
const composition = yield* makeLiveComposition({
|
|
1021
|
+
...options,
|
|
1022
|
+
objectNamespace: options.scopeId,
|
|
1023
|
+
changed,
|
|
1024
|
+
onFailure: (error) => Effect.sync(() => {
|
|
1025
|
+
failures.push(error.message);
|
|
1026
|
+
changed();
|
|
1027
|
+
})
|
|
1028
|
+
});
|
|
1029
|
+
readSnapshot = composition.snapshot;
|
|
1030
|
+
const sample = () => {
|
|
1031
|
+
if (closing) throw new PluginLifecycleError("admission", "Plugin root is closing");
|
|
1032
|
+
const snapshot = composition.checkpoint();
|
|
1033
|
+
if (snapshot === void 0) throw new PluginLifecycleError("admission", "Composition is not initialized");
|
|
1034
|
+
return modelContributions(snapshot, options.modelToolConflictPolicy);
|
|
1035
|
+
};
|
|
1036
|
+
const model = yield* makeModelConsumer(options, sample);
|
|
1037
|
+
yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
|
|
1038
|
+
const status = () => ({
|
|
1039
|
+
phase: closing ? "closing" : "open",
|
|
1040
|
+
failures: [...failures],
|
|
1041
|
+
...composition.status(),
|
|
1042
|
+
requests: model.requestCount(),
|
|
1043
|
+
isolatedTools: (() => {
|
|
1044
|
+
const snapshot = closing ? void 0 : composition.checkpoint();
|
|
1045
|
+
return snapshot === void 0 ? [] : modelContributions(snapshot, options.modelToolConflictPolicy).isolatedTools;
|
|
1046
|
+
})()
|
|
1047
|
+
});
|
|
1048
|
+
return {
|
|
1049
|
+
composition,
|
|
1050
|
+
model,
|
|
1051
|
+
commandTools: () => commandDirectory,
|
|
1052
|
+
subscribeCommands: (listener) => {
|
|
1053
|
+
commandListeners.add(listener);
|
|
1054
|
+
return () => {
|
|
1055
|
+
commandListeners.delete(listener);
|
|
1056
|
+
};
|
|
1057
|
+
},
|
|
1058
|
+
sample,
|
|
1059
|
+
status,
|
|
1060
|
+
changes,
|
|
1061
|
+
changed,
|
|
1062
|
+
reportFailure: (error) => {
|
|
1063
|
+
failures.push(ensureError(error).message);
|
|
1064
|
+
changed();
|
|
1065
|
+
},
|
|
1066
|
+
close: Effect.gen(function* () {
|
|
1067
|
+
closing = true;
|
|
1068
|
+
commandListeners.clear();
|
|
1069
|
+
yield* composition.stop;
|
|
1070
|
+
yield* model.close;
|
|
1071
|
+
yield* composition.close;
|
|
1072
|
+
})
|
|
1073
|
+
};
|
|
1074
|
+
});
|
|
1075
|
+
var PluginRoot = class extends Context.Service()("sorbet/plugins/PluginRoot") {};
|
|
1076
|
+
const liveScopes = /* @__PURE__ */ new WeakMap();
|
|
1077
|
+
/** Composition root. Desired persistence finishes before resource convergence begins. */
|
|
1078
|
+
var PluginPlatform = class PluginPlatform {
|
|
1079
|
+
#runtime;
|
|
1080
|
+
#root;
|
|
1081
|
+
#options;
|
|
1082
|
+
#members = [];
|
|
1083
|
+
#closing;
|
|
1084
|
+
#unsubscribe;
|
|
1085
|
+
#desiredLane = Promise.resolve();
|
|
1086
|
+
#generation = -1;
|
|
1087
|
+
#releaseScope = () => {};
|
|
1088
|
+
#sessionControl = {};
|
|
1089
|
+
#sessionRecords = {};
|
|
1090
|
+
constructor(options, runtime, root) {
|
|
1091
|
+
this.#options = options;
|
|
1092
|
+
this.#runtime = runtime;
|
|
1093
|
+
this.#root = root;
|
|
1094
|
+
}
|
|
1095
|
+
static async open(options) {
|
|
1096
|
+
const captured = { ...options };
|
|
1097
|
+
for (const duration of [captured.preparationTimeoutMs, captured.cleanupTimeoutMs]) if (duration !== void 0) decode(s.int({
|
|
1098
|
+
minimum: 1,
|
|
1099
|
+
maximum: Number.MAX_SAFE_INTEGER
|
|
1100
|
+
}), duration);
|
|
1101
|
+
const authority = captured.durable?.authority;
|
|
1102
|
+
const scopes = authority === void 0 ? void 0 : liveScopes.get(authority) ?? /* @__PURE__ */ new Set();
|
|
1103
|
+
if (scopes?.has(captured.scopeId)) throw new Error("Composition scope already has a live owner");
|
|
1104
|
+
if (authority !== void 0 && scopes !== void 0) {
|
|
1105
|
+
scopes.add(captured.scopeId);
|
|
1106
|
+
liveScopes.set(authority, scopes);
|
|
1107
|
+
}
|
|
1108
|
+
const sessionLifetime = new AbortController();
|
|
1109
|
+
const sessionControl = {};
|
|
1110
|
+
const sessionRecords = {};
|
|
1111
|
+
if (captured.sessions === void 0 && captured.sessionId !== void 0) {
|
|
1112
|
+
const sessionId = captured.sessionId;
|
|
1113
|
+
captured.sessions = (actor) => {
|
|
1114
|
+
return {
|
|
1115
|
+
discover: async () => [{ sessionId }],
|
|
1116
|
+
bind: async (requested, bindOptions) => ({
|
|
1117
|
+
sessionId: requested,
|
|
1118
|
+
signal: bindOptions?.signal === void 0 ? sessionLifetime.signal : AbortSignal.any([sessionLifetime.signal, bindOptions.signal]),
|
|
1119
|
+
control: sessionControl.current,
|
|
1120
|
+
...sessionRecords.current === void 0 ? {} : { records: sessionRecords.current({
|
|
1121
|
+
entryId: actor.entryId,
|
|
1122
|
+
...actor.activationId === void 0 ? {} : { activationId: actor.activationId }
|
|
1123
|
+
}) }
|
|
1124
|
+
})
|
|
1125
|
+
};
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
const runtime = makePluginRuntime(captured);
|
|
1129
|
+
let acquired;
|
|
1130
|
+
try {
|
|
1131
|
+
const root = await runtime.runPromise(PluginRoot);
|
|
1132
|
+
acquired = root;
|
|
1133
|
+
const platform = new PluginPlatform(captured, runtime, root);
|
|
1134
|
+
platform.#sessionControl = sessionControl;
|
|
1135
|
+
platform.#sessionRecords = sessionRecords;
|
|
1136
|
+
platform.#releaseScope = () => {
|
|
1137
|
+
scopes?.delete(captured.scopeId);
|
|
1138
|
+
sessionLifetime.abort();
|
|
1139
|
+
};
|
|
1140
|
+
await runtime.runPromise(root.composition.update([]));
|
|
1141
|
+
if (authority !== void 0) {
|
|
1142
|
+
await platform.reconcile();
|
|
1143
|
+
platform.#unsubscribe = authority.subscribeInvalidation(() => {
|
|
1144
|
+
root.changed();
|
|
1145
|
+
platform.reconcile().catch((cause) => root.reportFailure(ensureError(cause)));
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
return platform;
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
await runtime.dispose();
|
|
1151
|
+
acquired?.composition.detachObservation();
|
|
1152
|
+
scopes?.delete(captured.scopeId);
|
|
1153
|
+
throw error;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
get modelTools() {
|
|
1157
|
+
const root = this.#root;
|
|
1158
|
+
return {
|
|
1159
|
+
get commandTools() {
|
|
1160
|
+
return root.commandTools();
|
|
1161
|
+
},
|
|
1162
|
+
subscribeCommands: root.subscribeCommands,
|
|
1163
|
+
get tools() {
|
|
1164
|
+
return root.sample().tools.filter((tool) => tool.discovery?.exposure !== "hidden").map(captureModelToolMetadata);
|
|
1165
|
+
},
|
|
1166
|
+
get sessionBehaviors() {
|
|
1167
|
+
return root.sample().sessionBehaviors.map(captureSessionBehaviorMetadata);
|
|
1168
|
+
},
|
|
1169
|
+
get compaction() {
|
|
1170
|
+
const projection = root.sample();
|
|
1171
|
+
const policies = projection.compactionPolicies ?? [];
|
|
1172
|
+
const compilers = projection.compactionCompilers ?? [];
|
|
1173
|
+
const observers = projection.compactionObservers ?? [];
|
|
1174
|
+
if (policies.length > 1) throw new Error("Multiple compaction policies are installed");
|
|
1175
|
+
if (compilers.length > 1) throw new Error("Multiple compaction compilers are installed");
|
|
1176
|
+
const policy = policies[0];
|
|
1177
|
+
const compiler = compilers[0];
|
|
1178
|
+
if (policy === void 0 && compiler === void 0 && observers.length === 0) return void 0;
|
|
1179
|
+
return {
|
|
1180
|
+
...policy === void 0 ? {} : { policy },
|
|
1181
|
+
...compiler === void 0 ? {} : { compiler },
|
|
1182
|
+
...observers.length === 0 ? {} : { observers }
|
|
1183
|
+
};
|
|
1184
|
+
},
|
|
1185
|
+
acquire: (input) => {
|
|
1186
|
+
const closed = this.#closed();
|
|
1187
|
+
if (closed !== void 0) throw closed;
|
|
1188
|
+
return this.#runtime.runSync(root.model.acquire(input));
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
get objects() {
|
|
1193
|
+
return {
|
|
1194
|
+
catalog: () => Effect.suspend(() => {
|
|
1195
|
+
const closed = this.#closed();
|
|
1196
|
+
if (closed !== void 0) return Effect.fail(closed);
|
|
1197
|
+
return this.#root.composition.objects.catalog();
|
|
1198
|
+
}),
|
|
1199
|
+
acquire: (type, key) => Effect.suspend(() => {
|
|
1200
|
+
const closed = this.#closed();
|
|
1201
|
+
if (closed !== void 0) return Effect.fail(closed);
|
|
1202
|
+
return this.#root.composition.objects.acquire(type, key);
|
|
1203
|
+
})
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
get objectCapabilities() {
|
|
1207
|
+
return makeObjectCapabilitySource({
|
|
1208
|
+
catalog: () => this.objects.catalog(),
|
|
1209
|
+
acquireAddress: (address) => Effect.suspend(() => {
|
|
1210
|
+
const closed = this.#closed();
|
|
1211
|
+
if (closed !== void 0) return Effect.fail(closed);
|
|
1212
|
+
return this.#root.composition.objects.acquireAddress(address);
|
|
1213
|
+
})
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
/** Namespace of every Object this Platform owns. Object addresses are scoped by it. */
|
|
1217
|
+
get objectNamespace() {
|
|
1218
|
+
return this.#options.scopeId;
|
|
1219
|
+
}
|
|
1220
|
+
async replace(component) {
|
|
1221
|
+
if (this.#options.durable !== void 0) throw new Error("Durable composition uses Desired");
|
|
1222
|
+
const admission = component?.admission;
|
|
1223
|
+
const capturedAdmission = admission === void 0 ? void 0 : {
|
|
1224
|
+
available: admission.available.bind(admission),
|
|
1225
|
+
subscribe: admission.subscribe.bind(admission)
|
|
1226
|
+
};
|
|
1227
|
+
const captured = component === void 0 ? void 0 : {
|
|
1228
|
+
componentId: component.componentId,
|
|
1229
|
+
executionProfile: component.executionProfile,
|
|
1230
|
+
admission: capturedAdmission,
|
|
1231
|
+
load: component.load?.bind(component),
|
|
1232
|
+
activate: component.activate.bind(component)
|
|
1233
|
+
};
|
|
1234
|
+
await this.#runtime.runPromise(this.#root.composition.update(captured === void 0 ? [] : [{ component: captured }]));
|
|
1235
|
+
}
|
|
1236
|
+
async configure(entries) {
|
|
1237
|
+
if (this.#options.durable !== void 0) throw new Error("Durable composition uses Desired");
|
|
1238
|
+
const members = captureProgrammaticEntries(entries).map((entry) => {
|
|
1239
|
+
const identity = {
|
|
1240
|
+
kind: "programmatic",
|
|
1241
|
+
entryId: entry.key,
|
|
1242
|
+
apply: entry.apply,
|
|
1243
|
+
requires: entry.requires,
|
|
1244
|
+
provides: entry.provides,
|
|
1245
|
+
realm: entry.realm,
|
|
1246
|
+
replacement: entry.replacement,
|
|
1247
|
+
config: entry.config
|
|
1248
|
+
};
|
|
1249
|
+
return {
|
|
1250
|
+
component: this.#members.find((member) => sameEntryIdentity(member.identity, identity))?.component ?? entry.component,
|
|
1251
|
+
identity,
|
|
1252
|
+
requires: entry.requires,
|
|
1253
|
+
provides: entry.provides,
|
|
1254
|
+
realm: entry.realm,
|
|
1255
|
+
replacement: entry.replacement
|
|
1256
|
+
};
|
|
1257
|
+
});
|
|
1258
|
+
await this.#runtime.runPromise(this.#root.composition.update(members));
|
|
1259
|
+
this.#members = members;
|
|
1260
|
+
}
|
|
1261
|
+
/** Rebuilds current Desired resources. It never loads a historical request binding. */
|
|
1262
|
+
reconcile() {
|
|
1263
|
+
const run = this.#desiredLane.then(async () => {
|
|
1264
|
+
if (this.#closing !== void 0) return;
|
|
1265
|
+
const durable = this.#options.durable;
|
|
1266
|
+
if (durable === void 0) throw new Error("No Desired authority");
|
|
1267
|
+
const authority = durable.authority.status();
|
|
1268
|
+
if (authority.closed || authority.fenced) return;
|
|
1269
|
+
if (this.#generation === authority.sequence) return;
|
|
1270
|
+
const excluded = /* @__PURE__ */ new Set();
|
|
1271
|
+
for (const entry of authority.desired.entries) try {
|
|
1272
|
+
durable.authority.assertPackageExecution(entry.packageId);
|
|
1273
|
+
} catch (error) {
|
|
1274
|
+
if (!check(s.obj({ code: s.lit("revoked-package") }, { open: true }), error)) throw error;
|
|
1275
|
+
excluded.add(entry.entryId);
|
|
1276
|
+
}
|
|
1277
|
+
const entries = new Map(authority.desired.entries.map((entry) => [entry.entryId, entry]));
|
|
1278
|
+
const isExcluded = (entryId) => {
|
|
1279
|
+
const entry = entries.get(entryId);
|
|
1280
|
+
return excluded.has(entryId) || entry?.parentId != null && isExcluded(entry.parentId);
|
|
1281
|
+
};
|
|
1282
|
+
const members = authority.desired.entries.filter((entry) => entry.effectiveEnabled && !isExcluded(entry.entryId)).map((entry) => {
|
|
1283
|
+
const identity = {
|
|
1284
|
+
kind: "package",
|
|
1285
|
+
entryId: entry.entryId,
|
|
1286
|
+
packageId: entry.packageId,
|
|
1287
|
+
config: entry.config
|
|
1288
|
+
};
|
|
1289
|
+
const previous = this.#members.find((member) => sameEntryIdentity(member.identity, identity));
|
|
1290
|
+
return {
|
|
1291
|
+
identity,
|
|
1292
|
+
children: [],
|
|
1293
|
+
parentId: entry.parentId,
|
|
1294
|
+
component: previous?.component ?? durable.loader.componentAt(durable.authority.executionReference(entry.entryId))
|
|
1295
|
+
};
|
|
1296
|
+
});
|
|
1297
|
+
const byId = new Map(members.map((member) => [member.identity.entryId, member]));
|
|
1298
|
+
const roots = [];
|
|
1299
|
+
for (const member of members) if (member.parentId === null) roots.push(member);
|
|
1300
|
+
else {
|
|
1301
|
+
const parent = byId.get(member.parentId);
|
|
1302
|
+
if (parent === void 0) throw new Error("Missing Desired parent");
|
|
1303
|
+
parent.children.push(member);
|
|
1304
|
+
}
|
|
1305
|
+
await this.#runtime.runPromise(this.#root.composition.update(roots));
|
|
1306
|
+
this.#members = members;
|
|
1307
|
+
this.#generation = authority.sequence;
|
|
1308
|
+
});
|
|
1309
|
+
this.#desiredLane = run.catch(() => {});
|
|
1310
|
+
return run;
|
|
1311
|
+
}
|
|
1312
|
+
async status() {
|
|
1313
|
+
return this.#root.status();
|
|
1314
|
+
}
|
|
1315
|
+
async flush() {
|
|
1316
|
+
await this.#desiredLane;
|
|
1317
|
+
await this.#runtime.runPromise(this.#root.composition.flush);
|
|
1318
|
+
}
|
|
1319
|
+
async queryComposition() {
|
|
1320
|
+
const durable = this.#options.durable;
|
|
1321
|
+
if (durable === void 0) throw new Error("No Desired authority");
|
|
1322
|
+
const authority = durable.authority.status();
|
|
1323
|
+
return structuredClone({
|
|
1324
|
+
scopeId: this.#options.scopeId,
|
|
1325
|
+
generation: authority.desired.sequence,
|
|
1326
|
+
desired: authority.desired.entries,
|
|
1327
|
+
authority: {
|
|
1328
|
+
fenced: authority.fenced,
|
|
1329
|
+
closed: authority.closed
|
|
1330
|
+
},
|
|
1331
|
+
observed: this.#root.status()
|
|
1332
|
+
});
|
|
1333
|
+
}
|
|
1334
|
+
createCompositionControl(policy) {
|
|
1335
|
+
return makeCompositionControl({
|
|
1336
|
+
queryComposition: () => this.queryComposition(),
|
|
1337
|
+
applyComposition: (patch, authorize) => this.#applyComposition(patch, authorize),
|
|
1338
|
+
watchComposition: (observe, signal) => this.watchComposition(observe, signal)
|
|
1339
|
+
}, policy);
|
|
1340
|
+
}
|
|
1341
|
+
async #applyComposition(patch, authorize) {
|
|
1342
|
+
const durable = this.#options.durable;
|
|
1343
|
+
if (durable === void 0) throw new Error("No Desired authority");
|
|
1344
|
+
const receipt = await durable.authority.applyDesired(captureCompositionData(DesiredPluginPatchSchema, patch), authorize);
|
|
1345
|
+
this.reconcile().catch((cause) => this.#root.reportFailure(ensureError(cause)));
|
|
1346
|
+
return {
|
|
1347
|
+
accepted: true,
|
|
1348
|
+
generation: receipt[1].sequence,
|
|
1349
|
+
reconciliation: "pending",
|
|
1350
|
+
snapshot: await this.queryComposition()
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1353
|
+
async watchComposition(observe, signal) {
|
|
1354
|
+
const root = this.#root;
|
|
1355
|
+
const publish = Effect.tryPromise({
|
|
1356
|
+
try: async (observerSignal) => observe(await this.queryComposition(), observerSignal),
|
|
1357
|
+
catch: ensureError
|
|
1358
|
+
});
|
|
1359
|
+
await this.#runtime.runPromise(Effect.scoped(Effect.gen(function* () {
|
|
1360
|
+
const subscription = yield* PubSub.subscribe(root.changes);
|
|
1361
|
+
yield* publish;
|
|
1362
|
+
yield* Effect.forever(PubSub.take(subscription).pipe(Effect.andThen(publish)));
|
|
1363
|
+
})), { signal });
|
|
1364
|
+
}
|
|
1365
|
+
/** Root admission: every entry point that can still open work asks this one question. */
|
|
1366
|
+
#closed() {
|
|
1367
|
+
return this.#closing === void 0 ? void 0 : new PluginLifecycleError("admission", "Plugin root is closing");
|
|
1368
|
+
}
|
|
1369
|
+
/** Binds the current Host Session control used by Plugin `ctx.session.bind`. */
|
|
1370
|
+
bindSessionControl(control) {
|
|
1371
|
+
const closed = this.#closed();
|
|
1372
|
+
if (closed !== void 0) throw closed;
|
|
1373
|
+
this.#sessionControl.current = control;
|
|
1374
|
+
}
|
|
1375
|
+
/** Binds per-entry durable Records for the default single-Session directory. */
|
|
1376
|
+
bindSessionRecords(records) {
|
|
1377
|
+
const closed = this.#closed();
|
|
1378
|
+
if (closed !== void 0) throw closed;
|
|
1379
|
+
this.#sessionRecords.current = records;
|
|
1380
|
+
}
|
|
1381
|
+
close() {
|
|
1382
|
+
this.#unsubscribe?.();
|
|
1383
|
+
this.#closing ??= this.#desiredLane.then(async () => {
|
|
1384
|
+
await this.#runtime.runPromise(this.#root.close);
|
|
1385
|
+
await this.#runtime.dispose();
|
|
1386
|
+
this.#root.composition.detachObservation();
|
|
1387
|
+
this.#releaseScope();
|
|
1388
|
+
}).catch((error) => {
|
|
1389
|
+
this.#closing = void 0;
|
|
1390
|
+
throw error;
|
|
1391
|
+
});
|
|
1392
|
+
return this.#closing;
|
|
1393
|
+
}
|
|
1394
|
+
};
|
|
1395
|
+
function makePluginRuntime(options) {
|
|
1396
|
+
return ManagedRuntime.make(Layer.effect(PluginRoot, makeRoot(options)));
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
//#endregion
|
|
1400
|
+
export { DesiredPluginPatchSchema, MemoryPluginStore, PluginAuthorityError, PluginCompositionAuthority, PluginCompositionError, PluginConfigError, PluginLifecycleError, PluginModuleError, PluginPackageFormatError, PluginPlatform, PluginSessionSendInputSchema, PluginSessionWriteInputSchema, SessionBehaviorCommandSchema, SessionBehaviorMetadataSchema, SessionBehaviorViewSchema, decodePluginPackage, defineObject, encodePluginPackage, inspectPluginModules, materializePluginConfig, projectPluginComposition };
|