@relayfx/sdk 0.3.7 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/ai.js +1 -1
  2. package/dist/http-server.js +1 -1
  3. package/dist/{index-pw46cfne.js → index-3w6txjtg.js} +59 -426
  4. package/dist/{index-h8rx4xya.js → index-cs3be24t.js} +1 -1
  5. package/dist/{index-8awt651b.js → index-p43mg4kt.js} +5774 -5275
  6. package/dist/{index-t5bbk8cp.js → index-x32kbvxv.js} +935 -954
  7. package/dist/index.js +487 -22
  8. package/dist/migrations/20260719120000_rename_entity_to_resident/migration.sql +9 -0
  9. package/dist/migrations/mysql/0012_rename_entity_to_resident.sql +5 -0
  10. package/dist/migrations/pg/20260719120000_rename_entity_to_resident/migration.sql +9 -0
  11. package/dist/migrations/sqlite/0012_rename_entity_to_resident.sql +7 -0
  12. package/dist/mysql.js +18 -5
  13. package/dist/postgres.js +569 -550
  14. package/dist/sqlite.js +16 -5
  15. package/dist/types/relay/client-baton-agent.d.ts +30 -0
  16. package/dist/types/relay/client-child-runs.d.ts +35 -0
  17. package/dist/types/relay/client-error-mapping.d.ts +5 -0
  18. package/dist/types/relay/client-event-sequence.d.ts +3 -0
  19. package/dist/types/relay/client-execution-payloads.d.ts +12 -0
  20. package/dist/types/relay/client-public-agents.d.ts +15 -0
  21. package/dist/types/relay/client-public-child-runs.d.ts +9 -0
  22. package/dist/types/relay/client-public-envelope-ready.d.ts +6 -0
  23. package/dist/types/relay/client-public-executions.d.ts +247 -0
  24. package/dist/types/relay/client-public-messaging.d.ts +18 -0
  25. package/dist/types/relay/client-public-residents.d.ts +14 -0
  26. package/dist/types/relay/client-public-schedules.d.ts +6 -0
  27. package/dist/types/relay/client-public-tools.d.ts +12 -0
  28. package/dist/types/relay/client-public-workflows.d.ts +10 -0
  29. package/dist/types/relay/client-public.d.ts +133 -313
  30. package/dist/types/relay/client-runtime-wake.d.ts +10 -0
  31. package/dist/types/relay/client-tool-outcome.d.ts +16 -0
  32. package/dist/types/relay/client-view-mappers.d.ts +16 -0
  33. package/dist/types/relay/client-wait-signal.d.ts +5 -0
  34. package/dist/types/relay/client.d.ts +118 -1
  35. package/dist/types/relay/command.d.ts +6 -6
  36. package/dist/types/relay/http-server.d.ts +55 -37
  37. package/dist/types/relay/index.d.ts +3 -4
  38. package/dist/types/relay/internal-client.d.ts +5 -5
  39. package/dist/types/relay/mysql-migrations.d.ts +1 -1
  40. package/dist/types/relay/operation.d.ts +41 -41
  41. package/dist/types/relay/sqlite-migrations.d.ts +6 -1
  42. package/dist/types/runtime/agent/agent-loop-events.d.ts +24 -0
  43. package/dist/types/runtime/execution/event-log-memory.d.ts +7 -0
  44. package/dist/types/runtime/execution/event-log-repository.d.ts +8 -0
  45. package/dist/types/runtime/index.d.ts +2 -2
  46. package/dist/types/runtime/resident/resident-instance-service.d.ts +76 -0
  47. package/dist/types/runtime/resident/resident-registry-service.d.ts +35 -0
  48. package/dist/types/runtime/runner/runner-runtime-service.d.ts +14 -14
  49. package/dist/types/runtime/workflow/execution-workflow-state.d.ts +43 -0
  50. package/dist/types/schema/execution-schema.d.ts +2 -2
  51. package/dist/types/schema/ids-schema.d.ts +6 -6
  52. package/dist/types/schema/index.d.ts +1 -1
  53. package/dist/types/schema/{entity-schema.d.ts → resident-schema.d.ts} +6 -6
  54. package/dist/types/store-sql/envelope/envelope-ready-records.d.ts +51 -0
  55. package/dist/types/store-sql/envelope/envelope-records.d.ts +43 -0
  56. package/dist/types/store-sql/envelope/envelope-repository.d.ts +1 -2
  57. package/dist/types/store-sql/envelope/wait-records.d.ts +64 -0
  58. package/dist/types/store-sql/execution/execution-event-repository-memory.d.ts +8 -0
  59. package/dist/types/store-sql/execution/execution-event-repository-sql.d.ts +13 -0
  60. package/dist/types/store-sql/execution/execution-event-repository.d.ts +3 -4
  61. package/dist/types/store-sql/index.d.ts +1 -1
  62. package/dist/types/store-sql/portable.d.ts +1 -1
  63. package/dist/types/store-sql/resident/resident-repository.d.ts +36 -0
  64. package/dist/types/store-sql/schema/address-book-schema.d.ts +131 -0
  65. package/dist/types/store-sql/schema/agent-schema.d.ts +954 -0
  66. package/dist/types/store-sql/schema/communication-schema.d.ts +743 -0
  67. package/dist/types/store-sql/schema/envelope-schema.d.ts +701 -0
  68. package/dist/types/store-sql/schema/execution-schema.d.ts +1119 -0
  69. package/dist/types/store-sql/schema/idempotency-schema.d.ts +161 -0
  70. package/dist/types/store-sql/schema/presence-schema.d.ts +116 -0
  71. package/dist/types/store-sql/schema/relay-schema.d.ts +13 -6684
  72. package/dist/types/store-sql/schema/resident-schema.d.ts +294 -0
  73. package/dist/types/store-sql/schema/schedule-schema.d.ts +282 -0
  74. package/dist/types/store-sql/schema/schema-columns.d.ts +1 -0
  75. package/dist/types/store-sql/schema/session-schema.d.ts +228 -0
  76. package/dist/types/store-sql/schema/tool-schema.d.ts +627 -0
  77. package/dist/types/store-sql/schema/workflow-schema.d.ts +996 -0
  78. package/dist/types/store-sql/schema/workspace-schema.d.ts +338 -0
  79. package/dist/types/store-sql/session/session-entry-records.d.ts +52 -0
  80. package/dist/types/store-sql/session/session-records.d.ts +51 -0
  81. package/dist/types/store-sql/session/session-repository.d.ts +2 -3
  82. package/dist/types/store-sql/tool/tool-attempt-records.d.ts +52 -0
  83. package/dist/types/store-sql/tool/tool-call-records.d.ts +121 -0
  84. package/dist/types/store-sql/tool/tool-call-repository.d.ts +1 -2
  85. package/dist/types/store-sql/tool/tool-work-operations.d.ts +11 -0
  86. package/package.json +3 -3
  87. package/dist/types/runtime/entity/entity-instance-service.d.ts +0 -76
  88. package/dist/types/runtime/entity/entity-registry-service.d.ts +0 -35
  89. package/dist/types/store-sql/entity/entity-repository.d.ts +0 -36
@@ -3,7 +3,7 @@ import {
3
3
  __export
4
4
  } from "./index-nb39b5ae.js";
5
5
 
6
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/turn-policy.js
6
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/turn-policy.js
7
7
  var exports_turn_policy = {};
8
8
  __export(exports_turn_policy, {
9
9
  untilToolCall: () => untilToolCall,
@@ -74,7 +74,7 @@ var both = dual(2, (first, second) => ({
74
74
  }));
75
75
  var defaultPolicy = forever;
76
76
 
77
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/agent-event.js
77
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-event.js
78
78
  var exports_agent_event = {};
79
79
  __export(exports_agent_event, {
80
80
  addUsage: () => addUsage,
@@ -193,28 +193,223 @@ class ResumeMismatch extends Schema2.TaggedErrorClass()("@batonfx/core/ResumeMis
193
193
  }) {
194
194
  }
195
195
 
196
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/tool-context.js
196
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/memory.js
197
+ var exports_memory = {};
198
+ __export(exports_memory, {
199
+ testLayer: () => testLayer,
200
+ replaceRecalledMessage: () => replaceRecalledMessage,
201
+ recalledMessageIdentity: () => recalledMessageIdentity,
202
+ projectTranscript: () => projectTranscript,
203
+ noopLayer: () => noopLayer,
204
+ messageFromRecall: () => messageFromRecall,
205
+ merge: () => merge,
206
+ layerNoop: () => layerNoop,
207
+ itemFromPromptPart: () => itemFromPromptPart,
208
+ isMessageFromRecall: () => isMessageFromRecall,
209
+ MemoryError: () => MemoryError,
210
+ Memory: () => Memory
211
+ });
212
+ import { Context, Effect as Effect2, Layer as Layer2, Option, Schema as Schema3 } from "effect";
213
+ import { dual as dual2 } from "effect/Function";
214
+ import { Prompt as Prompt3 } from "effect/unstable/ai";
215
+ var provenanceOption = "@batonfx/core/memory";
216
+ var recallLineage = new WeakMap;
217
+ var itemFromPromptPart = Option.liftPredicate((part) => part.type === "text" || part.type === "file");
218
+ var isMessageFromRecall = (message) => {
219
+ const provenance = message.options[provenanceOption];
220
+ return typeof provenance === "object" && provenance !== null && !Array.isArray(provenance) && "origin" in provenance && provenance.origin === "memoryRecall";
221
+ };
222
+ var messageFromRecall = (content) => {
223
+ const message = Prompt3.makeMessage("user", {
224
+ content,
225
+ options: { [provenanceOption]: { origin: "memoryRecall" } }
226
+ });
227
+ recallLineage.set(message, message);
228
+ return message;
229
+ };
230
+ var replaceRecalledMessage = dual2(2, (message, content) => {
231
+ const options = isMessageFromRecall(message) ? { ...message.options, [provenanceOption]: { origin: "memoryRecall" } } : { ...message.options };
232
+ const replacement = Prompt3.makeMessage("user", { content, options });
233
+ if (isMessageFromRecall(message))
234
+ recallLineage.set(replacement, recallLineage.get(message) ?? message);
235
+ return replacement;
236
+ });
237
+ var recalledMessageIdentity = (message) => recallLineage.get(message) ?? message;
238
+ var projectTranscript = (transcript) => {
239
+ const content = transcript.content.filter((message) => !isMessageFromRecall(message));
240
+ return content.length === transcript.content.length ? transcript : Prompt3.fromMessages(content);
241
+ };
242
+
243
+ class MemoryError extends Schema3.TaggedErrorClass()("@batonfx/core/MemoryError", {
244
+ message: Schema3.String
245
+ }) {
246
+ }
247
+
248
+ class Memory extends Context.Service()("@batonfx/core/memory") {
249
+ }
250
+ var noop = {
251
+ recall: () => Effect2.succeed([]),
252
+ remember: () => Effect2.void,
253
+ forget: () => Effect2.void
254
+ };
255
+ var merge = dual2(2, (first, second) => ({
256
+ recall: (input) => Effect2.all([first.recall(input), second.recall(input)]).pipe(Effect2.map(([firstItems, secondItems]) => [...firstItems, ...secondItems])),
257
+ remember: (input) => Effect2.all([first.remember(input), second.remember(input)], { discard: true }),
258
+ forget: (input) => Effect2.all([first.forget(input), second.forget(input)], { discard: true })
259
+ }));
260
+ var layerNoop = Layer2.succeed(Memory, Memory.of(noop));
261
+ var noopLayer = layerNoop;
262
+ var testLayer = (implementation) => Layer2.succeed(Memory, Memory.of(implementation));
263
+
264
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/model-registry.js
265
+ var exports_model_registry = {};
266
+ __export(exports_model_registry, {
267
+ testLayer: () => testLayer2,
268
+ stream: () => stream,
269
+ registrations: () => registrations,
270
+ registrationFromLayer: () => registrationFromLayer,
271
+ register: () => register,
272
+ provide: () => provide,
273
+ operate: () => operate,
274
+ memoryLayer: () => memoryLayer,
275
+ layerMemory: () => layerMemory,
276
+ layerFromRegistrationEffects: () => layerFromRegistrationEffects,
277
+ layer: () => layer,
278
+ combine: () => combine,
279
+ classifyFailure: () => classifyFailure,
280
+ Service: () => Service,
281
+ LanguageModelNotRegistered: () => LanguageModelNotRegistered
282
+ });
283
+ import { Chunk, Context as Context2, Effect as Effect3, Function as Function2, Layer as Layer3, Option as Option2, Ref, Schema as Schema4, Semaphore, Stream } from "effect";
284
+ import { LanguageModel as LanguageModel2, Model } from "effect/unstable/ai";
285
+ var FailureClassifierTypeId = Symbol.for("@batonfx/core/model-registry/FailureClassifier");
286
+ var classifyFailure = Function2.dual(2, (model, error) => model[FailureClassifierTypeId]?.(error) ?? "other");
287
+ var attachFailureClassifier = (registration, context) => {
288
+ if (registration.classifyFailure === undefined)
289
+ return context;
290
+ const model = Context2.get(context, LanguageModel2.LanguageModel);
291
+ const classified = {
292
+ ...model,
293
+ [FailureClassifierTypeId]: registration.classifyFailure
294
+ };
295
+ return Context2.add(context, LanguageModel2.LanguageModel, classified);
296
+ };
297
+
298
+ class LanguageModelNotRegistered extends Schema4.TaggedErrorClass()("LanguageModelNotRegistered", {
299
+ provider: Schema4.String,
300
+ model: Schema4.String,
301
+ registration_key: Schema4.optionalKey(Schema4.String)
302
+ }) {
303
+ }
304
+
305
+ class Service extends Context2.Service()("@batonfx/core/model-registry/Service") {
306
+ }
307
+ var registrationVariantKey = (value) => value.registrationKey ?? null;
308
+ var selectionVariantKey = (selection) => selection.registrationKey ?? null;
309
+ var registryIdentity = (registration) => JSON.stringify([registration.provider, registration.model, registrationVariantKey(registration)]);
310
+ var matchesSelection = (selection) => (registration) => registration.provider === selection.provider && registration.model === selection.model && registrationVariantKey(registration) === selectionVariantKey(selection);
311
+ var upsertRegistration = (registry, registration) => {
312
+ const key = registryIdentity(registration);
313
+ const exists = Option2.isSome(Chunk.findFirst(registry, (item) => registryIdentity(item) === key));
314
+ if (!exists)
315
+ return Chunk.append(registry, registration);
316
+ return Chunk.map(registry, (item) => registryIdentity(item) === key ? registration : item);
317
+ };
318
+ var findRegistration = (registry, selection) => Chunk.findFirst(registry, matchesSelection(selection)).pipe(Option2.getOrUndefined);
319
+ var registrationFromLayer = (input) => Model.make(input.provider, input.model, input.layer).captureRequirements.pipe(Effect3.map((layer) => ({
320
+ provider: input.provider,
321
+ model: input.model,
322
+ layer,
323
+ ...input.registrationKey === undefined ? {} : { registrationKey: input.registrationKey },
324
+ ...input.metadata === undefined ? {} : { metadata: input.metadata },
325
+ ...input.classifyFailure === undefined ? {} : { classifyFailure: input.classifyFailure }
326
+ })));
327
+ var layer = Function2.dual((args) => args.length === 0 || args.length > 1 || Array.isArray(args[0]), (initialRegistrations = [], options) => Layer3.effect(Service, Effect3.gen(function* () {
328
+ const registry = yield* Ref.make(initialRegistrations.reduce(upsertRegistration, Chunk.empty()));
329
+ const semaphore = options?.maxConcurrentModelCalls === undefined ? undefined : yield* Semaphore.make(options.maxConcurrentModelCalls);
330
+ const register = Effect3.fn("ModelRegistry.register")(function* (input) {
331
+ yield* Ref.update(registry, (items) => upsertRegistration(items, input.registration));
332
+ });
333
+ const registrations = Ref.get(registry).pipe(Effect3.map(Chunk.toReadonlyArray));
334
+ const operate = Effect3.fn("ModelRegistry.operate")(function* (selection, effect) {
335
+ const items = yield* Ref.get(registry);
336
+ const registration = findRegistration(items, selection);
337
+ if (registration === undefined) {
338
+ return yield* LanguageModelNotRegistered.make({
339
+ provider: selection.provider,
340
+ model: selection.model,
341
+ ...selection.registrationKey === undefined ? {} : { registration_key: selection.registrationKey }
342
+ });
343
+ }
344
+ const provided = Effect3.scoped(Layer3.build(registration.layer).pipe(Effect3.flatMap((context) => effect.pipe(Effect3.provide(attachFailureClassifier(registration, context))))));
345
+ return yield* semaphore === undefined ? provided : semaphore.withPermits(1)(provided);
346
+ });
347
+ const stream = (selection, operation) => Stream.unwrap(Effect3.gen(function* () {
348
+ const items = yield* Ref.get(registry);
349
+ const registration = findRegistration(items, selection);
350
+ if (registration === undefined) {
351
+ return yield* LanguageModelNotRegistered.make({
352
+ provider: selection.provider,
353
+ model: selection.model,
354
+ ...selection.registrationKey === undefined ? {} : { registration_key: selection.registrationKey }
355
+ });
356
+ }
357
+ if (semaphore !== undefined) {
358
+ yield* Effect3.acquireRelease(semaphore.take(1), () => semaphore.release(1), { interruptible: true });
359
+ }
360
+ const context = attachFailureClassifier(registration, yield* Layer3.build(registration.layer));
361
+ return operation.pipe(Stream.provideContext(context));
362
+ }));
363
+ return Service.of({
364
+ register,
365
+ registrations,
366
+ operate,
367
+ stream,
368
+ provide: operate
369
+ });
370
+ })));
371
+ var layerFromRegistrationEffects = Function2.dual((args) => args.length !== 1 || Array.isArray(args[0]), (registrations, options) => Layer3.unwrap(Effect3.all(registrations).pipe(Effect3.map((items) => layer(items, options)))));
372
+ var combine = Function2.dual((args) => args.length !== 1 || Array.isArray(args[0]), (registries, options) => Layer3.unwrap(Effect3.forEach(registries, (registry) => Layer3.build(registry).pipe(Effect3.flatMap((context) => Context2.get(context, Service).registrations))).pipe(Effect3.map((groups) => layer(groups.flat(), options)))));
373
+ var layerMemory = layer;
374
+ var memoryLayer = layerMemory;
375
+ var testLayer2 = (implementation) => Layer3.succeed(Service, Service.of(implementation));
376
+ var register = Effect3.fn("ModelRegistry.register.call")(function* (input) {
377
+ const service = yield* Service;
378
+ return yield* service.register(input);
379
+ });
380
+ var registrations = Effect3.fn("ModelRegistry.registrations.call")(function* () {
381
+ const service = yield* Service;
382
+ return yield* service.registrations;
383
+ });
384
+ var operate = Function2.dual(2, (selection, effect) => Effect3.gen(function* () {
385
+ const service = yield* Service;
386
+ return yield* service.operate(selection, effect);
387
+ }));
388
+ var stream = Function2.dual(2, (selection, operation) => Stream.unwrap(Service.pipe(Effect3.map((service) => service.stream(selection, operation)))));
389
+ var provide = operate;
390
+
391
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-context.js
197
392
  var exports_tool_context = {};
198
393
  __export(exports_tool_context, {
199
- testLayer: () => testLayer,
394
+ testLayer: () => testLayer3,
200
395
  layerDefault: () => layerDefault,
201
396
  ToolContext: () => ToolContext
202
397
  });
203
- import { Context, Effect as Effect2, Layer as Layer2 } from "effect";
398
+ import { Context as Context3, Effect as Effect4, Layer as Layer4 } from "effect";
204
399
 
205
- class ToolContext extends Context.Service()("@batonfx/core/tool-context/ToolContext") {
400
+ class ToolContext extends Context3.Service()("@batonfx/core/tool-context/ToolContext") {
206
401
  }
207
- var layerDefault = Layer2.sync(ToolContext, () => ToolContext.of({
402
+ var layerDefault = Layer4.sync(ToolContext, () => ToolContext.of({
208
403
  signal: new AbortController().signal,
209
- emit: () => Effect2.void,
404
+ emit: () => Effect4.void,
210
405
  sessionId: "local"
211
406
  }));
212
- var testLayer = (implementation) => Layer2.succeed(ToolContext, ToolContext.of(implementation));
407
+ var testLayer3 = (implementation) => Layer4.succeed(ToolContext, ToolContext.of(implementation));
213
408
 
214
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/tool-executor.js
409
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-executor.js
215
410
  var exports_tool_executor = {};
216
411
  __export(exports_tool_executor, {
217
- testLayer: () => testLayer2,
412
+ testLayer: () => testLayer4,
218
413
  sandbox: () => sandbox,
219
414
  router: () => router,
220
415
  routeToolkit: () => routeToolkit,
@@ -229,34 +424,16 @@ __export(exports_tool_executor, {
229
424
  FrameworkStage: () => FrameworkStage,
230
425
  FrameworkFailure: () => FrameworkFailure
231
426
  });
232
- import { Context as Context2, Effect as Effect3, Layer as Layer3, Option, Schedule, Schema as Schema3, Sink, Stream } from "effect";
233
- import { AiError, Response as Response3, Tool as Tool2, Toolkit } from "effect/unstable/ai";
234
- var FrameworkStage = Schema3.Literals([
235
- "decode-input",
236
- "handler",
237
- "encode-success",
238
- "encode-domain-failure",
239
- "missing-handler",
240
- "route",
241
- "placement",
242
- "authorization"
243
- ]);
427
+ import { Context as Context4, Effect as Effect7, Layer as Layer5, Option as Option3, Schema as Schema6, Sink, Stream as Stream2 } from "effect";
428
+ import { AiError as AiError2, Response as Response3, Tool as Tool4, Toolkit } from "effect/unstable/ai";
244
429
 
245
- class FrameworkFailure extends Schema3.TaggedErrorClass()("@batonfx/core/FrameworkFailure", {
246
- stage: FrameworkStage,
247
- tool: Schema3.String,
248
- message: Schema3.String
249
- }) {
250
- }
430
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-placement.js
431
+ import { Effect as Effect6, Schedule } from "effect";
432
+ import { Tool as Tool3 } from "effect/unstable/ai";
251
433
 
252
- class RemoteRetryError extends Schema3.TaggedErrorClass()("@batonfx/core/RemoteRetryError", {
253
- reason: Schema3.Literals(["invalid-max-retries", "missing-operation-key", "changed-operation-key"]),
254
- message: Schema3.String
255
- }) {
256
- }
257
-
258
- class ToolExecutor extends Context2.Service()("@batonfx/core/tool-executor/ToolExecutor") {
259
- }
434
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-result-codec.js
435
+ import { Effect as Effect5, Schema as Schema5 } from "effect";
436
+ import { AiError, Tool as Tool2 } from "effect/unstable/ai";
260
437
  var resultMessage = (result) => {
261
438
  if (typeof result === "string")
262
439
  return result;
@@ -273,20 +450,20 @@ var schemaMessage = (error) => error instanceof Error ? error.message : typeof e
273
450
  var frameworkFailure = (stage, tool, error) => FrameworkFailure.make({ stage, tool, message: schemaMessage(error) });
274
451
  var encodeSuccess = (tool, result) => {
275
452
  const schema = tool.successSchema;
276
- return Schema3.encodeUnknownEffect(schema)(result).pipe(Effect3.map((encodedResult) => ({ _tag: "Success", result, encodedResult })), Effect3.mapError((error) => frameworkFailure("encode-success", tool.name, error)));
453
+ return Schema5.encodeUnknownEffect(schema)(result).pipe(Effect5.map((encodedResult) => ({ _tag: "Success", result, encodedResult })), Effect5.mapError((error) => frameworkFailure("encode-success", tool.name, error)));
277
454
  };
278
455
  var encodeDomainFailure = (tool, failure) => {
279
456
  const schema = tool.failureSchema;
280
- return Schema3.encodeUnknownEffect(schema)(failure).pipe(Effect3.map((encodedFailure) => ({ _tag: "DomainFailure", failure, encodedFailure })), Effect3.mapError((error) => frameworkFailure("encode-domain-failure", tool.name, error)));
457
+ return Schema5.encodeUnknownEffect(schema)(failure).pipe(Effect5.map((encodedFailure) => ({ _tag: "DomainFailure", failure, encodedFailure })), Effect5.mapError((error) => frameworkFailure("encode-domain-failure", tool.name, error)));
281
458
  };
282
- var encodeDomainCandidate = (tool, failure) => !Schema3.is(tool.failureSchema)(failure) ? Effect3.fail(frameworkFailure("handler", tool.name, failure)) : encodeDomainFailure(tool, failure);
459
+ var encodeDomainCandidate = (tool, failure) => !Schema5.is(tool.failureSchema)(failure) ? Effect5.fail(frameworkFailure("handler", tool.name, failure)) : encodeDomainFailure(tool, failure);
283
460
  var decodeInput = (tool, input) => {
284
461
  const schema = tool.parametersSchema;
285
- return Schema3.decodeUnknownEffect(schema)(input).pipe(Effect3.asVoid, Effect3.mapError((error) => frameworkFailure("decode-input", tool.name, error)));
462
+ return Schema5.decodeUnknownEffect(schema)(input).pipe(Effect5.asVoid, Effect5.mapError((error) => frameworkFailure("decode-input", tool.name, error)));
286
463
  };
287
464
  var decodeSuccess = (tool, result) => {
288
465
  const schema = tool.successSchema;
289
- return Schema3.decodeUnknownEffect(schema)(result).pipe(Effect3.mapError((error) => frameworkFailure("encode-success", tool.name, error)), Effect3.flatMap((decoded) => encodeSuccess(tool, decoded)));
466
+ return Schema5.decodeUnknownEffect(schema)(result).pipe(Effect5.mapError((error) => frameworkFailure("encode-success", tool.name, error)), Effect5.flatMap((decoded) => encodeSuccess(tool, decoded)));
290
467
  };
291
468
  var aiFrameworkFailure = (tool, error) => {
292
469
  switch (error.reason._tag) {
@@ -299,52 +476,94 @@ var aiFrameworkFailure = (tool, error) => {
299
476
  case "ToolResultEncodingError": {
300
477
  if (tool.failureMode === "error")
301
478
  return frameworkFailure("encode-success", tool.name, error);
302
- const isSuccess = Schema3.isSchema(tool.successSchema) && Schema3.is(tool.successSchema)(error.reason.toolResult);
303
- const isDomainFailure = Schema3.isSchema(tool.failureSchema) && Schema3.is(tool.failureSchema)(error.reason.toolResult);
479
+ const isSuccess = Schema5.isSchema(tool.successSchema) && Schema5.is(tool.successSchema)(error.reason.toolResult);
480
+ const isDomainFailure = Schema5.isSchema(tool.failureSchema) && Schema5.is(tool.failureSchema)(error.reason.toolResult);
304
481
  return frameworkFailure(isSuccess === isDomainFailure ? "handler" : isDomainFailure ? "encode-domain-failure" : "encode-success", tool.name, error);
305
482
  }
306
483
  default:
307
484
  return frameworkFailure("handler", tool.name, error);
308
485
  }
309
486
  };
310
- var placementOutcome = (placement, tool, response) => {
487
+ var toolResultCodec = {
488
+ aiFrameworkFailure,
489
+ decodeInput,
490
+ decodeSuccess,
491
+ encodeDomainCandidate,
492
+ encodeDomainFailure,
493
+ encodeSuccess,
494
+ frameworkFailure,
495
+ resultMessage,
496
+ schemaMessage
497
+ };
498
+
499
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-placement.js
500
+ var placementOutcomeFromResponse = (placement, tool, response) => {
311
501
  if (typeof response !== "object" || response === null || !("_tag" in response)) {
312
- return Effect3.fail(frameworkFailure("placement", tool.name, "Placement returned an invalid response"));
502
+ return Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Placement returned an invalid response"));
313
503
  }
314
504
  switch (response._tag) {
315
505
  case "DomainFailure":
316
- return "failure" in response ? encodeDomainFailure(tool, response.failure) : Effect3.fail(frameworkFailure("placement", tool.name, "DomainFailure response is missing failure"));
506
+ return "failure" in response ? toolResultCodec.encodeDomainFailure(tool, response.failure) : Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "DomainFailure response is missing failure"));
317
507
  case "Suspend":
318
- return "token" in response && typeof response.token === "string" ? Effect3.succeed({ _tag: "Suspend", token: response.token }) : Effect3.fail(frameworkFailure("placement", tool.name, "Suspend response is missing a string token"));
508
+ return "token" in response && typeof response.token === "string" ? Effect6.succeed({ _tag: "Suspend", token: response.token }) : Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Suspend response is missing a string token"));
319
509
  case "Success":
320
- return "result" in response ? decodeSuccess(tool, response.result).pipe(Effect3.mapError((error) => FrameworkFailure.make({ ...error, message: `${placement} result: ${error.message}` }))) : Effect3.fail(frameworkFailure("placement", tool.name, "Success response is missing result"));
510
+ return "result" in response ? toolResultCodec.decodeSuccess(tool, response.result).pipe(Effect6.mapError((error) => FrameworkFailure.make({ ...error, message: `${placement} result: ${error.message}` }))) : Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Success response is missing result"));
321
511
  default:
322
- return Effect3.fail(frameworkFailure("placement", tool.name, "Placement returned an unknown response tag"));
512
+ return Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Placement returned an unknown response tag"));
323
513
  }
324
514
  };
515
+ var placementOutcome = { fromResponse: placementOutcomeFromResponse };
516
+
517
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-executor.js
518
+ var FrameworkStage = Schema6.Literals([
519
+ "decode-input",
520
+ "handler",
521
+ "encode-success",
522
+ "encode-domain-failure",
523
+ "missing-handler",
524
+ "route",
525
+ "placement",
526
+ "authorization"
527
+ ]);
528
+
529
+ class FrameworkFailure extends Schema6.TaggedErrorClass()("@batonfx/core/FrameworkFailure", {
530
+ stage: FrameworkStage,
531
+ tool: Schema6.String,
532
+ message: Schema6.String
533
+ }) {
534
+ }
535
+
536
+ class RemoteRetryError extends Schema6.TaggedErrorClass()("@batonfx/core/RemoteRetryError", {
537
+ reason: Schema6.Literals(["invalid-max-retries", "missing-operation-key", "changed-operation-key"]),
538
+ message: Schema6.String
539
+ }) {
540
+ }
541
+
542
+ class ToolExecutor extends Context4.Service()("@batonfx/core/tool-executor/ToolExecutor") {
543
+ }
325
544
  var findTool = (tools, name) => tools[name];
326
545
  var executeWithToolkit = (toolkit, request) => {
327
546
  const tool = findTool(toolkit.tools, request.call.name);
328
547
  if (tool === undefined) {
329
- return Effect3.fail(frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
548
+ return Effect7.fail(toolResultCodec.frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
330
549
  }
331
550
  const handleFailure = (error) => {
332
- if (Schema3.is(FrameworkFailure)(error))
333
- return Effect3.fail(error);
334
- if (AiError.isAiError(error))
335
- return Effect3.fail(aiFrameworkFailure(tool, error));
336
- return encodeDomainCandidate(tool, error);
551
+ if (Schema6.is(FrameworkFailure)(error))
552
+ return Effect7.fail(error);
553
+ if (AiError2.isAiError(error))
554
+ return Effect7.fail(toolResultCodec.aiFrameworkFailure(tool, error));
555
+ return toolResultCodec.encodeDomainCandidate(tool, error);
337
556
  };
338
- return toolkit.handle(request.call.name, request.call.params).pipe(Effect3.flatMap((results) => results.pipe(Stream.filter((item) => item.preliminary === false), Stream.run(Sink.last()))), Effect3.flatMap((option) => {
339
- if (Option.isNone(option)) {
340
- return Effect3.fail(frameworkFailure("handler", tool.name, "Tool handler did not produce a final result"));
557
+ return toolkit.handle(request.call.name, request.call.params).pipe(Effect7.flatMap((results) => results.pipe(Stream2.filter((item) => item.preliminary === false), Stream2.run(Sink.last()))), Effect7.flatMap((option) => {
558
+ if (Option3.isNone(option)) {
559
+ return Effect7.fail(toolResultCodec.frameworkFailure("handler", tool.name, "Tool handler did not produce a final result"));
341
560
  }
342
561
  const result = option.value;
343
562
  if (!result.isFailure) {
344
- return Effect3.succeed({ _tag: "Success", result: result.result, encodedResult: result.encodedResult });
563
+ return Effect7.succeed({ _tag: "Success", result: result.result, encodedResult: result.encodedResult });
345
564
  }
346
- return AiError.isAiError(result.result) ? Effect3.fail(aiFrameworkFailure(tool, result.result)) : encodeDomainFailure(tool, result.result);
347
- }), Effect3.catchIf(() => true, handleFailure, handleFailure));
565
+ return AiError2.isAiError(result.result) ? Effect7.fail(toolResultCodec.aiFrameworkFailure(tool, result.result)) : toolResultCodec.encodeDomainFailure(tool, result.result);
566
+ }), Effect7.catchIf(() => true, handleFailure, handleFailure));
348
567
  };
349
568
  function executeToolkit(toolkitOrRequest, request) {
350
569
  if (request === undefined) {
@@ -355,10 +574,10 @@ function executeToolkit(toolkitOrRequest, request) {
355
574
  return pipeable;
356
575
  }
357
576
  const toolkit = toolkitOrRequest;
358
- return ("handle" in toolkit ? Effect3.succeed(toolkit) : toolkit).pipe(Effect3.flatMap((handled) => executeWithToolkit(handled, request)));
577
+ return ("handle" in toolkit ? Effect7.succeed(toolkit) : toolkit).pipe(Effect7.flatMap((handled) => executeWithToolkit(handled, request)));
359
578
  }
360
579
  function fromToolkit(toolkit) {
361
- return Layer3.effect(ToolExecutor, ("handle" in toolkit ? Effect3.succeed(toolkit) : toolkit).pipe(Effect3.map((handled) => ToolExecutor.of({
580
+ return Layer5.effect(ToolExecutor, ("handle" in toolkit ? Effect7.succeed(toolkit) : toolkit).pipe(Effect7.map((handled) => ToolExecutor.of({
362
581
  execute: (request) => executeWithToolkit(handled, request)
363
582
  }))));
364
583
  }
@@ -377,37 +596,37 @@ var placementRoute = (placement, options) => {
377
596
  execute: (request) => {
378
597
  const tool = findTool(options.toolkit.tools, request.call.name);
379
598
  if (tool === undefined) {
380
- return Effect3.fail(frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
599
+ return Effect7.fail(toolResultCodec.frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
381
600
  }
382
- return decodeInput(tool, request.call.params).pipe(Effect3.flatMap(() => {
601
+ return toolResultCodec.decodeInput(tool, request.call.params).pipe(Effect7.flatMap(() => {
383
602
  const effect = options.execute({ ...request, placement, tool });
384
603
  return effect;
385
- }), Effect3.mapError((error) => Schema3.is(FrameworkFailure)(error) || Schema3.is(RemoteRetryError)(error) ? error : frameworkFailure("placement", request.call.name, error)), Effect3.flatMap((response) => placementOutcome(placement, tool, response)));
604
+ }), Effect7.mapError((error) => Schema6.is(FrameworkFailure)(error) || Schema6.is(RemoteRetryError)(error) ? error : toolResultCodec.frameworkFailure("placement", request.call.name, error)), Effect7.flatMap((response) => placementOutcome.fromResponse(placement, tool, response)));
386
605
  }
387
606
  });
388
607
  };
389
608
  var remoteRetryError = (reason, message) => RemoteRetryError.make({ reason, message });
390
- var validateOperationKey = (operationKey) => typeof operationKey !== "string" || operationKey.trim().length === 0 ? Effect3.fail(remoteRetryError("missing-operation-key", "Remote retry operation key must be non-empty")) : Effect3.succeed(operationKey);
391
- var retryRemote = (options, request) => Effect3.suspend(() => {
609
+ var validateOperationKey = (operationKey) => typeof operationKey !== "string" || operationKey.trim().length === 0 ? Effect7.fail(remoteRetryError("missing-operation-key", "Remote retry operation key must be non-empty")) : Effect7.succeed(operationKey);
610
+ var retryRemote = (options, request) => Effect7.suspend(() => {
392
611
  if (!Number.isFinite(options.maxRetries) || !Number.isInteger(options.maxRetries) || options.maxRetries < 0) {
393
- return Effect3.fail(remoteRetryError("invalid-max-retries", "Remote retry maxRetries must be a non-negative finite integer"));
612
+ return Effect7.fail(remoteRetryError("invalid-max-retries", "Remote retry maxRetries must be a non-negative finite integer"));
394
613
  }
395
614
  const operationKey = typeof options.operationKey === "function" ? options.operationKey(request) : undefined;
396
- return validateOperationKey(operationKey).pipe(Effect3.flatMap((stableKey) => {
615
+ return validateOperationKey(operationKey).pipe(Effect7.flatMap((stableKey) => {
397
616
  let attempt = 0;
398
- const executeAttempt = Effect3.suspend(() => {
617
+ const executeAttempt = Effect7.suspend(() => {
399
618
  const currentKey = attempt === 0 ? stableKey : options.operationKey(request);
400
619
  attempt += 1;
401
- return validateOperationKey(currentKey).pipe(Effect3.match({
620
+ return validateOperationKey(currentKey).pipe(Effect7.match({
402
621
  onFailure: (error) => error,
403
622
  onSuccess: (validatedKey) => validatedKey
404
- }), Effect3.flatMap((validatedKey) => typeof validatedKey !== "string" ? Effect3.succeed(validatedKey) : validatedKey === stableKey ? options.execute({ ...request, operationKey: stableKey }) : Effect3.succeed(remoteRetryError("changed-operation-key", "Remote retry operation key changed between attempts"))));
623
+ }), Effect7.flatMap((validatedKey) => typeof validatedKey !== "string" ? Effect7.succeed(validatedKey) : validatedKey === stableKey ? options.execute({ ...request, operationKey: stableKey }) : Effect7.succeed(remoteRetryError("changed-operation-key", "Remote retry operation key changed between attempts"))));
405
624
  });
406
- return Effect3.retry(executeAttempt, {
625
+ return Effect7.retry(executeAttempt, {
407
626
  schedule: options.schedule,
408
627
  times: options.maxRetries,
409
- while: (error) => !Schema3.is(AgentError)(error) && !Schema3.is(FrameworkFailure)(error) && !Schema3.is(RemoteRetryError)(error)
410
- }).pipe(Effect3.flatMap((result) => Schema3.is(RemoteRetryError)(result) ? Effect3.fail(result) : Effect3.succeed(result)));
628
+ while: (error) => !Schema6.is(AgentError)(error) && !Schema6.is(FrameworkFailure)(error) && !Schema6.is(RemoteRetryError)(error)
629
+ }).pipe(Effect7.flatMap((result) => Schema6.is(RemoteRetryError)(result) ? Effect7.fail(result) : Effect7.succeed(result)));
411
630
  }));
412
631
  });
413
632
  var client = (options) => placementRoute("client", options);
@@ -423,128 +642,60 @@ function routeToolkit(toolkit) {
423
642
  tools: Object.keys(handled.tools),
424
643
  execute: (request) => executeWithToolkit(handled, request)
425
644
  });
426
- return "handle" in toolkit ? makeRoute(toolkit) : toolkit.pipe(Effect3.map(makeRoute));
645
+ return "handle" in toolkit ? makeRoute(toolkit) : toolkit.pipe(Effect7.map(makeRoute));
427
646
  }
428
- var routeInputEffect = (input) => Effect3.isEffect(input) ? input : Effect3.succeed(input);
647
+ var routeInputEffect = (input) => Effect7.isEffect(input) ? input : Effect7.succeed(input);
429
648
  function router(routes) {
430
- return Layer3.effect(ToolExecutor, Effect3.all(Array.from(routes, routeInputEffect)).pipe(Effect3.map((resolved) => ToolExecutor.of({
649
+ return Layer5.effect(ToolExecutor, Effect7.all(Array.from(routes, routeInputEffect)).pipe(Effect7.map((resolved) => ToolExecutor.of({
431
650
  execute: (request) => {
432
651
  const matched = resolved.find((candidate) => candidate.matches(request));
433
- return matched === undefined ? Effect3.fail(frameworkFailure("route", request.call.name, `Tool ${request.call.name} has no matching route`)) : matched.execute(request);
652
+ return matched === undefined ? Effect7.fail(toolResultCodec.frameworkFailure("route", request.call.name, `Tool ${request.call.name} has no matching route`)) : matched.execute(request);
434
653
  }
435
654
  }))));
436
655
  }
437
- var testLayer2 = (implementation) => Layer3.succeed(ToolExecutor, ToolExecutor.of(implementation));
656
+ var testLayer4 = (implementation) => Layer5.succeed(ToolExecutor, ToolExecutor.of(implementation));
438
657
 
439
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/approvals.js
658
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/approvals.js
440
659
  var exports_approvals = {};
441
660
  __export(exports_approvals, {
442
- testLayer: () => testLayer3,
661
+ testLayer: () => testLayer5,
443
662
  denyAll: () => denyAll,
444
663
  autoApprove: () => autoApprove,
445
664
  Approvals: () => Approvals
446
665
  });
447
- import { Context as Context3, Effect as Effect4, Layer as Layer4 } from "effect";
448
- class Approvals extends Context3.Service()("@batonfx/core/approvals") {
666
+ import { Context as Context5, Effect as Effect8, Layer as Layer6 } from "effect";
667
+ class Approvals extends Context5.Service()("@batonfx/core/approvals") {
449
668
  }
450
- var autoApprove = Layer4.succeed(Approvals, Approvals.of({ check: () => Effect4.succeed({ _tag: "Approved" }) }));
451
- var denyAll = Layer4.succeed(Approvals, Approvals.of({ check: () => Effect4.succeed({ _tag: "Denied" }) }));
452
- var testLayer3 = (implementation) => Layer4.succeed(Approvals, Approvals.of(implementation));
669
+ var autoApprove = Layer6.succeed(Approvals, Approvals.of({ check: () => Effect8.succeed({ _tag: "Approved" }) }));
670
+ var denyAll = Layer6.succeed(Approvals, Approvals.of({ check: () => Effect8.succeed({ _tag: "Denied" }) }));
671
+ var testLayer5 = (implementation) => Layer6.succeed(Approvals, Approvals.of(implementation));
453
672
 
454
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/memory.js
455
- var exports_memory = {};
456
- __export(exports_memory, {
457
- testLayer: () => testLayer4,
458
- replaceRecalledMessage: () => replaceRecalledMessage,
459
- recalledMessageIdentity: () => recalledMessageIdentity,
460
- projectTranscript: () => projectTranscript,
461
- noopLayer: () => noopLayer,
462
- messageFromRecall: () => messageFromRecall,
463
- merge: () => merge,
464
- layerNoop: () => layerNoop,
465
- itemFromPromptPart: () => itemFromPromptPart,
466
- isMessageFromRecall: () => isMessageFromRecall,
467
- MemoryError: () => MemoryError,
468
- Memory: () => Memory
469
- });
470
- import { Context as Context4, Effect as Effect5, Layer as Layer5, Option as Option2, Schema as Schema4 } from "effect";
471
- import { dual as dual2 } from "effect/Function";
472
- import { Prompt as Prompt3 } from "effect/unstable/ai";
473
- var provenanceOption = "@batonfx/core/memory";
474
- var recallLineage = new WeakMap;
475
- var itemFromPromptPart = Option2.liftPredicate((part) => part.type === "text" || part.type === "file");
476
- var isMessageFromRecall = (message) => {
477
- const provenance = message.options[provenanceOption];
478
- return typeof provenance === "object" && provenance !== null && !Array.isArray(provenance) && "origin" in provenance && provenance.origin === "memoryRecall";
479
- };
480
- var messageFromRecall = (content) => {
481
- const message = Prompt3.makeMessage("user", {
482
- content,
483
- options: { [provenanceOption]: { origin: "memoryRecall" } }
484
- });
485
- recallLineage.set(message, message);
486
- return message;
487
- };
488
- var replaceRecalledMessage = dual2(2, (message, content) => {
489
- const options = isMessageFromRecall(message) ? { ...message.options, [provenanceOption]: { origin: "memoryRecall" } } : { ...message.options };
490
- const replacement = Prompt3.makeMessage("user", { content, options });
491
- if (isMessageFromRecall(message))
492
- recallLineage.set(replacement, recallLineage.get(message) ?? message);
493
- return replacement;
494
- });
495
- var recalledMessageIdentity = (message) => recallLineage.get(message) ?? message;
496
- var projectTranscript = (transcript) => {
497
- const content = transcript.content.filter((message) => !isMessageFromRecall(message));
498
- return content.length === transcript.content.length ? transcript : Prompt3.fromMessages(content);
499
- };
500
-
501
- class MemoryError extends Schema4.TaggedErrorClass()("@batonfx/core/MemoryError", {
502
- message: Schema4.String
503
- }) {
504
- }
505
-
506
- class Memory extends Context4.Service()("@batonfx/core/memory") {
507
- }
508
- var noop = {
509
- recall: () => Effect5.succeed([]),
510
- remember: () => Effect5.void,
511
- forget: () => Effect5.void
512
- };
513
- var merge = dual2(2, (first, second) => ({
514
- recall: (input) => Effect5.all([first.recall(input), second.recall(input)]).pipe(Effect5.map(([firstItems, secondItems]) => [...firstItems, ...secondItems])),
515
- remember: (input) => Effect5.all([first.remember(input), second.remember(input)], { discard: true }),
516
- forget: (input) => Effect5.all([first.forget(input), second.forget(input)], { discard: true })
517
- }));
518
- var layerNoop = Layer5.succeed(Memory, Memory.of(noop));
519
- var noopLayer = layerNoop;
520
- var testLayer4 = (implementation) => Layer5.succeed(Memory, Memory.of(implementation));
521
-
522
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/session.js
673
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/session.js
523
674
  var exports_session = {};
524
675
  __export(exports_session, {
525
- testLayer: () => testLayer5,
526
- memoryLayer: () => memoryLayer,
527
- layerMemory: () => layerMemory,
676
+ testLayer: () => testLayer6,
677
+ memoryLayer: () => memoryLayer2,
678
+ layerMemory: () => layerMemory2,
528
679
  buildMemoryContext: () => buildMemoryContext,
529
680
  buildContext: () => buildContext,
530
681
  SessionStoreError: () => SessionStoreError,
531
682
  SessionStore: () => SessionStore,
532
683
  SessionConflict: () => SessionConflict
533
684
  });
534
- import { Context as Context5, Effect as Effect6, HashMap, Layer as Layer6, Option as Option3, Ref, Schema as Schema5 } from "effect";
685
+ import { Context as Context6, Effect as Effect9, HashMap, Layer as Layer7, Option as Option4, Ref as Ref2, Schema as Schema7 } from "effect";
535
686
  import { Prompt as Prompt4 } from "effect/unstable/ai";
536
- class SessionStoreError extends Schema5.TaggedErrorClass()("@batonfx/core/SessionStoreError", {
537
- message: Schema5.String
687
+ class SessionStoreError extends Schema7.TaggedErrorClass()("@batonfx/core/SessionStoreError", {
688
+ message: Schema7.String
538
689
  }) {
539
690
  }
540
691
 
541
- class SessionConflict extends Schema5.TaggedErrorClass()("@batonfx/core/SessionConflict", {
542
- reason: Schema5.Literals(["stale-leaf", "checkpoint-id-reused", "checkpoint-not-on-active-path"]),
543
- message: Schema5.String
692
+ class SessionConflict extends Schema7.TaggedErrorClass()("@batonfx/core/SessionConflict", {
693
+ reason: Schema7.Literals(["stale-leaf", "checkpoint-id-reused", "checkpoint-not-on-active-path"]),
694
+ message: Schema7.String
544
695
  }) {
545
696
  }
546
697
 
547
- class SessionStore extends Context5.Service()("@batonfx/core/session/SessionStore") {
698
+ class SessionStore extends Context6.Service()("@batonfx/core/session/SessionStore") {
548
699
  }
549
700
  var initialState = {
550
701
  entries: HashMap.empty(),
@@ -557,8 +708,8 @@ var failure = (message) => ({
557
708
  _tag: "Failure",
558
709
  error: SessionStoreError.make({ message })
559
710
  });
560
- var effectFromResult = (result) => result._tag === "Failure" ? Effect6.fail(result.error) : Effect6.succeed(result.value);
561
- var effectFromAppendResult = (result) => result._tag === "@batonfx/core/SessionConflict" ? Effect6.fail(result) : effectFromResult(result);
711
+ var effectFromResult = (result) => result._tag === "Failure" ? Effect9.fail(result.error) : Effect9.succeed(result.value);
712
+ var effectFromAppendResult = (result) => result._tag === "@batonfx/core/SessionConflict" ? Effect9.fail(result) : effectFromResult(result);
562
713
  var entryFromInput = (input, id, parentId) => {
563
714
  const base = {
564
715
  id,
@@ -593,7 +744,7 @@ var pathFromState = (state, leaf) => {
593
744
  if (entries.length > state.order.length)
594
745
  return failure(`Session path for leaf ${leaf} contains a cycle`);
595
746
  const entry = HashMap.get(state.entries, cursor);
596
- if (Option3.isNone(entry))
747
+ if (Option4.isNone(entry))
597
748
  return failure(`Session entry ${cursor} does not exist`);
598
749
  const value = entry.value;
599
750
  entries.push(value);
@@ -639,11 +790,11 @@ var appendState = (state, input, options) => {
639
790
  }
640
791
  ];
641
792
  };
642
- var promptEquivalence = Schema5.toEquivalence(Prompt4.Prompt);
793
+ var promptEquivalence = Schema7.toEquivalence(Prompt4.Prompt);
643
794
  var checkpointMatches = (entry, prepared) => entry.parentId === prepared.parentId && entry.summary === prepared.summary && promptEquivalence(entry.projectedHistory, prepared.projectedHistory);
644
795
  var appendCheckpointState = (state, prepared) => {
645
796
  const existing = HashMap.get(state.entries, prepared.id);
646
- if (Option3.isSome(existing)) {
797
+ if (Option4.isSome(existing)) {
647
798
  const entry = existing.value;
648
799
  if (entry._tag !== "Compaction" || entry.version !== 2 || !checkpointMatches(entry, prepared)) {
649
800
  return [
@@ -700,7 +851,7 @@ var appendCheckpointState = (state, prepared) => {
700
851
  ];
701
852
  };
702
853
  var setLeafState = (state, id) => {
703
- if (id !== null && Option3.isNone(HashMap.get(state.entries, id)))
854
+ if (id !== null && Option4.isNone(HashMap.get(state.entries, id)))
704
855
  return [failure(`Session entry ${id} does not exist`), state];
705
856
  return [success(undefined), { ...state, leaf: id }];
706
857
  };
@@ -784,46 +935,46 @@ var buildMemoryContext = (path) => {
784
935
  });
785
936
  return projectTranscript(Prompt4.fromMessages(messages));
786
937
  };
787
- var layerMemory = Layer6.effect(SessionStore, Ref.make(initialState).pipe(Effect6.map((state) => SessionStore.of({
788
- reserveEntryId: Ref.modify(state, (current) => [
938
+ var layerMemory2 = Layer7.effect(SessionStore, Ref2.make(initialState).pipe(Effect9.map((state) => SessionStore.of({
939
+ reserveEntryId: Ref2.modify(state, (current) => [
789
940
  String(current.counter),
790
941
  { ...current, counter: current.counter + 1 }
791
942
  ]),
792
- append: (entry, options) => Ref.modify(state, (current) => appendState(current, entry, options)).pipe(Effect6.flatMap(effectFromAppendResult)),
793
- appendCheckpoint: (checkpoint) => Ref.modify(state, (current) => appendCheckpointState(current, checkpoint)).pipe(Effect6.flatMap((result) => result._tag === "@batonfx/core/SessionConflict" ? Effect6.fail(result) : Effect6.succeed(result))),
794
- path: (leaf) => Ref.get(state).pipe(Effect6.flatMap((current) => leaf === undefined && current.leaf === null ? Effect6.succeed([]) : effectFromResult(pathFromState(current, leaf ?? current.leaf ?? "")))),
795
- setLeaf: (id) => Ref.modify(state, (current) => setLeafState(current, id)).pipe(Effect6.flatMap(effectFromResult)),
796
- leaf: Ref.get(state).pipe(Effect6.map((current) => current.leaf))
943
+ append: (entry, options) => Ref2.modify(state, (current) => appendState(current, entry, options)).pipe(Effect9.flatMap(effectFromAppendResult)),
944
+ appendCheckpoint: (checkpoint) => Ref2.modify(state, (current) => appendCheckpointState(current, checkpoint)).pipe(Effect9.flatMap((result) => result._tag === "@batonfx/core/SessionConflict" ? Effect9.fail(result) : Effect9.succeed(result))),
945
+ path: (leaf) => Ref2.get(state).pipe(Effect9.flatMap((current) => leaf === undefined && current.leaf === null ? Effect9.succeed([]) : effectFromResult(pathFromState(current, leaf ?? current.leaf ?? "")))),
946
+ setLeaf: (id) => Ref2.modify(state, (current) => setLeafState(current, id)).pipe(Effect9.flatMap(effectFromResult)),
947
+ leaf: Ref2.get(state).pipe(Effect9.map((current) => current.leaf))
797
948
  }))));
798
- var memoryLayer = layerMemory;
799
- var testLayer5 = (implementation) => Layer6.succeed(SessionStore, SessionStore.of(implementation));
949
+ var memoryLayer2 = layerMemory2;
950
+ var testLayer6 = (implementation) => Layer7.succeed(SessionStore, SessionStore.of(implementation));
800
951
 
801
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/tool-output.js
952
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-output.js
802
953
  var exports_tool_output = {};
803
954
  __export(exports_tool_output, {
804
- testLayer: () => testLayer6,
955
+ testLayer: () => testLayer7,
805
956
  layerNoop: () => layerNoop2,
806
- layerMemory: () => layerMemory2,
957
+ layerMemory: () => layerMemory3,
807
958
  bound: () => bound,
808
959
  ToolOutputStore: () => ToolOutputStore,
809
960
  ToolOutputError: () => ToolOutputError
810
961
  });
811
- import { Cause, Context as Context6, Effect as Effect7, Function as Function2, HashMap as HashMap2, Layer as Layer7, Option as Option4, Ref as Ref2, Schema as Schema6 } from "effect";
812
- class ToolOutputStore extends Context6.Service()("@batonfx/core/tool-output/ToolOutputStore") {
962
+ import { Cause, Context as Context7, Effect as Effect10, Function as Function3, HashMap as HashMap2, Layer as Layer8, Option as Option5, Ref as Ref3, Schema as Schema8 } from "effect";
963
+ class ToolOutputStore extends Context7.Service()("@batonfx/core/tool-output/ToolOutputStore") {
813
964
  }
814
965
 
815
- class ToolOutputError extends Schema6.TaggedErrorClass()("@batonfx/core/ToolOutputError", {
816
- message: Schema6.String
966
+ class ToolOutputError extends Schema8.TaggedErrorClass()("@batonfx/core/ToolOutputError", {
967
+ message: Schema8.String
817
968
  }) {
818
969
  }
819
- var layerNoop2 = Layer7.succeed(ToolOutputStore, ToolOutputStore.of({ put: () => Effect7.succeed(Option4.none()) }));
820
- var layerMemory2 = Layer7.effect(ToolOutputStore, Ref2.make({ next: 0, records: HashMap2.empty() }).pipe(Effect7.map((state) => ToolOutputStore.of({
821
- put: (toolCallId, content) => Ref2.modify(state, ({ next, records }) => {
970
+ var layerNoop2 = Layer8.succeed(ToolOutputStore, ToolOutputStore.of({ put: () => Effect10.succeed(Option5.none()) }));
971
+ var layerMemory3 = Layer8.effect(ToolOutputStore, Ref3.make({ next: 0, records: HashMap2.empty() }).pipe(Effect10.map((state) => ToolOutputStore.of({
972
+ put: (toolCallId, content) => Ref3.modify(state, ({ next, records }) => {
822
973
  const id = `mem:tool-output-${next + 1}`;
823
- return [Option4.some(id), { next: next + 1, records: HashMap2.set(records, id, { toolCallId, content }) }];
974
+ return [Option5.some(id), { next: next + 1, records: HashMap2.set(records, id, { toolCallId, content }) }];
824
975
  })
825
976
  }))));
826
- var testLayer6 = (implementation) => Layer7.succeed(ToolOutputStore, ToolOutputStore.of(implementation));
977
+ var testLayer7 = (implementation) => Layer8.succeed(ToolOutputStore, ToolOutputStore.of(implementation));
827
978
  var encoder = new TextEncoder;
828
979
  var decoder = new TextDecoder;
829
980
  var serialized = (value) => {
@@ -848,11 +999,11 @@ var bounded = (inline, outputPaths) => {
848
999
  return { _tag: "Success", result: output, encodedResult: output, outputPaths };
849
1000
  };
850
1001
  var boundedFromOriginal = (encoded, bytes, maxBytes, outputPaths) => bounded({ truncated: true, bytes, maxBytes, preview: preview(encoded, maxBytes) }, outputPaths);
851
- var optionalStore = (store, toolCallId, result) => store.put(toolCallId, { result: result.result, encodedResult: result.encodedResult }).pipe(Effect7.catchCause((cause) => {
1002
+ var optionalStore = (store, toolCallId, result) => store.put(toolCallId, { result: result.result, encodedResult: result.encodedResult }).pipe(Effect10.catchCause((cause) => {
852
1003
  const unrecoverable = cause.reasons.filter((reason) => Cause.isDieReason(reason) || Cause.isInterruptReason(reason));
853
- return unrecoverable.length === 0 ? Effect7.succeed(Option4.none()) : Effect7.failCause(Cause.fromReasons(unrecoverable));
1004
+ return unrecoverable.length === 0 ? Effect10.succeed(Option5.none()) : Effect10.failCause(Cause.fromReasons(unrecoverable));
854
1005
  }));
855
- var bound = Function2.dual(2, (result, options) => Effect7.gen(function* () {
1006
+ var bound = Function3.dual(2, (result, options) => Effect10.gen(function* () {
856
1007
  if (isToolOutput(result.encodedResult)) {
857
1008
  const output = result.encodedResult;
858
1009
  const outputPaths = output.outputPaths ?? [];
@@ -865,25 +1016,25 @@ var bound = Function2.dual(2, (result, options) => Effect7.gen(function* () {
865
1016
  const bytes = encoder.encode(encoded).byteLength;
866
1017
  if (bytes <= options.maxBytes)
867
1018
  return { ...result, outputPaths: [] };
868
- const maybeStore = yield* Effect7.serviceOption(ToolOutputStore);
869
- if (Option4.isNone(maybeStore))
1019
+ const maybeStore = yield* Effect10.serviceOption(ToolOutputStore);
1020
+ if (Option5.isNone(maybeStore))
870
1021
  return boundedFromOriginal(encoded, bytes, options.maxBytes, []);
871
1022
  const path = yield* optionalStore(maybeStore.value, options.toolCallId, result);
872
- if (Option4.isNone(path))
1023
+ if (Option5.isNone(path))
873
1024
  return boundedFromOriginal(encoded, bytes, options.maxBytes, []);
874
1025
  return boundedFromOriginal(encoded, bytes, options.maxBytes, [path.value]);
875
1026
  }));
876
1027
 
877
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/compaction.js
1028
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/compaction.js
878
1029
  var exports_compaction = {};
879
1030
  __export(exports_compaction, {
880
1031
  truncate: () => truncate,
881
1032
  toolOutputBound: () => toolOutputBound,
882
- testLayer: () => testLayer7,
1033
+ testLayer: () => testLayer8,
883
1034
  structuredSummary: () => structuredSummary,
884
1035
  strategy: () => strategy,
885
1036
  make: () => make2,
886
- layer: () => layer,
1037
+ layer: () => layer2,
887
1038
  keepRecent: () => keepRecent,
888
1039
  defaultStrategy: () => defaultStrategy,
889
1040
  SUMMARY_TEMPLATE: () => SUMMARY_TEMPLATE,
@@ -893,8 +1044,8 @@ __export(exports_compaction, {
893
1044
  Compaction: () => Compaction,
894
1045
  AgentSummary: () => AgentSummary
895
1046
  });
896
- import { Context as Context7, Effect as Effect8, Function as Function3, Layer as Layer8, Option as Option5, Schema as Schema7 } from "effect";
897
- import { LanguageModel as LanguageModel2, Prompt as Prompt5, Tokenizer, Toolkit as Toolkit2 } from "effect/unstable/ai";
1047
+ import { Context as Context8, Effect as Effect11, Function as Function4, Layer as Layer9, Option as Option6, Schema as Schema9 } from "effect";
1048
+ import { LanguageModel as LanguageModel3, Prompt as Prompt5, Tokenizer, Toolkit as Toolkit2 } from "effect/unstable/ai";
898
1049
  var DEFAULT_RESERVE_TOKENS = 16384;
899
1050
  var DEFAULT_KEEP_RECENT_TOKENS = 20000;
900
1051
  var SUMMARY_TEMPLATE = `Summarize the conversation so another agent can continue seamlessly.
@@ -912,21 +1063,21 @@ Use Markdown with these sections:
912
1063
  ## Critical Context
913
1064
 
914
1065
  Do not mention that context was compacted.`;
915
- var AgentSummary = Schema7.Struct({
916
- goal: Schema7.String,
917
- facts: Schema7.Array(Schema7.String),
918
- decisions: Schema7.Array(Schema7.String),
919
- openQuestions: Schema7.Array(Schema7.String),
920
- toolFindings: Schema7.Array(Schema7.String)
1066
+ var AgentSummary = Schema9.Struct({
1067
+ goal: Schema9.String,
1068
+ facts: Schema9.Array(Schema9.String),
1069
+ decisions: Schema9.Array(Schema9.String),
1070
+ openQuestions: Schema9.Array(Schema9.String),
1071
+ toolFindings: Schema9.Array(Schema9.String)
921
1072
  });
922
1073
 
923
- class CompactionError extends Schema7.TaggedErrorClass()("@batonfx/core/CompactionError", {
924
- message: Schema7.String,
925
- cause: Schema7.optionalKey(Schema7.Defect())
1074
+ class CompactionError extends Schema9.TaggedErrorClass()("@batonfx/core/CompactionError", {
1075
+ message: Schema9.String,
1076
+ cause: Schema9.optionalKey(Schema9.Defect())
926
1077
  }) {
927
1078
  }
928
1079
 
929
- class Compaction extends Context7.Service()("@batonfx/core/compaction") {
1080
+ class Compaction extends Context8.Service()("@batonfx/core/compaction") {
930
1081
  }
931
1082
  var serialized2 = (value) => {
932
1083
  const json = JSON.stringify(value);
@@ -962,7 +1113,7 @@ var isPromptToolResult = (part) => part.type === "tool-result";
962
1113
  var messageHasToolCall = (message) => typeof message.content !== "string" && message.content.some((part) => part.type === "tool-call");
963
1114
  var isToolMessage = (entry) => entry?._tag === "Message" && entry.message.role === "tool";
964
1115
  var isAssistantToolCallEntry = (entry) => entry?._tag === "Message" && entry.message.role === "assistant" && messageHasToolCall(entry.message);
965
- var compactToolPart = (part, maxBytes) => Effect8.gen(function* () {
1116
+ var compactToolPart = (part, maxBytes) => Effect11.gen(function* () {
966
1117
  if (part.isFailure)
967
1118
  return [part, false];
968
1119
  const success2 = { _tag: "Success", result: part.result, encodedResult: part.result };
@@ -979,7 +1130,7 @@ var compactToolPart = (part, maxBytes) => Effect8.gen(function* () {
979
1130
  true
980
1131
  ];
981
1132
  });
982
- var microcompactPrompt = (prompt, maxBytes) => Effect8.gen(function* () {
1133
+ var microcompactPrompt = (prompt, maxBytes) => Effect11.gen(function* () {
983
1134
  let changed = false;
984
1135
  const messages = [];
985
1136
  for (const message of prompt.content) {
@@ -1041,23 +1192,23 @@ var defaultStrategy = (options = {}) => ({
1041
1192
  cut: (entries, keepRecentTokens) => {
1042
1193
  const index = safeCutIndex(entries, keepRecentTokens);
1043
1194
  if (index <= 0 || index >= entries.length)
1044
- return Option5.none();
1195
+ return Option6.none();
1045
1196
  const recent = entries.slice(index);
1046
1197
  const first = recent[0];
1047
- return first === undefined ? Option5.none() : Option5.some({ firstKeptEntryId: first.id, head: entries.slice(0, index), recent });
1198
+ return first === undefined ? Option6.none() : Option6.some({ firstKeptEntryId: first.id, head: entries.slice(0, index), recent });
1048
1199
  },
1049
1200
  summarize: (plan, request) => {
1050
- const effect = Effect8.gen(function* () {
1201
+ const effect = Effect11.gen(function* () {
1051
1202
  const head = buildContext(plan.head);
1052
1203
  const [compactedHead] = request.toolOutputMaxBytes === undefined ? [head, false] : yield* microcompactPrompt(head, request.toolOutputMaxBytes);
1053
1204
  const prompt = summaryPrompt(options.summaryPrompt ?? SUMMARY_TEMPLATE, compactedHead);
1054
- const model = yield* LanguageModel2.LanguageModel;
1055
- return yield* model.generateText({ prompt, toolkit: Toolkit2.empty, toolChoice: "none" }).pipe(Effect8.map((response) => response.text), Effect8.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1205
+ const model = yield* LanguageModel3.LanguageModel;
1206
+ return yield* model.generateText({ prompt, toolkit: Toolkit2.empty, toolChoice: "none" }).pipe(Effect11.map((response) => response.text), Effect11.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1056
1207
  });
1057
- return options.summaryModel === undefined ? effect : Effect8.scoped(Layer8.build(options.summaryModel).pipe(Effect8.flatMap((context) => effect.pipe(Effect8.provide(context)))));
1208
+ return options.summaryModel === undefined ? effect : Effect11.scoped(Layer9.build(options.summaryModel).pipe(Effect11.flatMap((context) => effect.pipe(Effect11.provide(context)))));
1058
1209
  }
1059
1210
  });
1060
- var strategy = Function3.dual((args) => args.length !== 1 || Array.isArray(args[0]), (parts, base = defaultStrategy()) => parts.reduce((current, part) => ({
1211
+ var strategy = Function4.dual((args) => args.length !== 1 || Array.isArray(args[0]), (parts, base = defaultStrategy()) => parts.reduce((current, part) => ({
1061
1212
  shouldCompact: part.shouldCompact ?? current.shouldCompact,
1062
1213
  cut: part.cut ?? current.cut,
1063
1214
  summarize: part.summarize ?? current.summarize,
@@ -1072,27 +1223,27 @@ var keepRecent = (options) => ({
1072
1223
  });
1073
1224
  var structuredSummary = (options = {}) => ({
1074
1225
  summarize: (plan, request) => {
1075
- const effect = Effect8.gen(function* () {
1226
+ const effect = Effect11.gen(function* () {
1076
1227
  const head = buildContext(plan.head);
1077
1228
  const [compactedHead] = request.toolOutputMaxBytes === undefined ? [head, false] : yield* microcompactPrompt(head, request.toolOutputMaxBytes);
1078
1229
  const prompt = summaryPrompt(options.summaryPrompt ?? SUMMARY_TEMPLATE, compactedHead);
1079
- const model = yield* LanguageModel2.LanguageModel;
1230
+ const model = yield* LanguageModel3.LanguageModel;
1080
1231
  return yield* model.generateObject({
1081
1232
  prompt,
1082
1233
  schema: AgentSummary,
1083
1234
  objectName: options.objectName ?? "AgentSummary",
1084
1235
  toolChoice: "none"
1085
- }).pipe(Effect8.map((response) => renderAgentSummary(response.value)), Effect8.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1236
+ }).pipe(Effect11.map((response) => renderAgentSummary(response.value)), Effect11.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1086
1237
  });
1087
- return options.summaryModel === undefined ? effect : Effect8.scoped(Layer8.build(options.summaryModel).pipe(Effect8.flatMap((context) => effect.pipe(Effect8.provide(context)))));
1238
+ return options.summaryModel === undefined ? effect : Effect11.scoped(Layer9.build(options.summaryModel).pipe(Effect11.flatMap((context) => effect.pipe(Effect11.provide(context)))));
1088
1239
  }
1089
1240
  });
1090
- var make2 = Function3.dual((args) => args.length !== 1 || ("shouldCompact" in args[0]), (compactionStrategy, options = {}) => ({
1091
- maybeCompact: (input) => Effect8.gen(function* () {
1241
+ var make2 = Function4.dual((args) => args.length !== 1 || ("shouldCompact" in args[0]), (compactionStrategy, options = {}) => ({
1242
+ maybeCompact: (input) => Effect11.gen(function* () {
1092
1243
  const usage = normalizeUsage(input.usage, options);
1093
1244
  const shouldCompact = input.overflow || compactionStrategy.shouldCompact(usage);
1094
1245
  if (!shouldCompact)
1095
- return Option5.none();
1246
+ return Option6.none();
1096
1247
  let history = input.history;
1097
1248
  let prompt = input.prompt;
1098
1249
  let changed = false;
@@ -1104,11 +1255,11 @@ var make2 = Function3.dual((args) => args.length !== 1 || ("shouldCompact" in ar
1104
1255
  prompt = compactedPrompt;
1105
1256
  changed = historyChanged || promptChanged;
1106
1257
  if (changed && fits(history, prompt, usage))
1107
- return Option5.some(makeMicrocompact(history, prompt));
1258
+ return Option6.some(makeMicrocompact(history, prompt));
1108
1259
  }
1109
1260
  const plan = compactionStrategy.cut(input.path ?? [], compactionStrategy.keepRecentTokens ?? options.keepRecentTokens ?? DEFAULT_KEEP_RECENT_TOKENS);
1110
- if (Option5.isNone(plan))
1111
- return changed ? Option5.some(makeMicrocompact(history, prompt)) : Option5.none();
1261
+ if (Option6.isNone(plan))
1262
+ return changed ? Option6.some(makeMicrocompact(history, prompt)) : Option6.none();
1112
1263
  const summary = yield* compactionStrategy.summarize(plan.value, {
1113
1264
  ...input,
1114
1265
  history,
@@ -1118,7 +1269,7 @@ var make2 = Function3.dual((args) => args.length !== 1 || ("shouldCompact" in ar
1118
1269
  });
1119
1270
  const recent = buildContext(plan.value.recent);
1120
1271
  const [compactedRecent] = toolOutputMaxBytes === undefined ? [recent, false] : yield* microcompactPrompt(recent, toolOutputMaxBytes);
1121
- return Option5.some({
1272
+ return Option6.some({
1122
1273
  _tag: "Summarize",
1123
1274
  history: compactedHistory(summary, plan.value.head, compactedRecent),
1124
1275
  prompt,
@@ -1127,42 +1278,42 @@ var make2 = Function3.dual((args) => args.length !== 1 || ("shouldCompact" in ar
1127
1278
  });
1128
1279
  })
1129
1280
  }));
1130
- var layer = Function3.dual((args) => args.length !== 1 || !("shouldCompact" in args[0]), (options = {}, providedStrategy = options.strategy ?? defaultStrategy(options)) => Layer8.succeed(Compaction, Compaction.of(make2(providedStrategy, options))));
1281
+ var layer2 = Function4.dual((args) => args.length !== 1 || !("shouldCompact" in args[0]), (options = {}, providedStrategy = options.strategy ?? defaultStrategy(options)) => Layer9.succeed(Compaction, Compaction.of(make2(providedStrategy, options))));
1131
1282
  var truncate = (maxTokens) => ({
1132
- maybeCompact: (input) => Effect8.gen(function* () {
1283
+ maybeCompact: (input) => Effect11.gen(function* () {
1133
1284
  const usage = input.usage;
1134
1285
  if (!input.overflow && !(Number.isFinite(usage.contextWindow) && usage.contextTokens > usage.contextWindow - usage.reserveTokens)) {
1135
- return Option5.none();
1286
+ return Option6.none();
1136
1287
  }
1137
- const tokenizer = yield* Effect8.serviceOption(Tokenizer.Tokenizer);
1138
- if (Option5.isNone(tokenizer))
1139
- return Option5.none();
1140
- const prompt = yield* tokenizer.value.truncate(Prompt5.concat(input.history, input.prompt), maxTokens).pipe(Effect8.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1141
- return Option5.some(makeMicrocompact(Prompt5.empty, prompt));
1288
+ const tokenizer = yield* Effect11.serviceOption(Tokenizer.Tokenizer);
1289
+ if (Option6.isNone(tokenizer))
1290
+ return Option6.none();
1291
+ const prompt = yield* tokenizer.value.truncate(Prompt5.concat(input.history, input.prompt), maxTokens).pipe(Effect11.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1292
+ return Option6.some(makeMicrocompact(Prompt5.empty, prompt));
1142
1293
  })
1143
1294
  });
1144
- var testLayer7 = (implementation) => Layer8.succeed(Compaction, Compaction.of(implementation));
1295
+ var testLayer8 = (implementation) => Layer9.succeed(Compaction, Compaction.of(implementation));
1145
1296
 
1146
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/instructions.js
1297
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/instructions.js
1147
1298
  var exports_instructions = {};
1148
1299
  __export(exports_instructions, {
1149
- testLayer: () => testLayer8,
1300
+ testLayer: () => testLayer9,
1150
1301
  staticSource: () => staticSource,
1151
1302
  renderUpdate: () => renderUpdate,
1152
1303
  openEpoch: () => openEpoch,
1153
- layer: () => layer2,
1304
+ layer: () => layer3,
1154
1305
  Instructions: () => Instructions
1155
1306
  });
1156
- import { Context as Context8, Effect as Effect9, Layer as Layer9, Option as Option6 } from "effect";
1307
+ import { Context as Context9, Effect as Effect12, Layer as Layer10, Option as Option7 } from "effect";
1157
1308
  import { dual as dual3 } from "effect/Function";
1158
- class Instructions extends Context8.Service()("@batonfx/core/instructions") {
1309
+ class Instructions extends Context9.Service()("@batonfx/core/instructions") {
1159
1310
  }
1160
1311
  var staticSource = dual3(2, (id, text) => ({
1161
1312
  id,
1162
1313
  cache: "baseline",
1163
- render: () => Effect9.succeed(text.length === 0 ? Option6.none() : Option6.some(text))
1314
+ render: () => Effect12.succeed(text.length === 0 ? Option7.none() : Option7.some(text))
1164
1315
  }));
1165
- var openEpoch = dual3(2, (instructions, context) => Effect9.gen(function* () {
1316
+ var openEpoch = dual3(2, (instructions, context) => Effect12.gen(function* () {
1166
1317
  const baseline = [];
1167
1318
  const dynamic = [];
1168
1319
  for (const source of instructions.sources) {
@@ -1170,7 +1321,7 @@ var openEpoch = dual3(2, (instructions, context) => Effect9.gen(function* () {
1170
1321
  dynamic.push(source);
1171
1322
  } else {
1172
1323
  const rendered = yield* source.render(context);
1173
- if (Option6.isSome(rendered))
1324
+ if (Option7.isSome(rendered))
1174
1325
  baseline.push(rendered.value);
1175
1326
  }
1176
1327
  }
@@ -1178,164 +1329,37 @@ var openEpoch = dual3(2, (instructions, context) => Effect9.gen(function* () {
1178
1329
 
1179
1330
  `), dynamic };
1180
1331
  }));
1181
- var renderUpdate = dual3(2, (epoch, context) => Effect9.gen(function* () {
1332
+ var renderUpdate = dual3(2, (epoch, context) => Effect12.gen(function* () {
1182
1333
  const fragments = [];
1183
1334
  for (const source of epoch.dynamic) {
1184
1335
  const rendered = yield* source.render(context);
1185
- if (Option6.isSome(rendered))
1336
+ if (Option7.isSome(rendered))
1186
1337
  fragments.push(rendered.value);
1187
1338
  }
1188
- return fragments.length === 0 ? Option6.none() : Option6.some(fragments.join(`
1339
+ return fragments.length === 0 ? Option7.none() : Option7.some(fragments.join(`
1189
1340
 
1190
1341
  `));
1191
1342
  }));
1192
- var layer2 = (sources) => Layer9.succeed(Instructions, Instructions.of({ sources: [...sources] }));
1193
- var testLayer8 = (implementation) => Layer9.succeed(Instructions, Instructions.of(implementation));
1343
+ var layer3 = (sources) => Layer10.succeed(Instructions, Instructions.of({ sources: [...sources] }));
1344
+ var testLayer9 = (implementation) => Layer10.succeed(Instructions, Instructions.of(implementation));
1194
1345
 
1195
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/model-middleware.js
1346
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/model-middleware.js
1196
1347
  var exports_model_middleware = {};
1197
1348
  __export(exports_model_middleware, {
1198
- layerIdentity: () => layerIdentity,
1199
- layer: () => layer3,
1200
- identityLayer: () => identityLayer,
1201
- ModelMiddleware: () => ModelMiddleware
1202
- });
1203
- import { Context as Context9, Effect as Effect10, Layer as Layer10, Option as Option7 } from "effect";
1204
- import { Prompt as Prompt6, Response as Response4 } from "effect/unstable/ai";
1205
- class ModelMiddleware extends Context9.Service()("@batonfx/core/model-middleware/ModelMiddleware") {
1206
- }
1207
- var layerIdentity = Layer10.succeed(ModelMiddleware, []);
1208
- var identityLayer = layerIdentity;
1209
- var layer3 = (middleware) => Layer10.succeed(ModelMiddleware, middleware);
1210
-
1211
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/model-registry.js
1212
- var exports_model_registry = {};
1213
- __export(exports_model_registry, {
1214
- testLayer: () => testLayer9,
1215
- stream: () => stream,
1216
- registrations: () => registrations,
1217
- registrationFromLayer: () => registrationFromLayer,
1218
- register: () => register,
1219
- provide: () => provide,
1220
- operate: () => operate,
1221
- memoryLayer: () => memoryLayer2,
1222
- layerMemory: () => layerMemory3,
1223
- layerFromRegistrationEffects: () => layerFromRegistrationEffects,
1224
- layer: () => layer4,
1225
- combine: () => combine,
1226
- classifyFailure: () => classifyFailure,
1227
- Service: () => Service,
1228
- LanguageModelNotRegistered: () => LanguageModelNotRegistered
1229
- });
1230
- import { Chunk, Context as Context10, Effect as Effect11, Function as Function4, Layer as Layer11, Option as Option8, Ref as Ref3, Schema as Schema8, Semaphore, Stream as Stream2 } from "effect";
1231
- import { LanguageModel as LanguageModel3, Model } from "effect/unstable/ai";
1232
- var FailureClassifierTypeId = Symbol.for("@batonfx/core/model-registry/FailureClassifier");
1233
- var classifyFailure = Function4.dual(2, (model, error) => model[FailureClassifierTypeId]?.(error) ?? "other");
1234
- var attachFailureClassifier = (registration, context) => {
1235
- if (registration.classifyFailure === undefined)
1236
- return context;
1237
- const model = Context10.get(context, LanguageModel3.LanguageModel);
1238
- const classified = {
1239
- ...model,
1240
- [FailureClassifierTypeId]: registration.classifyFailure
1241
- };
1242
- return Context10.add(context, LanguageModel3.LanguageModel, classified);
1243
- };
1244
-
1245
- class LanguageModelNotRegistered extends Schema8.TaggedErrorClass()("LanguageModelNotRegistered", {
1246
- provider: Schema8.String,
1247
- model: Schema8.String,
1248
- registration_key: Schema8.optionalKey(Schema8.String)
1249
- }) {
1250
- }
1251
-
1252
- class Service extends Context10.Service()("@batonfx/core/model-registry/Service") {
1253
- }
1254
- var registrationVariantKey = (value) => value.registrationKey ?? null;
1255
- var selectionVariantKey = (selection) => selection.registrationKey ?? null;
1256
- var registryIdentity = (registration) => JSON.stringify([registration.provider, registration.model, registrationVariantKey(registration)]);
1257
- var matchesSelection = (selection) => (registration) => registration.provider === selection.provider && registration.model === selection.model && registrationVariantKey(registration) === selectionVariantKey(selection);
1258
- var upsertRegistration = (registry, registration) => {
1259
- const key = registryIdentity(registration);
1260
- const exists = Option8.isSome(Chunk.findFirst(registry, (item) => registryIdentity(item) === key));
1261
- if (!exists)
1262
- return Chunk.append(registry, registration);
1263
- return Chunk.map(registry, (item) => registryIdentity(item) === key ? registration : item);
1264
- };
1265
- var findRegistration = (registry, selection) => Chunk.findFirst(registry, matchesSelection(selection)).pipe(Option8.getOrUndefined);
1266
- var registrationFromLayer = (input) => Model.make(input.provider, input.model, input.layer).captureRequirements.pipe(Effect11.map((layer4) => ({
1267
- provider: input.provider,
1268
- model: input.model,
1269
- layer: layer4,
1270
- ...input.registrationKey === undefined ? {} : { registrationKey: input.registrationKey },
1271
- ...input.metadata === undefined ? {} : { metadata: input.metadata },
1272
- ...input.classifyFailure === undefined ? {} : { classifyFailure: input.classifyFailure }
1273
- })));
1274
- var layer4 = Function4.dual((args) => args.length === 0 || args.length > 1 || Array.isArray(args[0]), (initialRegistrations = [], options) => Layer11.effect(Service, Effect11.gen(function* () {
1275
- const registry = yield* Ref3.make(initialRegistrations.reduce(upsertRegistration, Chunk.empty()));
1276
- const semaphore = options?.maxConcurrentModelCalls === undefined ? undefined : yield* Semaphore.make(options.maxConcurrentModelCalls);
1277
- const register = Effect11.fn("ModelRegistry.register")(function* (input) {
1278
- yield* Ref3.update(registry, (items) => upsertRegistration(items, input.registration));
1279
- });
1280
- const registrations = Ref3.get(registry).pipe(Effect11.map(Chunk.toReadonlyArray));
1281
- const operate = Effect11.fn("ModelRegistry.operate")(function* (selection, effect) {
1282
- const items = yield* Ref3.get(registry);
1283
- const registration = findRegistration(items, selection);
1284
- if (registration === undefined) {
1285
- return yield* LanguageModelNotRegistered.make({
1286
- provider: selection.provider,
1287
- model: selection.model,
1288
- ...selection.registrationKey === undefined ? {} : { registration_key: selection.registrationKey }
1289
- });
1290
- }
1291
- const provided = Effect11.scoped(Layer11.build(registration.layer).pipe(Effect11.flatMap((context) => effect.pipe(Effect11.provide(attachFailureClassifier(registration, context))))));
1292
- return yield* semaphore === undefined ? provided : semaphore.withPermits(1)(provided);
1293
- });
1294
- const stream = (selection, operation) => Stream2.unwrap(Effect11.gen(function* () {
1295
- const items = yield* Ref3.get(registry);
1296
- const registration = findRegistration(items, selection);
1297
- if (registration === undefined) {
1298
- return yield* LanguageModelNotRegistered.make({
1299
- provider: selection.provider,
1300
- model: selection.model,
1301
- ...selection.registrationKey === undefined ? {} : { registration_key: selection.registrationKey }
1302
- });
1303
- }
1304
- if (semaphore !== undefined) {
1305
- yield* Effect11.acquireRelease(semaphore.take(1), () => semaphore.release(1), { interruptible: true });
1306
- }
1307
- const context = attachFailureClassifier(registration, yield* Layer11.build(registration.layer));
1308
- return operation.pipe(Stream2.provideContext(context));
1309
- }));
1310
- return Service.of({
1311
- register,
1312
- registrations,
1313
- operate,
1314
- stream,
1315
- provide: operate
1316
- });
1317
- })));
1318
- var layerFromRegistrationEffects = Function4.dual((args) => args.length !== 1 || Array.isArray(args[0]), (registrations, options) => Layer11.unwrap(Effect11.all(registrations).pipe(Effect11.map((items) => layer4(items, options)))));
1319
- var combine = Function4.dual((args) => args.length !== 1 || Array.isArray(args[0]), (registries, options) => Layer11.unwrap(Effect11.forEach(registries, (registry) => Layer11.build(registry).pipe(Effect11.flatMap((context) => Context10.get(context, Service).registrations))).pipe(Effect11.map((groups) => layer4(groups.flat(), options)))));
1320
- var layerMemory3 = layer4;
1321
- var memoryLayer2 = layerMemory3;
1322
- var testLayer9 = (implementation) => Layer11.succeed(Service, Service.of(implementation));
1323
- var register = Effect11.fn("ModelRegistry.register.call")(function* (input) {
1324
- const service = yield* Service;
1325
- return yield* service.register(input);
1326
- });
1327
- var registrations = Effect11.fn("ModelRegistry.registrations.call")(function* () {
1328
- const service = yield* Service;
1329
- return yield* service.registrations;
1349
+ layerIdentity: () => layerIdentity,
1350
+ layer: () => layer4,
1351
+ identityLayer: () => identityLayer,
1352
+ ModelMiddleware: () => ModelMiddleware
1330
1353
  });
1331
- var operate = Function4.dual(2, (selection, effect) => Effect11.gen(function* () {
1332
- const service = yield* Service;
1333
- return yield* service.operate(selection, effect);
1334
- }));
1335
- var stream = Function4.dual(2, (selection, operation) => Stream2.unwrap(Service.pipe(Effect11.map((service) => service.stream(selection, operation)))));
1336
- var provide = operate;
1354
+ import { Context as Context10, Effect as Effect13, Layer as Layer11, Option as Option8 } from "effect";
1355
+ import { Prompt as Prompt6, Response as Response4 } from "effect/unstable/ai";
1356
+ class ModelMiddleware extends Context10.Service()("@batonfx/core/model-middleware/ModelMiddleware") {
1357
+ }
1358
+ var layerIdentity = Layer11.succeed(ModelMiddleware, []);
1359
+ var identityLayer = layerIdentity;
1360
+ var layer4 = (middleware) => Layer11.succeed(ModelMiddleware, middleware);
1337
1361
 
1338
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/model-resilience.js
1362
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/model-resilience.js
1339
1363
  var exports_model_resilience = {};
1340
1364
  __export(exports_model_resilience, {
1341
1365
  testLayer: () => testLayer10,
@@ -1346,12 +1370,12 @@ __export(exports_model_resilience, {
1346
1370
  apply: () => apply,
1347
1371
  ModelResilience: () => ModelResilience
1348
1372
  });
1349
- import { Cause as Cause2, Context as Context11, Effect as Effect12, Function as Function5, Layer as Layer12, Result, Schedule as Schedule2, Schema as Schema9, Stream as Stream3 } from "effect";
1350
- import { AiError as AiError2, LanguageModel as LanguageModel4, Response as Response5, Tool as Tool3 } from "effect/unstable/ai";
1373
+ import { Cause as Cause2, Context as Context11, Effect as Effect14, Function as Function5, Layer as Layer12, Result, Schedule as Schedule2, Schema as Schema10, Stream as Stream3 } from "effect";
1374
+ import { AiError as AiError3, LanguageModel as LanguageModel4, Response as Response5, Tool as Tool5 } from "effect/unstable/ai";
1351
1375
 
1352
1376
  class ModelResilience extends Context11.Service()("@batonfx/core/model-resilience/ModelResilience") {
1353
1377
  }
1354
- var defaultClassify = (error) => AiError2.isAiError(error) && error.isRetryable ? "transient" : "terminal";
1378
+ var defaultClassify = (error) => AiError3.isAiError(error) && error.isRetryable ? "transient" : "terminal";
1355
1379
  var none = { classify: () => "terminal", retrySchedule: Schedule2.recurs(0) };
1356
1380
  var make3 = (input) => ({
1357
1381
  classify: input?.classify ?? defaultClassify,
@@ -1359,17 +1383,17 @@ var make3 = (input) => ({
1359
1383
  });
1360
1384
  var layer5 = (input) => Layer12.succeed(ModelResilience, ModelResilience.of(make3(input)));
1361
1385
  var testLayer10 = (implementation) => Layer12.succeed(ModelResilience, ModelResilience.of(implementation));
1362
- var retryEffect = (effect, resilience) => Effect12.suspend(effect).pipe(Effect12.map((value) => Result.succeed(value)), Effect12.catchCause((cause) => {
1386
+ var retryEffect = (effect, resilience) => Effect14.suspend(effect).pipe(Effect14.map((value) => Result.succeed(value)), Effect14.catchCause((cause) => {
1363
1387
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
1364
- return reason === undefined || !Cause2.isFailReason(reason) ? Effect12.succeed(Result.fail(cause)) : Effect12.fail(reason.error);
1365
- }), Effect12.retry({
1388
+ return reason === undefined || !Cause2.isFailReason(reason) ? Effect14.succeed(Result.fail(cause)) : Effect14.fail(reason.error);
1389
+ }), Effect14.retry({
1366
1390
  schedule: resilience.retrySchedule,
1367
1391
  while: (error) => resilience.classify(error) === "transient"
1368
- }), Effect12.flatMap((result) => Result.isFailure(result) ? Effect12.failCause(result.failure) : Effect12.succeed(result.success)));
1392
+ }), Effect14.flatMap((result) => Result.isFailure(result) ? Effect14.failCause(result.failure) : Effect14.succeed(result.success)));
1369
1393
  var retryStreamSchedule = (resilience) => resilience.retrySchedule.pipe(Schedule2.while(({ input }) => resilience.classify(input) === "transient"));
1370
1394
  var retryStream = (stream2, onEmittedFailure, resilience) => Stream3.suspend(() => {
1371
1395
  let emitted = false;
1372
- return stream2().pipe(Stream3.map((value) => Result.succeed(value)), Stream3.tap(() => Effect12.sync(() => {
1396
+ return stream2().pipe(Stream3.map((value) => Result.succeed(value)), Stream3.tap(() => Effect14.sync(() => {
1373
1397
  emitted = true;
1374
1398
  })), Stream3.catchCause((cause) => {
1375
1399
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
@@ -1388,7 +1412,7 @@ var apply = Function5.dual(2, (model, resilience) => ({
1388
1412
  streamText: (options) => retryStream(() => model.streamText(options), (error) => Response5.makePart("error", { error }), resilience)
1389
1413
  }));
1390
1414
 
1391
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/permissions.js
1415
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/permissions.js
1392
1416
  var exports_permissions = {};
1393
1417
  __export(exports_permissions, {
1394
1418
  testLayer: () => testLayer11,
@@ -1404,11 +1428,11 @@ __export(exports_permissions, {
1404
1428
  Permissions: () => Permissions,
1405
1429
  PermissionError: () => PermissionError
1406
1430
  });
1407
- import { Context as Context12, Effect as Effect13, Layer as Layer13, Option as Option9, Ref as Ref4, Schema as Schema10 } from "effect";
1431
+ import { Context as Context12, Effect as Effect15, Layer as Layer13, Option as Option9, Ref as Ref4, Schema as Schema11 } from "effect";
1408
1432
  import { dual as dual4 } from "effect/Function";
1409
1433
 
1410
- class PermissionError extends Schema10.TaggedErrorClass()("@batonfx/core/PermissionError", {
1411
- message: Schema10.String
1434
+ class PermissionError extends Schema11.TaggedErrorClass()("@batonfx/core/PermissionError", {
1435
+ message: Schema11.String
1412
1436
  }) {
1413
1437
  }
1414
1438
 
@@ -1504,25 +1528,25 @@ var decisionFor = (ruleset, request) => {
1504
1528
  }
1505
1529
  };
1506
1530
  var fromRuleset = (ruleset) => Layer13.succeed(Permissions, Permissions.of({
1507
- evaluate: (request) => Effect13.succeed(decisionFor(ruleset, request)),
1508
- await: () => Effect13.succeed(Option9.none())
1531
+ evaluate: (request) => Effect15.succeed(decisionFor(ruleset, request)),
1532
+ await: () => Effect15.succeed(Option9.none())
1509
1533
  }));
1510
1534
  var allowAll = Layer13.succeed(Permissions, Permissions.of({
1511
- evaluate: () => Effect13.succeed({ _tag: "Allow" }),
1512
- await: () => Effect13.succeed(Option9.none())
1535
+ evaluate: () => Effect15.succeed({ _tag: "Allow" }),
1536
+ await: () => Effect15.succeed(Option9.none())
1513
1537
  }));
1514
1538
  var interactive = (options) => Layer13.succeed(Permissions, Permissions.of({
1515
- evaluate: (request) => Effect13.succeed(decisionFor(options.ruleset, request)),
1516
- await: (pending) => options.onAsk(pending).pipe(Effect13.map(Option9.some))
1539
+ evaluate: (request) => Effect15.succeed(decisionFor(options.ruleset, request)),
1540
+ await: (pending) => options.onAsk(pending).pipe(Effect15.map(Option9.some))
1517
1541
  }));
1518
- var ruleStoreMemory = (initialRules = []) => Layer13.effect(RuleStore, Ref4.make(initialRules).pipe(Effect13.map((rules) => RuleStore.of({
1542
+ var ruleStoreMemory = (initialRules = []) => Layer13.effect(RuleStore, Ref4.make(initialRules).pipe(Effect15.map((rules) => RuleStore.of({
1519
1543
  remember: (rule) => Ref4.update(rules, (current) => [...current.filter((existing) => existing.pattern !== rule.pattern), rule]),
1520
1544
  rules: Ref4.get(rules)
1521
1545
  }))));
1522
1546
  var ruleStoreTestLayer = (implementation) => Layer13.succeed(RuleStore, RuleStore.of(implementation));
1523
1547
  var testLayer11 = (implementation) => Layer13.succeed(Permissions, Permissions.of(implementation));
1524
1548
 
1525
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/skill-source.js
1549
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/skill-source.js
1526
1550
  var exports_skill_source = {};
1527
1551
  __export(exports_skill_source, {
1528
1552
  testLayer: () => testLayer12,
@@ -1536,13 +1560,13 @@ __export(exports_skill_source, {
1536
1560
  SkillSource: () => SkillSource,
1537
1561
  DESCRIPTION_CAP: () => DESCRIPTION_CAP
1538
1562
  });
1539
- import { Context as Context13, Effect as Effect14, Function as Function6, Layer as Layer14, Schema as Schema11 } from "effect";
1540
- import { Tool as Tool4 } from "effect/unstable/ai";
1563
+ import { Context as Context13, Effect as Effect16, Function as Function6, Layer as Layer14, Schema as Schema12 } from "effect";
1564
+ import { Tool as Tool6 } from "effect/unstable/ai";
1541
1565
 
1542
- class SkillSourceError extends Schema11.TaggedErrorClass()("@batonfx/core/SkillSourceError", {
1543
- source: Schema11.String,
1544
- message: Schema11.String,
1545
- cause: Schema11.optionalKey(Schema11.Defect())
1566
+ class SkillSourceError extends Schema12.TaggedErrorClass()("@batonfx/core/SkillSourceError", {
1567
+ source: Schema12.String,
1568
+ message: Schema12.String,
1569
+ cause: Schema12.optionalKey(Schema12.Defect())
1546
1570
  }) {
1547
1571
  }
1548
1572
  var DESCRIPTION_CAP = 1024;
@@ -1554,14 +1578,14 @@ var fromSkills = (skills) => {
1554
1578
  const all = [...skills];
1555
1579
  const byName = new Map(all.map((skill) => [skill.frontmatter.name, skill]));
1556
1580
  return Layer14.succeed(SkillSource, SkillSource.of({
1557
- all: Effect14.succeed(all),
1558
- get: (name) => Effect14.succeed(byName.get(name))
1581
+ all: Effect16.succeed(all),
1582
+ get: (name) => Effect16.succeed(byName.get(name))
1559
1583
  }));
1560
1584
  };
1561
1585
  var empty = fromSkills([]);
1562
1586
  var testLayer12 = (implementation) => Layer14.succeed(SkillSource, SkillSource.of(implementation));
1563
1587
  var merge2 = (sources) => ({
1564
- all: Effect14.forEach(sources, (source) => source.all).pipe(Effect14.map((groups) => {
1588
+ all: Effect16.forEach(sources, (source) => source.all).pipe(Effect16.map((groups) => {
1565
1589
  const byName = new Map;
1566
1590
  for (const skills of groups) {
1567
1591
  for (const skill of skills)
@@ -1569,7 +1593,7 @@ var merge2 = (sources) => ({
1569
1593
  }
1570
1594
  return [...byName.values()];
1571
1595
  })),
1572
- get: (name) => Effect14.gen(function* () {
1596
+ get: (name) => Effect16.gen(function* () {
1573
1597
  for (const source of sources.toReversed()) {
1574
1598
  const found = yield* source.get(name);
1575
1599
  if (found !== undefined)
@@ -1578,7 +1602,7 @@ var merge2 = (sources) => ({
1578
1602
  return;
1579
1603
  })
1580
1604
  });
1581
- var layer6 = (sources) => Layer14.effect(SkillSource, Effect14.forEach(sources, (source) => source).pipe(Effect14.map((built) => SkillSource.of(merge2(built)))));
1605
+ var layer6 = (sources) => Layer14.effect(SkillSource, Effect16.forEach(sources, (source) => source).pipe(Effect16.map((built) => SkillSource.of(merge2(built)))));
1582
1606
  var estimatedTokens = (listing) => Math.ceil(listing.length / 4);
1583
1607
  var usageRank = (skill, recentlyUsed) => {
1584
1608
  const index = recentlyUsed.indexOf(skill.frontmatter.name);
@@ -1602,7 +1626,7 @@ var selectListings = Function6.dual(3, (skills, budgetTokens, recentlyUsed) => {
1602
1626
  return selected;
1603
1627
  });
1604
1628
 
1605
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/steering.js
1629
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/steering.js
1606
1630
  var exports_steering = {};
1607
1631
  __export(exports_steering, {
1608
1632
  testLayer: () => testLayer13,
@@ -1610,15 +1634,15 @@ __export(exports_steering, {
1610
1634
  SteeringQueueFull: () => SteeringQueueFull,
1611
1635
  Steering: () => Steering
1612
1636
  });
1613
- import { Context as Context14, Effect as Effect15, Exit, Layer as Layer15, Queue, Schema as Schema12 } from "effect";
1637
+ import { Context as Context14, Effect as Effect17, Exit, Layer as Layer15, Queue, Schema as Schema13 } from "effect";
1614
1638
  import { Prompt as Prompt7 } from "effect/unstable/ai";
1615
1639
 
1616
1640
  class Steering extends Context14.Service()("@batonfx/core/steering") {
1617
1641
  }
1618
1642
 
1619
- class SteeringQueueFull extends Schema12.TaggedErrorClass()("@batonfx/core/SteeringQueueFull", {
1620
- queue: Schema12.Literals(["steering", "followUp"]),
1621
- capacity: Schema12.Finite
1643
+ class SteeringQueueFull extends Schema13.TaggedErrorClass()("@batonfx/core/SteeringQueueFull", {
1644
+ queue: Schema13.Literals(["steering", "followUp"]),
1645
+ capacity: Schema13.Finite
1622
1646
  }) {
1623
1647
  }
1624
1648
  var resolvePolicy = (policy, mode) => ({
@@ -1637,18 +1661,18 @@ var queueStrategy = (strategy2) => {
1637
1661
  return "suspend";
1638
1662
  }
1639
1663
  };
1640
- var makeQueue = (name, policy) => (policy.capacity === undefined ? Queue.unbounded() : Queue.make({ capacity: policy.capacity, strategy: queueStrategy(policy.onFull) })).pipe(Effect15.map((queue) => ({ name, queue, policy })));
1641
- var offer = (runtime, message) => Queue.offer(runtime.queue, message).pipe(Effect15.flatMap((offered) => {
1664
+ var makeQueue = (name, policy) => (policy.capacity === undefined ? Queue.unbounded() : Queue.make({ capacity: policy.capacity, strategy: queueStrategy(policy.onFull) })).pipe(Effect17.map((queue) => ({ name, queue, policy })));
1665
+ var offer = (runtime, message) => Queue.offer(runtime.queue, message).pipe(Effect17.flatMap((offered) => {
1642
1666
  if (offered || runtime.policy.capacity === undefined || runtime.policy.onFull !== "fail")
1643
- return Effect15.void;
1667
+ return Effect17.void;
1644
1668
  return SteeringQueueFull.make({ queue: runtime.name, capacity: runtime.policy.capacity });
1645
1669
  }));
1646
- var drainOne = (queue) => Effect15.sync(() => {
1670
+ var drainOne = (queue) => Effect17.sync(() => {
1647
1671
  const taken = Queue.takeUnsafe(queue);
1648
1672
  return taken === undefined || !Exit.isSuccess(taken) ? [] : [taken.value];
1649
1673
  });
1650
1674
  var drain = (queue, mode) => mode === "all" ? Queue.clear(queue) : drainOne(queue);
1651
- var layer7 = (options = {}) => Layer15.effect(Steering, Effect15.gen(function* () {
1675
+ var layer7 = (options = {}) => Layer15.effect(Steering, Effect17.gen(function* () {
1652
1676
  const steeringQueue = yield* makeQueue("steering", resolvePolicy(options.steering, "all"));
1653
1677
  const followUpQueue = yield* makeQueue("followUp", resolvePolicy(options.followUp, "one-at-a-time"));
1654
1678
  return Steering.of({
@@ -1660,35 +1684,33 @@ var layer7 = (options = {}) => Layer15.effect(Steering, Effect15.gen(function* (
1660
1684
  }));
1661
1685
  var testLayer13 = (implementation) => Layer15.succeed(Steering, Steering.of(implementation));
1662
1686
 
1663
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/agent.js
1687
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent.js
1664
1688
  var exports_agent = {};
1665
1689
  __export(exports_agent, {
1666
- streamObject: () => streamObject,
1667
1690
  stream: () => stream2,
1668
1691
  provideModel: () => provideModel,
1669
- persistedObject: () => persistedObject,
1670
- persisted: () => persisted,
1671
1692
  make: () => make5,
1672
- generatePersistedObject: () => generatePersistedObject,
1673
- generatePersisted: () => generatePersisted,
1674
- generateObject: () => generateObject,
1675
1693
  generate: () => generate,
1676
1694
  defaultObjectPrompt: () => defaultObjectPrompt
1677
1695
  });
1678
- import { Cause as Cause4, Channel, Effect as Effect18, Equal, Exit as Exit2, Fiber, HashMap as HashMap4, Layer as Layer17, Option as Option12, Queue as Queue2, Ref as Ref5, Schema as Schema14, Semaphore as Semaphore2, Stream as Stream4, Types } from "effect";
1696
+ import { Effect as Effect22, Layer as Layer17, Option as Option15, Schema as Schema19, Stream as Stream5, Types } from "effect";
1679
1697
  import { dual as dual7 } from "effect/Function";
1680
- import { AiError as AiError3, Chat, LanguageModel as LanguageModel5, Prompt as Prompt9, Response as Response7, Telemetry, Tokenizer as Tokenizer2, Tool as Tool7, Toolkit as Toolkit4 } from "effect/unstable/ai";
1698
+ import { AiError as AiError5, Chat as Chat3, LanguageModel as LanguageModel6, Prompt as Prompt12, Tool as Tool11, Toolkit as Toolkit5 } from "effect/unstable/ai";
1699
+
1700
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-run.js
1701
+ import { Cause as Cause4, Channel, Effect as Effect21, Equal as Equal2, Exit as Exit2, Fiber, HashMap as HashMap5, Option as Option14, Queue as Queue2, Ref as Ref5, Schema as Schema18, Semaphore as Semaphore3, Stream as Stream4 } from "effect";
1702
+ import { AiError as AiError4, Chat as Chat2, LanguageModel as LanguageModel5, Prompt as Prompt11, Response as Response10, Telemetry, Tokenizer as Tokenizer2, Tool as Tool10, Toolkit as Toolkit4 } from "effect/unstable/ai";
1681
1703
 
1682
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/tool-authorization.js
1683
- import { Cause as Cause3, Context as Context15, Effect as Effect16, Layer as Layer16, Option as Option10, Schema as Schema13 } from "effect";
1704
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-authorization.js
1705
+ import { Cause as Cause3, Context as Context15, Effect as Effect18, Layer as Layer16, Option as Option10, Schema as Schema14 } from "effect";
1684
1706
  import { dual as dual5 } from "effect/Function";
1685
- import { Prompt as Prompt8, Response as Response6, Tool as Tool5 } from "effect/unstable/ai";
1686
- class PermissionDenied extends Schema13.TaggedErrorClass()("@batonfx/core/PermissionDenied", {
1687
- message: Schema13.String
1707
+ import { Prompt as Prompt8, Response as Response6, Tool as Tool7 } from "effect/unstable/ai";
1708
+ class PermissionDenied extends Schema14.TaggedErrorClass()("@batonfx/core/PermissionDenied", {
1709
+ message: Schema14.String
1688
1710
  }) {
1689
1711
  }
1690
1712
 
1691
- class AuthorizationError extends Schema13.TaggedErrorClass()("@batonfx/core/AuthorizationError", { message: Schema13.String, cause: Schema13.optional(Schema13.Defect()) }) {
1713
+ class AuthorizationError extends Schema14.TaggedErrorClass()("@batonfx/core/AuthorizationError", { message: Schema14.String, cause: Schema14.optional(Schema14.Defect()) }) {
1692
1714
  }
1693
1715
 
1694
1716
  class ToolAuthorizerService extends Context15.Service()("@batonfx/core/tool-authorization/ToolAuthorizerService") {
@@ -1715,16 +1737,16 @@ var authorizationError = (error) => AuthorizationError.make({ message: error.mes
1715
1737
  var approvalRequired = (request) => {
1716
1738
  const needsApproval = request.tool?.needsApproval;
1717
1739
  if (needsApproval === undefined)
1718
- return Effect16.succeed(false);
1740
+ return Effect18.succeed(false);
1719
1741
  if (typeof needsApproval === "boolean")
1720
- return Effect16.succeed(needsApproval);
1721
- return Effect16.suspend(() => {
1742
+ return Effect18.succeed(needsApproval);
1743
+ return Effect18.suspend(() => {
1722
1744
  const result = needsApproval(request.call.params, {
1723
1745
  toolCallId: request.call.id,
1724
1746
  messages: request.messages
1725
1747
  });
1726
- return Effect16.isEffect(result) ? result : Effect16.succeed(result);
1727
- }).pipe(Effect16.catchCause((cause) => Cause3.hasInterrupts(cause) ? Effect16.interrupt : Effect16.succeed(true)));
1748
+ return Effect18.isEffect(result) ? result : Effect18.succeed(result);
1749
+ }).pipe(Effect18.catchCause((cause) => Cause3.hasInterrupts(cause) ? Effect18.interrupt : Effect18.succeed(true)));
1728
1750
  };
1729
1751
  var evaluationRequest = (request) => ({
1730
1752
  tool: request.call.name,
@@ -1734,7 +1756,7 @@ var evaluationRequest = (request) => ({
1734
1756
  toolCallId: request.call.id,
1735
1757
  sessionId: request.execution.sessionId
1736
1758
  });
1737
- var rememberedDecision = (request, ruleStore) => ruleStore?.rules === undefined ? Effect16.succeedNone : ruleStore.rules.pipe(Effect16.map((rules) => {
1759
+ var rememberedDecision = (request, ruleStore) => ruleStore?.rules === undefined ? Effect18.succeedNone : ruleStore.rules.pipe(Effect18.map((rules) => {
1738
1760
  if (rules.length === 0)
1739
1761
  return Option10.none();
1740
1762
  const matched = matchRule({ rules }, request.call.name, request.call.params);
@@ -1751,8 +1773,8 @@ var rememberedDecision = (request, ruleStore) => ruleStore?.rules === undefined
1751
1773
  case "ask":
1752
1774
  return Option10.some({ _tag: "Ask", token: `permission:${request.call.id}` });
1753
1775
  }
1754
- }), Effect16.mapError(authorizationError));
1755
- var resolveRequiredApproval = (request, approvals) => Effect16.gen(function* () {
1776
+ }), Effect18.mapError(authorizationError));
1777
+ var resolveRequiredApproval = (request, approvals) => Effect18.gen(function* () {
1756
1778
  yield* request.onApprovalRequired;
1757
1779
  if (approvals === undefined)
1758
1780
  return deny("Approvals service is required for approval-gated tools");
@@ -1766,13 +1788,13 @@ var resolveRequiredApproval = (request, approvals) => Effect16.gen(function* ()
1766
1788
  return suspension(request, decision2.token, "approval");
1767
1789
  }
1768
1790
  });
1769
- var finalApproval = (request, approvals) => approvalRequired(request).pipe(Effect16.flatMap((required) => {
1791
+ var finalApproval = (request, approvals) => approvalRequired(request).pipe(Effect18.flatMap((required) => {
1770
1792
  if (!required)
1771
- return Effect16.succeed({ _tag: "Execute" });
1793
+ return Effect18.succeed({ _tag: "Execute" });
1772
1794
  return resolveRequiredApproval(request, approvals);
1773
1795
  }));
1774
1796
  var make4 = (options = {}) => ({
1775
- authorize: (request) => Effect16.gen(function* () {
1797
+ authorize: (request) => Effect18.gen(function* () {
1776
1798
  if (!request.active || request.tool === undefined) {
1777
1799
  return deny(`Tool ${request.call.name} is not active for turn ${request.execution.turn}`);
1778
1800
  }
@@ -1786,7 +1808,7 @@ var make4 = (options = {}) => ({
1786
1808
  if (request.authorizationStage === "permission") {
1787
1809
  const token = request.authorizationToken ?? `permission:${request.call.id}`;
1788
1810
  if (options.permissions !== undefined) {
1789
- const current2 = yield* options.permissions.evaluate(evaluationRequest(request)).pipe(Effect16.mapError(authorizationError));
1811
+ const current2 = yield* options.permissions.evaluate(evaluationRequest(request)).pipe(Effect18.mapError(authorizationError));
1790
1812
  if (current2._tag === "Deny")
1791
1813
  return deny(current2.reason ?? "Permission denied");
1792
1814
  }
@@ -1800,13 +1822,13 @@ var make4 = (options = {}) => ({
1800
1822
  agentName: request.execution.agentName,
1801
1823
  turn: request.execution.turn,
1802
1824
  toolCallId: request.call.id
1803
- }).pipe(Effect16.mapError(authorizationError));
1825
+ }).pipe(Effect18.mapError(authorizationError));
1804
1826
  if (Option10.isNone(answer2))
1805
1827
  return suspension(request, token, "permission");
1806
1828
  if (answer2.value._tag === "Denied")
1807
1829
  return deny(answer2.value.reason ?? "Permission denied");
1808
1830
  if (answer2.value._tag === "Always" && options.ruleStore !== undefined) {
1809
- yield* options.ruleStore.remember({ pattern: request.call.name, level: "allow" }).pipe(Effect16.mapError(authorizationError));
1831
+ yield* options.ruleStore.remember({ pattern: request.call.name, level: "allow" }).pipe(Effect18.mapError(authorizationError));
1810
1832
  }
1811
1833
  return yield* finalApproval(request, options.approvals);
1812
1834
  }
@@ -1818,7 +1840,7 @@ var make4 = (options = {}) => ({
1818
1840
  return yield* finalApproval(request, options.approvals);
1819
1841
  }
1820
1842
  const permissions = options.permissions;
1821
- const current = yield* permissions.evaluate(evaluationRequest(request)).pipe(Effect16.mapError(authorizationError));
1843
+ const current = yield* permissions.evaluate(evaluationRequest(request)).pipe(Effect18.mapError(authorizationError));
1822
1844
  if (current._tag === "Deny")
1823
1845
  return deny(current.reason ?? "Permission denied");
1824
1846
  if (current._tag !== "Ask" || Option10.isSome(remembered) && remembered.value._tag === "Allow") {
@@ -1833,7 +1855,7 @@ var make4 = (options = {}) => ({
1833
1855
  toolCallId: request.call.id
1834
1856
  };
1835
1857
  yield* request.onApprovalRequired;
1836
- const answer = yield* permissions.await(pending).pipe(Effect16.mapError(authorizationError));
1858
+ const answer = yield* permissions.await(pending).pipe(Effect18.mapError(authorizationError));
1837
1859
  if (Option10.isNone(answer))
1838
1860
  return suspension(request, current.token, "permission");
1839
1861
  switch (answer.value._tag) {
@@ -1841,7 +1863,7 @@ var make4 = (options = {}) => ({
1841
1863
  return deny(answer.value.reason ?? "Permission denied");
1842
1864
  case "Always":
1843
1865
  if (options.ruleStore !== undefined) {
1844
- yield* options.ruleStore.remember({ pattern: request.call.name, level: "allow" }).pipe(Effect16.mapError(authorizationError));
1866
+ yield* options.ruleStore.remember({ pattern: request.call.name, level: "allow" }).pipe(Effect18.mapError(authorizationError));
1845
1867
  }
1846
1868
  return yield* finalApproval(request, options.approvals);
1847
1869
  case "Approved":
@@ -1851,10 +1873,10 @@ var make4 = (options = {}) => ({
1851
1873
  });
1852
1874
  var fromPermissions = dual5((args) => args.length === 2 || args.length === 1 && ("evaluate" in args[0]), (permissions, options = {}) => make4({ ...options, permissions }));
1853
1875
 
1854
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/tool-registry.js
1855
- import { Effect as Effect17, HashMap as HashMap3, Option as Option11 } from "effect";
1876
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-registry.js
1877
+ import { Effect as Effect19, HashMap as HashMap3, Option as Option11 } from "effect";
1856
1878
  import { dual as dual6 } from "effect/Function";
1857
- import { Tool as Tool6, Toolkit as Toolkit3 } from "effect/unstable/ai";
1879
+ import { Tool as Tool8, Toolkit as Toolkit3 } from "effect/unstable/ai";
1858
1880
  var makeToolkit = (entries) => {
1859
1881
  const toolkit = Toolkit3.make(...entries.map((candidate) => candidate.tool));
1860
1882
  for (const entry of entries) {
@@ -1881,14 +1903,14 @@ var assemble = (candidates) => {
1881
1903
  for (const candidate of candidates) {
1882
1904
  const conflicts = grouped.get(candidate.tool.name);
1883
1905
  if (conflicts !== undefined && conflicts.length > 1) {
1884
- return Effect17.fail(ToolNameCollision.make({
1906
+ return Effect19.fail(ToolNameCollision.make({
1885
1907
  name: candidate.tool.name,
1886
1908
  origins: [conflicts[0].origin, ...conflicts.slice(1).map((conflict) => conflict.origin)]
1887
1909
  }));
1888
1910
  }
1889
1911
  }
1890
1912
  const entries = [...candidates];
1891
- return Effect17.succeed({
1913
+ return Effect19.succeed({
1892
1914
  entries,
1893
1915
  byName: HashMap3.fromIterable(entries.map((candidate) => [candidate.tool.name, candidate])),
1894
1916
  toolkit: makeToolkit(entries)
@@ -1904,89 +1926,9 @@ var select = dual6(2, (registry, names) => {
1904
1926
  };
1905
1927
  });
1906
1928
 
1907
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/agent.js
1908
- var AgentTypeId = Symbol.for("@batonfx/core/Agent");
1909
- var ModelLayerTypeId = Symbol.for("@batonfx/core/Agent/ModelLayer");
1910
- var classifyOtherFailure = () => "other";
1911
- function make5(nameOrOptions, options = {}) {
1912
- if (nameOrOptions === undefined || typeof nameOrOptions !== "string" && !("name" in nameOrOptions)) {
1913
- const curriedOptions = nameOrOptions ?? {};
1914
- if ("tools" in curriedOptions && Array.isArray(curriedOptions.tools)) {
1915
- const tools = curriedOptions.tools;
1916
- return (name) => make5({
1917
- name,
1918
- tools,
1919
- ...curriedOptions.instructions === undefined ? {} : { instructions: curriedOptions.instructions },
1920
- ...curriedOptions.policy === undefined ? {} : { policy: curriedOptions.policy },
1921
- ...curriedOptions.model === undefined ? {} : { model: curriedOptions.model },
1922
- ...curriedOptions.memory === undefined ? {} : { memory: curriedOptions.memory },
1923
- ...curriedOptions.authorization === undefined ? {} : { authorization: curriedOptions.authorization },
1924
- ...curriedOptions.toolExecution === undefined ? {} : { toolExecution: curriedOptions.toolExecution },
1925
- ...curriedOptions.metadata === undefined ? {} : { metadata: curriedOptions.metadata }
1926
- });
1927
- }
1928
- return (name) => make5({
1929
- name,
1930
- ...curriedOptions.instructions === undefined ? {} : { instructions: curriedOptions.instructions },
1931
- ...curriedOptions.toolkit === undefined ? {} : { toolkit: curriedOptions.toolkit },
1932
- ...curriedOptions.policy === undefined ? {} : { policy: curriedOptions.policy },
1933
- ...curriedOptions.model === undefined ? {} : { model: curriedOptions.model },
1934
- ...curriedOptions.memory === undefined ? {} : { memory: curriedOptions.memory },
1935
- ...curriedOptions.authorization === undefined ? {} : { authorization: curriedOptions.authorization },
1936
- ...curriedOptions.toolExecution === undefined ? {} : { toolExecution: curriedOptions.toolExecution },
1937
- ...curriedOptions.metadata === undefined ? {} : { metadata: curriedOptions.metadata }
1938
- });
1939
- }
1940
- const resolved = typeof nameOrOptions === "string" ? { ...options, name: nameOrOptions } : nameOrOptions;
1941
- const declaredTools = "tools" in resolved && Array.isArray(resolved.tools) ? resolved.tools : undefined;
1942
- const toolkit = declaredTools === undefined ? resolved.toolkit ?? Toolkit4.empty : Toolkit4.make(...declaredTools);
1943
- if (declaredTools !== undefined) {
1944
- for (const tool of declaredTools) {
1945
- if (!Object.hasOwn(toolkit.tools, tool.name)) {
1946
- Object.defineProperty(toolkit.tools, tool.name, {
1947
- configurable: true,
1948
- enumerable: true,
1949
- value: tool,
1950
- writable: true
1951
- });
1952
- }
1953
- }
1954
- }
1955
- return {
1956
- [AgentTypeId]: {
1957
- tools: (value) => value,
1958
- requirements: (value) => value
1959
- },
1960
- name: resolved.name,
1961
- ...resolved.instructions === undefined ? {} : { instructions: resolved.instructions },
1962
- toolkit,
1963
- policy: resolved.policy ?? defaultPolicy,
1964
- ...resolved.model === undefined ? {} : { model: resolved.model },
1965
- ...resolved.memory === undefined ? {} : { memory: resolved.memory },
1966
- ...resolved.authorization === undefined ? {} : { authorization: resolved.authorization },
1967
- ...resolved.toolExecution === undefined ? {} : { toolExecution: resolved.toolExecution },
1968
- ...resolved.metadata === undefined ? {} : { metadata: resolved.metadata },
1969
- toolDeclarations: (declaredTools ?? Object.values(toolkit.tools)).map((tool) => ({
1970
- tool,
1971
- origin: { _tag: "Static", agent: resolved.name }
1972
- }))
1973
- };
1974
- }
1975
- var defaultProgressOverflowPolicy = { _tag: "Backpressure", capacity: 64 };
1976
- var progressCapacitySchema = Schema14.Finite.pipe(Schema14.check(Schema14.isInt(), Schema14.isGreaterThan(0)));
1977
- var progressOverflowPolicySchema = Schema14.Union([
1978
- Schema14.TaggedStruct("Backpressure", { capacity: progressCapacitySchema }),
1979
- Schema14.TaggedStruct("Dropping", { capacity: progressCapacitySchema }),
1980
- Schema14.TaggedStruct("Sliding", { capacity: progressCapacitySchema }),
1981
- Schema14.TaggedStruct("Fail", { capacity: progressCapacitySchema })
1982
- ]);
1983
- var defaultObjectPrompt = "Return the final structured output for the task above.";
1984
- var steeringDrainedEvent = (turn, queue, messages) => ({
1985
- _tag: "SteeringDrained",
1986
- turn,
1987
- queue,
1988
- count: messages.length
1989
- });
1929
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-persistence-lock.js
1930
+ import { Semaphore as Semaphore2 } from "effect";
1931
+ import { Chat } from "effect/unstable/ai";
1990
1932
  var persistenceLocks = new WeakMap;
1991
1933
  var reservePersistedChatLock = (persistence, chatId) => {
1992
1934
  const locks = persistenceLocks.get(persistence) ?? new Map;
@@ -2001,16 +1943,6 @@ var reservePersistedChatLock = (persistence, chatId) => {
2001
1943
  locks.set(chatId, created);
2002
1944
  return created;
2003
1945
  };
2004
- var suspensionCheckpointOption = "@batonfx/core/suspension";
2005
- var suspensionMetadata = Schema14.Struct({
2006
- token: Schema14.String,
2007
- reason: Schema14.Literals(["tool-wait", "approval"]),
2008
- authorization_stage: Schema14.optional(Schema14.Literals(["permission", "approval"])),
2009
- tool_call_index: Schema14.optional(Schema14.Int.check(Schema14.isGreaterThanOrEqualTo(0))),
2010
- tool_call_batch_ids: Schema14.Array(Schema14.String),
2011
- active_tools: Schema14.optional(Schema14.Array(Schema14.String)),
2012
- activated_skills: Schema14.optional(Schema14.Array(Schema14.String))
2013
- });
2014
1946
  var releasePersistedChatLock = (persistence, chatId, lock) => {
2015
1947
  lock.users -= 1;
2016
1948
  if (lock.users !== 0)
@@ -2022,6 +1954,95 @@ var releasePersistedChatLock = (persistence, chatId, lock) => {
2022
1954
  if (locks.size === 0)
2023
1955
  persistenceLocks.delete(persistence);
2024
1956
  };
1957
+
1958
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-message.js
1959
+ import { Effect as Effect20, Option as Option12, Schema as Schema16 } from "effect";
1960
+ import { Prompt as Prompt9, Response as Response7 } from "effect/unstable/ai";
1961
+
1962
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-skill-tool.js
1963
+ import { Schema as Schema15 } from "effect";
1964
+ import { Tool as Tool9 } from "effect/unstable/ai";
1965
+ var skillListingBudgetTokens = 2048;
1966
+ var activateSkillToolName = "activate_skill";
1967
+ var activateSkillParameters = Schema15.Struct({ name: Schema15.String });
1968
+ var activateSkillSuccess = Schema15.Struct({
1969
+ name: Schema15.String,
1970
+ body: Schema15.String,
1971
+ allowedTools: Schema15.Array(Schema15.String)
1972
+ });
1973
+ var activateSkillFailure = Schema15.Struct({
1974
+ reason: Schema15.Literals(["not-found", "not-model-invocable"]),
1975
+ message: Schema15.String
1976
+ });
1977
+ var activateSkillTool = Tool9.make(activateSkillToolName, {
1978
+ description: "Load the full body for one listed Baton skill by name before applying that skill.",
1979
+ parameters: activateSkillParameters,
1980
+ success: activateSkillSuccess,
1981
+ failure: activateSkillFailure,
1982
+ failureMode: "return"
1983
+ });
1984
+
1985
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-message.js
1986
+ var withSystem = (instructions, prompt) => Prompt9.fromMessages([Prompt9.makeMessage("system", { content: instructions }), ...prompt.content]);
1987
+ var skillListingsInstructions = (listings) => `Available skills:
1988
+ ${listings}
1989
+
1990
+ Call ${activateSkillToolName} with a listed skill name to load its full body before using it.`;
1991
+ var recalledMessages = (prompt) => prompt.content.filter(isMessageFromRecall).map(recalledMessageIdentity);
1992
+ var messageJsonStringCodec = Schema16.fromJsonString(Schema16.toCodecJson(Prompt9.Message));
1993
+ var encodeMessage = Schema16.encodeEffect(messageJsonStringCodec);
1994
+ var decodeMessage = Schema16.decodeEffect(messageJsonStringCodec);
1995
+ var detachMessage = (message) => encodeMessage(message).pipe(Effect20.flatMap(decodeMessage), Effect20.map((detached) => isMessageFromRecall(message) && message.role === "user" && detached.role === "user" ? replaceRecalledMessage(message, detached.content) : detached));
1996
+ var detachPrompt = (prompt) => Effect20.forEach(prompt.content, detachMessage).pipe(Effect20.map(Prompt9.fromMessages));
1997
+ var detachEntry = (entry) => entry._tag === "Message" || entry._tag === "Steering" ? detachMessage(entry.message).pipe(Effect20.map((message) => ({ ...entry, message }))) : Effect20.succeed(entry);
1998
+ var preservesRecalledMessages = (allowed, required, transformed) => {
1999
+ const allowedSet = new Set(allowed);
2000
+ const transformedMessages = recalledMessages(transformed);
2001
+ const transformedSet = new Set(transformedMessages);
2002
+ return transformedSet.size === transformedMessages.length && transformedMessages.every((message) => allowedSet.has(message)) && required.every((message) => transformedSet.has(message));
2003
+ };
2004
+ var applyPromptChain = (chain, prompt, context) => Effect20.gen(function* () {
2005
+ let current = prompt;
2006
+ for (const middleware of chain) {
2007
+ if (middleware.transformPrompt !== undefined) {
2008
+ const recalled = recalledMessages(current);
2009
+ const transformed = yield* middleware.transformPrompt(current, context);
2010
+ if (!preservesRecalledMessages(recalled, recalled, transformed)) {
2011
+ return yield* MiddlewareViolation.make({
2012
+ turn: context.turn,
2013
+ detail: "Prompt middleware must preserve recalled-memory message lineage"
2014
+ });
2015
+ }
2016
+ current = transformed;
2017
+ }
2018
+ }
2019
+ return current;
2020
+ });
2021
+ var applyPartChain = (chain, part, context) => Effect20.gen(function* () {
2022
+ let current = Option12.some(part);
2023
+ for (const middleware of chain) {
2024
+ if (Option12.isNone(current))
2025
+ break;
2026
+ if (middleware.transformPart !== undefined) {
2027
+ current = yield* middleware.transformPart(current.value, context);
2028
+ }
2029
+ }
2030
+ return current;
2031
+ });
2032
+
2033
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-suspension.js
2034
+ import { Equal, Option as Option13, Schema as Schema17 } from "effect";
2035
+ import { Prompt as Prompt10, Response as Response8 } from "effect/unstable/ai";
2036
+ var suspensionCheckpointOption = "@batonfx/core/suspension";
2037
+ var suspensionMetadata = Schema17.Struct({
2038
+ token: Schema17.String,
2039
+ reason: Schema17.Literals(["tool-wait", "approval"]),
2040
+ authorization_stage: Schema17.optional(Schema17.Literals(["permission", "approval"])),
2041
+ tool_call_index: Schema17.optional(Schema17.Int.check(Schema17.isGreaterThanOrEqualTo(0))),
2042
+ tool_call_batch_ids: Schema17.Array(Schema17.String),
2043
+ active_tools: Schema17.optional(Schema17.Array(Schema17.String)),
2044
+ activated_skills: Schema17.optional(Schema17.Array(Schema17.String))
2045
+ });
2025
2046
  var unresolvedToolCall = (messages, toolCallId) => {
2026
2047
  const unpaired = new Map;
2027
2048
  const ambiguous = new Set;
@@ -2051,10 +2072,10 @@ var unresolvedToolCall = (messages, toolCallId) => {
2051
2072
  }
2052
2073
  }
2053
2074
  const unresolved = [...unpaired.entries()].flatMap(([id, occurrences]) => ambiguous.has(id) ? [] : occurrences.filter(({ call }) => !call.providerExecuted));
2054
- const pending = toolCallId === undefined ? unresolved.find(({ call }) => Option12.isSome(Schema14.decodeUnknownOption(suspensionMetadata)(call.options[suspensionCheckpointOption]))) : unresolved.find(({ call }) => call.id === toolCallId);
2075
+ const pending = toolCallId === undefined ? unresolved.find(({ call }) => Option13.isSome(Schema17.decodeUnknownOption(suspensionMetadata)(call.options[suspensionCheckpointOption]))) : unresolved.find(({ call }) => call.id === toolCallId);
2055
2076
  const pendingMessage = pending === undefined ? undefined : messages[pending.messageIndex];
2056
2077
  const toolCallBatch = pendingMessage?.role === "assistant" ? pendingMessage.content.flatMap((part) => part.type === "tool-call" && !part.providerExecuted ? [
2057
- Response7.makePart("tool-call", {
2078
+ Response8.makePart("tool-call", {
2058
2079
  id: part.id,
2059
2080
  name: part.name,
2060
2081
  params: part.params,
@@ -2073,8 +2094,8 @@ var suspensionCheckpoint = (messages) => {
2073
2094
  const unresolved = unresolvedToolCall(messages);
2074
2095
  if (unresolved === undefined)
2075
2096
  return;
2076
- const metadata = Schema14.decodeUnknownOption(suspensionMetadata)(unresolved.call.options[suspensionCheckpointOption]);
2077
- if (Option12.isNone(metadata))
2097
+ const metadata = Schema17.decodeUnknownOption(suspensionMetadata)(unresolved.call.options[suspensionCheckpointOption]);
2098
+ if (Option13.isNone(metadata))
2078
2099
  return;
2079
2100
  if (!Equal.equals(metadata.value.tool_call_batch_ids, unresolved.toolCallBatch.map((call) => call.id)))
2080
2101
  return;
@@ -2091,44 +2112,20 @@ var suspensionCheckpoint = (messages) => {
2091
2112
  };
2092
2113
  };
2093
2114
  var sameSuspension = (left, right) => left.token === right.token && left.reason === right.reason && left.authorization_stage === right.authorization_stage && left.tool_call_index === right.tool_call_index && Equal.equals(left.tool_call_batch, right.tool_call_batch) && left.tool_call_id === right.tool_call_id && left.tool_name === right.tool_name && Equal.equals(left.tool_params, right.tool_params) && Equal.equals(left.active_tools, right.active_tools) && Equal.equals(left.activated_skills, right.activated_skills);
2094
- var skillListingBudgetTokens = 2048;
2095
- var activateSkillToolName = "activate_skill";
2096
- var activateSkillParameters = Schema14.Struct({ name: Schema14.String });
2097
- var activateSkillSuccess = Schema14.Struct({
2098
- name: Schema14.String,
2099
- body: Schema14.String,
2100
- allowedTools: Schema14.Array(Schema14.String)
2101
- });
2102
- var activateSkillFailure = Schema14.Struct({
2103
- reason: Schema14.Literals(["not-found", "not-model-invocable"]),
2104
- message: Schema14.String
2105
- });
2106
- var activateSkillTool = Tool7.make(activateSkillToolName, {
2107
- description: "Load the full body for one listed Baton skill by name before applying that skill.",
2108
- parameters: activateSkillParameters,
2109
- success: activateSkillSuccess,
2110
- failure: activateSkillFailure,
2111
- failureMode: "return"
2115
+ var suspended = (call, toolCallBatch, toolCallIndex, token, reason) => AgentSuspended.make({
2116
+ token,
2117
+ reason,
2118
+ tool_call_index: toolCallIndex,
2119
+ tool_call_id: call.id,
2120
+ tool_name: call.name,
2121
+ tool_params: call.params,
2122
+ tool_call_batch: toolCallBatch.calls
2112
2123
  });
2113
- var errorMessage = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
2114
- var isToolNameCollision = Schema14.is(ToolNameCollision);
2115
- var appendInstructionFragment = (base, fragment) => {
2116
- if (fragment === undefined || fragment.length === 0)
2117
- return base;
2118
- if (base === undefined || base.length === 0)
2119
- return fragment;
2120
- return `${base}
2121
2124
 
2122
- ${fragment}`;
2123
- };
2124
- var isTurnPolicyDecision = (input) => {
2125
- if (typeof input !== "object" || input === null || !("_tag" in input))
2126
- return false;
2127
- if (input._tag === "Continue")
2128
- return true;
2129
- return input._tag === "Stop" && "reason" in input && Schema14.is(StopReason)(input.reason);
2130
- };
2131
- var successResult = (call, outcome) => Response7.toolResultPart({
2125
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-tool-result.js
2126
+ import { HashMap as HashMap4 } from "effect";
2127
+ import { Response as Response9 } from "effect/unstable/ai";
2128
+ var successResult = (call, outcome) => Response9.toolResultPart({
2132
2129
  id: call.id,
2133
2130
  name: call.name,
2134
2131
  isFailure: false,
@@ -2137,7 +2134,7 @@ var successResult = (call, outcome) => Response7.toolResultPart({
2137
2134
  providerExecuted: false,
2138
2135
  preliminary: false
2139
2136
  });
2140
- var domainFailureResult = (call, outcome) => Response7.toolResultPart({
2137
+ var domainFailureResult = (call, outcome) => Response9.toolResultPart({
2141
2138
  id: call.id,
2142
2139
  name: call.name,
2143
2140
  isFailure: true,
@@ -2146,62 +2143,43 @@ var domainFailureResult = (call, outcome) => Response7.toolResultPart({
2146
2143
  providerExecuted: false,
2147
2144
  preliminary: false
2148
2145
  });
2149
- var suspended = (call, toolCallBatch, toolCallIndex, token, reason) => AgentSuspended.make({
2150
- token,
2151
- reason,
2152
- tool_call_index: toolCallIndex,
2153
- tool_call_id: call.id,
2154
- tool_name: call.name,
2155
- tool_params: call.params,
2156
- tool_call_batch: toolCallBatch.calls
2157
- });
2158
- var withSystem = (instructions, prompt) => Prompt9.fromMessages([Prompt9.makeMessage("system", { content: instructions }), ...prompt.content]);
2159
- var skillListingsInstructions = (listings) => `Available skills:
2160
- ${listings}
2161
2146
 
2162
- Call ${activateSkillToolName} with a listed skill name to load its full body before using it.`;
2163
- var recalledMessages = (prompt) => prompt.content.filter(isMessageFromRecall).map(recalledMessageIdentity);
2164
- var messageJsonStringCodec = Schema14.fromJsonString(Schema14.toCodecJson(Prompt9.Message));
2165
- var encodeMessage = Schema14.encodeEffect(messageJsonStringCodec);
2166
- var decodeMessage = Schema14.decodeEffect(messageJsonStringCodec);
2167
- var detachMessage = (message) => encodeMessage(message).pipe(Effect18.flatMap(decodeMessage), Effect18.map((detached) => isMessageFromRecall(message) && message.role === "user" && detached.role === "user" ? replaceRecalledMessage(message, detached.content) : detached));
2168
- var detachPrompt = (prompt) => Effect18.forEach(prompt.content, detachMessage).pipe(Effect18.map(Prompt9.fromMessages));
2169
- var detachEntry = (entry) => entry._tag === "Message" || entry._tag === "Steering" ? detachMessage(entry.message).pipe(Effect18.map((message) => ({ ...entry, message }))) : Effect18.succeed(entry);
2170
- var preservesRecalledMessages = (allowed, required, transformed) => {
2171
- const allowedSet = new Set(allowed);
2172
- const transformedMessages = recalledMessages(transformed);
2173
- const transformedSet = new Set(transformedMessages);
2174
- return transformedSet.size === transformedMessages.length && transformedMessages.every((message) => allowedSet.has(message)) && required.every((message) => transformedSet.has(message));
2147
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-run.js
2148
+ var ModelLayerTypeId = Symbol.for("@batonfx/core/Agent/ModelLayer");
2149
+ var classifyOtherFailure = () => "other";
2150
+ var defaultProgressOverflowPolicy = { _tag: "Backpressure", capacity: 64 };
2151
+ var progressCapacitySchema = Schema18.Finite.pipe(Schema18.check(Schema18.isInt(), Schema18.isGreaterThan(0)));
2152
+ var progressOverflowPolicySchema = Schema18.Union([
2153
+ Schema18.TaggedStruct("Backpressure", { capacity: progressCapacitySchema }),
2154
+ Schema18.TaggedStruct("Dropping", { capacity: progressCapacitySchema }),
2155
+ Schema18.TaggedStruct("Sliding", { capacity: progressCapacitySchema }),
2156
+ Schema18.TaggedStruct("Fail", { capacity: progressCapacitySchema })
2157
+ ]);
2158
+ var errorMessage = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
2159
+ var isToolNameCollision = Schema18.is(ToolNameCollision);
2160
+ var appendInstructionFragment = (base, fragment) => {
2161
+ if (fragment === undefined || fragment.length === 0)
2162
+ return base;
2163
+ if (base === undefined || base.length === 0)
2164
+ return fragment;
2165
+ return `${base}
2166
+
2167
+ ${fragment}`;
2175
2168
  };
2176
- var applyPromptChain = (chain, prompt, context) => Effect18.gen(function* () {
2177
- let current = prompt;
2178
- for (const middleware of chain) {
2179
- if (middleware.transformPrompt !== undefined) {
2180
- const recalled = recalledMessages(current);
2181
- const transformed = yield* middleware.transformPrompt(current, context);
2182
- if (!preservesRecalledMessages(recalled, recalled, transformed)) {
2183
- return yield* MiddlewareViolation.make({
2184
- turn: context.turn,
2185
- detail: "Prompt middleware must preserve recalled-memory message lineage"
2186
- });
2187
- }
2188
- current = transformed;
2189
- }
2190
- }
2191
- return current;
2192
- });
2193
- var applyPartChain = (chain, part, context) => Effect18.gen(function* () {
2194
- let current = Option12.some(part);
2195
- for (const middleware of chain) {
2196
- if (Option12.isNone(current))
2197
- break;
2198
- if (middleware.transformPart !== undefined) {
2199
- current = yield* middleware.transformPart(current.value, context);
2200
- }
2201
- }
2202
- return current;
2169
+ var isTurnPolicyDecision = (input) => {
2170
+ if (typeof input !== "object" || input === null || !("_tag" in input))
2171
+ return false;
2172
+ if (input._tag === "Continue")
2173
+ return true;
2174
+ return input._tag === "Stop" && "reason" in input && Schema18.is(StopReason)(input.reason);
2175
+ };
2176
+ var steeringDrainedEvent = (turn, queue, messages) => ({
2177
+ _tag: "SteeringDrained",
2178
+ turn,
2179
+ queue,
2180
+ count: messages.length
2203
2181
  });
2204
- var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen(function* () {
2182
+ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen(function* () {
2205
2183
  if (options.history !== undefined && options.persistence !== undefined) {
2206
2184
  return yield* AgentError.make({
2207
2185
  message: "RunOptions.history and RunOptions.persistence are mutually exclusive",
@@ -2210,52 +2188,52 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2210
2188
  }
2211
2189
  const persistenceOptions = options.persistence;
2212
2190
  const resume = options.resume;
2213
- const persistenceService = yield* Effect18.serviceOption(Chat.Persistence);
2214
- const compactionService = yield* Effect18.serviceOption(Compaction);
2215
- const sessionService = yield* Effect18.serviceOption(SessionStore);
2216
- const persisted = persistenceOptions === undefined ? undefined : yield* Option12.match(persistenceService, {
2217
- onNone: () => Effect18.fail(AgentError.make({
2191
+ const persistenceService = yield* Effect21.serviceOption(Chat2.Persistence);
2192
+ const compactionService = yield* Effect21.serviceOption(Compaction);
2193
+ const sessionService = yield* Effect21.serviceOption(SessionStore);
2194
+ const persisted = persistenceOptions === undefined ? undefined : yield* Option14.match(persistenceService, {
2195
+ onNone: () => Effect21.fail(AgentError.make({
2218
2196
  message: "RunOptions.persistence requires Chat.Persistence in context",
2219
2197
  turn: 0
2220
2198
  })),
2221
- onSome: (service) => Effect18.gen(function* () {
2222
- const lock = yield* Effect18.acquireRelease(Effect18.sync(() => reservePersistedChatLock(service, persistenceOptions.chatId)), (reserved) => Effect18.sync(() => releasePersistedChatLock(service, persistenceOptions.chatId, reserved)));
2223
- yield* Effect18.acquireRelease(lock.semaphore.take(1), () => lock.semaphore.release(1), {
2199
+ onSome: (service) => Effect21.gen(function* () {
2200
+ const lock = yield* Effect21.acquireRelease(Effect21.sync(() => reservePersistedChatLock(service, persistenceOptions.chatId)), (reserved) => Effect21.sync(() => releasePersistedChatLock(service, persistenceOptions.chatId, reserved)));
2201
+ yield* Effect21.acquireRelease(lock.semaphore.take(1), () => lock.semaphore.release(1), {
2224
2202
  interruptible: true
2225
2203
  });
2226
2204
  const getOptions = persistenceOptions.timeToLive === undefined ? undefined : { timeToLive: persistenceOptions.timeToLive };
2227
- return yield* resume === undefined ? service.getOrCreate(persistenceOptions.chatId, getOptions).pipe(Effect18.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error }))) : service.get(persistenceOptions.chatId, getOptions).pipe(Effect18.mapError((error) => error._tag === "ChatNotFoundError" ? ResumeMismatch.make({
2205
+ return yield* resume === undefined ? service.getOrCreate(persistenceOptions.chatId, getOptions).pipe(Effect21.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error }))) : service.get(persistenceOptions.chatId, getOptions).pipe(Effect21.mapError((error) => error._tag === "ChatNotFoundError" ? ResumeMismatch.make({
2228
2206
  reason: "checkpoint-not-found",
2229
2207
  received: resume.suspension
2230
2208
  }) : AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2231
2209
  })
2232
2210
  });
2233
2211
  let recoveredHistory;
2234
- if (resume !== undefined && persisted !== undefined && Option12.isSome(compactionService) && Option12.isSome(sessionService)) {
2235
- yield* Effect18.gen(function* () {
2212
+ if (resume !== undefined && persisted !== undefined && Option14.isSome(compactionService) && Option14.isSome(sessionService)) {
2213
+ yield* Effect21.gen(function* () {
2236
2214
  const path = yield* sessionService.value.path();
2237
2215
  const checkpoint = path.at(-1);
2238
2216
  if (checkpoint?._tag !== "Compaction" || checkpoint.version !== 2)
2239
2217
  return;
2240
2218
  const history = yield* Ref5.get(persisted.history);
2241
2219
  const before = buildContext(path.slice(0, -1));
2242
- if (!Schema14.toEquivalence(Prompt9.Prompt)(before, history))
2220
+ if (!Schema18.toEquivalence(Prompt11.Prompt)(before, history))
2243
2221
  return;
2244
2222
  recoveredHistory = buildContext(path);
2245
- }).pipe(Effect18.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2223
+ }).pipe(Effect21.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2246
2224
  }
2247
2225
  let resumeChat;
2248
2226
  let validatedResume;
2249
2227
  if (resume !== undefined) {
2250
- resumeChat = persisted ?? (yield* options.history === undefined ? Chat.empty : Chat.fromPrompt(options.history));
2228
+ resumeChat = persisted ?? (yield* options.history === undefined ? Chat2.empty : Chat2.fromPrompt(options.history));
2251
2229
  const received = resume.suspension;
2252
2230
  const resumeHistory = recoveredHistory ?? (yield* Ref5.get(resumeChat.history));
2253
- validatedResume = yield* Effect18.succeed(resumeHistory).pipe(Effect18.flatMap((history) => {
2231
+ validatedResume = yield* Effect21.succeed(resumeHistory).pipe(Effect21.flatMap((history) => {
2254
2232
  const expected = suspensionCheckpoint(history.content);
2255
2233
  if (expected === undefined) {
2256
2234
  return ResumeMismatch.make({ reason: "checkpoint-not-found", received });
2257
2235
  }
2258
- return sameSuspension(expected.suspension, received) ? Effect18.succeed(expected) : ResumeMismatch.make({
2236
+ return sameSuspension(expected.suspension, received) ? Effect21.succeed(expected) : ResumeMismatch.make({
2259
2237
  reason: "identity-mismatch",
2260
2238
  expected: expected.suspension,
2261
2239
  received
@@ -2263,7 +2241,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2263
2241
  }));
2264
2242
  if (recoveredHistory !== undefined && persisted !== undefined) {
2265
2243
  yield* Ref5.set(persisted.history, recoveredHistory);
2266
- yield* persisted.save.pipe(Effect18.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2244
+ yield* persisted.save.pipe(Effect21.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2267
2245
  }
2268
2246
  }
2269
2247
  const staticCandidates = (agent.toolDeclarations ?? Object.values(agent.toolkit.tools).map((tool) => ({
@@ -2282,17 +2260,17 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2282
2260
  turn: 0
2283
2261
  });
2284
2262
  }
2285
- const executor = yield* Effect18.serviceOption(ToolExecutor);
2286
- const approvals = yield* Effect18.serviceOption(Approvals);
2287
- const chain = yield* Effect18.serviceOption(ModelMiddleware).pipe(Effect18.map(Option12.match({ onNone: () => [], onSome: (service) => service })));
2263
+ const executor = yield* Effect21.serviceOption(ToolExecutor);
2264
+ const approvals = yield* Effect21.serviceOption(Approvals);
2265
+ const chain = yield* Effect21.serviceOption(ModelMiddleware).pipe(Effect21.map(Option14.match({ onNone: () => [], onSome: (service) => service })));
2288
2266
  if (options.toolOutputMaxBytes !== undefined && (!Number.isFinite(options.toolOutputMaxBytes) || options.toolOutputMaxBytes < 0)) {
2289
2267
  return yield* AgentError.make({
2290
2268
  message: "RunOptions.toolOutputMaxBytes must be a non-negative finite number",
2291
2269
  turn: 0
2292
2270
  });
2293
2271
  }
2294
- const decodedProgressPolicy = Schema14.decodeUnknownOption(progressOverflowPolicySchema)(options.toolProgress === undefined ? defaultProgressOverflowPolicy : options.toolProgress);
2295
- if (Option12.isNone(decodedProgressPolicy)) {
2272
+ const decodedProgressPolicy = Schema18.decodeUnknownOption(progressOverflowPolicySchema)(options.toolProgress === undefined ? defaultProgressOverflowPolicy : options.toolProgress);
2273
+ if (Option14.isNone(decodedProgressPolicy)) {
2296
2274
  return yield* AgentError.make({
2297
2275
  message: "RunOptions.toolProgress must select a supported policy with a positive safe-integer capacity",
2298
2276
  turn: 0
@@ -2312,11 +2290,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2312
2290
  });
2313
2291
  }
2314
2292
  const sessionId = options.sessionId ?? "local";
2315
- const instructionsService = yield* Effect18.serviceOption(Instructions);
2316
- const skillSourceService = yield* Effect18.serviceOption(SkillSource);
2317
- const skillRuntime = Option12.isNone(skillSourceService) ? undefined : {
2293
+ const instructionsService = yield* Effect21.serviceOption(Instructions);
2294
+ const skillSourceService = yield* Effect21.serviceOption(SkillSource);
2295
+ const skillRuntime = Option14.isNone(skillSourceService) ? undefined : {
2318
2296
  source: skillSourceService.value,
2319
- skills: yield* skillSourceService.value.all.pipe(Effect18.mapError((error) => AgentError.make({ message: error.message, turn: 0, cause: error })))
2297
+ skills: yield* skillSourceService.value.all.pipe(Effect21.mapError((error) => AgentError.make({ message: error.message, turn: 0, cause: error })))
2320
2298
  };
2321
2299
  const selectedSkills = skillRuntime === undefined ? [] : selectListings(skillRuntime.skills, skillListingBudgetTokens, []);
2322
2300
  const skillListings = selectedSkills.map((skill) => skill.listing).join(`
@@ -2332,50 +2310,50 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2332
2310
  }
2333
2311
  ] : []
2334
2312
  ]);
2335
- const instructionsEpoch = options.system === undefined && options.history === undefined && Option12.isSome(instructionsService) ? yield* openEpoch(instructionsService.value, { agentName: agent.name, turn: 0 }) : undefined;
2313
+ const instructionsEpoch = options.system === undefined && options.history === undefined && Option14.isSome(instructionsService) ? yield* openEpoch(instructionsService.value, { agentName: agent.name, turn: 0 }) : undefined;
2336
2314
  const baseSystem = options.system ?? (instructionsEpoch === undefined ? agent.instructions : instructionsEpoch.baseline.length === 0 ? agent.instructions : instructionsEpoch.baseline);
2337
2315
  const system = appendInstructionFragment(baseSystem, options.history === undefined && skillListings.length > 0 ? skillListingsInstructions(skillListings) : undefined);
2338
- const resilienceService = yield* Effect18.serviceOption(ModelResilience);
2339
- const modelRegistryService = yield* Effect18.serviceOption(Service);
2340
- const permissionsService = yield* Effect18.serviceOption(Permissions);
2341
- const ruleStoreService = yield* Effect18.serviceOption(RuleStore);
2342
- const authorizationService = yield* Effect18.serviceOption(ToolAuthorizerService);
2343
- const steeringService = yield* Effect18.serviceOption(Steering);
2344
- const memoryService = yield* Effect18.serviceOption(Memory);
2345
- const tokenizerService = yield* Effect18.serviceOption(Tokenizer2.Tokenizer);
2346
- const authorizer = agent.authorization ?? Option12.getOrElse(authorizationService, () => make4({
2347
- ...Option12.isNone(permissionsService) ? {} : { permissions: permissionsService.value },
2348
- ...Option12.isNone(approvals) ? {} : { approvals: approvals.value },
2349
- ...Option12.isNone(ruleStoreService) ? {} : { ruleStore: ruleStoreService.value }
2316
+ const resilienceService = yield* Effect21.serviceOption(ModelResilience);
2317
+ const modelRegistryService = yield* Effect21.serviceOption(Service);
2318
+ const permissionsService = yield* Effect21.serviceOption(Permissions);
2319
+ const ruleStoreService = yield* Effect21.serviceOption(RuleStore);
2320
+ const authorizationService = yield* Effect21.serviceOption(ToolAuthorizerService);
2321
+ const steeringService = yield* Effect21.serviceOption(Steering);
2322
+ const memoryService = yield* Effect21.serviceOption(Memory);
2323
+ const tokenizerService = yield* Effect21.serviceOption(Tokenizer2.Tokenizer);
2324
+ const authorizer = agent.authorization ?? Option14.getOrElse(authorizationService, () => make4({
2325
+ ...Option14.isNone(permissionsService) ? {} : { permissions: permissionsService.value },
2326
+ ...Option14.isNone(approvals) ? {} : { approvals: approvals.value },
2327
+ ...Option14.isNone(ruleStoreService) ? {} : { ruleStore: ruleStoreService.value }
2350
2328
  }));
2351
2329
  const memoryOptions = options.memory ?? (agent.memory === undefined ? undefined : { key: agent.memory });
2352
2330
  const agentModel = agent.model;
2353
- const agentModelRegistry = agentModel === undefined ? undefined : yield* Option12.match(modelRegistryService, {
2354
- onNone: () => Effect18.fail(AgentError.make({
2331
+ const agentModelRegistry = agentModel === undefined ? undefined : yield* Option14.match(modelRegistryService, {
2332
+ onNone: () => Effect21.fail(AgentError.make({
2355
2333
  message: "Agent.model requires ModelRegistry in context",
2356
2334
  turn: 0
2357
2335
  })),
2358
- onSome: Effect18.succeed
2336
+ onSome: Effect21.succeed
2359
2337
  });
2360
2338
  const memoryRuntime = memoryOptions === undefined ? undefined : {
2361
2339
  key: memoryOptions.key,
2362
- service: yield* Option12.match(memoryService, {
2363
- onNone: () => Effect18.fail(AgentError.make({
2340
+ service: yield* Option14.match(memoryService, {
2341
+ onNone: () => Effect21.fail(AgentError.make({
2364
2342
  message: options.memory === undefined ? "Agent.memory requires Memory in context" : "RunOptions.memory requires Memory in context",
2365
2343
  turn: 0
2366
2344
  })),
2367
- onSome: Effect18.succeed
2345
+ onSome: Effect21.succeed
2368
2346
  })
2369
2347
  };
2370
2348
  const seedSystem = persisted !== undefined && system !== undefined && (yield* Ref5.get(persisted.history)).content.length === 0 ? system : undefined;
2371
- const freshChat = options.history !== undefined ? Chat.fromPrompt(options.history) : system !== undefined ? Chat.fromPrompt([Prompt9.makeMessage("system", { content: system })]) : Chat.empty;
2349
+ const freshChat = options.history !== undefined ? Chat2.fromPrompt(options.history) : system !== undefined ? Chat2.fromPrompt([Prompt11.makeMessage("system", { content: system })]) : Chat2.empty;
2372
2350
  const chat = resumeChat ?? persisted ?? (yield* freshChat);
2373
- const savePersisted = (turn) => persisted === undefined ? Effect18.void : persisted.save.pipe(Effect18.mapError((error) => AgentError.make({ message: errorMessage(error), turn, cause: error })));
2374
- const appendPending = (turn, pending) => pending.length === 0 ? Ref5.get(chat.history) : Ref5.updateAndGet(chat.history, (history) => Prompt9.concat(history, Prompt9.fromResponseParts(pending))).pipe(Effect18.tap(() => savePersisted(turn)));
2375
- const checkpointSuspended = (turn, pending, suspension2) => Effect18.gen(function* () {
2351
+ const savePersisted = (turn) => persisted === undefined ? Effect21.void : persisted.save.pipe(Effect21.mapError((error) => AgentError.make({ message: errorMessage(error), turn, cause: error })));
2352
+ const appendPending = (turn, pending) => pending.length === 0 ? Ref5.get(chat.history) : Ref5.updateAndGet(chat.history, (history) => Prompt11.concat(history, Prompt11.fromResponseParts(pending))).pipe(Effect21.tap(() => savePersisted(turn)));
2353
+ const checkpointSuspended = (turn, pending, suspension2) => Effect21.gen(function* () {
2376
2354
  const withPending = yield* appendPending(turn, pending);
2377
2355
  const unresolved = unresolvedToolCall(withPending.content, suspension2.tool_call_id);
2378
- if (unresolved === undefined || unresolved.call.id !== suspension2.tool_call_id || unresolved.call.name !== suspension2.tool_name || !Equal.equals(unresolved.call.params, suspension2.tool_params)) {
2356
+ if (unresolved === undefined || unresolved.call.id !== suspension2.tool_call_id || unresolved.call.name !== suspension2.tool_name || !Equal2.equals(unresolved.call.params, suspension2.tool_params)) {
2379
2357
  return yield* AgentError.make({
2380
2358
  message: "Suspension does not match the unresolved checkpoint call",
2381
2359
  turn
@@ -2393,8 +2371,8 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2393
2371
  const messages = withPending.content.map((message, messageIndex) => {
2394
2372
  if (messageIndex !== unresolved.messageIndex || message.role !== "assistant")
2395
2373
  return message;
2396
- return Prompt9.makeMessage("assistant", {
2397
- content: message.content.map((part, partIndex) => partIndex === unresolved.partIndex && part.type === "tool-call" ? Prompt9.makePart("tool-call", {
2374
+ return Prompt11.makeMessage("assistant", {
2375
+ content: message.content.map((part, partIndex) => partIndex === unresolved.partIndex && part.type === "tool-call" ? Prompt11.makePart("tool-call", {
2398
2376
  id: part.id,
2399
2377
  name: part.name,
2400
2378
  params: part.params,
@@ -2404,15 +2382,15 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2404
2382
  options: message.options
2405
2383
  });
2406
2384
  });
2407
- const checkpoint = Prompt9.fromMessages(messages);
2385
+ const checkpoint = Prompt11.fromMessages(messages);
2408
2386
  const path = yield* syncSession(turn, withPending);
2409
2387
  const parentId = path.at(-1)?.id ?? null;
2410
- yield* applyCompactionResult(turn, { _tag: "Microcompact", history: checkpoint, prompt: Prompt9.empty }, parentId);
2411
- if (Option12.isNone(activeSession))
2388
+ yield* applyCompactionResult(turn, { _tag: "Microcompact", history: checkpoint, prompt: Prompt11.empty }, parentId);
2389
+ if (Option14.isNone(activeSession))
2412
2390
  yield* savePersisted(turn);
2413
2391
  return yield* Ref5.get(chat.history);
2414
2392
  });
2415
- const checkpointPending = (turn, pending) => appendPending(turn, pending).pipe(Effect18.tap((checkpoint) => syncSession(turn, checkpoint)));
2393
+ const checkpointPending = (turn, pending) => appendPending(turn, pending).pipe(Effect21.tap((checkpoint) => syncSession(turn, checkpoint)));
2416
2394
  const failSuspended = (call, toolCallBatch, toolCallIndex, token, reason) => Stream4.fail(suspended(call, toolCallBatch, toolCallIndex, token, reason));
2417
2395
  const state = {
2418
2396
  text: "",
@@ -2425,15 +2403,15 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2425
2403
  registry: initialRegistry,
2426
2404
  activatedSkillBodies: new Map
2427
2405
  });
2428
- const restoreActivatedSkills = (history) => Effect18.gen(function* () {
2406
+ const restoreActivatedSkills = (history) => Effect21.gen(function* () {
2429
2407
  for (const message of history.content) {
2430
2408
  if (!Array.isArray(message.content))
2431
2409
  continue;
2432
2410
  for (const part of message.content) {
2433
2411
  if (String(part.type) !== "tool-result" || String(part.name) !== activateSkillToolName || part.isFailure === true)
2434
2412
  continue;
2435
- const activation = Schema14.decodeUnknownOption(activateSkillSuccess)(part.result);
2436
- if (Option12.isNone(activation))
2413
+ const activation = Schema18.decodeUnknownOption(activateSkillSuccess)(part.result);
2414
+ if (Option14.isNone(activation))
2437
2415
  continue;
2438
2416
  if (skillRuntime === undefined) {
2439
2417
  return yield* AgentError.make({
@@ -2464,10 +2442,10 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2464
2442
  yield* Ref5.set(toolState, { registry, activatedSkillBodies });
2465
2443
  }
2466
2444
  }
2467
- }).pipe(Effect18.mapError((error) => isToolNameCollision(error) ? error : AgentError.make({ message: error.message, turn: 0, cause: error })));
2445
+ }).pipe(Effect21.mapError((error) => isToolNameCollision(error) ? error : AgentError.make({ message: error.message, turn: 0, cause: error })));
2468
2446
  if (validatedResume !== undefined)
2469
- yield* Ref5.get(chat.history).pipe(Effect18.flatMap(restoreActivatedSkills));
2470
- const activeSession = Option12.isSome(compactionService) ? sessionService : Option12.none();
2447
+ yield* Ref5.get(chat.history).pipe(Effect21.flatMap(restoreActivatedSkills));
2448
+ const activeSession = Option14.isSome(compactionService) ? sessionService : Option14.none();
2471
2449
  const sessionError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2472
2450
  const compactionError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2473
2451
  const memoryError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
@@ -2479,35 +2457,35 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2479
2457
  return prompt;
2480
2458
  const memoryMessage2 = messageFromRecall(content);
2481
2459
  const [first, ...rest] = prompt.content;
2482
- return first?.role === "system" ? Prompt9.fromMessages([first, memoryMessage2, ...rest]) : Prompt9.fromMessages([memoryMessage2, ...prompt.content]);
2460
+ return first?.role === "system" ? Prompt11.fromMessages([first, memoryMessage2, ...rest]) : Prompt11.fromMessages([memoryMessage2, ...prompt.content]);
2483
2461
  };
2484
- const recallInitialPrompt = (prompt) => memoryRuntime === undefined ? Effect18.succeed(prompt) : memoryRuntime.service.recall({ key: memoryRuntime.key, turn: 0, prompt }).pipe(Effect18.mapError((error) => memoryError(0, error)), Effect18.map((items) => insertRecalledItems(prompt, items)));
2485
- const rememberTurn = (turn, transcript, terminal, path) => memoryRuntime === undefined ? Effect18.void : memoryRuntime.service.remember({
2462
+ const recallInitialPrompt = (prompt) => memoryRuntime === undefined ? Effect21.succeed(prompt) : memoryRuntime.service.recall({ key: memoryRuntime.key, turn: 0, prompt }).pipe(Effect21.mapError((error) => memoryError(0, error)), Effect21.map((items) => insertRecalledItems(prompt, items)));
2463
+ const rememberTurn = (turn, transcript, terminal, path) => memoryRuntime === undefined ? Effect21.void : memoryRuntime.service.remember({
2486
2464
  key: memoryRuntime.key,
2487
2465
  turn,
2488
- transcript: Option12.isSome(activeSession) ? buildMemoryContext(path) : projectTranscript(transcript),
2466
+ transcript: Option14.isSome(activeSession) ? buildMemoryContext(path) : projectTranscript(transcript),
2489
2467
  terminal
2490
- }).pipe(Effect18.mapError((error) => memoryError(turn, error)));
2491
- const messageEquivalence = Schema14.toEquivalence(Prompt9.Message);
2492
- const promptEquivalence2 = Schema14.toEquivalence(Prompt9.Prompt);
2468
+ }).pipe(Effect21.mapError((error) => memoryError(turn, error)));
2469
+ const messageEquivalence = Schema18.toEquivalence(Prompt11.Message);
2470
+ const promptEquivalence2 = Schema18.toEquivalence(Prompt11.Prompt);
2493
2471
  const sessionTranscriptCursor = (projection, transcript) => {
2494
2472
  if (projection.length === 0)
2495
- return Option12.some(0);
2473
+ return Option14.some(0);
2496
2474
  const matches2 = [];
2497
2475
  for (let start = 0;start <= transcript.length - projection.length; start += 1) {
2498
2476
  if (transcript.slice(0, start).every((message) => message.role === "system") && projection.every((message, index) => messageEquivalence(message, transcript[start + index]))) {
2499
2477
  matches2.push(start + projection.length);
2500
2478
  }
2501
2479
  }
2502
- return matches2.length === 1 ? Option12.some(matches2[0]) : Option12.none();
2480
+ return matches2.length === 1 ? Option14.some(matches2[0]) : Option14.none();
2503
2481
  };
2504
- const syncSession = (turn, transcript) => Option12.match(activeSession, {
2505
- onNone: () => Effect18.succeed([]),
2506
- onSome: (session) => Effect18.gen(function* () {
2482
+ const syncSession = (turn, transcript) => Option14.match(activeSession, {
2483
+ onNone: () => Effect21.succeed([]),
2484
+ onSome: (session) => Effect21.gen(function* () {
2507
2485
  let path = yield* session.path();
2508
2486
  const projection = buildContext(path);
2509
2487
  const cursor = sessionTranscriptCursor(projection.content, transcript.content);
2510
- if (Option12.isNone(cursor)) {
2488
+ if (Option14.isNone(cursor)) {
2511
2489
  const checkpoint = path.at(-1);
2512
2490
  const before = buildContext(path.slice(0, -1));
2513
2491
  if (checkpoint?._tag === "Compaction" && checkpoint.version === 2 && promptEquivalence2(before, transcript)) {
@@ -2528,13 +2506,13 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2528
2506
  if (expectedLeafId !== (path.at(-1)?.id ?? null))
2529
2507
  path = yield* session.path();
2530
2508
  return path;
2531
- }).pipe(Effect18.mapError((error) => Schema14.is(AgentError)(error) ? error : sessionError(turn, error)))
2509
+ }).pipe(Effect21.mapError((error) => Schema18.is(AgentError)(error) ? error : sessionError(turn, error)))
2532
2510
  });
2533
- const countTokens = (turn, prompt) => Option12.match(tokenizerService, {
2534
- onNone: () => Effect18.succeed(Math.ceil(JSON.stringify(prompt.content).length / 4)),
2535
- onSome: (tokenizer) => tokenizer.tokenize(prompt).pipe(Effect18.map((tokens) => tokens.length), Effect18.mapError((error) => AgentError.make({ message: errorMessage(error), turn, cause: error })))
2511
+ const countTokens = (turn, prompt) => Option14.match(tokenizerService, {
2512
+ onNone: () => Effect21.succeed(Math.ceil(JSON.stringify(prompt.content).length / 4)),
2513
+ onSome: (tokenizer) => tokenizer.tokenize(prompt).pipe(Effect21.map((tokens) => tokens.length), Effect21.mapError((error) => AgentError.make({ message: errorMessage(error), turn, cause: error })))
2536
2514
  });
2537
- const compactionUsage = (turn, history, prompt) => countTokens(turn, Prompt9.concat(history, prompt)).pipe(Effect18.map((contextTokens) => ({
2515
+ const compactionUsage = (turn, history, prompt) => countTokens(turn, Prompt11.concat(history, prompt)).pipe(Effect21.map((contextTokens) => ({
2538
2516
  contextTokens,
2539
2517
  contextWindow: options.compaction?.contextWindow ?? Number.POSITIVE_INFINITY,
2540
2518
  reserveTokens: DEFAULT_RESERVE_TOKENS
@@ -2542,17 +2520,17 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2542
2520
  const validateCompactionProjection = (turn, result) => {
2543
2521
  const pending = new Set;
2544
2522
  const optional = new Set;
2545
- for (const message of Prompt9.concat(result.history, result.prompt).content) {
2523
+ for (const message of Prompt11.concat(result.history, result.prompt).content) {
2546
2524
  if (typeof message.content === "string") {
2547
2525
  if (pending.size > 0) {
2548
- return Effect18.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2526
+ return Effect21.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2549
2527
  }
2550
2528
  optional.clear();
2551
2529
  continue;
2552
2530
  }
2553
2531
  const hasResult = message.content.some((part) => part.type === "tool-result");
2554
2532
  if (pending.size > 0 && !hasResult) {
2555
- return Effect18.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2533
+ return Effect21.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2556
2534
  }
2557
2535
  if (!hasResult)
2558
2536
  optional.clear();
@@ -2560,7 +2538,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2560
2538
  for (const part of message.content) {
2561
2539
  if (part.type === "tool-call") {
2562
2540
  if (responseCalls.has(part.id)) {
2563
- return Effect18.fail(AgentError.make({ message: `Compaction projection contains duplicate tool call ${part.id}`, turn }));
2541
+ return Effect21.fail(AgentError.make({ message: `Compaction projection contains duplicate tool call ${part.id}`, turn }));
2564
2542
  }
2565
2543
  responseCalls.add(part.id);
2566
2544
  if (part.providerExecuted)
@@ -2570,38 +2548,38 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2570
2548
  }
2571
2549
  if (part.type === "tool-result") {
2572
2550
  if (!pending.delete(part.id) && !optional.delete(part.id)) {
2573
- return Effect18.fail(AgentError.make({ message: `Compaction projection contains orphan tool result ${part.id}`, turn }));
2551
+ return Effect21.fail(AgentError.make({ message: `Compaction projection contains orphan tool result ${part.id}`, turn }));
2574
2552
  }
2575
2553
  }
2576
2554
  }
2577
2555
  }
2578
- return pending.size === 0 ? Effect18.void : Effect18.fail(AgentError.make({ message: "Compaction projection contains an unresolved tool call", turn }));
2556
+ return pending.size === 0 ? Effect21.void : Effect21.fail(AgentError.make({ message: "Compaction projection contains an unresolved tool call", turn }));
2579
2557
  };
2580
- const applyCompactionResult = (turn, result, parentId) => Option12.match(activeSession, {
2558
+ const applyCompactionResult = (turn, result, parentId) => Option14.match(activeSession, {
2581
2559
  onNone: () => Ref5.set(chat.history, result.history),
2582
- onSome: (session) => Effect18.gen(function* () {
2560
+ onSome: (session) => Effect21.gen(function* () {
2583
2561
  const id = yield* session.reserveEntryId;
2584
- yield* Effect18.uninterruptibleMask((restore) => restore(session.appendCheckpoint({
2562
+ yield* Effect21.uninterruptibleMask((restore) => restore(session.appendCheckpoint({
2585
2563
  id,
2586
2564
  parentId,
2587
2565
  projectedHistory: result.history,
2588
2566
  ...result._tag === "Summarize" ? { summary: result.summary } : {}
2589
- })).pipe(Effect18.flatMap((appended) => restore(session.path(appended.leafId))), Effect18.map(buildContext), Effect18.tap((projection) => Ref5.set(chat.history, projection)), Effect18.andThen(restore(savePersisted(turn)))));
2590
- }).pipe(Effect18.mapError((error) => Schema14.is(AgentError)(error) ? error : sessionError(turn, error)))
2567
+ })).pipe(Effect21.flatMap((appended) => restore(session.path(appended.leafId))), Effect21.map(buildContext), Effect21.tap((projection) => Ref5.set(chat.history, projection)), Effect21.andThen(restore(savePersisted(turn)))));
2568
+ }).pipe(Effect21.mapError((error) => Schema18.is(AgentError)(error) ? error : sessionError(turn, error)))
2591
2569
  });
2592
- const preparePrompt = (turn, prompt, overflow) => Option12.match(compactionService, {
2593
- onNone: () => Effect18.succeed({ prompt, changed: false }),
2594
- onSome: (compaction) => Effect18.gen(function* () {
2570
+ const preparePrompt = (turn, prompt, overflow) => Option14.match(compactionService, {
2571
+ onNone: () => Effect21.succeed({ prompt, changed: false }),
2572
+ onSome: (compaction) => Effect21.gen(function* () {
2595
2573
  const history = yield* Ref5.get(chat.history);
2596
2574
  const path = yield* syncSession(turn, history);
2597
2575
  const usage = yield* compactionUsage(turn, history, prompt);
2598
2576
  const historyRecalled = recalledMessages(history);
2599
2577
  const promptRecalled = recalledMessages(prompt);
2600
- const detachedHistory = yield* detachPrompt(history).pipe(Effect18.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2601
- const detachedPrompt = yield* detachPrompt(prompt).pipe(Effect18.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2602
- const originalHistory = yield* detachPrompt(detachedHistory).pipe(Effect18.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2603
- const originalPrompt = yield* detachPrompt(detachedPrompt).pipe(Effect18.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2604
- const detachedPath = yield* Effect18.forEach(path, detachEntry).pipe(Effect18.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2578
+ const detachedHistory = yield* detachPrompt(history).pipe(Effect21.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2579
+ const detachedPrompt = yield* detachPrompt(prompt).pipe(Effect21.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2580
+ const originalHistory = yield* detachPrompt(detachedHistory).pipe(Effect21.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2581
+ const originalPrompt = yield* detachPrompt(detachedPrompt).pipe(Effect21.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2582
+ const detachedPath = yield* Effect21.forEach(path, detachEntry).pipe(Effect21.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2605
2583
  const compacted = yield* compaction.maybeCompact({
2606
2584
  agentName: agent.name,
2607
2585
  sessionId,
@@ -2612,15 +2590,15 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2612
2590
  usage,
2613
2591
  overflow,
2614
2592
  ...options.toolOutputMaxBytes === undefined ? {} : { toolOutputMaxBytes: options.toolOutputMaxBytes }
2615
- }).pipe(Effect18.mapError((error) => compactionError(turn, error)));
2616
- if (Option12.isNone(compacted))
2593
+ }).pipe(Effect21.mapError((error) => compactionError(turn, error)));
2594
+ if (Option14.isNone(compacted))
2617
2595
  return { prompt, changed: false };
2618
- const changed = !Equal.equals(originalHistory.content, compacted.value.history.content) || !Equal.equals(originalPrompt.content, compacted.value.prompt.content);
2596
+ const changed = !Equal2.equals(originalHistory.content, compacted.value.history.content) || !Equal2.equals(originalPrompt.content, compacted.value.prompt.content);
2619
2597
  if (!changed)
2620
2598
  return { prompt, changed: false };
2621
2599
  const allowed = [...historyRecalled, ...promptRecalled];
2622
- const required = Option12.isSome(activeSession) ? promptRecalled : allowed;
2623
- if (!preservesRecalledMessages(allowed, required, Prompt9.concat(compacted.value.history, compacted.value.prompt))) {
2600
+ const required = Option14.isSome(activeSession) ? promptRecalled : allowed;
2601
+ if (!preservesRecalledMessages(allowed, required, Prompt11.concat(compacted.value.history, compacted.value.prompt))) {
2624
2602
  return yield* MiddlewareViolation.make({
2625
2603
  turn,
2626
2604
  detail: "Compaction must preserve recalled-memory message lineage outside the lossless Session path"
@@ -2631,18 +2609,18 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2631
2609
  return { prompt: compacted.value.prompt, changed: true };
2632
2610
  })
2633
2611
  });
2634
- const boundedSuccessResult = (call, outcome) => options.toolOutputMaxBytes === undefined ? Effect18.succeed(successResult(call, outcome)) : bound(outcome, { toolCallId: call.id, maxBytes: options.toolOutputMaxBytes }).pipe(Effect18.map((bounded2) => successResult(call, bounded2)));
2612
+ const boundedSuccessResult = (call, outcome) => options.toolOutputMaxBytes === undefined ? Effect21.succeed(successResult(call, outcome)) : bound(outcome, { toolCallId: call.id, maxBytes: options.toolOutputMaxBytes }).pipe(Effect21.map((bounded2) => successResult(call, bounded2)));
2635
2613
  const outcomeEvents = (turn, toolCallBatch, toolCallIndex, call, outcome, droppedProgress, registry) => {
2636
2614
  const metadata = droppedProgress === 0 ? {} : { metadata: { toolProgress: { dropped: droppedProgress } } };
2637
2615
  switch (outcome._tag) {
2638
2616
  case "Success":
2639
- return (isSkillActivationCall(call, registry) ? Effect18.succeed(successResult(call, outcome)) : boundedSuccessResult(call, outcome)).pipe(Effect18.map((result) => Stream4.fromIterable([{ _tag: "ToolExecutionCompleted", turn, call, result, ...metadata }])));
2617
+ return (isSkillActivationCall(call, registry) ? Effect21.succeed(successResult(call, outcome)) : boundedSuccessResult(call, outcome)).pipe(Effect21.map((result) => Stream4.fromIterable([{ _tag: "ToolExecutionCompleted", turn, call, result, ...metadata }])));
2640
2618
  case "DomainFailure": {
2641
2619
  const result = domainFailureResult(call, outcome);
2642
- return Effect18.succeed(Stream4.fromIterable([{ _tag: "ToolExecutionCompleted", turn, call, result, ...metadata }]));
2620
+ return Effect21.succeed(Stream4.fromIterable([{ _tag: "ToolExecutionCompleted", turn, call, result, ...metadata }]));
2643
2621
  }
2644
2622
  case "Suspend":
2645
- return Effect18.succeed(failSuspended(call, toolCallBatch, toolCallIndex, outcome.token, "tool-wait"));
2623
+ return Effect21.succeed(failSuspended(call, toolCallBatch, toolCallIndex, outcome.token, "tool-wait"));
2646
2624
  }
2647
2625
  };
2648
2626
  const defaultExecute = (request, registry) => {
@@ -2650,11 +2628,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2650
2628
  if (registered?.dispatch === "Static") {
2651
2629
  return executeToolkit(staticToolkit, request);
2652
2630
  }
2653
- return registered === undefined ? Effect18.fail(FrameworkFailure.make({
2631
+ return registered === undefined ? Effect21.fail(FrameworkFailure.make({
2654
2632
  stage: "missing-handler",
2655
2633
  tool: request.call.name,
2656
2634
  message: `Tool ${request.call.name} is not registered`
2657
- })) : Effect18.fail(FrameworkFailure.make({
2635
+ })) : Effect21.fail(FrameworkFailure.make({
2658
2636
  stage: "missing-handler",
2659
2637
  tool: request.call.name,
2660
2638
  message: `Activated skill tool ${request.call.name} requires ToolExecutor`
@@ -2671,11 +2649,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2671
2649
  return Queue2.sliding(progressPolicy.capacity);
2672
2650
  }
2673
2651
  };
2674
- const executeApproved = (turn, call, request, registry) => Stream4.concat(Stream4.fromIterable([{ _tag: "ToolExecutionStarted", turn, call }]), Stream4.unwrap(Effect18.gen(function* () {
2675
- const progressQueue = yield* Effect18.acquireRelease(makeProgressQueue(), Queue2.shutdown);
2652
+ const executeApproved = (turn, call, request, registry) => Stream4.concat(Stream4.fromIterable([{ _tag: "ToolExecutionStarted", turn, call }]), Stream4.unwrap(Effect21.gen(function* () {
2653
+ const progressQueue = yield* Effect21.acquireRelease(makeProgressQueue(), Queue2.shutdown);
2676
2654
  const droppedProgress = yield* Ref5.make(0);
2677
- const emitSemaphore = yield* Semaphore2.make(1);
2678
- const signal = yield* Effect18.abortSignal;
2655
+ const emitSemaphore = yield* Semaphore3.make(1);
2656
+ const signal = yield* Effect21.abortSignal;
2679
2657
  const context = ToolContext.of({
2680
2658
  signal,
2681
2659
  sessionId,
@@ -2687,9 +2665,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2687
2665
  ...progress.message === undefined ? {} : { message: progress.message },
2688
2666
  ...progress.data === undefined ? {} : { data: progress.data }
2689
2667
  };
2690
- return emitSemaphore.withPermit(Effect18.gen(function* () {
2668
+ return emitSemaphore.withPermit(Effect21.gen(function* () {
2691
2669
  if (progressPolicy._tag === "Sliding") {
2692
- const dropped = yield* Effect18.sync(() => {
2670
+ const dropped = yield* Effect21.sync(() => {
2693
2671
  const full = Queue2.isFullUnsafe(progressQueue);
2694
2672
  Queue2.offerUnsafe(progressQueue, event);
2695
2673
  return full;
@@ -2707,11 +2685,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2707
2685
  }));
2708
2686
  }
2709
2687
  });
2710
- const execution = isSkillActivationCall(call, registry) ? activateSkillOutcome(turn, call) : Option12.isNone(executor) ? defaultExecute(request, registry) : executor.value.execute(request).pipe(Effect18.mapError((error) => Schema14.is(RemoteRetryError)(error) ? AgentError.make({ message: error.message, turn, cause: error }) : error));
2711
- const fiber = yield* execution.pipe(Effect18.provideService(ToolContext, context), Effect18.ensuring(Queue2.end(progressQueue).pipe(Effect18.asVoid)), Effect18.forkScoped({ startImmediately: true }));
2712
- return Stream4.concat(Stream4.fromQueue(progressQueue), Stream4.fromEffect(Fiber.join(fiber)).pipe(Stream4.flatMap((outcome) => Stream4.unwrap(Ref5.get(droppedProgress).pipe(Effect18.flatMap((dropped) => outcomeEvents(turn, request.toolCallBatch, request.toolCallIndex, call, outcome, dropped, registry)))))));
2688
+ const execution = isSkillActivationCall(call, registry) ? activateSkillOutcome(turn, call) : Option14.isNone(executor) ? defaultExecute(request, registry) : executor.value.execute(request).pipe(Effect21.mapError((error) => Schema18.is(RemoteRetryError)(error) ? AgentError.make({ message: error.message, turn, cause: error }) : error));
2689
+ const fiber = yield* execution.pipe(Effect21.provideService(ToolContext, context), Effect21.ensuring(Queue2.end(progressQueue).pipe(Effect21.asVoid)), Effect21.forkScoped({ startImmediately: true }));
2690
+ return Stream4.concat(Stream4.fromQueue(progressQueue), Stream4.fromEffect(Fiber.join(fiber)).pipe(Stream4.flatMap((outcome) => Stream4.unwrap(Ref5.get(droppedProgress).pipe(Effect21.flatMap((dropped) => outcomeEvents(turn, request.toolCallBatch, request.toolCallIndex, call, outcome, dropped, registry)))))));
2713
2691
  })));
2714
- const activateSkillOutcome = (turn, call) => Effect18.gen(function* () {
2692
+ const activateSkillOutcome = (turn, call) => Effect21.gen(function* () {
2715
2693
  if (skillRuntime === undefined) {
2716
2694
  return yield* FrameworkFailure.make({
2717
2695
  stage: "missing-handler",
@@ -2719,8 +2697,8 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2719
2697
  message: "SkillSource is not available"
2720
2698
  });
2721
2699
  }
2722
- const params = Schema14.decodeUnknownOption(activateSkillParameters)(call.params);
2723
- if (Option12.isNone(params)) {
2700
+ const params = Schema18.decodeUnknownOption(activateSkillParameters)(call.params);
2701
+ if (Option14.isNone(params)) {
2724
2702
  return yield* FrameworkFailure.make({
2725
2703
  stage: "decode-input",
2726
2704
  tool: call.name,
@@ -2761,7 +2739,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2761
2739
  allowedTools: [...skill.frontmatter.allowedTools ?? []]
2762
2740
  };
2763
2741
  return { _tag: "Success", result: output, encodedResult: output };
2764
- }).pipe(Effect18.mapError((error) => isToolNameCollision(error) || Schema14.is(FrameworkFailure)(error) ? error : skillError(turn, error)));
2742
+ }).pipe(Effect21.mapError((error) => isToolNameCollision(error) || Schema18.is(FrameworkFailure)(error) ? error : skillError(turn, error)));
2765
2743
  const authorizationError2 = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2766
2744
  const toolCallEvents = (turn, toolCallBatch, toolCallIndex, call, messages, registry, authorizationStage, authorizationToken) => {
2767
2745
  const request = { call, toolCallBatch, turn, toolCallIndex, agentName: agent.name, sessionId };
@@ -2773,7 +2751,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2773
2751
  message: `Tool ${call.name} is not active for turn ${turn}`
2774
2752
  }));
2775
2753
  const activeTools = registry.entries.map((entry) => entry.tool.name);
2776
- return Stream4.unwrap(Effect18.gen(function* () {
2754
+ return Stream4.unwrap(Effect21.gen(function* () {
2777
2755
  const activatedSkills = [...(yield* Ref5.get(toolState)).activatedSkillBodies.keys()];
2778
2756
  const approvalEvents = yield* Queue2.bounded(1);
2779
2757
  const fiber = yield* authorizer.authorize({
@@ -2786,8 +2764,8 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2786
2764
  ...authorizationToken === undefined ? {} : { authorizationToken },
2787
2765
  messages,
2788
2766
  execution: request,
2789
- onApprovalRequired: Queue2.offer(approvalEvents, { _tag: "ApprovalRequested", turn, call }).pipe(Effect18.asVoid)
2790
- }).pipe(Effect18.mapError((error) => authorizationError2(turn, error)), Effect18.ensuring(Queue2.end(approvalEvents).pipe(Effect18.asVoid)), Effect18.forkScoped({ startImmediately: true }));
2767
+ onApprovalRequired: Queue2.offer(approvalEvents, { _tag: "ApprovalRequested", turn, call }).pipe(Effect21.asVoid)
2768
+ }).pipe(Effect21.mapError((error) => authorizationError2(turn, error)), Effect21.ensuring(Queue2.end(approvalEvents).pipe(Effect21.asVoid)), Effect21.forkScoped({ startImmediately: true }));
2791
2769
  return Stream4.concat(Stream4.fromQueue(approvalEvents), Stream4.fromEffect(Fiber.join(fiber)).pipe(Stream4.flatMap((decision2) => {
2792
2770
  switch (decision2._tag) {
2793
2771
  case "Execute":
@@ -2815,8 +2793,8 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2815
2793
  })));
2816
2794
  }));
2817
2795
  };
2818
- const captureFinishPart = (part) => Effect18.gen(function* () {
2819
- const span = yield* Effect18.currentSpan;
2796
+ const captureFinishPart = (part) => Effect21.gen(function* () {
2797
+ const span = yield* Effect21.currentSpan;
2820
2798
  state.finish = {
2821
2799
  usage: state.finish === undefined ? part.usage : addUsage(state.finish.usage, part.usage),
2822
2800
  reason: part.reason
@@ -2830,9 +2808,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2830
2808
  },
2831
2809
  response: { finishReasons: [part.reason] }
2832
2810
  });
2833
- }).pipe(Effect18.orDie);
2834
- const captureStructuredUsage = (content) => Effect18.gen(function* () {
2835
- const span = yield* Effect18.currentSpan;
2811
+ }).pipe(Effect21.orDie);
2812
+ const captureStructuredUsage = (content) => Effect21.gen(function* () {
2813
+ const span = yield* Effect21.currentSpan;
2836
2814
  for (const part of content) {
2837
2815
  if (part.type === "finish") {
2838
2816
  state.usage = state.usage === undefined ? part.usage : addUsage(state.usage, part.usage);
@@ -2846,10 +2824,10 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2846
2824
  });
2847
2825
  }
2848
2826
  }
2849
- }).pipe(Effect18.orDie);
2850
- const withModelResilience = (effect) => Option12.match(resilienceService, {
2827
+ }).pipe(Effect21.orDie);
2828
+ const withModelResilience = (effect) => Option14.match(resilienceService, {
2851
2829
  onNone: () => effect,
2852
- onSome: (resilience) => Effect18.flatMap(LanguageModel5.LanguageModel, (model) => effect.pipe(Effect18.provideService(LanguageModel5.LanguageModel, apply(model, {
2830
+ onSome: (resilience) => Effect21.flatMap(LanguageModel5.LanguageModel, (model) => effect.pipe(Effect21.provideService(LanguageModel5.LanguageModel, apply(model, {
2853
2831
  ...resilience,
2854
2832
  classify: (error) => classifyFailure(model, error) === "context-overflow" ? "terminal" : resilience.classify(error)
2855
2833
  }))))
@@ -2873,33 +2851,33 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2873
2851
  }
2874
2852
  return modelPart;
2875
2853
  };
2876
- const recordPending = (event) => Effect18.sync(() => {
2854
+ const recordPending = (event) => Effect21.sync(() => {
2877
2855
  if (event._tag === "ToolExecutionCompleted")
2878
2856
  state.pending.push(event.result);
2879
2857
  });
2880
- const transformPart = (turn, part) => applyPartChain(chain, part, { agentName: agent.name, turn }).pipe(Effect18.flatMap(Option12.match({
2881
- onSome: (transformed) => Effect18.succeed(Option12.some(transformed)),
2882
- onNone: () => part.type === "tool-call" ? Effect18.fail(MiddlewareViolation.make({
2858
+ const transformPart = (turn, part) => applyPartChain(chain, part, { agentName: agent.name, turn }).pipe(Effect21.flatMap(Option14.match({
2859
+ onSome: (transformed) => Effect21.succeed(Option14.some(transformed)),
2860
+ onNone: () => part.type === "tool-call" ? Effect21.fail(MiddlewareViolation.make({
2883
2861
  turn,
2884
2862
  detail: "ModelMiddleware dropped a tool-call part"
2885
- })) : Effect18.succeed(Option12.none())
2863
+ })) : Effect21.succeed(Option14.none())
2886
2864
  })));
2887
2865
  const validateToolCallId = (idState, part) => {
2888
2866
  if (part.type !== "tool-call")
2889
- return Effect18.void;
2867
+ return Effect21.void;
2890
2868
  return Ref5.modify(idState, (current) => {
2891
- const existingFirstIndex = HashMap4.get(current.firstIndexes, part.id);
2892
- const duplicate = Option12.map(existingFirstIndex, (index) => DuplicateToolCallId.make({ id: part.id, firstIndex: index, duplicateIndex: current.nextIndex }));
2869
+ const existingFirstIndex = HashMap5.get(current.firstIndexes, part.id);
2870
+ const duplicate = Option14.map(existingFirstIndex, (index) => DuplicateToolCallId.make({ id: part.id, firstIndex: index, duplicateIndex: current.nextIndex }));
2893
2871
  return [
2894
2872
  duplicate,
2895
2873
  {
2896
2874
  nextIndex: current.nextIndex + 1,
2897
- firstIndexes: Option12.isSome(existingFirstIndex) ? current.firstIndexes : HashMap4.set(current.firstIndexes, part.id, current.nextIndex)
2875
+ firstIndexes: Option14.isSome(existingFirstIndex) ? current.firstIndexes : HashMap5.set(current.firstIndexes, part.id, current.nextIndex)
2898
2876
  }
2899
2877
  ];
2900
- }).pipe(Effect18.flatMap(Option12.match({
2901
- onNone: () => Effect18.void,
2902
- onSome: Effect18.fail
2878
+ }).pipe(Effect21.flatMap(Option14.match({
2879
+ onNone: () => Effect21.void,
2880
+ onSome: Effect21.fail
2903
2881
  })));
2904
2882
  };
2905
2883
  const modelTurn = (turn, prompt, registry, overrides) => {
@@ -2911,32 +2889,32 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2911
2889
  let preparedState;
2912
2890
  const singleFailure = (cause) => {
2913
2891
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
2914
- return reason !== undefined && Cause4.isFailReason(reason) ? Option12.some(reason.error) : Option12.none();
2892
+ return reason !== undefined && Cause4.isFailReason(reason) ? Option14.some(reason.error) : Option14.none();
2915
2893
  };
2916
2894
  const retryableOverflow = (cause, hasEmitted) => {
2917
2895
  const failure2 = singleFailure(cause);
2918
- return retryOverflow && !hasEmitted && Option12.isSome(failure2) && classifyFailure2(failure2.value) === "context-overflow" && Option12.isSome(compactionService);
2896
+ return retryOverflow && !hasEmitted && Option14.isSome(failure2) && classifyFailure2(failure2.value) === "context-overflow" && Option14.isSome(compactionService);
2919
2897
  };
2920
2898
  return Stream4.fromChannel(Channel.acquireUseRelease(Ref5.make({
2921
2899
  nextIndex: 0,
2922
- firstIndexes: HashMap4.empty()
2923
- }), (toolCallIds) => Stream4.unwrap(Effect18.gen(function* () {
2900
+ firstIndexes: HashMap5.empty()
2901
+ }), (toolCallIds) => Stream4.unwrap(Effect21.gen(function* () {
2924
2902
  const activeModel = yield* LanguageModel5.LanguageModel;
2925
2903
  classifyFailure2 = (error) => classifyFailure(activeModel, error);
2926
2904
  const prepared = yield* preparePrompt(turn, activePrompt, compactOverflow);
2927
2905
  if (compactOverflow && !prepared.changed && overflowCause !== undefined) {
2928
- return yield* Effect18.failCause(overflowCause);
2906
+ return yield* Effect21.failCause(overflowCause);
2929
2907
  }
2930
2908
  const preparedPrompt = prepared.prompt;
2931
2909
  const history = yield* Ref5.get(chat.history);
2932
2910
  preparedState = { history, preparedPrompt };
2933
- const responsePrompt = Prompt9.concat(history, preparedPrompt);
2911
+ const responsePrompt = Prompt11.concat(history, preparedPrompt);
2934
2912
  const messages = responsePrompt.content;
2935
2913
  const rawParts = LanguageModel5.streamText({
2936
2914
  prompt: responsePrompt,
2937
2915
  toolkit: activeRegistry.toolkit,
2938
2916
  disableToolCallResolution: true
2939
- }).pipe(Stream4.tap(() => Effect18.sync(() => {
2917
+ }).pipe(Stream4.tap(() => Effect21.sync(() => {
2940
2918
  emitted = true;
2941
2919
  })), Stream4.catchCause((cause) => {
2942
2920
  if (Cause4.hasInterrupts(cause) || Cause4.hasDies(cause))
@@ -2944,18 +2922,18 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2944
2922
  if (retryableOverflow(cause, emitted))
2945
2923
  return Stream4.failCause(cause);
2946
2924
  const error = singleFailure(cause);
2947
- if (Option12.isNone(error))
2925
+ if (Option14.isNone(error))
2948
2926
  return Stream4.failCause(cause);
2949
- return Stream4.make(Response7.makePart("error", { error: error.value }));
2927
+ return Stream4.make(Response10.makePart("error", { error: error.value }));
2950
2928
  }));
2951
- return rawParts.pipe(Stream4.mapEffect((part) => transformPart(turn, part)), Stream4.flatMap(Option12.match({ onNone: () => Stream4.empty, onSome: Stream4.make })), Stream4.map((part) => ({
2929
+ return rawParts.pipe(Stream4.mapEffect((part) => transformPart(turn, part)), Stream4.flatMap(Option14.match({ onNone: () => Stream4.empty, onSome: Stream4.make })), Stream4.map((part) => ({
2952
2930
  part,
2953
2931
  messages,
2954
- accept: validateToolCallId(toolCallIds, part).pipe(Effect18.andThen(Effect18.sync(() => {
2932
+ accept: validateToolCallId(toolCallIds, part).pipe(Effect21.andThen(Effect21.sync(() => {
2955
2933
  transformedParts.push(part);
2956
2934
  })))
2957
2935
  })));
2958
- })).pipe(Stream4.toChannel), (_, exit) => preparedState === undefined || Exit2.isFailure(exit) && retryableOverflow(exit.cause, emitted) ? Effect18.void : Ref5.set(chat.history, Prompt9.concat(Prompt9.concat(preparedState.history, preparedState.preparedPrompt), Prompt9.fromResponseParts(transformedParts))).pipe(Effect18.andThen(persisted === undefined ? Effect18.void : persisted.save), Effect18.orDie, Effect18.asVoid))).pipe(Stream4.catchCause((cause) => {
2936
+ })).pipe(Stream4.toChannel), (_, exit) => preparedState === undefined || Exit2.isFailure(exit) && retryableOverflow(exit.cause, emitted) ? Effect21.void : Ref5.set(chat.history, Prompt11.concat(Prompt11.concat(preparedState.history, preparedState.preparedPrompt), Prompt11.fromResponseParts(transformedParts))).pipe(Effect21.andThen(persisted === undefined ? Effect21.void : persisted.save), Effect21.orDie, Effect21.asVoid))).pipe(Stream4.catchCause((cause) => {
2959
2937
  if (Cause4.hasInterrupts(cause) || Cause4.hasDies(cause))
2960
2938
  return Stream4.failCause(cause);
2961
2939
  if (retryableOverflow(cause, emitted)) {
@@ -2964,15 +2942,15 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2964
2942
  return Stream4.failCause(cause);
2965
2943
  }), Stream4.catchCause((cause) => {
2966
2944
  const failure2 = singleFailure(cause);
2967
- return Option12.isSome(failure2) && AiError3.isAiError(failure2.value) ? Stream4.fail(AgentError.make({ message: errorMessage(failure2.value), turn, cause: failure2.value })) : Stream4.failCause(cause);
2945
+ return Option14.isSome(failure2) && AiError4.isAiError(failure2.value) ? Stream4.fail(AgentError.make({ message: errorMessage(failure2.value), turn, cause: failure2.value })) : Stream4.failCause(cause);
2968
2946
  }));
2969
2947
  };
2970
- const parts = Stream4.unwrap(applyPromptChain(chain, Prompt9.make(prompt), { agentName: agent.name, turn }).pipe(Effect18.map((transformedPrompt) => {
2948
+ const parts = Stream4.unwrap(applyPromptChain(chain, Prompt11.make(prompt), { agentName: agent.name, turn }).pipe(Effect21.map((transformedPrompt) => {
2971
2949
  let nextToolCallIndex = 0;
2972
2950
  const calls = new Array;
2973
2951
  const executions = new Array;
2974
2952
  const toolCallBatch = { calls };
2975
- const accepted = attempt(transformedPrompt, true).pipe(Stream4.mapEffect(({ accept, part, messages }) => accept.pipe(Effect18.as({ part, messages }))), Stream4.map(({ part, messages }) => {
2953
+ const accepted = attempt(transformedPrompt, true).pipe(Stream4.mapEffect(({ accept, part, messages }) => accept.pipe(Effect21.as({ part, messages }))), Stream4.map(({ part, messages }) => {
2976
2954
  const toolCallIndex = nextToolCallIndex;
2977
2955
  if (part.type === "tool-call" && part.providerExecuted !== true) {
2978
2956
  const call = part;
@@ -2990,9 +2968,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
2990
2968
  return concurrency === 1 ? executionStreams.pipe(Stream4.flatMap(({ call, messages, toolCallIndex }) => toolCallEvents(turn, toolCallBatch, toolCallIndex, call, messages, activeRegistry)), Stream4.tap(recordPending)) : executionStreams.pipe(Stream4.mapEffect(({ call, messages, toolCallIndex }) => Stream4.runCollect(toolCallEvents(turn, toolCallBatch, toolCallIndex, call, messages, activeRegistry)), { concurrency }), Stream4.flatMap(Stream4.fromIterable), Stream4.tap(recordPending));
2991
2969
  }));
2992
2970
  })));
2993
- const resilientParts = Option12.match(resilienceService, {
2971
+ const resilientParts = Option14.match(resilienceService, {
2994
2972
  onNone: () => parts,
2995
- onSome: (resilience) => Stream4.unwrap(LanguageModel5.LanguageModel.pipe(Effect18.map((model) => parts.pipe(Stream4.provideService(LanguageModel5.LanguageModel, apply(model, {
2973
+ onSome: (resilience) => Stream4.unwrap(LanguageModel5.LanguageModel.pipe(Effect21.map((model) => parts.pipe(Stream4.provideService(LanguageModel5.LanguageModel, apply(model, {
2996
2974
  ...resilience,
2997
2975
  classify: (error) => classifyFailure(model, error) === "context-overflow" ? "terminal" : resilience.classify(error)
2998
2976
  }))))))
@@ -3012,30 +2990,30 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
3012
2990
  transcript,
3013
2991
  ...state.usage === undefined ? {} : { usage: state.usage }
3014
2992
  });
3015
- const structuredFinalEvents = (structuredTurn, config) => Stream4.fromEffect(Effect18.gen(function* () {
3016
- const transformedPrompt = yield* applyPromptChain(chain, Prompt9.make(config.objectPrompt), {
2993
+ const structuredFinalEvents = (structuredTurn, config) => Stream4.fromEffect(Effect21.gen(function* () {
2994
+ const transformedPrompt = yield* applyPromptChain(chain, Prompt11.make(config.objectPrompt), {
3017
2995
  agentName: agent.name,
3018
2996
  turn: structuredTurn
3019
2997
  });
3020
2998
  const history = yield* Ref5.get(chat.history);
3021
2999
  const response = yield* LanguageModel5.generateObject({
3022
- prompt: Prompt9.concat(history, transformedPrompt),
3000
+ prompt: Prompt11.concat(history, transformedPrompt),
3023
3001
  schema: config.schema,
3024
3002
  objectName: config.objectName,
3025
3003
  toolChoice: "none"
3026
- }).pipe(withModelResilience, withAgentModel, Effect18.catchCause((cause) => {
3004
+ }).pipe(withModelResilience, withAgentModel, Effect21.catchCause((cause) => {
3027
3005
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
3028
- return reason !== undefined && Cause4.isFailReason(reason) ? Effect18.fail(AgentError.make({
3006
+ return reason !== undefined && Cause4.isFailReason(reason) ? Effect21.fail(AgentError.make({
3029
3007
  message: errorMessage(reason.error),
3030
3008
  turn: structuredTurn,
3031
3009
  cause: reason.error
3032
- })) : Effect18.failCause(cause);
3010
+ })) : Effect21.failCause(cause);
3033
3011
  }));
3034
3012
  yield* captureStructuredUsage(response.content);
3035
- const transcript = Prompt9.concat(Prompt9.concat(history, transformedPrompt), Prompt9.fromResponseParts(response.content));
3013
+ const transcript = Prompt11.concat(Prompt11.concat(history, transformedPrompt), Prompt11.fromResponseParts(response.content));
3036
3014
  const path = yield* syncSession(structuredTurn, history);
3037
- yield* applyCompactionResult(structuredTurn, { _tag: "Microcompact", history: transcript, prompt: Prompt9.empty }, path.at(-1)?.id ?? null);
3038
- if (Option12.isNone(activeSession))
3015
+ yield* applyCompactionResult(structuredTurn, { _tag: "Microcompact", history: transcript, prompt: Prompt11.empty }, path.at(-1)?.id ?? null);
3016
+ if (Option14.isNone(activeSession))
3039
3017
  yield* savePersisted(structuredTurn);
3040
3018
  const structuredOutput = {
3041
3019
  _tag: "StructuredOutput",
@@ -3045,16 +3023,16 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
3045
3023
  };
3046
3024
  return [structuredOutput, terminalCompletedEvent(structuredTurn, transcript)];
3047
3025
  })).pipe(Stream4.flatMap((events) => Stream4.fromIterable(events)));
3048
- const promptFromSteeringMessages = (messages) => messages.reduce((prompt, message) => Prompt9.concat(prompt, message.prompt), Prompt9.empty);
3049
- const takeSteering = () => Option12.match(steeringService, {
3050
- onNone: () => Effect18.succeed([]),
3026
+ const promptFromSteeringMessages = (messages) => messages.reduce((prompt, message) => Prompt11.concat(prompt, message.prompt), Prompt11.empty);
3027
+ const takeSteering = () => Option14.match(steeringService, {
3028
+ onNone: () => Effect21.succeed([]),
3051
3029
  onSome: (service) => service.takeSteering
3052
3030
  });
3053
- const takeFollowUp = () => Option12.match(steeringService, {
3054
- onNone: () => Effect18.succeed([]),
3031
+ const takeFollowUp = () => Option14.match(steeringService, {
3032
+ onNone: () => Effect21.succeed([]),
3055
3033
  onSome: (service) => service.takeFollowUp
3056
3034
  });
3057
- const afterTurn = (turn) => Effect18.gen(function* () {
3035
+ const afterTurn = (turn) => Effect21.gen(function* () {
3058
3036
  const pending = state.pending;
3059
3037
  const transcript = yield* checkpointPending(turn, pending);
3060
3038
  const path = yield* syncSession(turn, transcript);
@@ -3110,7 +3088,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
3110
3088
  }
3111
3089
  state.pending = [];
3112
3090
  const steering = yield* takeSteering();
3113
- const basePrompt = steering.length === 0 ? Prompt9.empty : promptFromSteeringMessages(steering);
3091
+ const basePrompt = steering.length === 0 ? Prompt11.empty : promptFromSteeringMessages(steering);
3114
3092
  const prompt = decision2.overrides?.instructions === undefined ? basePrompt : withSystem(decision2.overrides.instructions, basePrompt);
3115
3093
  return {
3116
3094
  events: Stream4.fromIterable(steering.length === 0 ? [completed] : [completed, steeringDrainedEvent(turn, "steering", steering)]),
@@ -3124,7 +3102,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
3124
3102
  const runTurn = (turn, prompt, overrides) => {
3125
3103
  let next;
3126
3104
  let structuredTurn;
3127
- const currentTurn = Stream4.fromIterable([{ _tag: "TurnStarted", turn }]).pipe(Stream4.concat(resetTurnState(turn)), Stream4.concat(Stream4.unwrap(Ref5.get(toolState).pipe(Effect18.map(({ registry }) => modelTurn(turn, prompt, registry, overrides))))), Stream4.concat(Stream4.unwrap(afterTurn(turn).pipe(Effect18.map((result) => {
3105
+ const currentTurn = Stream4.fromIterable([{ _tag: "TurnStarted", turn }]).pipe(Stream4.concat(resetTurnState(turn)), Stream4.concat(Stream4.unwrap(Ref5.get(toolState).pipe(Effect21.map(({ registry }) => modelTurn(turn, prompt, registry, overrides))))), Stream4.concat(Stream4.unwrap(afterTurn(turn).pipe(Effect21.map((result) => {
3128
3106
  next = result.next;
3129
3107
  structuredTurn = result.structuredTurn;
3130
3108
  return result.events;
@@ -3138,10 +3116,10 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
3138
3116
  };
3139
3117
  const resumeStream = (checkpoint) => {
3140
3118
  let next;
3141
- const currentTurn = resetTurnState(0).pipe(Stream4.concat(Stream4.unwrap(Ref5.get(toolState).pipe(Effect18.map((tools) => {
3119
+ const currentTurn = resetTurnState(0).pipe(Stream4.concat(Stream4.unwrap(Ref5.get(toolState).pipe(Effect21.map((tools) => {
3142
3120
  const suspension2 = checkpoint.suspension;
3143
3121
  const registry = suspension2.authorization_stage === undefined && suspension2.active_tools === undefined ? tools.registry : select(tools.registry, suspension2.active_tools ?? []);
3144
- const calls = suspension2.tool_call_batch.map((call) => Response7.makePart("tool-call", {
3122
+ const calls = suspension2.tool_call_batch.map((call) => Response10.makePart("tool-call", {
3145
3123
  id: call.id,
3146
3124
  name: call.name,
3147
3125
  params: call.params,
@@ -3157,23 +3135,23 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
3157
3135
  const execute = ({ call, toolCallIndex }) => toolCallEvents(0, toolCallBatch, toolCallIndex, call, checkpoint.messages, registry, toolCallIndex === startIndex ? suspension2.authorization_stage : undefined, toolCallIndex === startIndex ? suspension2.token : undefined);
3158
3136
  const concurrency = agent.toolExecution?.concurrency ?? 1;
3159
3137
  return concurrency === 1 ? executions.pipe(Stream4.flatMap(execute), Stream4.tap(recordPending)) : executions.pipe(Stream4.mapEffect((execution) => Stream4.runCollect(execute(execution)), { concurrency }), Stream4.flatMap(Stream4.fromIterable), Stream4.tap(recordPending));
3160
- })))), Stream4.concat(Stream4.unwrap(afterTurn(0).pipe(Effect18.map((result) => {
3138
+ })))), Stream4.concat(Stream4.unwrap(afterTurn(0).pipe(Effect21.map((result) => {
3161
3139
  next = result.next;
3162
3140
  return result.events;
3163
3141
  })))), Stream4.withSpan("Baton.Agent.turn", { attributes: { "baton.turn": 0 } }));
3164
3142
  return Stream4.concat(currentTurn, Stream4.suspend(() => next === undefined ? Stream4.empty : runTurn(1, next.prompt, next.overrides)));
3165
3143
  };
3166
- const baseInitialPrompt = seedSystem === undefined ? Prompt9.make(options.prompt) : withSystem(seedSystem, Prompt9.make(options.prompt));
3144
+ const baseInitialPrompt = seedSystem === undefined ? Prompt11.make(options.prompt) : withSystem(seedSystem, Prompt11.make(options.prompt));
3167
3145
  const initialPrompt = options.resume === undefined ? yield* recallInitialPrompt(baseInitialPrompt) : baseInitialPrompt;
3168
3146
  const runStream = validatedResume === undefined ? runTurn(0, initialPrompt) : resumeStream(validatedResume);
3169
3147
  return runStream.pipe(Stream4.catchCause((cause) => {
3170
3148
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
3171
- if (reason !== undefined && Cause4.isFailReason(reason) && Schema14.is(DuplicateToolCallId)(reason.error)) {
3172
- return Stream4.unwrap(checkpointPending(state.turn, state.pending).pipe(Effect18.map(() => Stream4.failCause(cause))));
3149
+ if (reason !== undefined && Cause4.isFailReason(reason) && Schema18.is(DuplicateToolCallId)(reason.error)) {
3150
+ return Stream4.unwrap(checkpointPending(state.turn, state.pending).pipe(Effect21.map(() => Stream4.failCause(cause))));
3173
3151
  }
3174
- if (reason !== undefined && Cause4.isFailReason(reason) && Schema14.is(AgentSuspended)(reason.error)) {
3152
+ if (reason !== undefined && Cause4.isFailReason(reason) && Schema18.is(AgentSuspended)(reason.error)) {
3175
3153
  const suspension2 = reason.error;
3176
- return Stream4.unwrap(Effect18.gen(function* () {
3154
+ return Stream4.unwrap(Effect21.gen(function* () {
3177
3155
  const checkpoint = yield* checkpointSuspended(state.turn, state.pending, suspension2);
3178
3156
  yield* syncSession(state.turn, checkpoint);
3179
3157
  return Stream4.concat(Stream4.fromIterable([turnCompletedEvent(state.turn, checkpoint)]), Stream4.failCause(cause));
@@ -3182,6 +3160,45 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect18.gen
3182
3160
  return Stream4.failCause(cause);
3183
3161
  }));
3184
3162
  })).pipe(Stream4.withSpan("Baton.Agent.run", { attributes: { "baton.agent.name": agent.name } }), (run) => agent[ModelLayerTypeId] === undefined ? run : run.pipe(Stream4.provide(agent[ModelLayerTypeId])));
3163
+
3164
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent.js
3165
+ var AgentTypeId = Symbol.for("@batonfx/core/Agent");
3166
+ function make5(options) {
3167
+ const declaredTools = "tools" in options && Array.isArray(options.tools) ? options.tools : undefined;
3168
+ const toolkit = declaredTools === undefined ? options.toolkit ?? Toolkit5.empty : Toolkit5.make(...declaredTools);
3169
+ if (declaredTools !== undefined) {
3170
+ for (const tool of declaredTools) {
3171
+ if (!Object.hasOwn(toolkit.tools, tool.name)) {
3172
+ Object.defineProperty(toolkit.tools, tool.name, {
3173
+ configurable: true,
3174
+ enumerable: true,
3175
+ value: tool,
3176
+ writable: true
3177
+ });
3178
+ }
3179
+ }
3180
+ }
3181
+ return {
3182
+ [AgentTypeId]: {
3183
+ tools: (value) => value,
3184
+ requirements: (value) => value
3185
+ },
3186
+ name: options.name,
3187
+ ...options.instructions === undefined ? {} : { instructions: options.instructions },
3188
+ toolkit,
3189
+ policy: options.policy ?? defaultPolicy,
3190
+ ...options.model === undefined ? {} : { model: options.model },
3191
+ ...options.memory === undefined ? {} : { memory: options.memory },
3192
+ ...options.authorization === undefined ? {} : { authorization: options.authorization },
3193
+ ...options.toolExecution === undefined ? {} : { toolExecution: options.toolExecution },
3194
+ ...options.metadata === undefined ? {} : { metadata: options.metadata },
3195
+ toolDeclarations: (declaredTools ?? Object.values(toolkit.tools)).map((tool) => ({
3196
+ tool,
3197
+ origin: { _tag: "Static", agent: options.name }
3198
+ }))
3199
+ };
3200
+ }
3201
+ var defaultObjectPrompt = "Return the final structured output for the task above.";
3185
3202
  var provideModel = dual7(2, (agent, layer8) => ({
3186
3203
  ...agent,
3187
3204
  policy: agent.policy,
@@ -3194,99 +3211,63 @@ var provideModel = dual7(2, (agent, layer8) => ({
3194
3211
  },
3195
3212
  [ModelLayerTypeId]: layer8
3196
3213
  }));
3197
- var stream2 = dual7(2, (agent, options) => streamInternal(agent, options, undefined));
3198
- var persisted = dual7(2, (agent, options) => streamInternal(agent, options, undefined));
3199
- var streamObject = dual7(2, (agent, options) => streamInternal(agent, options, {
3200
- schema: options.schema,
3201
- objectName: options.objectName ?? "output",
3202
- objectPrompt: options.objectPrompt ?? defaultObjectPrompt
3203
- }));
3204
- var persistedObject = dual7(2, (agent, options) => streamInternal(agent, options, {
3214
+ var stream2 = dual7(2, (agent, options) => streamInternal(agent, options, options.schema === undefined ? undefined : {
3205
3215
  schema: options.schema,
3206
3216
  objectName: options.objectName ?? "output",
3207
3217
  objectPrompt: options.objectPrompt ?? defaultObjectPrompt
3208
3218
  }));
3209
- var generate = dual7(2, (agent, options) => Stream4.runLast(stream2(agent, options)).pipe(Effect18.flatMap(Option12.match({
3210
- onNone: () => Effect18.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 })),
3211
- onSome: (event) => event._tag === "Completed" ? Effect18.succeed({ text: event.text, turns: event.turns, transcript: event.transcript }) : Effect18.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 }))
3212
- }))));
3213
- var generatePersisted = dual7(2, (agent, options) => Stream4.runLast(persisted(agent, options)).pipe(Effect18.flatMap(Option12.match({
3214
- onNone: () => Effect18.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 })),
3215
- onSome: (event) => event._tag === "Completed" ? Effect18.succeed({ text: event.text, turns: event.turns, transcript: event.transcript }) : Effect18.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 }))
3216
- }))));
3217
- var generateObject = dual7(2, (agent, options) => Stream4.runFold(streamObject(agent, options), () => ({
3218
- value: Option12.none(),
3219
- completed: Option12.none()
3220
- }), (acc, event) => {
3221
- if (event._tag === "StructuredOutput") {
3222
- return { ...acc, value: Option12.some(event.value) };
3223
- }
3224
- if (event._tag === "Completed") {
3225
- return { ...acc, completed: Option12.some(event) };
3226
- }
3227
- return acc;
3228
- }).pipe(Effect18.flatMap(({ value, completed }) => Option12.match(completed, {
3229
- onNone: () => Effect18.fail(AgentError.make({ message: "Agent object run ended without a Completed event", turn: 0 })),
3230
- onSome: (event) => Option12.match(value, {
3231
- onNone: () => Effect18.fail(AgentError.make({
3232
- message: "Agent object run ended without a StructuredOutput event",
3233
- turn: 0
3234
- })),
3235
- onSome: (typedValue) => Effect18.succeed({
3236
- text: event.text,
3237
- turns: event.turns,
3238
- transcript: event.transcript,
3239
- value: typedValue
3240
- })
3241
- })
3242
- }))));
3243
- var generatePersistedObject = dual7(2, (agent, options) => Stream4.runFold(persistedObject(agent, options), () => ({ value: Option12.none(), completed: Option12.none() }), (acc, event) => event._tag === "StructuredOutput" ? { ...acc, value: Option12.some(event.value) } : event._tag === "Completed" ? { ...acc, completed: Option12.some(event) } : acc).pipe(Effect18.flatMap(({ value, completed }) => Option12.match(completed, {
3244
- onNone: () => Effect18.fail(AgentError.make({ message: "Agent object run ended without a Completed event", turn: 0 })),
3245
- onSome: (event) => Option12.match(value, {
3246
- onNone: () => Effect18.fail(AgentError.make({ message: "Agent object run ended without a StructuredOutput event", turn: 0 })),
3247
- onSome: (typedValue) => Effect18.succeed({
3219
+ var generateText = (agent, options) => Stream5.runLast(stream2(agent, options)).pipe(Effect22.flatMap(Option15.match({
3220
+ onNone: () => Effect22.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 })),
3221
+ onSome: (event) => event._tag === "Completed" ? Effect22.succeed({ text: event.text, turns: event.turns, transcript: event.transcript }) : Effect22.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 }))
3222
+ })));
3223
+ var generateObjectResult = (agent, options) => Stream5.runFold(stream2(agent, options), () => ({ value: Option15.none(), completed: Option15.none() }), (acc, event) => event._tag === "StructuredOutput" ? { ...acc, value: Option15.some(event.value) } : event._tag === "Completed" ? { ...acc, completed: Option15.some(event) } : acc).pipe(Effect22.flatMap(({ value, completed }) => Option15.match(completed, {
3224
+ onNone: () => Effect22.fail(AgentError.make({ message: "Agent object run ended without a Completed event", turn: 0 })),
3225
+ onSome: (event) => Option15.match(value, {
3226
+ onNone: () => Effect22.fail(AgentError.make({ message: "Agent object run ended without a StructuredOutput event", turn: 0 })),
3227
+ onSome: (typedValue) => Effect22.succeed({
3248
3228
  text: event.text,
3249
3229
  turns: event.turns,
3250
3230
  transcript: event.transcript,
3251
3231
  value: typedValue
3252
3232
  })
3253
3233
  })
3254
- }))));
3234
+ })));
3235
+ var generate = dual7(2, (agent, options) => options.schema === undefined ? generateText(agent, options) : generateObjectResult(agent, options));
3255
3236
 
3256
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/agent-tool.js
3237
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-tool.js
3257
3238
  var exports_agent_tool = {};
3258
3239
  __export(exports_agent_tool, {
3259
3240
  asTool: () => asTool
3260
3241
  });
3261
- import { Cause as Cause5, Effect as Effect19, Function as Function7, Schema as Schema15 } from "effect";
3262
- import { Prompt as Prompt10, Tool as Tool8, Toolkit as Toolkit5 } from "effect/unstable/ai";
3263
- var defaultParameters = Schema15.Struct({ prompt: Schema15.String });
3242
+ import { Cause as Cause5, Effect as Effect23, Function as Function7, Schema as Schema20 } from "effect";
3243
+ import { Prompt as Prompt13, Tool as Tool12, Toolkit as Toolkit6 } from "effect/unstable/ai";
3244
+ var defaultParameters = Schema20.Struct({ prompt: Schema20.String });
3264
3245
  var errorMessage2 = (error) => {
3265
- if (Schema15.is(AgentSuspended)(error)) {
3246
+ if (Schema20.is(AgentSuspended)(error)) {
3266
3247
  return `suspended on ${error.tool_name}: ${error.reason}`;
3267
3248
  }
3268
- if (Schema15.is(AgentError)(error)) {
3249
+ if (Schema20.is(AgentError)(error)) {
3269
3250
  return `failed on turn ${error.turn}: ${error.message}`;
3270
3251
  }
3271
- if (Schema15.is(ResumeMismatch)(error)) {
3252
+ if (Schema20.is(ResumeMismatch)(error)) {
3272
3253
  return `resume mismatch: ${error.reason}`;
3273
3254
  }
3274
- if (Schema15.is(TurnLimitExceeded)(error)) {
3255
+ if (Schema20.is(TurnLimitExceeded)(error)) {
3275
3256
  return `turn limit exceeded at turn ${error.turn}`;
3276
3257
  }
3277
- if (Schema15.is(TurnPolicyStopped)(error)) {
3258
+ if (Schema20.is(TurnPolicyStopped)(error)) {
3278
3259
  return `policy stopped at turn ${error.turn}: ${error.reason._tag}`;
3279
3260
  }
3280
- if (Schema15.is(TurnPolicyError)(error)) {
3261
+ if (Schema20.is(TurnPolicyError)(error)) {
3281
3262
  return `turn policy failed: ${error.message}`;
3282
3263
  }
3283
- if (Schema15.is(MiddlewareViolation)(error)) {
3264
+ if (Schema20.is(MiddlewareViolation)(error)) {
3284
3265
  return `middleware violation on turn ${error.turn}: ${error.detail}`;
3285
3266
  }
3286
- if (Schema15.is(DuplicateToolCallId)(error)) {
3267
+ if (Schema20.is(DuplicateToolCallId)(error)) {
3287
3268
  return `duplicate tool-call ID '${error.id}' at position ${error.duplicateIndex} (first at ${error.firstIndex})`;
3288
3269
  }
3289
- if (Schema15.is(ToolNameCollision)(error)) {
3270
+ if (Schema20.is(ToolNameCollision)(error)) {
3290
3271
  return `tool name collision: ${error.name} (${error.origins.map((origin) => origin._tag === "Static" ? `static:${origin.agent}` : origin._tag === "Builtin" ? `builtin:${origin.builtin}` : origin._tag === "Skill" ? `skill:${origin.skill}` : `handoff:${origin.specialist}`).join(", ")})`;
3291
3272
  }
3292
3273
  return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
@@ -3296,35 +3277,35 @@ var lazyHandled = (toolkit, name, handler) => ({
3296
3277
  tools: toolkit.tools,
3297
3278
  handle: (toolName, params) => toolkit.toHandlers({
3298
3279
  [name]: handler
3299
- }).pipe(Effect19.flatMap((handlers) => toolkit.pipe(Effect19.provide(handlers))), Effect19.flatMap((handled) => handled.handle(toolName, params)))
3280
+ }).pipe(Effect23.flatMap((handlers) => toolkit.pipe(Effect23.provide(handlers))), Effect23.flatMap((handled) => handled.handle(toolName, params)))
3300
3281
  });
3301
3282
  var asTool = Function7.dual((args) => args.length !== 1 || ("name" in args[0]), (agent, options = {}) => {
3302
3283
  const name = options.name ?? agent.name;
3303
3284
  const parameters = options.parameters ?? defaultParameters;
3304
- const success2 = options.success ?? Schema15.String;
3285
+ const success2 = options.success ?? Schema20.String;
3305
3286
  const toPrompt = options.toPrompt ?? ((params) => params.prompt);
3306
3287
  const fromResult = options.fromResult ?? ((result) => result.text);
3307
- const tool = Tool8.make(name, {
3288
+ const tool = Tool12.make(name, {
3308
3289
  ...options.description === undefined ? {} : { description: options.description },
3309
3290
  parameters,
3310
3291
  success: success2,
3311
- failure: Schema15.String,
3292
+ failure: Schema20.String,
3312
3293
  failureMode: "return"
3313
3294
  });
3314
- const toolkit = Toolkit5.make(tool);
3315
- const handler = (params) => Effect19.gen(function* () {
3316
- const prompt = yield* Effect19.try({ try: () => toPrompt(params), catch: errorMessage2 });
3317
- const result = yield* generate(agent, { prompt }).pipe(Effect19.catchCause((cause) => {
3295
+ const toolkit = Toolkit6.make(tool);
3296
+ const handler = (params) => Effect23.gen(function* () {
3297
+ const prompt = yield* Effect23.try({ try: () => toPrompt(params), catch: errorMessage2 });
3298
+ const result = yield* generate(agent, { prompt }).pipe(Effect23.catchCause((cause) => {
3318
3299
  if (Cause5.hasInterrupts(cause))
3319
- return Effect19.interrupt;
3320
- return Effect19.fail(causeMessage(agent.name, cause));
3300
+ return Effect23.interrupt;
3301
+ return Effect23.fail(causeMessage(agent.name, cause));
3321
3302
  }));
3322
- return yield* Effect19.try({ try: () => fromResult(result), catch: errorMessage2 });
3303
+ return yield* Effect23.try({ try: () => fromResult(result), catch: errorMessage2 });
3323
3304
  });
3324
3305
  return lazyHandled(toolkit, name, handler);
3325
3306
  });
3326
3307
 
3327
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/guardrail.js
3308
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/guardrail.js
3328
3309
  var exports_guardrail = {};
3329
3310
  __export(exports_guardrail, {
3330
3311
  validateInput: () => validateInput,
@@ -3332,17 +3313,17 @@ __export(exports_guardrail, {
3332
3313
  redactInput: () => redactInput,
3333
3314
  filterOutput: () => filterOutput
3334
3315
  });
3335
- import { Effect as Effect20, Option as Option13 } from "effect";
3336
- import { Prompt as Prompt11, Response as Response8 } from "effect/unstable/ai";
3316
+ import { Effect as Effect24, Option as Option16 } from "effect";
3317
+ import { Prompt as Prompt14, Response as Response11 } from "effect/unstable/ai";
3337
3318
  var replacement = (options) => options.replacement ?? "[redacted]";
3338
3319
  var redactText = (text, options) => text.replace(options.pattern, replacement(options));
3339
- var redactUserPart = (part, options) => part.type === "text" ? Prompt11.makePart("text", { text: redactText(part.text, options), options: part.options }) : part;
3320
+ var redactUserPart = (part, options) => part.type === "text" ? Prompt14.makePart("text", { text: redactText(part.text, options), options: part.options }) : part;
3340
3321
  var redactAssistantPart = (part, options) => {
3341
3322
  switch (part.type) {
3342
3323
  case "text":
3343
- return Prompt11.makePart("text", { text: redactText(part.text, options), options: part.options });
3324
+ return Prompt14.makePart("text", { text: redactText(part.text, options), options: part.options });
3344
3325
  case "reasoning":
3345
- return Prompt11.makePart("reasoning", { text: redactText(part.text, options), options: part.options });
3326
+ return Prompt14.makePart("reasoning", { text: redactText(part.text, options), options: part.options });
3346
3327
  default:
3347
3328
  return part;
3348
3329
  }
@@ -3350,51 +3331,51 @@ var redactAssistantPart = (part, options) => {
3350
3331
  var redactToolPart = (part, options) => {
3351
3332
  if (part.type !== "tool-approval-response" || part.reason === undefined)
3352
3333
  return part;
3353
- return Prompt11.makePart("tool-approval-response", {
3334
+ return Prompt14.makePart("tool-approval-response", {
3354
3335
  approvalId: part.approvalId,
3355
3336
  approved: part.approved,
3356
3337
  reason: redactText(part.reason, options),
3357
3338
  options: part.options
3358
3339
  });
3359
3340
  };
3360
- var redactPromptText = (prompt, options) => Prompt11.fromMessages(prompt.content.map((message) => {
3341
+ var redactPromptText = (prompt, options) => Prompt14.fromMessages(prompt.content.map((message) => {
3361
3342
  switch (message.role) {
3362
3343
  case "system":
3363
- return Prompt11.makeMessage("system", {
3344
+ return Prompt14.makeMessage("system", {
3364
3345
  content: redactText(message.content, options),
3365
3346
  options: message.options
3366
3347
  });
3367
3348
  case "user":
3368
- return isMessageFromRecall(message) ? replaceRecalledMessage(message, message.content.map((part) => redactUserPart(part, options))) : Prompt11.makeMessage("user", {
3349
+ return isMessageFromRecall(message) ? replaceRecalledMessage(message, message.content.map((part) => redactUserPart(part, options))) : Prompt14.makeMessage("user", {
3369
3350
  content: message.content.map((part) => redactUserPart(part, options)),
3370
3351
  options: message.options
3371
3352
  });
3372
3353
  case "assistant":
3373
- return Prompt11.makeMessage("assistant", {
3354
+ return Prompt14.makeMessage("assistant", {
3374
3355
  content: message.content.map((part) => redactAssistantPart(part, options)),
3375
3356
  options: message.options
3376
3357
  });
3377
3358
  case "tool":
3378
- return Prompt11.makeMessage("tool", {
3359
+ return Prompt14.makeMessage("tool", {
3379
3360
  content: message.content.map((part) => redactToolPart(part, options)),
3380
3361
  options: message.options
3381
3362
  });
3382
3363
  }
3383
3364
  }));
3384
3365
  var validateInput = (check) => ({
3385
- transformPrompt: (prompt, context) => check(prompt, context).pipe(Effect20.flatMap(Option13.match({
3386
- onNone: () => Effect20.succeed(prompt),
3387
- onSome: (reason) => Effect20.fail(AgentError.make({ message: `Input guardrail blocked: ${reason}`, turn: context.turn }))
3366
+ transformPrompt: (prompt, context) => check(prompt, context).pipe(Effect24.flatMap(Option16.match({
3367
+ onNone: () => Effect24.succeed(prompt),
3368
+ onSome: (reason) => Effect24.fail(AgentError.make({ message: `Input guardrail blocked: ${reason}`, turn: context.turn }))
3388
3369
  })))
3389
3370
  });
3390
3371
  var redactInput = (options) => ({
3391
- transformPrompt: (prompt) => Effect20.succeed(redactPromptText(prompt, options))
3372
+ transformPrompt: (prompt) => Effect24.succeed(redactPromptText(prompt, options))
3392
3373
  });
3393
3374
  var redactOutput = (options) => ({
3394
3375
  transformPart: (part) => {
3395
3376
  if (part.type !== "text-delta")
3396
- return Effect20.succeed(Option13.some(part));
3397
- return Effect20.succeed(Option13.some(Response8.makePart("text-delta", {
3377
+ return Effect24.succeed(Option16.some(part));
3378
+ return Effect24.succeed(Option16.some(Response11.makePart("text-delta", {
3398
3379
  id: part.id,
3399
3380
  delta: redactText(part.delta, options),
3400
3381
  metadata: part.metadata
@@ -3402,23 +3383,23 @@ var redactOutput = (options) => ({
3402
3383
  }
3403
3384
  });
3404
3385
  var filterOutput = (keep) => ({
3405
- transformPart: (part, context) => Effect20.succeed(part.type === "tool-call" || keep(part, context) ? Option13.some(part) : Option13.none())
3386
+ transformPart: (part, context) => Effect24.succeed(part.type === "tool-call" || keep(part, context) ? Option16.some(part) : Option16.none())
3406
3387
  });
3407
3388
 
3408
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/handoff.js
3389
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/handoff.js
3409
3390
  var exports_handoff = {};
3410
3391
  __export(exports_handoff, {
3411
3392
  transferTool: () => transferTool,
3412
3393
  supervisor: () => supervisor,
3413
3394
  fanOut: () => fanOut
3414
3395
  });
3415
- import { Effect as Effect21, Function as Function8, Schema as Schema16 } from "effect";
3416
- import { AiError as AiError4, LanguageModel as LanguageModel6, Prompt as Prompt12, Tool as Tool9, Toolkit as Toolkit6 } from "effect/unstable/ai";
3417
- var defaultTransferParameters = Schema16.Struct({ prompt: Schema16.String });
3396
+ import { Effect as Effect25, Function as Function8, Schema as Schema21 } from "effect";
3397
+ import { AiError as AiError6, LanguageModel as LanguageModel7, Prompt as Prompt15, Tool as Tool13, Toolkit as Toolkit7 } from "effect/unstable/ai";
3398
+ var defaultTransferParameters = Schema21.Struct({ prompt: Schema21.String });
3418
3399
  var transferName = (agentName) => `transfer_to_${agentName}`;
3419
3400
  var positiveConcurrency = (value) => {
3420
3401
  const concurrency = value ?? 4;
3421
- return Number.isInteger(concurrency) && concurrency > 0 ? Effect21.succeed(concurrency) : Effect21.fail(AgentError.make({
3402
+ return Number.isInteger(concurrency) && concurrency > 0 ? Effect25.succeed(concurrency) : Effect25.fail(AgentError.make({
3422
3403
  message: "Handoff.fanOut concurrency must be a positive integer",
3423
3404
  turn: 0
3424
3405
  }));
@@ -3436,10 +3417,10 @@ var mergeHandled = (toolkits) => {
3436
3417
  tools,
3437
3418
  handle: (name, params) => {
3438
3419
  const entry = entries.get(String(name));
3439
- return entry === undefined ? Effect21.fail(AiError4.make({
3420
+ return entry === undefined ? Effect25.fail(AiError6.make({
3440
3421
  module: "Handoff",
3441
3422
  method: `${String(name)}.handle`,
3442
- reason: AiError4.ToolNotFoundError.make({
3423
+ reason: AiError6.ToolNotFoundError.make({
3443
3424
  toolName: String(name),
3444
3425
  availableTools: Object.keys(tools)
3445
3426
  })
@@ -3447,7 +3428,7 @@ var mergeHandled = (toolkits) => {
3447
3428
  }
3448
3429
  };
3449
3430
  };
3450
- var toolkitFromHandled = (toolkit) => Toolkit6.make(...Object.values(toolkit.tools));
3431
+ var toolkitFromHandled = (toolkit) => Toolkit7.make(...Object.values(toolkit.tools));
3451
3432
  var transferTool = Function8.dual((args) => args.length !== 1 || ("name" in args[0]), (target, options = {}) => asTool(target, {
3452
3433
  name: options.nameOverride ?? transferName(target.name),
3453
3434
  description: options.description ?? `Transfer to ${target.name}`,
@@ -3456,7 +3437,7 @@ var transferTool = Function8.dual((args) => args.length !== 1 || ("name" in args
3456
3437
  ...options.toPrompt === undefined ? {} : { toPrompt: options.toPrompt },
3457
3438
  ...options.fromResult === undefined ? {} : { fromResult: options.fromResult }
3458
3439
  }));
3459
- var fanOut = Function8.dual((args) => args.length !== 1 || Array.isArray(args[0]), (children, options = {}) => positiveConcurrency(options.concurrency).pipe(Effect21.flatMap((concurrency) => Effect21.forEach(children, (child) => {
3440
+ var fanOut = Function8.dual((args) => args.length !== 1 || Array.isArray(args[0]), (children, options = {}) => positiveConcurrency(options.concurrency).pipe(Effect25.flatMap((concurrency) => Effect25.forEach(children, (child) => {
3460
3441
  const runOptions = {
3461
3442
  ...child.options,
3462
3443
  prompt: child.prompt
@@ -3485,7 +3466,7 @@ var supervisor = (options) => {
3485
3466
  };
3486
3467
  };
3487
3468
 
3488
- // ../../node_modules/.bun/@batonfx+core@0.6.4/node_modules/@batonfx/core/dist/index.js
3489
- import { AiError as AiError5, Chat as Chat2, EmbeddingModel, IdGenerator, LanguageModel as LanguageModel7, Model as Model2, Prompt as Prompt13, Response as Response9, ResponseIdTracker, Telemetry as Telemetry2, Tokenizer as Tokenizer3, Tool as Tool10, Toolkit as Toolkit7 } from "effect/unstable/ai";
3469
+ // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/index.js
3470
+ import { AiError as AiError7, Chat as Chat4, EmbeddingModel, IdGenerator, LanguageModel as LanguageModel8, Model as Model2, Prompt as Prompt16, Response as Response12, ResponseIdTracker, Telemetry as Telemetry2, Tokenizer as Tokenizer3, Tool as Tool14, Toolkit as Toolkit8 } from "effect/unstable/ai";
3490
3471
 
3491
- export { exports_turn_policy, exports_agent_event, exports_tool_context, exports_tool_executor, exports_approvals, exports_memory, exports_session, exports_tool_output, exports_compaction, exports_instructions, exports_model_middleware, exports_model_registry, exports_model_resilience, exports_permissions, exports_skill_source, exports_steering, exports_agent, exports_agent_tool, exports_guardrail, exports_handoff, AiError5 as AiError, Chat2 as Chat, EmbeddingModel, IdGenerator, Model2 as Model, Prompt13 as Prompt, Response9 as Response, ResponseIdTracker, Telemetry2 as Telemetry, Tokenizer3 as Tokenizer, Tool10 as Tool, Toolkit7 as Toolkit };
3472
+ export { exports_turn_policy, exports_agent_event, exports_memory, exports_model_registry, exports_tool_context, exports_tool_executor, exports_approvals, exports_session, exports_tool_output, exports_compaction, exports_instructions, exports_model_middleware, exports_model_resilience, exports_permissions, exports_skill_source, exports_steering, exports_agent, exports_agent_tool, exports_guardrail, exports_handoff, AiError7 as AiError, Chat4 as Chat, EmbeddingModel, IdGenerator, Model2 as Model, Prompt16 as Prompt, Response12 as Response, ResponseIdTracker, Telemetry2 as Telemetry, Tokenizer3 as Tokenizer, Tool14 as Tool, Toolkit8 as Toolkit };