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