@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,488 @@
1
+ import * as s from "@earendil-works/pi-schema";
2
+ import { check, decode } from "@sorbetai/schema";
3
+ import { ContextXmlElementSchema, JsonValueSchema, NamedStateNameSchema, captureJsonValue } from "@sorbetai/context";
4
+ import { isEqual, isFunction, sortBy } from "es-toolkit";
5
+
6
+ //#region src/contributions/tool-declaration.ts
7
+ const ToolRecoveryPolicy = s.union([s.lit("unsafe"), s.lit("safe")]);
8
+ const PluginToolDiscoverySchema = s.obj({
9
+ exposure: s.opt(s.union([
10
+ s.lit("direct"),
11
+ s.lit("deferred"),
12
+ s.lit("hidden")
13
+ ])),
14
+ namespace: s.opt(s.obj({
15
+ name: s.str(),
16
+ description: s.opt(s.str())
17
+ }, { open: false }))
18
+ }, { open: false });
19
+ const ModelToolMetadataProperties = {
20
+ contributionId: s.str({ minLength: 1 }),
21
+ name: s.str({ minLength: 1 }),
22
+ label: s.opt(s.str()),
23
+ description: s.str(),
24
+ parameters: s.map(JsonValueSchema),
25
+ outputSchema: s.opt(s.map(JsonValueSchema)),
26
+ discovery: s.opt(PluginToolDiscoverySchema),
27
+ metadata: s.opt(s.map(JsonValueSchema))
28
+ };
29
+ const ModelToolMetadataSchema = s.obj(ModelToolMetadataProperties, { open: false });
30
+ /** Captures only model-facing metadata, omitting absent optional fields in durable descriptors. */
31
+ function captureModelToolMetadata(tool) {
32
+ decode(ToolRecoveryPolicy, tool.recovery ?? "unsafe");
33
+ return decode(ModelToolMetadataSchema, captureJsonValue({
34
+ contributionId: tool.contributionId,
35
+ name: tool.name,
36
+ label: tool.label,
37
+ description: tool.description,
38
+ parameters: tool.parameters,
39
+ outputSchema: tool.outputSchema,
40
+ metadata: tool.metadata,
41
+ discovery: tool.discovery
42
+ }));
43
+ }
44
+
45
+ //#endregion
46
+ //#region src/contributions/session-behavior.ts
47
+ const Identity = s.str({ minLength: 1 });
48
+ const SessionBehaviorViewSchema = s.obj({
49
+ active: s.bool(),
50
+ contextState: s.opt(JsonValueSchema),
51
+ constraints: s.opt(s.obj({
52
+ toolNames: s.arr(Identity, { uniqueItems: true }),
53
+ workspace: s.opt(s.lit("read-only"))
54
+ }, { open: false })),
55
+ instructions: s.opt(s.str()),
56
+ checklist: s.opt(s.arr(s.obj({
57
+ content: Identity,
58
+ status: s.union([
59
+ s.lit("pending"),
60
+ s.lit("in_progress"),
61
+ s.lit("completed")
62
+ ])
63
+ }, { open: false }))),
64
+ decision: s.opt(s.obj({
65
+ id: Identity,
66
+ title: Identity,
67
+ markdown: s.str(),
68
+ choices: s.arr(s.obj({
69
+ id: Identity,
70
+ title: Identity
71
+ }, { open: false }), { minItems: 1 })
72
+ }, { open: false })),
73
+ continuation: s.opt(s.obj({
74
+ id: Identity,
75
+ prompt: Identity
76
+ }, { open: false }))
77
+ }, { open: false });
78
+ const SessionBehaviorMetadataSchema = s.obj({
79
+ contributionId: Identity,
80
+ name: Identity,
81
+ title: Identity,
82
+ stateSchema: s.map(JsonValueSchema),
83
+ initialState: s.opt(JsonValueSchema),
84
+ initialView: s.opt(SessionBehaviorViewSchema)
85
+ }, { open: false });
86
+ const SessionBehaviorCommandSchema = s.obj({
87
+ name: Identity,
88
+ input: JsonValueSchema
89
+ }, { open: false });
90
+ function captureSessionBehaviors(entries) {
91
+ const names = /* @__PURE__ */ new Set();
92
+ const identities = /* @__PURE__ */ new Set();
93
+ return entries.map((entry) => {
94
+ if (names.has(entry.name) || identities.has(entry.contributionId)) throw new TypeError("Duplicate Session behavior");
95
+ names.add(entry.name);
96
+ identities.add(entry.contributionId);
97
+ return {
98
+ ...captureSessionBehaviorMetadata(entry),
99
+ reduce: entry.reduce.bind(entry),
100
+ project: entry.project.bind(entry)
101
+ };
102
+ });
103
+ }
104
+ function captureSessionBehaviorMetadata(entry) {
105
+ const initialState = entry.initialState === void 0 ? void 0 : decode(JsonValueSchema, decode(entry.stateSchema, entry.initialState));
106
+ return decode(SessionBehaviorMetadataSchema, {
107
+ contributionId: entry.contributionId,
108
+ name: entry.name,
109
+ title: entry.title,
110
+ stateSchema: structuredClone(entry.stateSchema),
111
+ initialState: structuredClone(initialState),
112
+ initialView: initialState === void 0 ? void 0 : entry.project(structuredClone(initialState))
113
+ });
114
+ }
115
+
116
+ //#endregion
117
+ //#region src/contributions/input-transform.ts
118
+ const PluginInputSchema = s.union([s.str({ minLength: 1 }), s.arr(s.union([s.obj({
119
+ type: s.lit("text"),
120
+ text: s.str(),
121
+ textSignature: s.opt(s.str())
122
+ }, { open: false }), s.obj({
123
+ type: s.lit("image"),
124
+ data: s.str({ minLength: 1 }),
125
+ mimeType: s.str({ minLength: 1 })
126
+ }, { open: false })]), { minItems: 1 })]);
127
+ const InputTransformMetadataProperties = { contributionId: s.str({ minLength: 1 }) };
128
+ const InputTransformMetadataSchema = s.obj(InputTransformMetadataProperties, { open: false });
129
+ function captureInputTransforms(values) {
130
+ const captured = values.map(({ contributionId }) => decode(InputTransformMetadataSchema, { contributionId }));
131
+ if (new Set(captured.map((value) => value.contributionId)).size !== captured.length) throw new TypeError("Duplicate Plugin input transformation");
132
+ return sortBy(captured, ["contributionId"]);
133
+ }
134
+
135
+ //#endregion
136
+ //#region src/contributions/context-preparation.ts
137
+ const PreparationHookMetadataProperties = { hookId: s.str({ minLength: 1 }) };
138
+ const PreparationHookMetadataSchema = s.obj(PreparationHookMetadataProperties, { open: false });
139
+ function capturePreparationHooks(hooks) {
140
+ const metadata = hooks.map(({ hookId }) => decode(PreparationHookMetadataSchema, { hookId }));
141
+ if (new Set(metadata.map((hook) => hook.hookId)).size !== metadata.length) throw new TypeError("Duplicate Plugin Context preparation Hook");
142
+ return metadata;
143
+ }
144
+
145
+ //#endregion
146
+ //#region src/contributions/prefix.ts
147
+ const PluginPrefixContributionSchema = s.obj({
148
+ contributionId: s.str({ minLength: 1 }),
149
+ content: s.str()
150
+ }, { open: false });
151
+ function capturePluginPrefixes(prefixes) {
152
+ const captured = prefixes.map((prefix) => structuredClone(decode(PluginPrefixContributionSchema, prefix)));
153
+ if (new Set(captured.map((prefix) => prefix.contributionId)).size !== captured.length) throw new TypeError("Duplicate Plugin Prefix contribution");
154
+ return sortBy(captured, ["contributionId"]);
155
+ }
156
+
157
+ //#endregion
158
+ //#region src/contributions/named-state.ts
159
+ const NamedStateMetadataProperties = {
160
+ contributionId: s.str({ minLength: 1 }),
161
+ stateName: NamedStateNameSchema,
162
+ schema: s.map(JsonValueSchema),
163
+ itemKey: s.opt(s.str({ minLength: 1 }))
164
+ };
165
+ const NamedStateMetadataSchema = s.obj(NamedStateMetadataProperties, { open: false });
166
+ const PluginStateReadResultSchema = s.union([s.obj({
167
+ present: s.lit(true),
168
+ value: JsonValueSchema,
169
+ element: ContextXmlElementSchema
170
+ }, { open: false }), s.obj({ present: s.lit(false) }, { open: false })]);
171
+ function captureNamedStateMetadata(state) {
172
+ return decode(NamedStateMetadataSchema, {
173
+ contributionId: state.contributionId,
174
+ stateName: state.stateName,
175
+ schema: captureJsonValue(state.schema),
176
+ itemKey: state.itemKey
177
+ });
178
+ }
179
+ function orderNamedStates(states) {
180
+ const names = new Set(states.map((state) => state.stateName));
181
+ const ids = new Set(states.map((state) => state.contributionId));
182
+ if (names.size !== states.length || ids.size !== states.length) throw new TypeError("Duplicate Plugin named state");
183
+ return sortBy(states, ["stateName"]);
184
+ }
185
+
186
+ //#endregion
187
+ //#region src/contributions/callback.ts
188
+ /** JavaScript checks callability; the owning native boundary supplies the callback signature. */
189
+ function decodeCallback(input) {
190
+ if (!isFunction(input)) throw new TypeError("Plugin callback must be a function");
191
+ return input;
192
+ }
193
+
194
+ //#endregion
195
+ //#region src/contributions/tool-result.ts
196
+ const ToolResultProperties = {
197
+ content: s.arr(s.union([s.obj({
198
+ type: s.lit("text"),
199
+ text: s.str()
200
+ }, { open: true }), s.obj({
201
+ type: s.lit("image"),
202
+ data: s.str(),
203
+ mimeType: s.str()
204
+ }, { open: true })])),
205
+ details: JsonValueSchema,
206
+ structuredContent: s.opt(JsonValueSchema),
207
+ isError: s.opt(s.bool())
208
+ };
209
+ const ToolResultSchema = s.obj(ToolResultProperties, { open: false });
210
+
211
+ //#endregion
212
+ //#region src/contributions/tool-hooks.ts
213
+ const ToolHookMetadataProperties = {
214
+ contributionId: s.str({ minLength: 1 }),
215
+ version: s.opt(s.int({ minimum: 1 })),
216
+ before: s.opt(s.arr(s.str({ minLength: 1 }))),
217
+ after: s.opt(s.arr(s.str({ minLength: 1 })))
218
+ };
219
+ const ToolHookMetadataSchema = s.obj(ToolHookMetadataProperties, { open: false });
220
+ function captureToolHookMetadata(hook) {
221
+ return decode(ToolHookMetadataSchema, captureJsonValue({
222
+ contributionId: hook.contributionId,
223
+ version: hook.version ?? 1,
224
+ before: hook.before,
225
+ after: hook.after
226
+ }));
227
+ }
228
+ const ToolHookFeedbackSchema = s.obj({
229
+ ...ToolResultProperties,
230
+ isError: s.bool()
231
+ }, { open: false });
232
+ const HookInputSchema = s.obj({
233
+ input: JsonValueSchema,
234
+ state: s.opt(JsonValueSchema)
235
+ }, { open: false });
236
+ const HookBlockSchema = s.obj({
237
+ block: s.lit(true),
238
+ reason: s.str()
239
+ }, { open: false });
240
+ const HookResponseSchema = s.obj({
241
+ respond: ToolHookFeedbackSchema,
242
+ input: JsonValueSchema
243
+ }, { open: false });
244
+ const ToolHookPreparationSchema = s.union([
245
+ HookInputSchema,
246
+ HookBlockSchema,
247
+ HookResponseSchema
248
+ ]);
249
+ const PreparedToolHooksSchema = s.obj({
250
+ input: JsonValueSchema,
251
+ steps: s.arr(s.obj({
252
+ contributionId: s.str(),
253
+ version: s.int({ minimum: 1 }),
254
+ state: JsonValueSchema
255
+ }, { open: true })),
256
+ outcome: s.union([
257
+ s.obj({ kind: s.lit("execute") }, { open: true }),
258
+ s.obj({
259
+ kind: s.lit("block"),
260
+ contributionId: s.str(),
261
+ reason: s.str()
262
+ }, { open: true }),
263
+ s.obj({
264
+ kind: s.lit("respond"),
265
+ contributionId: s.str(),
266
+ result: ToolHookFeedbackSchema
267
+ }, { open: true })
268
+ ])
269
+ }, { open: true });
270
+ const ToolHookCallbacksProperties = {
271
+ prepare: s.opt(s.unknown()),
272
+ feedback: s.opt(s.unknown())
273
+ };
274
+ const ToolHookCallbacksSchema = {
275
+ ...s.obj(ToolHookCallbacksProperties, { open: true }),
276
+ anyOf: [{ required: ["prepare"] }, { required: ["feedback"] }]
277
+ };
278
+ function captureToolHookCallbacks(input) {
279
+ const callbacks = decode(ToolHookCallbacksSchema, input);
280
+ return {
281
+ prepare: callbacks.prepare === void 0 ? void 0 : decodeCallback(callbacks.prepare),
282
+ feedback: callbacks.feedback === void 0 ? void 0 : decodeCallback(callbacks.feedback)
283
+ };
284
+ }
285
+ function orderToolHooks(hooks) {
286
+ const byId = new Map(hooks.map((hook) => [hook.contributionId, hook]));
287
+ if (byId.size !== hooks.length) throw new Error("Duplicate Tool Hook contribution");
288
+ const dependencies = new Map(hooks.map((hook) => [hook.contributionId, new Set(hook.after)]));
289
+ for (const hook of hooks) {
290
+ decode(ToolHookMetadataSchema, {
291
+ contributionId: hook.contributionId,
292
+ version: hook.version ?? 1,
293
+ before: hook.before,
294
+ after: hook.after
295
+ });
296
+ for (const target of [...hook.before ?? [], ...hook.after ?? []]) if (!byId.has(target)) throw new Error(`Unknown Tool Hook ordering target: ${target}`);
297
+ for (const target of hook.before ?? []) dependencies.get(target)?.add(hook.contributionId);
298
+ }
299
+ const ordered = [];
300
+ const pending = sortBy(hooks, ["contributionId"]);
301
+ while (pending.length > 0) {
302
+ const index = pending.findIndex((hook$1) => dependencies.get(hook$1.contributionId)?.size === 0);
303
+ if (index < 0) throw new Error("Cyclic Tool Hook ordering");
304
+ const [hook] = pending.splice(index, 1);
305
+ if (hook === void 0) throw new Error("Missing ordered Tool Hook");
306
+ ordered.push(hook);
307
+ for (const remaining of dependencies.values()) remaining.delete(hook.contributionId);
308
+ }
309
+ return ordered;
310
+ }
311
+ /** The caller persists this value before waiting for approval or dispatching an Effect. */
312
+ async function prepareToolHooks(hooks, input, context) {
313
+ const prepared = {
314
+ input: structuredClone(input),
315
+ steps: [],
316
+ outcome: { kind: "execute" }
317
+ };
318
+ for (const hook of hooks) {
319
+ context.signal.throwIfAborted();
320
+ const output = decode(ToolHookPreparationSchema, captureJsonValue(await hook.prepare?.(structuredClone(prepared.input), context) ?? { input: prepared.input }));
321
+ context.signal.throwIfAborted();
322
+ if (check(HookBlockSchema, output)) {
323
+ prepared.outcome = {
324
+ kind: "block",
325
+ contributionId: hook.contributionId,
326
+ reason: output.reason
327
+ };
328
+ break;
329
+ }
330
+ prepared.input = output.input;
331
+ if (check(HookResponseSchema, output)) {
332
+ prepared.outcome = {
333
+ kind: "respond",
334
+ contributionId: hook.contributionId,
335
+ result: output.respond
336
+ };
337
+ break;
338
+ }
339
+ prepared.steps.push({
340
+ contributionId: hook.contributionId,
341
+ version: hook.version ?? 1,
342
+ state: output.state ?? null
343
+ });
344
+ }
345
+ return prepared;
346
+ }
347
+ async function finishToolHooks(hooks, prepared, result, context) {
348
+ let feedback = structuredClone(result);
349
+ for (let index = prepared.steps.length - 1; index >= 0; index--) {
350
+ context.signal.throwIfAborted();
351
+ const step = prepared.steps[index];
352
+ const hook = hooks[index];
353
+ if (step === void 0 || hook === void 0 || hook.contributionId !== step.contributionId || (hook.version ?? 1) !== step.version) throw new Error("Prepared Tool Hook chain is unavailable");
354
+ feedback = decode(ToolHookFeedbackSchema, captureJsonValue(await hook.feedback?.(feedback, structuredClone(step.state), context) ?? feedback));
355
+ context.signal.throwIfAborted();
356
+ }
357
+ return feedback;
358
+ }
359
+ /** A/B compatibility assembly; durable executors commit between these same two phases. */
360
+ async function runToolHooks(hooks, input, context, continuation) {
361
+ const prepared = await prepareToolHooks(hooks, input, context);
362
+ const outcome = prepared.outcome;
363
+ if (outcome.kind === "block") return continuation.block(outcome.reason, outcome.contributionId);
364
+ const result = outcome.kind === "respond" ? await continuation.respond(prepared.input, outcome.result, outcome.contributionId) : await continuation.execute(prepared.input);
365
+ if (continuation.canProcessFeedback?.() === false) return result;
366
+ return finishToolHooks(hooks, prepared, result, context);
367
+ }
368
+
369
+ //#endregion
370
+ //#region src/contributions/component.ts
371
+ const toolCaptures = /* @__PURE__ */ new WeakMap();
372
+ const callbackRetention = /* @__PURE__ */ new WeakMap();
373
+ /** Execution adapters attach retention without adding transport handles to public metadata. */
374
+ function bindCallbackRetention(callback, retain) {
375
+ callbackRetention.set(callback, retain);
376
+ return callback;
377
+ }
378
+ function captureCallbackRetention(captured, source) {
379
+ const retain = callbackRetention.get(source);
380
+ if (retain !== void 0) callbackRetention.set(captured, retain);
381
+ return captured;
382
+ }
383
+ /** Committed views and request leases independently retain their captured callback registrations. */
384
+ function retainPluginCallbacks(contributions, toolNames) {
385
+ const releases = [];
386
+ const release = () => {
387
+ for (const close of releases.splice(0)) close();
388
+ };
389
+ try {
390
+ const callbacks = [
391
+ ...contributions.tools.filter((tool) => toolNames === void 0 || toolNames.has(tool.name)),
392
+ ...contributions.namedStates ?? [],
393
+ ...contributions.inputTransforms ?? [],
394
+ ...contributions.runYield ?? []
395
+ ];
396
+ if (toolNames === void 0) callbacks.push(...contributions.objectFactories ?? []);
397
+ for (const callback of callbacks) {
398
+ const retain = callbackRetention.get(callback);
399
+ if (retain !== void 0) releases.push(retain());
400
+ }
401
+ return release;
402
+ } catch (cause) {
403
+ release();
404
+ throw cause;
405
+ }
406
+ }
407
+ /** Captures author declarations and binds their callbacks at registration. */
408
+ function capturePluginContributions(output, previous) {
409
+ const previousTools = new Map(previous?.tools.map((tool) => [tool.contributionId, tool]));
410
+ return {
411
+ runYield: (output.runYield ?? []).map((hook) => captureCallbackRetention({
412
+ ...hook,
413
+ onYield: hook.onYield.bind(hook)
414
+ }, hook)),
415
+ compactionPolicies: (output.compactionPolicies ?? []).map((policy) => captureCallbackRetention({
416
+ ...policy,
417
+ shouldCompact: policy.shouldCompact.bind(policy)
418
+ }, policy)),
419
+ compactionCompilers: (output.compactionCompilers ?? []).map((compiler) => captureCallbackRetention({
420
+ ...compiler,
421
+ compile: compiler.compile.bind(compiler)
422
+ }, compiler)),
423
+ compactionObservers: (output.compactionObservers ?? []).map((observer) => captureCallbackRetention({
424
+ ...observer,
425
+ before: observer.before === void 0 ? void 0 : observer.before.bind(observer)
426
+ }, observer)),
427
+ objectFactories: [...output.objectFactories ?? []],
428
+ sessionBehaviors: captureSessionBehaviors(output.sessionBehaviors ?? []),
429
+ tools: output.tools.map((tool) => {
430
+ const metadata = captureModelToolMetadata(tool);
431
+ const before = previousTools.get(tool.contributionId);
432
+ const capture = before === void 0 ? void 0 : toolCaptures.get(before);
433
+ if (before !== void 0 && capture?.source === tool && capture.execute === tool.execute && capture.prepareArguments === tool.prepareArguments && before.recovery === tool.recovery && isEqual(capture.metadata, metadata)) return before;
434
+ const captured = {
435
+ ...metadata,
436
+ recovery: tool.recovery,
437
+ execute: tool.execute.bind(tool),
438
+ prepareArguments: tool.prepareArguments?.bind(tool)
439
+ };
440
+ toolCaptures.set(captured, {
441
+ source: tool,
442
+ metadata,
443
+ execute: tool.execute,
444
+ prepareArguments: tool.prepareArguments
445
+ });
446
+ return captureCallbackRetention(captured, tool);
447
+ }),
448
+ hooks: (output.hooks ?? []).map((hook) => ({
449
+ ...captureToolHookCallbacks(hook),
450
+ ...captureToolHookMetadata(hook),
451
+ prepare: hook.prepare?.bind(hook),
452
+ feedback: hook.feedback?.bind(hook)
453
+ })),
454
+ namedStates: (output.namedStates ?? []).map((reader) => captureCallbackRetention({
455
+ ...captureNamedStateMetadata(reader),
456
+ read: reader.read.bind(reader)
457
+ }, reader)),
458
+ prefixes: capturePluginPrefixes(output.prefixes ?? []),
459
+ preparationHooks: (output.preparationHooks ?? []).map((hook) => ({
460
+ ...decode(PreparationHookMetadataSchema, { hookId: hook.hookId }),
461
+ around: hook.around.bind(hook)
462
+ })),
463
+ inputTransforms: (output.inputTransforms ?? []).map((handler) => captureCallbackRetention({
464
+ ...decode(InputTransformMetadataSchema, { contributionId: handler.contributionId }),
465
+ transform: handler.transform.bind(handler)
466
+ }, handler)),
467
+ historySelectors: (output.historySelectors ?? []).map((selector) => ({
468
+ selectorId: selector.selectorId,
469
+ select: selector.select
470
+ }))
471
+ };
472
+ }
473
+
474
+ //#endregion
475
+ //#region src/contributions/object-borrow.ts
476
+ const objectRefs = /* @__PURE__ */ new WeakMap();
477
+ function bindObjectRefPort(ref, port) {
478
+ objectRefs.set(ref, { capture: port.capture.bind(port) });
479
+ return ref;
480
+ }
481
+ function captureObjectMethod(ref, name) {
482
+ const port = objectRefs.get(ref);
483
+ if (port === void 0) throw new TypeError("Object method bindings require a Sorbet-owned Object Ref");
484
+ return port.capture(name);
485
+ }
486
+
487
+ //#endregion
488
+ export { capturePreparationHooks as A, ModelToolMetadataProperties as B, PluginStateReadResultSchema as C, capturePluginPrefixes as D, PluginPrefixContributionSchema as E, SessionBehaviorCommandSchema as F, JsonValueSchema as H, SessionBehaviorMetadataSchema as I, SessionBehaviorViewSchema as L, InputTransformMetadataSchema as M, PluginInputSchema as N, PreparationHookMetadataProperties as O, captureInputTransforms as P, captureSessionBehaviorMetadata as R, NamedStateMetadataSchema as S, orderNamedStates as T, captureJsonValue as U, captureModelToolMetadata as V, prepareToolHooks as _, capturePluginContributions as a, decodeCallback as b, ToolHookCallbacksProperties as c, ToolHookMetadataSchema as d, ToolHookPreparationSchema as f, orderToolHooks as g, finishToolHooks as h, captureCallbackRetention as i, InputTransformMetadataProperties as j, PreparationHookMetadataSchema as k, ToolHookFeedbackSchema as l, captureToolHookMetadata as m, captureObjectMethod as n, retainPluginCallbacks as o, captureToolHookCallbacks as p, bindCallbackRetention as r, PreparedToolHooksSchema as s, bindObjectRefPort as t, ToolHookMetadataProperties as u, runToolHooks as v, captureNamedStateMetadata as w, NamedStateMetadataProperties as x, ToolResultSchema as y, captureSessionBehaviors as z };
@@ -0,0 +1,15 @@
1
+ import * as s from "@earendil-works/pi-schema";
2
+
3
+ //#region src/contributions/object-invocation.ts
4
+ /** An invocation may have produced external effects; this error never authorizes replay. */
5
+ var ObjectInvocationUnknownError = class extends Error {
6
+ code = "object-invocation-unknown";
7
+ constructor(message, options) {
8
+ super(message, options);
9
+ this.name = "ObjectInvocationUnknownError";
10
+ }
11
+ };
12
+ const ObjectInvocationUnknownSchema = s.obj({ code: s.lit("object-invocation-unknown") }, { open: true });
13
+
14
+ //#endregion
15
+ export { ObjectInvocationUnknownSchema as n, ObjectInvocationUnknownError as t };
@@ -0,0 +1,13 @@
1
+ import * as s from "@earendil-works/pi-schema";
2
+
3
+ //#region src/contributions/object-invocation.d.ts
4
+ /** An invocation may have produced external effects; this error never authorizes replay. */
5
+ declare class ObjectInvocationUnknownError extends Error {
6
+ readonly code = "object-invocation-unknown";
7
+ constructor(message: string, options?: ErrorOptions);
8
+ }
9
+ declare const ObjectInvocationUnknownSchema: s.Schema<{
10
+ code: "object-invocation-unknown";
11
+ }>;
12
+ //#endregion
13
+ export { ObjectInvocationUnknownSchema as n, ObjectInvocationUnknownError as t };
@@ -0,0 +1,69 @@
1
+ import { B as ModelToolMetadataProperties, n as captureObjectMethod, r as bindCallbackRetention } from "./object-borrow-C81Gj5tq.js";
2
+ import * as s from "@earendil-works/pi-schema";
3
+ import { decode } from "@sorbetai/schema";
4
+ import * as Effect from "effect/Effect";
5
+ import ensureError from "ensure-error";
6
+
7
+ //#region src/model/object-method.ts
8
+ const BindingMetadataSchema = s.obj({
9
+ key: s.opt(s.str({ minLength: 1 })),
10
+ name: ModelToolMetadataProperties.name,
11
+ description: ModelToolMetadataProperties.description
12
+ }, { open: false });
13
+ /** Captures a method generation. Model arguments always use { input: nativeInput }.
14
+ * Committed contributions and request leases independently extend the binding's scoped borrow. */
15
+ function bindObjectMethod(ref, method, metadata) {
16
+ return makeObjectMethodBinding(ref, method, metadata).pipe(Effect.map(({ tool }) => tool));
17
+ }
18
+ function makeObjectMethodBinding(ref, method, metadata) {
19
+ return Effect.gen(function* () {
20
+ const captured = yield* Effect.try({
21
+ try: () => {
22
+ const declaration = Object.freeze({ ...decode(BindingMetadataSchema, metadata) });
23
+ const port = captureObjectMethod(ref, method);
24
+ return {
25
+ declaration,
26
+ port,
27
+ target: {
28
+ address: { ...port.address },
29
+ method
30
+ },
31
+ parameters: s.obj({ input: port.input }, { open: false }),
32
+ outputSchema: port.output
33
+ };
34
+ },
35
+ catch: ensureError
36
+ });
37
+ const borrow = Effect.acquireRelease(Effect.try({
38
+ try: () => captured.port.retain(),
39
+ catch: ensureError
40
+ }), (release) => Effect.sync(release).pipe(Effect.andThen(captured.port.settle))).pipe(Effect.asVoid);
41
+ yield* borrow;
42
+ return {
43
+ tool: bindCallbackRetention(Object.freeze({
44
+ ...captured.declaration,
45
+ description: `${captured.declaration.description}\n\nTarget: ${JSON.stringify(captured.target)}`,
46
+ parameters: captured.parameters,
47
+ outputSchema: captured.outputSchema,
48
+ execute: async (input, context) => {
49
+ context.signal.throwIfAborted();
50
+ captured.port.assertAvailable();
51
+ const argumentsValue = decode(captured.parameters, input);
52
+ const output = await Effect.runPromise(captured.port.invoke(argumentsValue.input), { signal: context.signal });
53
+ return {
54
+ content: [{
55
+ type: "text",
56
+ text: JSON.stringify(output)
57
+ }],
58
+ details: { object: captured.target },
59
+ structuredContent: output
60
+ };
61
+ }
62
+ }), () => captured.port.retain()),
63
+ borrow
64
+ };
65
+ });
66
+ }
67
+
68
+ //#endregion
69
+ export { makeObjectMethodBinding as n, bindObjectMethod as t };
@@ -0,0 +1,113 @@
1
+ import { H as JsonValueSchema, U as captureJsonValue } from "./object-borrow-C81Gj5tq.js";
2
+ import { check, decode } from "@sorbetai/schema";
3
+ import * as Effect from "effect/Effect";
4
+ import ensureError from "ensure-error";
5
+ import { cloneDeep } from "es-toolkit";
6
+ import canonicalize from "canonicalize";
7
+
8
+ //#region src/contributions/objects.ts
9
+ /** Captures mutable SDK schemas once. Internal consumers borrow the resulting readonly contract. */
10
+ function defineObject(id, definition) {
11
+ return {
12
+ id,
13
+ version: definition.version ?? 1,
14
+ key: cloneDeep(definition.key),
15
+ methods: cloneDeep(definition.methods)
16
+ };
17
+ }
18
+ function captureObjectAddress(type, key, namespace) {
19
+ const capturedType = type;
20
+ const descriptor = type;
21
+ const capturedKey = captureJsonValue(decode(JsonValueSchema, key));
22
+ if (!check(capturedType.key, capturedKey)) throw new TypeError("Invalid Object key");
23
+ const address = {
24
+ namespace,
25
+ typeId: capturedType.id,
26
+ version: capturedType.version,
27
+ key: capturedKey
28
+ };
29
+ const indexKey = canonicalize(address);
30
+ if (indexKey === void 0) throw new TypeError("Invalid Object address");
31
+ return {
32
+ address,
33
+ indexKey,
34
+ descriptor,
35
+ methods: capturedType.methods,
36
+ createRef: (binding, observations) => createObjectRef(capturedType, address, binding, observations)
37
+ };
38
+ }
39
+ function createObjectRef(type, address, binding, observations) {
40
+ const capturedType = type;
41
+ return {
42
+ address,
43
+ states: observations.states.bind(observations),
44
+ watchState: observations.watchState.bind(observations),
45
+ call(name, input) {
46
+ return Effect.gen(function* () {
47
+ const method = capturedType.methods[name];
48
+ if (method === void 0) return yield* Effect.fail(/* @__PURE__ */ new TypeError("Unknown Object method"));
49
+ const captured = yield* Effect.try({
50
+ try: () => {
51
+ return captureJsonValue(input);
52
+ },
53
+ catch: ensureError
54
+ });
55
+ const output = yield* binding.call(name, captured);
56
+ return yield* Effect.try({
57
+ try: () => {
58
+ return decode(method.output, output);
59
+ },
60
+ catch: ensureError
61
+ });
62
+ });
63
+ }
64
+ };
65
+ }
66
+ function captureObjectFactory(type, factory) {
67
+ const capturedType = type;
68
+ const descriptor = type;
69
+ const create = factory.create.bind(factory);
70
+ return {
71
+ typeId: capturedType.id,
72
+ version: capturedType.version,
73
+ descriptor,
74
+ create(key, self) {
75
+ return Effect.gen(function* () {
76
+ const implementation = yield* yield* Effect.try({
77
+ try: () => {
78
+ return create(decode(capturedType.key, key), self);
79
+ },
80
+ catch: ensureError
81
+ });
82
+ const methods = /* @__PURE__ */ new Map();
83
+ for (const name of Object.keys(capturedType.methods)) {
84
+ const schema = capturedType.methods[name];
85
+ const method = implementation[name];
86
+ if (schema === void 0 || method === void 0) return yield* Effect.fail(/* @__PURE__ */ new TypeError(`Missing Object method: ${name}`));
87
+ const invoke = method.bind(implementation);
88
+ methods.set(name, (_name, input) => Effect.gen(function* () {
89
+ const output = yield* yield* Effect.try({
90
+ try: () => {
91
+ return invoke(decode(schema.input, input));
92
+ },
93
+ catch: ensureError
94
+ });
95
+ return yield* Effect.try({
96
+ try: () => {
97
+ return captureJsonValue(output);
98
+ },
99
+ catch: ensureError
100
+ });
101
+ }));
102
+ }
103
+ return { call(name, input) {
104
+ const method = methods.get(name);
105
+ return method === void 0 ? Effect.fail(/* @__PURE__ */ new TypeError("Unknown Object method")) : method(name, input);
106
+ } };
107
+ });
108
+ }
109
+ };
110
+ }
111
+
112
+ //#endregion
113
+ export { captureObjectFactory as n, defineObject as r, captureObjectAddress as t };