@relayfx/sdk 0.5.0 → 0.6.1

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 (27) hide show
  1. package/dist/ai.js +1 -1
  2. package/dist/{index-x32kbvxv.js → index-5vjhqzbk.js} +995 -958
  3. package/dist/{index-h1cf8za4.js → index-dm4yqr8f.js} +1 -1
  4. package/dist/{index-8asvg7x0.js → index-ftgf8py0.js} +888 -706
  5. package/dist/index.js +269 -117
  6. package/dist/migrations/20260721170000_session_writer_ownership/migration.sql +5 -0
  7. package/dist/migrations/mysql/0014_session_writer_ownership.sql +5 -0
  8. package/dist/migrations/pg/20260721170000_session_writer_ownership/migration.sql +5 -0
  9. package/dist/migrations/sqlite/0014_session_writer_ownership.sql +5 -0
  10. package/dist/mysql.js +13 -4
  11. package/dist/postgres.js +9 -5
  12. package/dist/sqlite.js +13 -4
  13. package/dist/types/ai/language-model/language-model-registration.d.ts +23 -11
  14. package/dist/types/relay/language-model-registration.d.ts +25 -11
  15. package/dist/types/relay/mysql-migrations.d.ts +1 -1
  16. package/dist/types/relay/sqlite-migrations.d.ts +6 -1
  17. package/dist/types/runtime/agent/agent-loop-error.d.ts +1 -1
  18. package/dist/types/runtime/agent/relay-permissions.d.ts +2 -2
  19. package/dist/types/runtime/execution/active-execution-registry.d.ts +1 -0
  20. package/dist/types/runtime/model/model-hub.d.ts +5 -5
  21. package/dist/types/runtime/runner/runner-runtime-service.d.ts +4 -4
  22. package/dist/types/runtime/session/session-store-service.d.ts +1 -0
  23. package/dist/types/store-sql/schema/session-schema.d.ts +45 -0
  24. package/dist/types/store-sql/session/session-records.d.ts +5 -47
  25. package/dist/types/store-sql/session/session-repository.d.ts +37 -1
  26. package/dist/types/store-sql/session/session-row.d.ts +60 -0
  27. package/package.json +3 -3
@@ -3,13 +3,12 @@ import {
3
3
  __export
4
4
  } from "./index-nb39b5ae.js";
5
5
 
6
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/turn-policy.js
6
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/turn-policy.js
7
7
  var exports_turn_policy = {};
8
8
  __export(exports_turn_policy, {
9
9
  untilToolCall: () => untilToolCall,
10
10
  recurs: () => recurs,
11
11
  make: () => make,
12
- fromLegacy: () => fromLegacy,
13
12
  forever: () => forever,
14
13
  defaultPolicy: () => defaultPolicy,
15
14
  decision: () => decision,
@@ -40,7 +39,6 @@ var decision = {
40
39
  stop: (reason) => ({ _tag: "Stop", reason })
41
40
  };
42
41
  var make = (decide) => ({ decide });
43
- var fromLegacy = (decide) => make((info) => decide(info).pipe(Effect.map((result) => result._tag === "Stop" ? decision.stop({ _tag: "Policy", detail: "Legacy policy stopped" }) : result)));
44
42
  var forever = {
45
43
  decide: () => Effect.succeed(decision.continue()),
46
44
  snapshot: { _tag: "Forever" }
@@ -74,7 +72,7 @@ var both = dual(2, (first, second) => ({
74
72
  }));
75
73
  var defaultPolicy = forever;
76
74
 
77
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-event.js
75
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-event.js
78
76
  var exports_agent_event = {};
79
77
  __export(exports_agent_event, {
80
78
  addUsage: () => addUsage,
@@ -83,14 +81,88 @@ __export(exports_agent_event, {
83
81
  ToolOrigin: () => ToolOrigin,
84
82
  ToolNameCollision: () => ToolNameCollision,
85
83
  ResumeMismatch: () => ResumeMismatch,
86
- ProgressOverflowError: () => ProgressOverflowError,
84
+ ProgressOverflow: () => ProgressOverflow,
87
85
  MiddlewareViolation: () => MiddlewareViolation,
88
86
  DuplicateToolCallId: () => DuplicateToolCallId,
89
87
  AgentSuspended: () => AgentSuspended,
90
88
  AgentError: () => AgentError
91
89
  });
92
- import { Function, Schema as Schema2 } from "effect";
93
- import { Prompt as Prompt2, Response as Response2, Tool } from "effect/unstable/ai";
90
+ import { Function, Schema as Schema3 } from "effect";
91
+ import { Prompt as Prompt3, Response as Response2, Tool } from "effect/unstable/ai";
92
+
93
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/session-sync.js
94
+ import { Schema as Schema2 } from "effect";
95
+ import { Prompt as Prompt2 } from "effect/unstable/ai";
96
+ var Divergence = Schema2.Struct({
97
+ index: Schema2.Finite,
98
+ durableRole: Schema2.optionalKey(Schema2.String),
99
+ authoritativeRole: Schema2.optionalKey(Schema2.String),
100
+ durablePartTypes: Schema2.Array(Schema2.String),
101
+ authoritativePartTypes: Schema2.Array(Schema2.String),
102
+ durableDigest: Schema2.optionalKey(Schema2.String),
103
+ authoritativeDigest: Schema2.optionalKey(Schema2.String)
104
+ });
105
+ var Diagnostics = Schema2.Struct({
106
+ sessionId: Schema2.String,
107
+ ownerToken: Schema2.optionalKey(Schema2.String),
108
+ durableEntryCount: Schema2.Finite,
109
+ durableMessageCount: Schema2.Finite,
110
+ authoritativeMessageCount: Schema2.Finite,
111
+ alignmentCount: Schema2.Finite,
112
+ commonPrefixLength: Schema2.Finite,
113
+ lastDurableEntryTag: Schema2.optionalKey(Schema2.String),
114
+ firstDivergence: Schema2.optionalKey(Divergence)
115
+ });
116
+ var digest = (value) => {
117
+ let hash = 2166136261;
118
+ for (let index = 0;index < value.length; index += 1) {
119
+ hash ^= value.charCodeAt(index);
120
+ hash = Math.imul(hash, 16777619);
121
+ }
122
+ return (hash >>> 0).toString(16).padStart(8, "0");
123
+ };
124
+ var partTypes = (message) => typeof message.content === "string" ? ["text"] : message.content.map((part) => part.type);
125
+ var messageDigest = (message) => digest(JSON.stringify(message));
126
+ var diagnose = (input) => {
127
+ const equals = Schema2.toEquivalence(Prompt2.Message);
128
+ let alignmentCount = 0;
129
+ if (input.projection.length === 0)
130
+ alignmentCount = 1;
131
+ else
132
+ for (let start = 0;start <= input.transcript.length - input.projection.length; start += 1) {
133
+ if (input.transcript.slice(0, start).every((message) => message.role === "system") && input.projection.every((message, index) => equals(message, input.transcript[start + index])))
134
+ alignmentCount += 1;
135
+ }
136
+ let commonPrefixLength = 0;
137
+ while (commonPrefixLength < input.projection.length && commonPrefixLength < input.transcript.length && equals(input.projection[commonPrefixLength], input.transcript[commonPrefixLength]))
138
+ commonPrefixLength += 1;
139
+ const durable = input.projection[commonPrefixLength];
140
+ const authoritative = input.transcript[commonPrefixLength];
141
+ const lastDurableEntryTag = input.durableEntryTags.at(-1);
142
+ return {
143
+ sessionId: input.sessionId,
144
+ ...input.ownerToken === undefined ? {} : { ownerToken: input.ownerToken },
145
+ durableEntryCount: input.durableEntryTags.length,
146
+ durableMessageCount: input.projection.length,
147
+ authoritativeMessageCount: input.transcript.length,
148
+ alignmentCount,
149
+ commonPrefixLength,
150
+ ...lastDurableEntryTag === undefined ? {} : { lastDurableEntryTag },
151
+ ...durable === undefined && authoritative === undefined ? {} : {
152
+ firstDivergence: {
153
+ index: commonPrefixLength,
154
+ ...durable === undefined ? {} : { durableRole: durable.role },
155
+ ...authoritative === undefined ? {} : { authoritativeRole: authoritative.role },
156
+ durablePartTypes: durable === undefined ? [] : partTypes(durable),
157
+ authoritativePartTypes: authoritative === undefined ? [] : partTypes(authoritative),
158
+ ...durable === undefined ? {} : { durableDigest: messageDigest(durable) },
159
+ ...authoritative === undefined ? {} : { authoritativeDigest: messageDigest(authoritative) }
160
+ }
161
+ }
162
+ };
163
+ };
164
+
165
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-event.js
94
166
  var addUsageField = (left, right) => left === undefined && right === undefined ? undefined : (left ?? 0) + (right ?? 0);
95
167
  var addUsage = Function.dual(2, (left, right) => Response2.Usage.make({
96
168
  inputTokens: {
@@ -106,112 +178,111 @@ var addUsage = Function.dual(2, (left, right) => Response2.Usage.make({
106
178
  }
107
179
  }));
108
180
 
109
- class AgentError extends Schema2.TaggedErrorClass()("@batonfx/core/AgentError", {
110
- message: Schema2.String,
111
- turn: Schema2.Finite,
112
- cause: Schema2.optionalKey(Schema2.Defect())
181
+ class AgentError extends Schema3.TaggedErrorClass()("@batonfx/core/AgentError", {
182
+ message: Schema3.String,
183
+ turn: Schema3.Finite,
184
+ cause: Schema3.optionalKey(Schema3.Defect()),
185
+ diagnostics: Schema3.optionalKey(Diagnostics)
113
186
  }) {
114
187
  }
115
188
 
116
- class TurnLimitExceeded extends Schema2.TaggedErrorClass()("@batonfx/core/TurnLimitExceeded", {
117
- turn: Schema2.Finite,
118
- limit: Schema2.Finite,
119
- pending: Schema2.Array(Schema2.Struct({
120
- tool_call_id: Schema2.String,
121
- tool_name: Schema2.String
189
+ class TurnLimitExceeded extends Schema3.TaggedErrorClass()("@batonfx/core/TurnLimitExceeded", {
190
+ turn: Schema3.Finite,
191
+ limit: Schema3.Finite,
192
+ pending: Schema3.Array(Schema3.Struct({
193
+ tool_call_id: Schema3.String,
194
+ tool_name: Schema3.String
122
195
  }))
123
196
  }) {
124
197
  }
125
198
 
126
- class TurnPolicyStopped extends Schema2.TaggedErrorClass()("@batonfx/core/TurnPolicyStopped", {
127
- turn: Schema2.Finite,
199
+ class TurnPolicyStopped extends Schema3.TaggedErrorClass()("@batonfx/core/TurnPolicyStopped", {
200
+ turn: Schema3.Finite,
128
201
  reason: StopReason,
129
- pending: Schema2.Array(Schema2.Struct({
130
- tool_call_id: Schema2.String,
131
- tool_name: Schema2.String
202
+ pending: Schema3.Array(Schema3.Struct({
203
+ tool_call_id: Schema3.String,
204
+ tool_name: Schema3.String
132
205
  }))
133
206
  }) {
134
207
  }
135
208
 
136
- class MiddlewareViolation extends Schema2.TaggedErrorClass()("@batonfx/core/MiddlewareViolation", {
137
- turn: Schema2.Finite,
138
- detail: Schema2.String
209
+ class MiddlewareViolation extends Schema3.TaggedErrorClass()("@batonfx/core/MiddlewareViolation", {
210
+ turn: Schema3.Finite,
211
+ detail: Schema3.String
139
212
  }) {
140
213
  }
141
214
 
142
- class DuplicateToolCallId extends Schema2.TaggedErrorClass()("@batonfx/core/DuplicateToolCallId", {
143
- id: Schema2.String,
144
- firstIndex: Schema2.Finite,
145
- duplicateIndex: Schema2.Finite
215
+ class DuplicateToolCallId extends Schema3.TaggedErrorClass()("@batonfx/core/DuplicateToolCallId", {
216
+ id: Schema3.String,
217
+ firstIndex: Schema3.Finite,
218
+ duplicateIndex: Schema3.Finite
146
219
  }) {
147
220
  }
148
221
 
149
- class ProgressOverflowError extends Schema2.TaggedErrorClass()("@batonfx/core/ProgressOverflowError", {
150
- turn: Schema2.Finite,
151
- toolCallId: Schema2.String,
152
- capacity: Schema2.Finite
222
+ class ProgressOverflow extends Schema3.TaggedErrorClass()("@batonfx/core/ProgressOverflow", {
223
+ turn: Schema3.Finite,
224
+ toolCallId: Schema3.String,
225
+ capacity: Schema3.Finite
153
226
  }) {
154
227
  }
155
- var ToolOrigin = Schema2.Union([
156
- Schema2.TaggedStruct("Static", { agent: Schema2.String }),
157
- Schema2.TaggedStruct("Builtin", { builtin: Schema2.Literal("activate_skill") }),
158
- Schema2.TaggedStruct("Skill", { skill: Schema2.String }),
159
- Schema2.TaggedStruct("Handoff", { specialist: Schema2.String })
228
+ var ToolOrigin = Schema3.Union([
229
+ Schema3.TaggedStruct("Static", { agent: Schema3.String }),
230
+ Schema3.TaggedStruct("Builtin", { builtin: Schema3.Literal("activate_skill") }),
231
+ Schema3.TaggedStruct("Skill", { skill: Schema3.String }),
232
+ Schema3.TaggedStruct("Handoff", { specialist: Schema3.String })
160
233
  ]);
161
234
 
162
- class ToolNameCollision extends Schema2.TaggedErrorClass()("@batonfx/core/ToolNameCollision", {
163
- name: Schema2.String,
164
- origins: Schema2.NonEmptyArray(ToolOrigin)
235
+ class ToolNameCollision extends Schema3.TaggedErrorClass()("@batonfx/core/ToolNameCollision", {
236
+ name: Schema3.String,
237
+ origins: Schema3.NonEmptyArray(ToolOrigin)
165
238
  }) {
166
239
  }
167
240
 
168
- class AgentSuspended extends Schema2.TaggedErrorClass()("@batonfx/core/AgentSuspended", {
169
- token: Schema2.String,
170
- reason: Schema2.Literals(["tool-wait", "approval"]),
171
- authorization_stage: Schema2.optional(Schema2.Literals(["permission", "approval"])),
172
- tool_call_index: Schema2.optional(Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(0))),
173
- tool_call_id: Schema2.String,
174
- tool_name: Schema2.String,
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,
241
+ class AgentSuspended extends Schema3.TaggedErrorClass()("@batonfx/core/AgentSuspended", {
242
+ token: Schema3.String,
243
+ reason: Schema3.Literals(["tool-wait", "approval"]),
244
+ tool_call_index: Schema3.optional(Schema3.Int.check(Schema3.isGreaterThanOrEqualTo(0))),
245
+ tool_call_id: Schema3.String,
246
+ tool_name: Schema3.String,
247
+ tool_params: Schema3.Unknown,
248
+ tool_call_batch: Schema3.Array(Schema3.Struct({
249
+ type: Schema3.Literal("tool-call"),
250
+ id: Schema3.String,
251
+ name: Schema3.String,
252
+ params: Schema3.Unknown,
253
+ providerExecuted: Schema3.Boolean,
182
254
  metadata: Response2.ProviderMetadata
183
255
  })),
184
- active_tools: Schema2.optional(Schema2.Array(Schema2.String)),
185
- activated_skills: Schema2.optional(Schema2.Array(Schema2.String))
256
+ active_tools: Schema3.optional(Schema3.Array(Schema3.String)),
257
+ activated_skills: Schema3.optional(Schema3.Array(Schema3.String))
186
258
  }) {
187
259
  }
188
260
 
189
- class ResumeMismatch extends Schema2.TaggedErrorClass()("@batonfx/core/ResumeMismatch", {
190
- reason: Schema2.Literals(["checkpoint-not-found", "identity-mismatch"]),
191
- expected: Schema2.optional(AgentSuspended),
261
+ class ResumeMismatch extends Schema3.TaggedErrorClass()("@batonfx/core/ResumeMismatch", {
262
+ reason: Schema3.Literals(["checkpoint-not-found", "identity-mismatch"]),
263
+ expected: Schema3.optional(AgentSuspended),
192
264
  received: AgentSuspended
193
265
  }) {
194
266
  }
195
267
 
196
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/memory.js
268
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/memory.js
197
269
  var exports_memory = {};
198
270
  __export(exports_memory, {
199
- testLayer: () => testLayer,
200
271
  replaceRecalledMessage: () => replaceRecalledMessage,
201
272
  recalledMessageIdentity: () => recalledMessageIdentity,
202
273
  projectTranscript: () => projectTranscript,
203
- noopLayer: () => noopLayer,
204
274
  messageFromRecall: () => messageFromRecall,
205
275
  merge: () => merge,
276
+ layerTest: () => layerTest,
206
277
  layerNoop: () => layerNoop,
207
278
  itemFromPromptPart: () => itemFromPromptPart,
208
279
  isMessageFromRecall: () => isMessageFromRecall,
209
280
  MemoryError: () => MemoryError,
210
281
  Memory: () => Memory
211
282
  });
212
- import { Context, Effect as Effect2, Layer as Layer2, Option, Schema as Schema3 } from "effect";
283
+ import { Context, Effect as Effect2, Layer as Layer2, Option, Schema as Schema4 } from "effect";
213
284
  import { dual as dual2 } from "effect/Function";
214
- import { Prompt as Prompt3 } from "effect/unstable/ai";
285
+ import { Prompt as Prompt4 } from "effect/unstable/ai";
215
286
  var provenanceOption = "@batonfx/core/memory";
216
287
  var recallLineage = new WeakMap;
217
288
  var itemFromPromptPart = Option.liftPredicate((part) => part.type === "text" || part.type === "file");
@@ -220,7 +291,7 @@ var isMessageFromRecall = (message) => {
220
291
  return typeof provenance === "object" && provenance !== null && !Array.isArray(provenance) && "origin" in provenance && provenance.origin === "memoryRecall";
221
292
  };
222
293
  var messageFromRecall = (content) => {
223
- const message = Prompt3.makeMessage("user", {
294
+ const message = Prompt4.makeMessage("user", {
224
295
  content,
225
296
  options: { [provenanceOption]: { origin: "memoryRecall" } }
226
297
  });
@@ -229,7 +300,7 @@ var messageFromRecall = (content) => {
229
300
  };
230
301
  var replaceRecalledMessage = dual2(2, (message, content) => {
231
302
  const options = isMessageFromRecall(message) ? { ...message.options, [provenanceOption]: { origin: "memoryRecall" } } : { ...message.options };
232
- const replacement = Prompt3.makeMessage("user", { content, options });
303
+ const replacement = Prompt4.makeMessage("user", { content, options });
233
304
  if (isMessageFromRecall(message))
234
305
  recallLineage.set(replacement, recallLineage.get(message) ?? message);
235
306
  return replacement;
@@ -237,15 +308,15 @@ var replaceRecalledMessage = dual2(2, (message, content) => {
237
308
  var recalledMessageIdentity = (message) => recallLineage.get(message) ?? message;
238
309
  var projectTranscript = (transcript) => {
239
310
  const content = transcript.content.filter((message) => !isMessageFromRecall(message));
240
- return content.length === transcript.content.length ? transcript : Prompt3.fromMessages(content);
311
+ return content.length === transcript.content.length ? transcript : Prompt4.fromMessages(content);
241
312
  };
242
313
 
243
- class MemoryError extends Schema3.TaggedErrorClass()("@batonfx/core/MemoryError", {
244
- message: Schema3.String
314
+ class MemoryError extends Schema4.TaggedErrorClass()("@batonfx/core/MemoryError", {
315
+ message: Schema4.String
245
316
  }) {
246
317
  }
247
318
 
248
- class Memory extends Context.Service()("@batonfx/core/memory") {
319
+ class Memory extends Context.Service()("@batonfx/core/Memory") {
249
320
  }
250
321
  var noop = {
251
322
  recall: () => Effect2.succeed([]),
@@ -258,29 +329,25 @@ var merge = dual2(2, (first, second) => ({
258
329
  forget: (input) => Effect2.all([first.forget(input), second.forget(input)], { discard: true })
259
330
  }));
260
331
  var layerNoop = Layer2.succeed(Memory, Memory.of(noop));
261
- var noopLayer = layerNoop;
262
- var testLayer = (implementation) => Layer2.succeed(Memory, Memory.of(implementation));
332
+ var layerTest = (implementation) => Layer2.succeed(Memory, Memory.of(implementation));
263
333
 
264
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/model-registry.js
334
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/model-registry.js
265
335
  var exports_model_registry = {};
266
336
  __export(exports_model_registry, {
267
- testLayer: () => testLayer2,
268
337
  stream: () => stream,
269
338
  registrations: () => registrations,
270
- registrationFromLayer: () => registrationFromLayer,
339
+ registration: () => registration,
271
340
  register: () => register,
272
- provide: () => provide,
273
341
  operate: () => operate,
274
- memoryLayer: () => memoryLayer,
342
+ layerTest: () => layerTest2,
275
343
  layerMemory: () => layerMemory,
276
- layerFromRegistrationEffects: () => layerFromRegistrationEffects,
344
+ layerCombined: () => layerCombined,
277
345
  layer: () => layer,
278
- combine: () => combine,
279
346
  classifyFailure: () => classifyFailure,
280
- Service: () => Service,
347
+ ModelRegistry: () => ModelRegistry,
281
348
  LanguageModelNotRegistered: () => LanguageModelNotRegistered
282
349
  });
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";
350
+ import { Context as Context2, Effect as Effect3, Fiber, Function as Function2, HashMap, Layer as Layer3, Option as Option2, Ref, Schema as Schema5, Scope, Semaphore, Stream } from "effect";
284
351
  import { LanguageModel as LanguageModel2, Model } from "effect/unstable/ai";
285
352
  var FailureClassifierTypeId = Symbol.for("@batonfx/core/model-registry/FailureClassifier");
286
353
  var classifyFailure = Function2.dual(2, (model, error) => model[FailureClassifierTypeId]?.(error) ?? "other");
@@ -295,28 +362,25 @@ var attachFailureClassifier = (registration, context) => {
295
362
  return Context2.add(context, LanguageModel2.LanguageModel, classified);
296
363
  };
297
364
 
298
- class LanguageModelNotRegistered extends Schema4.TaggedErrorClass()("LanguageModelNotRegistered", {
299
- provider: Schema4.String,
300
- model: Schema4.String,
301
- registration_key: Schema4.optionalKey(Schema4.String)
365
+ class LanguageModelNotRegistered extends Schema5.TaggedErrorClass()("@batonfx/core/LanguageModelNotRegistered", {
366
+ provider: Schema5.String,
367
+ model: Schema5.String,
368
+ registration_key: Schema5.optionalKey(Schema5.String)
302
369
  }) {
303
370
  }
304
371
 
305
- class Service extends Context2.Service()("@batonfx/core/model-registry/Service") {
372
+ class ModelRegistry extends Context2.Service()("@batonfx/core/ModelRegistry") {
306
373
  }
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) => ({
374
+ var selectionKey = (selection) => JSON.stringify([selection.provider, selection.model, selection.registrationKey ?? null]);
375
+ var upsertRegistration = (registry, entry) => {
376
+ const key = selectionKey(entry.registration);
377
+ return {
378
+ byKey: HashMap.set(registry.byKey, key, entry),
379
+ keys: HashMap.has(registry.byKey, key) ? registry.keys : [...registry.keys, key]
380
+ };
381
+ };
382
+ var findRegistration = (registry, selection) => HashMap.get(registry.byKey, selectionKey(selection)).pipe(Option2.getOrUndefined);
383
+ var registration = (input) => Model.make(input.provider, input.model, input.layer).captureRequirements.pipe(Effect3.map((layer) => ({
320
384
  provider: input.provider,
321
385
  model: input.model,
322
386
  layer,
@@ -324,30 +388,44 @@ var registrationFromLayer = (input) => Model.make(input.provider, input.model, i
324
388
  ...input.metadata === undefined ? {} : { metadata: input.metadata },
325
389
  ...input.classifyFailure === undefined ? {} : { classifyFailure: input.classifyFailure }
326
390
  })));
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()));
391
+ var makeLayer = (initialRegistrations, options) => Layer3.effect(ModelRegistry, Effect3.gen(function* () {
392
+ const memoMap = yield* Layer3.makeMemoMap;
393
+ const scope = yield* Effect3.scope;
394
+ const makeEntry = Effect3.fnUntraced(function* (candidate) {
395
+ const fiber = yield* Effect3.cached(Effect3.forkIn(Layer3.buildWithMemoMap(candidate.layer, memoMap, scope), scope, {
396
+ startImmediately: true
397
+ }));
398
+ const context = Effect3.uninterruptible(fiber).pipe(Effect3.flatMap(Fiber.join));
399
+ return { registration: candidate, context };
400
+ });
401
+ const initialEntries = yield* Effect3.forEach(initialRegistrations, makeEntry);
402
+ const registry = yield* Ref.make(initialEntries.reduce(upsertRegistration, {
403
+ byKey: HashMap.empty(),
404
+ keys: []
405
+ }));
329
406
  const semaphore = options?.maxConcurrentModelCalls === undefined ? undefined : yield* Semaphore.make(options.maxConcurrentModelCalls);
330
407
  const register = Effect3.fn("ModelRegistry.register")(function* (input) {
331
- yield* Ref.update(registry, (items) => upsertRegistration(items, input.registration));
408
+ const entry = yield* makeEntry(input.registration);
409
+ yield* Ref.update(registry, (items) => upsertRegistration(items, entry));
332
410
  });
333
- const registrations = Ref.get(registry).pipe(Effect3.map(Chunk.toReadonlyArray));
411
+ const registrations = Ref.get(registry).pipe(Effect3.map((items) => items.keys.map((key) => HashMap.getUnsafe(items.byKey, key).registration)));
334
412
  const operate = Effect3.fn("ModelRegistry.operate")(function* (selection, effect) {
335
413
  const items = yield* Ref.get(registry);
336
- const registration = findRegistration(items, selection);
337
- if (registration === undefined) {
414
+ const entry = findRegistration(items, selection);
415
+ if (entry === undefined) {
338
416
  return yield* LanguageModelNotRegistered.make({
339
417
  provider: selection.provider,
340
418
  model: selection.model,
341
419
  ...selection.registrationKey === undefined ? {} : { registration_key: selection.registrationKey }
342
420
  });
343
421
  }
344
- const provided = Effect3.scoped(Layer3.build(registration.layer).pipe(Effect3.flatMap((context) => effect.pipe(Effect3.provide(attachFailureClassifier(registration, context))))));
422
+ const provided = entry.context.pipe(Effect3.flatMap((context) => effect.pipe(Effect3.provide(attachFailureClassifier(entry.registration, context)))));
345
423
  return yield* semaphore === undefined ? provided : semaphore.withPermits(1)(provided);
346
424
  });
347
425
  const stream = (selection, operation) => Stream.unwrap(Effect3.gen(function* () {
348
426
  const items = yield* Ref.get(registry);
349
- const registration = findRegistration(items, selection);
350
- if (registration === undefined) {
427
+ const entry = findRegistration(items, selection);
428
+ if (entry === undefined) {
351
429
  return yield* LanguageModelNotRegistered.make({
352
430
  provider: selection.provider,
353
431
  model: selection.model,
@@ -357,82 +435,79 @@ var layer = Function2.dual((args) => args.length === 0 || args.length > 1 || Arr
357
435
  if (semaphore !== undefined) {
358
436
  yield* Effect3.acquireRelease(semaphore.take(1), () => semaphore.release(1), { interruptible: true });
359
437
  }
360
- const context = attachFailureClassifier(registration, yield* Layer3.build(registration.layer));
438
+ const context = attachFailureClassifier(entry.registration, yield* entry.context);
361
439
  return operation.pipe(Stream.provideContext(context));
362
440
  }));
363
- return Service.of({
441
+ return ModelRegistry.of({
364
442
  register,
365
443
  registrations,
366
444
  operate,
367
- stream,
368
- provide: operate
445
+ stream
369
446
  });
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)))));
447
+ }));
448
+ var layer = Function2.dual((args) => args.length === 0 || args.length > 1 || Array.isArray(args[0]), (registrations = [], options) => Layer3.unwrap(Effect3.all(registrations).pipe(Effect3.map((initialRegistrations) => makeLayer(initialRegistrations, options)))));
449
+ var layerCombined = 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, ModelRegistry).registrations))).pipe(Effect3.map((groups) => makeLayer(groups.flat(), options)))));
373
450
  var layerMemory = layer;
374
- var memoryLayer = layerMemory;
375
- var testLayer2 = (implementation) => Layer3.succeed(Service, Service.of(implementation));
451
+ var layerTest2 = (implementation) => Layer3.succeed(ModelRegistry, ModelRegistry.of(implementation));
376
452
  var register = Effect3.fn("ModelRegistry.register.call")(function* (input) {
377
- const service = yield* Service;
453
+ const service = yield* ModelRegistry;
378
454
  return yield* service.register(input);
379
455
  });
380
456
  var registrations = Effect3.fn("ModelRegistry.registrations.call")(function* () {
381
- const service = yield* Service;
457
+ const service = yield* ModelRegistry;
382
458
  return yield* service.registrations;
383
459
  });
384
460
  var operate = Function2.dual(2, (selection, effect) => Effect3.gen(function* () {
385
- const service = yield* Service;
461
+ const service = yield* ModelRegistry;
386
462
  return yield* service.operate(selection, effect);
387
463
  }));
388
- var stream = Function2.dual(2, (selection, operation) => Stream.unwrap(Service.pipe(Effect3.map((service) => service.stream(selection, operation)))));
389
- var provide = operate;
464
+ var stream = Function2.dual(2, (selection, operation) => Stream.unwrap(ModelRegistry.pipe(Effect3.map((service) => service.stream(selection, operation)))));
390
465
 
391
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-context.js
466
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-context.js
392
467
  var exports_tool_context = {};
393
468
  __export(exports_tool_context, {
394
- testLayer: () => testLayer3,
469
+ layerTest: () => layerTest3,
395
470
  layerDefault: () => layerDefault,
396
471
  ToolContext: () => ToolContext
397
472
  });
398
473
  import { Context as Context3, Effect as Effect4, Layer as Layer4 } from "effect";
399
474
 
400
- class ToolContext extends Context3.Service()("@batonfx/core/tool-context/ToolContext") {
475
+ class ToolContext extends Context3.Service()("@batonfx/core/ToolContext") {
401
476
  }
402
477
  var layerDefault = Layer4.sync(ToolContext, () => ToolContext.of({
403
478
  signal: new AbortController().signal,
404
479
  emit: () => Effect4.void,
405
480
  sessionId: "local"
406
481
  }));
407
- var testLayer3 = (implementation) => Layer4.succeed(ToolContext, ToolContext.of(implementation));
482
+ var layerTest3 = (implementation) => Layer4.succeed(ToolContext, ToolContext.of(implementation));
408
483
 
409
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-executor.js
484
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-executor.js
410
485
  var exports_tool_executor = {};
411
486
  __export(exports_tool_executor, {
412
- testLayer: () => testLayer4,
413
487
  sandbox: () => sandbox,
414
- router: () => router,
415
488
  routeToolkit: () => routeToolkit,
416
489
  route: () => route,
417
490
  remote: () => remote,
418
491
  mcp: () => mcp,
419
- fromToolkit: () => fromToolkit,
492
+ layerToolkit: () => layerToolkit,
493
+ layerTest: () => layerTest4,
494
+ layerRouter: () => layerRouter,
420
495
  executeToolkit: () => executeToolkit,
421
496
  client: () => client,
422
497
  ToolExecutor: () => ToolExecutor,
423
- RemoteRetryError: () => RemoteRetryError,
498
+ RemoteRetryMisconfigured: () => RemoteRetryMisconfigured,
424
499
  FrameworkStage: () => FrameworkStage,
425
500
  FrameworkFailure: () => FrameworkFailure
426
501
  });
427
- import { Context as Context4, Effect as Effect7, Layer as Layer5, Option as Option3, Schema as Schema6, Sink, Stream as Stream2 } from "effect";
502
+ import { Context as Context4, Effect as Effect7, Layer as Layer5, Option as Option3, Schema as Schema7, Stream as Stream2 } from "effect";
428
503
  import { AiError as AiError2, Response as Response3, Tool as Tool4, Toolkit } from "effect/unstable/ai";
429
504
 
430
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-placement.js
505
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-placement.js
431
506
  import { Effect as Effect6, Schedule } from "effect";
432
507
  import { Tool as Tool3 } from "effect/unstable/ai";
433
508
 
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";
509
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-result-codec.js
510
+ import { Effect as Effect5, Schema as Schema6 } from "effect";
436
511
  import { AiError, Tool as Tool2 } from "effect/unstable/ai";
437
512
  var resultMessage = (result) => {
438
513
  if (typeof result === "string")
@@ -450,20 +525,20 @@ var schemaMessage = (error) => error instanceof Error ? error.message : typeof e
450
525
  var frameworkFailure = (stage, tool, error) => FrameworkFailure.make({ stage, tool, message: schemaMessage(error) });
451
526
  var encodeSuccess = (tool, result) => {
452
527
  const schema = tool.successSchema;
453
- return Schema5.encodeUnknownEffect(schema)(result).pipe(Effect5.map((encodedResult) => ({ _tag: "Success", result, encodedResult })), Effect5.mapError((error) => frameworkFailure("encode-success", tool.name, error)));
528
+ return Schema6.encodeUnknownEffect(schema)(result).pipe(Effect5.map((encodedResult) => ({ _tag: "Success", result, encodedResult })), Effect5.mapError((error) => frameworkFailure("encode-success", tool.name, error)));
454
529
  };
455
530
  var encodeDomainFailure = (tool, failure) => {
456
531
  const schema = tool.failureSchema;
457
- return Schema5.encodeUnknownEffect(schema)(failure).pipe(Effect5.map((encodedFailure) => ({ _tag: "DomainFailure", failure, encodedFailure })), Effect5.mapError((error) => frameworkFailure("encode-domain-failure", tool.name, error)));
532
+ return Schema6.encodeUnknownEffect(schema)(failure).pipe(Effect5.map((encodedFailure) => ({ _tag: "DomainFailure", failure, encodedFailure })), Effect5.mapError((error) => frameworkFailure("encode-domain-failure", tool.name, error)));
458
533
  };
459
- var encodeDomainCandidate = (tool, failure) => !Schema5.is(tool.failureSchema)(failure) ? Effect5.fail(frameworkFailure("handler", tool.name, failure)) : encodeDomainFailure(tool, failure);
534
+ var encodeDomainCandidate = (tool, failure) => !Schema6.is(tool.failureSchema)(failure) ? Effect5.fail(frameworkFailure("handler", tool.name, failure)) : encodeDomainFailure(tool, failure);
460
535
  var decodeInput = (tool, input) => {
461
536
  const schema = tool.parametersSchema;
462
- return Schema5.decodeUnknownEffect(schema)(input).pipe(Effect5.asVoid, Effect5.mapError((error) => frameworkFailure("decode-input", tool.name, error)));
537
+ return Schema6.decodeUnknownEffect(schema)(input).pipe(Effect5.asVoid, Effect5.mapError((error) => frameworkFailure("decode-input", tool.name, error)));
463
538
  };
464
539
  var decodeSuccess = (tool, result) => {
465
540
  const schema = tool.successSchema;
466
- return Schema5.decodeUnknownEffect(schema)(result).pipe(Effect5.mapError((error) => frameworkFailure("encode-success", tool.name, error)), Effect5.flatMap((decoded) => encodeSuccess(tool, decoded)));
541
+ return Schema6.decodeUnknownEffect(schema)(result).pipe(Effect5.mapError((error) => frameworkFailure("encode-success", tool.name, error)), Effect5.flatMap((decoded) => encodeSuccess(tool, decoded)));
467
542
  };
468
543
  var aiFrameworkFailure = (tool, error) => {
469
544
  switch (error.reason._tag) {
@@ -476,8 +551,8 @@ var aiFrameworkFailure = (tool, error) => {
476
551
  case "ToolResultEncodingError": {
477
552
  if (tool.failureMode === "error")
478
553
  return frameworkFailure("encode-success", tool.name, error);
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);
554
+ const isSuccess = Schema6.isSchema(tool.successSchema) && Schema6.is(tool.successSchema)(error.reason.toolResult);
555
+ const isDomainFailure = Schema6.isSchema(tool.failureSchema) && Schema6.is(tool.failureSchema)(error.reason.toolResult);
481
556
  return frameworkFailure(isSuccess === isDomainFailure ? "handler" : isDomainFailure ? "encode-domain-failure" : "encode-success", tool.name, error);
482
557
  }
483
558
  default:
@@ -496,7 +571,7 @@ var toolResultCodec = {
496
571
  schemaMessage
497
572
  };
498
573
 
499
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-placement.js
574
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-placement.js
500
575
  var placementOutcomeFromResponse = (placement, tool, response) => {
501
576
  if (typeof response !== "object" || response === null || !("_tag" in response)) {
502
577
  return Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Placement returned an invalid response"));
@@ -514,8 +589,8 @@ var placementOutcomeFromResponse = (placement, tool, response) => {
514
589
  };
515
590
  var placementOutcome = { fromResponse: placementOutcomeFromResponse };
516
591
 
517
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-executor.js
518
- var FrameworkStage = Schema6.Literals([
592
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-executor.js
593
+ var FrameworkStage = Schema7.Literals([
519
594
  "decode-input",
520
595
  "handler",
521
596
  "encode-success",
@@ -526,20 +601,20 @@ var FrameworkStage = Schema6.Literals([
526
601
  "authorization"
527
602
  ]);
528
603
 
529
- class FrameworkFailure extends Schema6.TaggedErrorClass()("@batonfx/core/FrameworkFailure", {
604
+ class FrameworkFailure extends Schema7.TaggedErrorClass()("@batonfx/core/FrameworkFailure", {
530
605
  stage: FrameworkStage,
531
- tool: Schema6.String,
532
- message: Schema6.String
606
+ tool: Schema7.String,
607
+ message: Schema7.String
533
608
  }) {
534
609
  }
535
610
 
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
611
+ class RemoteRetryMisconfigured extends Schema7.TaggedErrorClass()("@batonfx/core/RemoteRetryMisconfigured", {
612
+ reason: Schema7.Literals(["invalid-max-retries", "missing-operation-key", "changed-operation-key"]),
613
+ message: Schema7.String
539
614
  }) {
540
615
  }
541
616
 
542
- class ToolExecutor extends Context4.Service()("@batonfx/core/tool-executor/ToolExecutor") {
617
+ class ToolExecutor extends Context4.Service()("@batonfx/core/ToolExecutor") {
543
618
  }
544
619
  var findTool = (tools, name) => tools[name];
545
620
  var executeWithToolkit = (toolkit, request) => {
@@ -548,13 +623,13 @@ var executeWithToolkit = (toolkit, request) => {
548
623
  return Effect7.fail(toolResultCodec.frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
549
624
  }
550
625
  const handleFailure = (error) => {
551
- if (Schema6.is(FrameworkFailure)(error))
626
+ if (Schema7.is(FrameworkFailure)(error))
552
627
  return Effect7.fail(error);
553
628
  if (AiError2.isAiError(error))
554
629
  return Effect7.fail(toolResultCodec.aiFrameworkFailure(tool, error));
555
630
  return toolResultCodec.encodeDomainCandidate(tool, error);
556
631
  };
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) => {
632
+ return toolkit.handle(request.call.name, request.call.params).pipe(Effect7.flatMap((results) => results.pipe(Stream2.filter((item) => item.preliminary === false), Stream2.runLast)), Effect7.flatMap((option) => {
558
633
  if (Option3.isNone(option)) {
559
634
  return Effect7.fail(toolResultCodec.frameworkFailure("handler", tool.name, "Tool handler did not produce a final result"));
560
635
  }
@@ -576,7 +651,7 @@ function executeToolkit(toolkitOrRequest, request) {
576
651
  const toolkit = toolkitOrRequest;
577
652
  return ("handle" in toolkit ? Effect7.succeed(toolkit) : toolkit).pipe(Effect7.flatMap((handled) => executeWithToolkit(handled, request)));
578
653
  }
579
- function fromToolkit(toolkit) {
654
+ function layerToolkit(toolkit) {
580
655
  return Layer5.effect(ToolExecutor, ("handle" in toolkit ? Effect7.succeed(toolkit) : toolkit).pipe(Effect7.map((handled) => ToolExecutor.of({
581
656
  execute: (request) => executeWithToolkit(handled, request)
582
657
  }))));
@@ -601,11 +676,11 @@ var placementRoute = (placement, options) => {
601
676
  return toolResultCodec.decodeInput(tool, request.call.params).pipe(Effect7.flatMap(() => {
602
677
  const effect = options.execute({ ...request, placement, tool });
603
678
  return effect;
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)));
679
+ }), Effect7.mapError((error) => Schema7.is(FrameworkFailure)(error) || Schema7.is(RemoteRetryMisconfigured)(error) ? error : toolResultCodec.frameworkFailure("placement", request.call.name, error)), Effect7.flatMap((response) => placementOutcome.fromResponse(placement, tool, response)));
605
680
  }
606
681
  });
607
682
  };
608
- var remoteRetryError = (reason, message) => RemoteRetryError.make({ reason, message });
683
+ var remoteRetryError = (reason, message) => RemoteRetryMisconfigured.make({ reason, message });
609
684
  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
685
  var retryRemote = (options, request) => Effect7.suspend(() => {
611
686
  if (!Number.isFinite(options.maxRetries) || !Number.isInteger(options.maxRetries) || options.maxRetries < 0) {
@@ -625,12 +700,12 @@ var retryRemote = (options, request) => Effect7.suspend(() => {
625
700
  return Effect7.retry(executeAttempt, {
626
701
  schedule: options.schedule,
627
702
  times: options.maxRetries,
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)));
703
+ while: (error) => !Schema7.is(AgentError)(error) && !Schema7.is(FrameworkFailure)(error) && !Schema7.is(RemoteRetryMisconfigured)(error)
704
+ }).pipe(Effect7.flatMap((result) => Schema7.is(RemoteRetryMisconfigured)(result) ? Effect7.fail(result) : Effect7.succeed(result)));
630
705
  }));
631
706
  });
632
707
  var client = (options) => placementRoute("client", options);
633
- var remote = (options) => options.retrySafe === true ? placementRoute("remote", {
708
+ var remote = (options) => options.idempotent === true ? placementRoute("remote", {
634
709
  toolkit: options.toolkit,
635
710
  ...options.tools === undefined ? {} : { tools: options.tools },
636
711
  execute: (request) => retryRemote(options, request)
@@ -645,7 +720,7 @@ function routeToolkit(toolkit) {
645
720
  return "handle" in toolkit ? makeRoute(toolkit) : toolkit.pipe(Effect7.map(makeRoute));
646
721
  }
647
722
  var routeInputEffect = (input) => Effect7.isEffect(input) ? input : Effect7.succeed(input);
648
- function router(routes) {
723
+ function layerRouter(routes) {
649
724
  return Layer5.effect(ToolExecutor, Effect7.all(Array.from(routes, routeInputEffect)).pipe(Effect7.map((resolved) => ToolExecutor.of({
650
725
  execute: (request) => {
651
726
  const matched = resolved.find((candidate) => candidate.matches(request));
@@ -653,28 +728,28 @@ function router(routes) {
653
728
  }
654
729
  }))));
655
730
  }
656
- var testLayer4 = (implementation) => Layer5.succeed(ToolExecutor, ToolExecutor.of(implementation));
731
+ var layerTest4 = (implementation) => Layer5.succeed(ToolExecutor, ToolExecutor.of(implementation));
657
732
 
658
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/approvals.js
733
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/approvals.js
659
734
  var exports_approvals = {};
660
735
  __export(exports_approvals, {
661
- testLayer: () => testLayer5,
662
- denyAll: () => denyAll,
663
- autoApprove: () => autoApprove,
736
+ layerTest: () => layerTest5,
737
+ layerDenyAll: () => layerDenyAll,
738
+ layerAutoApprove: () => layerAutoApprove,
664
739
  Approvals: () => Approvals
665
740
  });
666
741
  import { Context as Context5, Effect as Effect8, Layer as Layer6 } from "effect";
667
- class Approvals extends Context5.Service()("@batonfx/core/approvals") {
742
+
743
+ class Approvals extends Context5.Service()("@batonfx/core/Approvals") {
668
744
  }
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));
745
+ var layerAutoApprove = Layer6.succeed(Approvals, Approvals.of({ resolve: () => Effect8.succeed({ _tag: "Approved" }) }));
746
+ var layerDenyAll = Layer6.succeed(Approvals, Approvals.of({ resolve: () => Effect8.succeed({ _tag: "Denied" }) }));
747
+ var layerTest5 = (implementation) => Layer6.succeed(Approvals, Approvals.of(implementation));
672
748
 
673
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/session.js
749
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/session.js
674
750
  var exports_session = {};
675
751
  __export(exports_session, {
676
- testLayer: () => testLayer6,
677
- memoryLayer: () => memoryLayer2,
752
+ layerTest: () => layerTest6,
678
753
  layerMemory: () => layerMemory2,
679
754
  buildMemoryContext: () => buildMemoryContext,
680
755
  buildContext: () => buildContext,
@@ -682,23 +757,23 @@ __export(exports_session, {
682
757
  SessionStore: () => SessionStore,
683
758
  SessionConflict: () => SessionConflict
684
759
  });
685
- import { Context as Context6, Effect as Effect9, HashMap, Layer as Layer7, Option as Option4, Ref as Ref2, Schema as Schema7 } from "effect";
686
- import { Prompt as Prompt4 } from "effect/unstable/ai";
687
- class SessionStoreError extends Schema7.TaggedErrorClass()("@batonfx/core/SessionStoreError", {
688
- message: Schema7.String
760
+ import { Context as Context6, Effect as Effect9, HashMap as HashMap2, Layer as Layer7, Option as Option4, Ref as Ref2, Schema as Schema8 } from "effect";
761
+ import { Prompt as Prompt5 } from "effect/unstable/ai";
762
+ class SessionStoreError extends Schema8.TaggedErrorClass()("@batonfx/core/SessionStoreError", {
763
+ message: Schema8.String
689
764
  }) {
690
765
  }
691
766
 
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
767
+ class SessionConflict extends Schema8.TaggedErrorClass()("@batonfx/core/SessionConflict", {
768
+ reason: Schema8.Literals(["stale-leaf", "checkpoint-id-reused", "checkpoint-not-on-active-path", "fenced"]),
769
+ message: Schema8.String
695
770
  }) {
696
771
  }
697
772
 
698
- class SessionStore extends Context6.Service()("@batonfx/core/session/SessionStore") {
773
+ class SessionStore extends Context6.Service()("@batonfx/core/SessionStore") {
699
774
  }
700
775
  var initialState = {
701
- entries: HashMap.empty(),
776
+ entries: HashMap2.empty(),
702
777
  order: [],
703
778
  leaf: null,
704
779
  counter: 0
@@ -743,7 +818,7 @@ var pathFromState = (state, leaf) => {
743
818
  while (cursor !== null) {
744
819
  if (entries.length > state.order.length)
745
820
  return failure(`Session path for leaf ${leaf} contains a cycle`);
746
- const entry = HashMap.get(state.entries, cursor);
821
+ const entry = HashMap2.get(state.entries, cursor);
747
822
  if (Option4.isNone(entry))
748
823
  return failure(`Session entry ${cursor} does not exist`);
749
824
  const value = entry.value;
@@ -783,17 +858,17 @@ var appendState = (state, input, options) => {
783
858
  return [
784
859
  success(entry),
785
860
  {
786
- entries: HashMap.set(state.entries, id, entry),
861
+ entries: HashMap2.set(state.entries, id, entry),
787
862
  order: [...state.order, id],
788
863
  leaf: id,
789
864
  counter: state.counter + 1
790
865
  }
791
866
  ];
792
867
  };
793
- var promptEquivalence = Schema7.toEquivalence(Prompt4.Prompt);
868
+ var promptEquivalence = Schema8.toEquivalence(Prompt5.Prompt);
794
869
  var checkpointMatches = (entry, prepared) => entry.parentId === prepared.parentId && entry.summary === prepared.summary && promptEquivalence(entry.projectedHistory, prepared.projectedHistory);
795
870
  var appendCheckpointState = (state, prepared) => {
796
- const existing = HashMap.get(state.entries, prepared.id);
871
+ const existing = HashMap2.get(state.entries, prepared.id);
797
872
  if (Option4.isSome(existing)) {
798
873
  const entry = existing.value;
799
874
  if (entry._tag !== "Compaction" || entry.version !== 2 || !checkpointMatches(entry, prepared)) {
@@ -844,18 +919,18 @@ var appendCheckpointState = (state, prepared) => {
844
919
  { _tag: "Appended", checkpoint, leafId: checkpoint.id },
845
920
  {
846
921
  ...state,
847
- entries: HashMap.set(state.entries, checkpoint.id, checkpoint),
922
+ entries: HashMap2.set(state.entries, checkpoint.id, checkpoint),
848
923
  order: [...state.order, checkpoint.id],
849
924
  leaf: checkpoint.id
850
925
  }
851
926
  ];
852
927
  };
853
928
  var setLeafState = (state, id) => {
854
- if (id !== null && Option4.isNone(HashMap.get(state.entries, id)))
929
+ if (id !== null && Option4.isNone(HashMap2.get(state.entries, id)))
855
930
  return [failure(`Session entry ${id} does not exist`), state];
856
931
  return [success(undefined), { ...state, leaf: id }];
857
932
  };
858
- var messageFromText = (role, text) => role === "system" ? Prompt4.makeMessage("system", { content: text }) : Prompt4.makeMessage("user", { content: [Prompt4.makePart("text", { text })] });
933
+ var messageFromText = (role, text) => role === "system" ? Prompt5.makeMessage("system", { content: text }) : Prompt5.makeMessage("user", { content: [Prompt5.makePart("text", { text })] });
859
934
  var checkpointMessage = (summary) => messageFromText("user", `<conversation-checkpoint>
860
935
  ${summary}
861
936
  </conversation-checkpoint>`);
@@ -887,10 +962,10 @@ var projectedMessages = (path) => {
887
962
  messages.push(entry.message);
888
963
  break;
889
964
  case "ToolCall":
890
- messages.push(Prompt4.makeMessage("assistant", { content: [entry.part] }));
965
+ messages.push(Prompt5.makeMessage("assistant", { content: [entry.part] }));
891
966
  break;
892
967
  case "ToolResult":
893
- messages.push(Prompt4.makeMessage("tool", { content: [entry.part] }));
968
+ messages.push(Prompt5.makeMessage("tool", { content: [entry.part] }));
894
969
  break;
895
970
  case "Memory":
896
971
  messages.push(memoryMessage(entry.items));
@@ -913,16 +988,16 @@ var projectedMessages = (path) => {
913
988
  }
914
989
  return messages;
915
990
  };
916
- var buildContext = (path) => Prompt4.fromMessages(projectedMessages(path));
991
+ var buildContext = (path) => Prompt5.fromMessages(projectedMessages(path));
917
992
  var buildMemoryContext = (path) => {
918
993
  const messages = path.flatMap((entry) => {
919
994
  switch (entry._tag) {
920
995
  case "Message":
921
996
  return [entry.message];
922
997
  case "ToolCall":
923
- return [Prompt4.makeMessage("assistant", { content: [entry.part] })];
998
+ return [Prompt5.makeMessage("assistant", { content: [entry.part] })];
924
999
  case "ToolResult":
925
- return [Prompt4.makeMessage("tool", { content: [entry.part] })];
1000
+ return [Prompt5.makeMessage("tool", { content: [entry.part] })];
926
1001
  case "Steering":
927
1002
  return [entry.message];
928
1003
  case "Memory":
@@ -933,7 +1008,7 @@ var buildMemoryContext = (path) => {
933
1008
  return [];
934
1009
  }
935
1010
  });
936
- return projectTranscript(Prompt4.fromMessages(messages));
1011
+ return projectTranscript(Prompt5.fromMessages(messages));
937
1012
  };
938
1013
  var layerMemory2 = Layer7.effect(SessionStore, Ref2.make(initialState).pipe(Effect9.map((state) => SessionStore.of({
939
1014
  reserveEntryId: Ref2.modify(state, (current) => [
@@ -946,35 +1021,34 @@ var layerMemory2 = Layer7.effect(SessionStore, Ref2.make(initialState).pipe(Effe
946
1021
  setLeaf: (id) => Ref2.modify(state, (current) => setLeafState(current, id)).pipe(Effect9.flatMap(effectFromResult)),
947
1022
  leaf: Ref2.get(state).pipe(Effect9.map((current) => current.leaf))
948
1023
  }))));
949
- var memoryLayer2 = layerMemory2;
950
- var testLayer6 = (implementation) => Layer7.succeed(SessionStore, SessionStore.of(implementation));
1024
+ var layerTest6 = (implementation) => Layer7.succeed(SessionStore, SessionStore.of(implementation));
951
1025
 
952
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/tool-output.js
1026
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-output.js
953
1027
  var exports_tool_output = {};
954
1028
  __export(exports_tool_output, {
955
- testLayer: () => testLayer7,
1029
+ layerTest: () => layerTest7,
956
1030
  layerNoop: () => layerNoop2,
957
1031
  layerMemory: () => layerMemory3,
958
1032
  bound: () => bound,
959
1033
  ToolOutputStore: () => ToolOutputStore,
960
1034
  ToolOutputError: () => ToolOutputError
961
1035
  });
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") {
1036
+ import { Cause, Context as Context7, Effect as Effect10, Function as Function3, HashMap as HashMap3, Layer as Layer8, Option as Option5, Ref as Ref3, Schema as Schema9 } from "effect";
1037
+ class ToolOutputStore extends Context7.Service()("@batonfx/core/ToolOutputStore") {
964
1038
  }
965
1039
 
966
- class ToolOutputError extends Schema8.TaggedErrorClass()("@batonfx/core/ToolOutputError", {
967
- message: Schema8.String
1040
+ class ToolOutputError extends Schema9.TaggedErrorClass()("@batonfx/core/ToolOutputError", {
1041
+ message: Schema9.String
968
1042
  }) {
969
1043
  }
970
1044
  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({
1045
+ var layerMemory3 = Layer8.effect(ToolOutputStore, Ref3.make({ next: 0, records: HashMap3.empty() }).pipe(Effect10.map((state) => ToolOutputStore.of({
972
1046
  put: (toolCallId, content) => Ref3.modify(state, ({ next, records }) => {
973
1047
  const id = `mem:tool-output-${next + 1}`;
974
- return [Option5.some(id), { next: next + 1, records: HashMap2.set(records, id, { toolCallId, content }) }];
1048
+ return [Option5.some(id), { next: next + 1, records: HashMap3.set(records, id, { toolCallId, content }) }];
975
1049
  })
976
1050
  }))));
977
- var testLayer7 = (implementation) => Layer8.succeed(ToolOutputStore, ToolOutputStore.of(implementation));
1051
+ var layerTest7 = (implementation) => Layer8.succeed(ToolOutputStore, ToolOutputStore.of(implementation));
978
1052
  var encoder = new TextEncoder;
979
1053
  var decoder = new TextDecoder;
980
1054
  var serialized = (value) => {
@@ -1025,15 +1099,15 @@ var bound = Function3.dual(2, (result, options) => Effect10.gen(function* () {
1025
1099
  return boundedFromOriginal(encoded, bytes, options.maxBytes, [path.value]);
1026
1100
  }));
1027
1101
 
1028
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/compaction.js
1102
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/compaction.js
1029
1103
  var exports_compaction = {};
1030
1104
  __export(exports_compaction, {
1031
1105
  truncate: () => truncate,
1032
1106
  toolOutputBound: () => toolOutputBound,
1033
- testLayer: () => testLayer8,
1034
1107
  structuredSummary: () => structuredSummary,
1035
1108
  strategy: () => strategy,
1036
1109
  make: () => make2,
1110
+ layerTest: () => layerTest8,
1037
1111
  layer: () => layer2,
1038
1112
  keepRecent: () => keepRecent,
1039
1113
  defaultStrategy: () => defaultStrategy,
@@ -1044,8 +1118,35 @@ __export(exports_compaction, {
1044
1118
  Compaction: () => Compaction,
1045
1119
  AgentSummary: () => AgentSummary
1046
1120
  });
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";
1121
+ import { Context as Context9, Effect as Effect12, Function as Function4, Layer as Layer10, Option as Option6, Schema as Schema10 } from "effect";
1122
+ import { LanguageModel as LanguageModel4, Prompt as Prompt6, Tokenizer, Toolkit as Toolkit2 } from "effect/unstable/ai";
1123
+
1124
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/summary-model.js
1125
+ import { Context as Context8, Deferred, Effect as Effect11, Fiber as Fiber2, Layer as Layer9, Scope as Scope2 } from "effect";
1126
+ import { LanguageModel as LanguageModel3 } from "effect/unstable/ai";
1127
+ var makeSummaryModelProvider = (model) => {
1128
+ const fibers = new WeakMap;
1129
+ return (effect) => Effect11.contextWith((context) => {
1130
+ const memoMap = Context8.getOrUndefined(context, Layer9.CurrentMemoMap);
1131
+ const scope = Context8.getOrUndefined(context, Scope2.Scope);
1132
+ if (memoMap === undefined || scope === undefined) {
1133
+ return Effect11.scoped(Layer9.build(model).pipe(Effect11.flatMap((modelContext) => effect.pipe(Effect11.provide(modelContext)))));
1134
+ }
1135
+ const sharedFiber = Effect11.uninterruptible(Effect11.sync(() => {
1136
+ const existing = fibers.get(scope);
1137
+ if (existing !== undefined)
1138
+ return [existing, false];
1139
+ const created = Deferred.makeUnsafe();
1140
+ fibers.set(scope, created);
1141
+ return [created, true];
1142
+ }).pipe(Effect11.flatMap(([deferred, start]) => start ? Effect11.forkIn(Layer9.buildWithMemoMap(model, memoMap, scope), scope, {
1143
+ startImmediately: true
1144
+ }).pipe(Effect11.tap((fiber) => Deferred.succeed(deferred, fiber)), Effect11.as(deferred)) : Effect11.succeed(deferred))));
1145
+ return sharedFiber.pipe(Effect11.flatMap(Deferred.await), Effect11.flatMap(Fiber2.join), Effect11.flatMap((modelContext) => effect.pipe(Effect11.provide(modelContext))));
1146
+ });
1147
+ };
1148
+
1149
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/compaction.js
1049
1150
  var DEFAULT_RESERVE_TOKENS = 16384;
1050
1151
  var DEFAULT_KEEP_RECENT_TOKENS = 20000;
1051
1152
  var SUMMARY_TEMPLATE = `Summarize the conversation so another agent can continue seamlessly.
@@ -1063,21 +1164,21 @@ Use Markdown with these sections:
1063
1164
  ## Critical Context
1064
1165
 
1065
1166
  Do not mention that context was compacted.`;
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)
1167
+ var AgentSummary = Schema10.Struct({
1168
+ goal: Schema10.String,
1169
+ facts: Schema10.Array(Schema10.String),
1170
+ decisions: Schema10.Array(Schema10.String),
1171
+ openQuestions: Schema10.Array(Schema10.String),
1172
+ toolFindings: Schema10.Array(Schema10.String)
1072
1173
  });
1073
1174
 
1074
- class CompactionError extends Schema9.TaggedErrorClass()("@batonfx/core/CompactionError", {
1075
- message: Schema9.String,
1076
- cause: Schema9.optionalKey(Schema9.Defect())
1175
+ class CompactionError extends Schema10.TaggedErrorClass()("@batonfx/core/CompactionError", {
1176
+ message: Schema10.String,
1177
+ cause: Schema10.optionalKey(Schema10.Defect())
1077
1178
  }) {
1078
1179
  }
1079
1180
 
1080
- class Compaction extends Context8.Service()("@batonfx/core/compaction") {
1181
+ class Compaction extends Context9.Service()("@batonfx/core/Compaction") {
1081
1182
  }
1082
1183
  var serialized2 = (value) => {
1083
1184
  const json = JSON.stringify(value);
@@ -1108,12 +1209,12 @@ var APPROX_CHARS_PER_TOKEN = 4;
1108
1209
  var estimateTokens = (text) => Math.ceil(text.length / APPROX_CHARS_PER_TOKEN);
1109
1210
  var estimateEntryTokens = (entry) => estimateTokens(serialized2(entry));
1110
1211
  var estimatePromptTokens = (prompt) => estimateTokens(serialized2(prompt.content));
1111
- var fits = (history, prompt, usage) => Number.isFinite(usage.contextWindow) && estimatePromptTokens(Prompt5.concat(history, prompt)) <= usage.contextWindow - usage.reserveTokens;
1212
+ var fits = (history, prompt, usage) => Number.isFinite(usage.contextWindow) && estimatePromptTokens(Prompt6.concat(history, prompt)) <= usage.contextWindow - usage.reserveTokens;
1112
1213
  var isPromptToolResult = (part) => part.type === "tool-result";
1113
1214
  var messageHasToolCall = (message) => typeof message.content !== "string" && message.content.some((part) => part.type === "tool-call");
1114
1215
  var isToolMessage = (entry) => entry?._tag === "Message" && entry.message.role === "tool";
1115
1216
  var isAssistantToolCallEntry = (entry) => entry?._tag === "Message" && entry.message.role === "assistant" && messageHasToolCall(entry.message);
1116
- var compactToolPart = (part, maxBytes) => Effect11.gen(function* () {
1217
+ var compactToolPart = (part, maxBytes) => Effect12.gen(function* () {
1117
1218
  if (part.isFailure)
1118
1219
  return [part, false];
1119
1220
  const success2 = { _tag: "Success", result: part.result, encodedResult: part.result };
@@ -1121,7 +1222,7 @@ var compactToolPart = (part, maxBytes) => Effect11.gen(function* () {
1121
1222
  if (bounded2.encodedResult === success2.encodedResult)
1122
1223
  return [part, false];
1123
1224
  return [
1124
- Prompt5.makePart("tool-result", {
1225
+ Prompt6.makePart("tool-result", {
1125
1226
  id: part.id,
1126
1227
  name: part.name,
1127
1228
  isFailure: false,
@@ -1130,7 +1231,7 @@ var compactToolPart = (part, maxBytes) => Effect11.gen(function* () {
1130
1231
  true
1131
1232
  ];
1132
1233
  });
1133
- var microcompactPrompt = (prompt, maxBytes) => Effect11.gen(function* () {
1234
+ var microcompactPrompt = (prompt, maxBytes) => Effect12.gen(function* () {
1134
1235
  let changed = false;
1135
1236
  const messages = [];
1136
1237
  for (const message of prompt.content) {
@@ -1152,19 +1253,19 @@ var microcompactPrompt = (prompt, maxBytes) => Effect11.gen(function* () {
1152
1253
  messages.push(messageChanged ? { ...message, content } : message);
1153
1254
  }
1154
1255
  }
1155
- return [changed ? Prompt5.fromMessages(messages) : prompt, changed];
1256
+ return [changed ? Prompt6.fromMessages(messages) : prompt, changed];
1156
1257
  });
1157
- var checkpointMessage2 = (summary) => Prompt5.makeMessage("user", {
1158
- content: [Prompt5.makePart("text", { text: `<conversation-checkpoint>
1258
+ var checkpointMessage2 = (summary) => Prompt6.makeMessage("user", {
1259
+ content: [Prompt6.makePart("text", { text: `<conversation-checkpoint>
1159
1260
  ${summary}
1160
1261
  </conversation-checkpoint>` })]
1161
1262
  });
1162
- var summaryPrompt = (template, prompt) => Prompt5.make(`${template}
1263
+ var summaryPrompt = (template, prompt) => Prompt6.make(`${template}
1163
1264
 
1164
1265
  Conversation to summarize:
1165
1266
  ${serialized2(prompt.content)}`);
1166
1267
  var systemMessages = (entries) => entries.flatMap((entry) => entry._tag === "Message" && entry.message.role === "system" ? [entry.message] : []);
1167
- var compactedHistory = (summary, head, recent) => Prompt5.concat(Prompt5.fromMessages([...systemMessages(head), checkpointMessage2(summary)]), recent);
1268
+ var compactedHistory = (summary, head, recent) => Prompt6.concat(Prompt6.fromMessages([...systemMessages(head), checkpointMessage2(summary)]), recent);
1168
1269
  var normalizeUsage = (usage, options) => ({
1169
1270
  contextTokens: Number.isFinite(usage.contextTokens) ? usage.contextTokens : 0,
1170
1271
  contextWindow: Number.isFinite(usage.contextWindow) ? usage.contextWindow : options.contextWindow ?? Number.POSITIVE_INFINITY,
@@ -1187,27 +1288,30 @@ var safeCutIndex = (entries, keepRecentTokens) => {
1187
1288
  }
1188
1289
  return index;
1189
1290
  };
1190
- var defaultStrategy = (options = {}) => ({
1191
- shouldCompact: (usage) => Number.isFinite(usage.contextWindow) && usage.contextTokens > usage.contextWindow - usage.reserveTokens,
1192
- cut: (entries, keepRecentTokens) => {
1193
- const index = safeCutIndex(entries, keepRecentTokens);
1194
- if (index <= 0 || index >= entries.length)
1195
- return Option6.none();
1196
- const recent = entries.slice(index);
1197
- const first = recent[0];
1198
- return first === undefined ? Option6.none() : Option6.some({ firstKeptEntryId: first.id, head: entries.slice(0, index), recent });
1199
- },
1200
- summarize: (plan, request) => {
1201
- const effect = Effect11.gen(function* () {
1202
- const head = buildContext(plan.head);
1203
- const [compactedHead] = request.toolOutputMaxBytes === undefined ? [head, false] : yield* microcompactPrompt(head, request.toolOutputMaxBytes);
1204
- const prompt = summaryPrompt(options.summaryPrompt ?? SUMMARY_TEMPLATE, compactedHead);
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 })));
1207
- });
1208
- return options.summaryModel === undefined ? effect : Effect11.scoped(Layer9.build(options.summaryModel).pipe(Effect11.flatMap((context) => effect.pipe(Effect11.provide(context)))));
1209
- }
1210
- });
1291
+ var defaultStrategy = (options = {}) => {
1292
+ const provideSummaryModel = options.summaryModel === undefined ? undefined : makeSummaryModelProvider(options.summaryModel);
1293
+ return {
1294
+ shouldCompact: (usage) => Number.isFinite(usage.contextWindow) && usage.contextTokens > usage.contextWindow - usage.reserveTokens,
1295
+ cut: (entries, keepRecentTokens) => {
1296
+ const index = safeCutIndex(entries, keepRecentTokens);
1297
+ if (index <= 0 || index >= entries.length)
1298
+ return Option6.none();
1299
+ const recent = entries.slice(index);
1300
+ const first = recent[0];
1301
+ return first === undefined ? Option6.none() : Option6.some({ firstKeptEntryId: first.id, head: entries.slice(0, index), recent });
1302
+ },
1303
+ summarize: (plan, request) => {
1304
+ const effect = Effect12.gen(function* () {
1305
+ const head = buildContext(plan.head);
1306
+ const [compactedHead] = request.toolOutputMaxBytes === undefined ? [head, false] : yield* microcompactPrompt(head, request.toolOutputMaxBytes);
1307
+ const prompt = summaryPrompt(options.summaryPrompt ?? SUMMARY_TEMPLATE, compactedHead);
1308
+ const model = yield* LanguageModel4.LanguageModel;
1309
+ return yield* model.generateText({ prompt, toolkit: Toolkit2.empty, toolChoice: "none" }).pipe(Effect12.map((response) => response.text), Effect12.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1310
+ });
1311
+ return provideSummaryModel === undefined ? effect : provideSummaryModel(effect);
1312
+ }
1313
+ };
1314
+ };
1211
1315
  var strategy = Function4.dual((args) => args.length !== 1 || Array.isArray(args[0]), (parts, base = defaultStrategy()) => parts.reduce((current, part) => ({
1212
1316
  shouldCompact: part.shouldCompact ?? current.shouldCompact,
1213
1317
  cut: part.cut ?? current.cut,
@@ -1221,25 +1325,28 @@ var toolOutputBound = (options) => ({
1221
1325
  var keepRecent = (options) => ({
1222
1326
  keepRecentTokens: safeNonNegativeInteger("KeepRecentOptions.tokens", options.tokens)
1223
1327
  });
1224
- var structuredSummary = (options = {}) => ({
1225
- summarize: (plan, request) => {
1226
- const effect = Effect11.gen(function* () {
1227
- const head = buildContext(plan.head);
1228
- const [compactedHead] = request.toolOutputMaxBytes === undefined ? [head, false] : yield* microcompactPrompt(head, request.toolOutputMaxBytes);
1229
- const prompt = summaryPrompt(options.summaryPrompt ?? SUMMARY_TEMPLATE, compactedHead);
1230
- const model = yield* LanguageModel3.LanguageModel;
1231
- return yield* model.generateObject({
1232
- prompt,
1233
- schema: AgentSummary,
1234
- objectName: options.objectName ?? "AgentSummary",
1235
- toolChoice: "none"
1236
- }).pipe(Effect11.map((response) => renderAgentSummary(response.value)), Effect11.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1237
- });
1238
- return options.summaryModel === undefined ? effect : Effect11.scoped(Layer9.build(options.summaryModel).pipe(Effect11.flatMap((context) => effect.pipe(Effect11.provide(context)))));
1239
- }
1240
- });
1328
+ var structuredSummary = (options = {}) => {
1329
+ const provideSummaryModel = options.summaryModel === undefined ? undefined : makeSummaryModelProvider(options.summaryModel);
1330
+ return {
1331
+ summarize: (plan, request) => {
1332
+ const effect = Effect12.gen(function* () {
1333
+ const head = buildContext(plan.head);
1334
+ const [compactedHead] = request.toolOutputMaxBytes === undefined ? [head, false] : yield* microcompactPrompt(head, request.toolOutputMaxBytes);
1335
+ const prompt = summaryPrompt(options.summaryPrompt ?? SUMMARY_TEMPLATE, compactedHead);
1336
+ const model = yield* LanguageModel4.LanguageModel;
1337
+ return yield* model.generateObject({
1338
+ prompt,
1339
+ schema: AgentSummary,
1340
+ objectName: options.objectName ?? "AgentSummary",
1341
+ toolChoice: "none"
1342
+ }).pipe(Effect12.map((response) => renderAgentSummary(response.value)), Effect12.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1343
+ });
1344
+ return provideSummaryModel === undefined ? effect : provideSummaryModel(effect);
1345
+ }
1346
+ };
1347
+ };
1241
1348
  var make2 = Function4.dual((args) => args.length !== 1 || ("shouldCompact" in args[0]), (compactionStrategy, options = {}) => ({
1242
- maybeCompact: (input) => Effect11.gen(function* () {
1349
+ maybeCompact: (input) => Effect12.gen(function* () {
1243
1350
  const usage = normalizeUsage(input.usage, options);
1244
1351
  const shouldCompact = input.overflow || compactionStrategy.shouldCompact(usage);
1245
1352
  if (!shouldCompact)
@@ -1278,102 +1385,82 @@ var make2 = Function4.dual((args) => args.length !== 1 || ("shouldCompact" in ar
1278
1385
  });
1279
1386
  })
1280
1387
  }));
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))));
1388
+ var layer2 = Function4.dual((args) => args.length !== 1 || !("shouldCompact" in args[0]), (options = {}, providedStrategy = options.strategy ?? defaultStrategy(options)) => Layer10.succeed(Compaction, Compaction.of(make2(providedStrategy, options))));
1282
1389
  var truncate = (maxTokens) => ({
1283
- maybeCompact: (input) => Effect11.gen(function* () {
1390
+ maybeCompact: (input) => Effect12.gen(function* () {
1284
1391
  const usage = input.usage;
1285
1392
  if (!input.overflow && !(Number.isFinite(usage.contextWindow) && usage.contextTokens > usage.contextWindow - usage.reserveTokens)) {
1286
1393
  return Option6.none();
1287
1394
  }
1288
- const tokenizer = yield* Effect11.serviceOption(Tokenizer.Tokenizer);
1395
+ const tokenizer = yield* Effect12.serviceOption(Tokenizer.Tokenizer);
1289
1396
  if (Option6.isNone(tokenizer))
1290
1397
  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));
1398
+ const prompt = yield* tokenizer.value.truncate(Prompt6.concat(input.history, input.prompt), maxTokens).pipe(Effect12.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1399
+ return Option6.some(makeMicrocompact(Prompt6.empty, prompt));
1293
1400
  })
1294
1401
  });
1295
- var testLayer8 = (implementation) => Layer9.succeed(Compaction, Compaction.of(implementation));
1402
+ var layerTest8 = (implementation) => Layer10.succeed(Compaction, Compaction.of(implementation));
1296
1403
 
1297
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/instructions.js
1404
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/instructions.js
1298
1405
  var exports_instructions = {};
1299
1406
  __export(exports_instructions, {
1300
- testLayer: () => testLayer9,
1301
1407
  staticSource: () => staticSource,
1302
- renderUpdate: () => renderUpdate,
1303
1408
  openEpoch: () => openEpoch,
1409
+ layerTest: () => layerTest9,
1304
1410
  layer: () => layer3,
1305
1411
  Instructions: () => Instructions
1306
1412
  });
1307
- import { Context as Context9, Effect as Effect12, Layer as Layer10, Option as Option7 } from "effect";
1413
+ import { Context as Context10, Effect as Effect13, Layer as Layer11, Option as Option7 } from "effect";
1308
1414
  import { dual as dual3 } from "effect/Function";
1309
- class Instructions extends Context9.Service()("@batonfx/core/instructions") {
1415
+ class Instructions extends Context10.Service()("@batonfx/core/Instructions") {
1310
1416
  }
1311
1417
  var staticSource = dual3(2, (id, text) => ({
1312
1418
  id,
1313
- cache: "baseline",
1314
- render: () => Effect12.succeed(text.length === 0 ? Option7.none() : Option7.some(text))
1419
+ render: () => Effect13.succeed(text.length === 0 ? Option7.none() : Option7.some(text))
1315
1420
  }));
1316
- var openEpoch = dual3(2, (instructions, context) => Effect12.gen(function* () {
1421
+ var openEpoch = dual3(2, (instructions, context) => Effect13.gen(function* () {
1317
1422
  const baseline = [];
1318
- const dynamic = [];
1319
1423
  for (const source of instructions.sources) {
1320
- if (source.cache === "dynamic") {
1321
- dynamic.push(source);
1322
- } else {
1323
- const rendered = yield* source.render(context);
1324
- if (Option7.isSome(rendered))
1325
- baseline.push(rendered.value);
1326
- }
1327
- }
1328
- return { baseline: baseline.join(`
1329
-
1330
- `), dynamic };
1331
- }));
1332
- var renderUpdate = dual3(2, (epoch, context) => Effect12.gen(function* () {
1333
- const fragments = [];
1334
- for (const source of epoch.dynamic) {
1335
1424
  const rendered = yield* source.render(context);
1336
1425
  if (Option7.isSome(rendered))
1337
- fragments.push(rendered.value);
1426
+ baseline.push(rendered.value);
1338
1427
  }
1339
- return fragments.length === 0 ? Option7.none() : Option7.some(fragments.join(`
1428
+ return baseline.join(`
1340
1429
 
1341
- `));
1430
+ `);
1342
1431
  }));
1343
- var layer3 = (sources) => Layer10.succeed(Instructions, Instructions.of({ sources: [...sources] }));
1344
- var testLayer9 = (implementation) => Layer10.succeed(Instructions, Instructions.of(implementation));
1432
+ var layer3 = (sources) => Layer11.succeed(Instructions, Instructions.of({ sources: [...sources] }));
1433
+ var layerTest9 = (implementation) => Layer11.succeed(Instructions, Instructions.of(implementation));
1345
1434
 
1346
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/model-middleware.js
1435
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/model-middleware.js
1347
1436
  var exports_model_middleware = {};
1348
1437
  __export(exports_model_middleware, {
1349
1438
  layerIdentity: () => layerIdentity,
1350
1439
  layer: () => layer4,
1351
- identityLayer: () => identityLayer,
1352
1440
  ModelMiddleware: () => ModelMiddleware
1353
1441
  });
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") {
1442
+ import { Context as Context11, Effect as Effect14, Layer as Layer12, Option as Option8 } from "effect";
1443
+ import { Prompt as Prompt7, Response as Response4 } from "effect/unstable/ai";
1444
+ class ModelMiddleware extends Context11.Service()("@batonfx/core/ModelMiddleware") {
1357
1445
  }
1358
- var layerIdentity = Layer11.succeed(ModelMiddleware, []);
1359
- var identityLayer = layerIdentity;
1360
- var layer4 = (middleware) => Layer11.succeed(ModelMiddleware, middleware);
1446
+ var layerIdentity = Layer12.succeed(ModelMiddleware, []);
1447
+ var layer4 = (middleware) => Layer12.succeed(ModelMiddleware, middleware);
1361
1448
 
1362
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/model-resilience.js
1449
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/model-resilience.js
1363
1450
  var exports_model_resilience = {};
1364
1451
  __export(exports_model_resilience, {
1365
- testLayer: () => testLayer10,
1366
1452
  none: () => none,
1367
1453
  make: () => make3,
1454
+ layerTest: () => layerTest10,
1368
1455
  layer: () => layer5,
1369
1456
  defaultClassify: () => defaultClassify,
1370
1457
  apply: () => apply,
1371
1458
  ModelResilience: () => ModelResilience
1372
1459
  });
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";
1460
+ import { Cause as Cause2, Context as Context12, Effect as Effect15, Function as Function5, Layer as Layer13, Result, Schedule as Schedule2, Schema as Schema11, Stream as Stream3 } from "effect";
1461
+ import { AiError as AiError3, LanguageModel as LanguageModel5, Response as Response5, Tool as Tool5 } from "effect/unstable/ai";
1375
1462
 
1376
- class ModelResilience extends Context11.Service()("@batonfx/core/model-resilience/ModelResilience") {
1463
+ class ModelResilience extends Context12.Service()("@batonfx/core/ModelResilience") {
1377
1464
  }
1378
1465
  var defaultClassify = (error) => AiError3.isAiError(error) && error.isRetryable ? "transient" : "terminal";
1379
1466
  var none = { classify: () => "terminal", retrySchedule: Schedule2.recurs(0) };
@@ -1381,19 +1468,19 @@ var make3 = (input) => ({
1381
1468
  classify: input?.classify ?? defaultClassify,
1382
1469
  retrySchedule: input?.retrySchedule ?? none.retrySchedule
1383
1470
  });
1384
- var layer5 = (input) => Layer12.succeed(ModelResilience, ModelResilience.of(make3(input)));
1385
- var testLayer10 = (implementation) => Layer12.succeed(ModelResilience, ModelResilience.of(implementation));
1386
- var retryEffect = (effect, resilience) => Effect14.suspend(effect).pipe(Effect14.map((value) => Result.succeed(value)), Effect14.catchCause((cause) => {
1471
+ var layer5 = (input) => Layer13.succeed(ModelResilience, ModelResilience.of(make3(input)));
1472
+ var layerTest10 = (implementation) => Layer13.succeed(ModelResilience, ModelResilience.of(implementation));
1473
+ var retryEffect = (effect, resilience) => Effect15.suspend(effect).pipe(Effect15.map((value) => Result.succeed(value)), Effect15.catchCause((cause) => {
1387
1474
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
1388
- return reason === undefined || !Cause2.isFailReason(reason) ? Effect14.succeed(Result.fail(cause)) : Effect14.fail(reason.error);
1389
- }), Effect14.retry({
1475
+ return reason === undefined || !Cause2.isFailReason(reason) ? Effect15.succeed(Result.fail(cause)) : Effect15.fail(reason.error);
1476
+ }), Effect15.retry({
1390
1477
  schedule: resilience.retrySchedule,
1391
1478
  while: (error) => resilience.classify(error) === "transient"
1392
- }), Effect14.flatMap((result) => Result.isFailure(result) ? Effect14.failCause(result.failure) : Effect14.succeed(result.success)));
1479
+ }), Effect15.flatMap((result) => Result.isFailure(result) ? Effect15.failCause(result.failure) : Effect15.succeed(result.success)));
1393
1480
  var retryStreamSchedule = (resilience) => resilience.retrySchedule.pipe(Schedule2.while(({ input }) => resilience.classify(input) === "transient"));
1394
1481
  var retryStream = (stream2, onEmittedFailure, resilience) => Stream3.suspend(() => {
1395
1482
  let emitted = false;
1396
- return stream2().pipe(Stream3.map((value) => Result.succeed(value)), Stream3.tap(() => Effect14.sync(() => {
1483
+ return stream2().pipe(Stream3.map((value) => Result.succeed(value)), Stream3.tap(() => Effect15.sync(() => {
1397
1484
  emitted = true;
1398
1485
  })), Stream3.catchCause((cause) => {
1399
1486
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
@@ -1412,34 +1499,34 @@ var apply = Function5.dual(2, (model, resilience) => ({
1412
1499
  streamText: (options) => retryStream(() => model.streamText(options), (error) => Response5.makePart("error", { error }), resilience)
1413
1500
  }));
1414
1501
 
1415
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/permissions.js
1502
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/permissions.js
1416
1503
  var exports_permissions = {};
1417
1504
  __export(exports_permissions, {
1418
- testLayer: () => testLayer11,
1419
- ruleStoreTestLayer: () => ruleStoreTestLayer,
1420
- ruleStoreMemory: () => ruleStoreMemory,
1421
1505
  matches: () => matches,
1422
1506
  matchRule: () => matchRule,
1423
- interactive: () => interactive,
1424
- fromRuleset: () => fromRuleset,
1507
+ layerTest: () => layerTest11,
1508
+ layerRuleset: () => layerRuleset,
1509
+ layerRuleStoreTest: () => layerRuleStoreTest,
1510
+ layerRuleStoreMemory: () => layerRuleStoreMemory,
1511
+ layerAllowAll: () => layerAllowAll,
1512
+ evaluateWithRules: () => evaluateWithRules,
1425
1513
  evaluate: () => evaluate,
1426
- allowAll: () => allowAll,
1427
1514
  RuleStore: () => RuleStore,
1428
1515
  Permissions: () => Permissions,
1429
1516
  PermissionError: () => PermissionError
1430
1517
  });
1431
- import { Context as Context12, Effect as Effect15, Layer as Layer13, Option as Option9, Ref as Ref4, Schema as Schema11 } from "effect";
1518
+ import { Context as Context13, Effect as Effect16, Layer as Layer14, Option as Option9, Ref as Ref4, Schema as Schema12 } from "effect";
1432
1519
  import { dual as dual4 } from "effect/Function";
1433
1520
 
1434
- class PermissionError extends Schema11.TaggedErrorClass()("@batonfx/core/PermissionError", {
1435
- message: Schema11.String
1521
+ class PermissionError extends Schema12.TaggedErrorClass()("@batonfx/core/PermissionError", {
1522
+ message: Schema12.String
1436
1523
  }) {
1437
1524
  }
1438
1525
 
1439
- class Permissions extends Context12.Service()("@batonfx/core/permissions") {
1526
+ class Permissions extends Context13.Service()("@batonfx/core/Permissions") {
1440
1527
  }
1441
1528
 
1442
- class RuleStore extends Context12.Service()("@batonfx/core/permissions/RuleStore") {
1529
+ class RuleStore extends Context13.Service()("@batonfx/core/RuleStore") {
1443
1530
  }
1444
1531
  var escapeRegExp = (value) => value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
1445
1532
  var glob = (pattern) => new RegExp(`^${pattern.split("*").map(escapeRegExp).join(".*")}$`);
@@ -1514,9 +1601,9 @@ var matchingRule = (ruleset, tool, params) => {
1514
1601
  };
1515
1602
  var matchRule = dual4(3, (ruleset, tool, params) => Option9.fromNullishOr(matchingRule(ruleset, tool, params)));
1516
1603
  var evaluate = dual4(3, (ruleset, tool, params) => matchingRule(ruleset, tool, params)?.level ?? ruleset.fallback ?? "ask");
1517
- var tokenFor = (request) => `permission:${request.toolCallId ?? `${request.agentName}:${request.turn}:${request.tool}`}`;
1604
+ var tokenFor = (request) => `permission:${request.call.id}`;
1518
1605
  var decisionFor = (ruleset, request) => {
1519
- const rule = matchingRule(ruleset, request.tool, request.params);
1606
+ const rule = matchingRule(ruleset, request.call.name, request.call.params);
1520
1607
  const level = rule?.level ?? ruleset.fallback ?? "ask";
1521
1608
  switch (level) {
1522
1609
  case "allow":
@@ -1527,65 +1614,93 @@ var decisionFor = (ruleset, request) => {
1527
1614
  return { _tag: "Ask", token: tokenFor(request) };
1528
1615
  }
1529
1616
  };
1530
- var fromRuleset = (ruleset) => Layer13.succeed(Permissions, Permissions.of({
1531
- evaluate: (request) => Effect15.succeed(decisionFor(ruleset, request)),
1532
- await: () => Effect15.succeed(Option9.none())
1617
+ var evaluateWithRules = dual4(3, (base, store, request) => Effect16.gen(function* () {
1618
+ const baseDecision = yield* base.evaluate(request);
1619
+ if (baseDecision._tag === "Deny")
1620
+ return baseDecision;
1621
+ const rules = yield* store.rules;
1622
+ const rule = matchingRule({ rules }, request.call.name, request.call.params);
1623
+ if (rule === undefined)
1624
+ return baseDecision;
1625
+ switch (rule.level) {
1626
+ case "allow":
1627
+ return { _tag: "Allow" };
1628
+ case "deny":
1629
+ return { _tag: "Deny", ...rule.reason === undefined ? {} : { reason: rule.reason } };
1630
+ case "ask":
1631
+ return { _tag: "Ask", token: tokenFor(request) };
1632
+ }
1533
1633
  }));
1534
- var allowAll = Layer13.succeed(Permissions, Permissions.of({
1535
- evaluate: () => Effect15.succeed({ _tag: "Allow" }),
1536
- await: () => Effect15.succeed(Option9.none())
1634
+ var layerRuleset = (ruleset) => Layer14.succeed(Permissions, Permissions.of({
1635
+ evaluate: (request) => Effect16.succeed(decisionFor(ruleset, request))
1537
1636
  }));
1538
- var interactive = (options) => Layer13.succeed(Permissions, Permissions.of({
1539
- evaluate: (request) => Effect15.succeed(decisionFor(options.ruleset, request)),
1540
- await: (pending) => options.onAsk(pending).pipe(Effect15.map(Option9.some))
1637
+ var layerAllowAll = Layer14.succeed(Permissions, Permissions.of({
1638
+ evaluate: () => Effect16.succeed({ _tag: "Allow" })
1541
1639
  }));
1542
- var ruleStoreMemory = (initialRules = []) => Layer13.effect(RuleStore, Ref4.make(initialRules).pipe(Effect15.map((rules) => RuleStore.of({
1640
+ var layerRuleStoreMemory = (initialRules = []) => Layer14.effect(RuleStore, Ref4.make(initialRules).pipe(Effect16.map((rules) => RuleStore.of({
1543
1641
  remember: (rule) => Ref4.update(rules, (current) => [...current.filter((existing) => existing.pattern !== rule.pattern), rule]),
1544
1642
  rules: Ref4.get(rules)
1545
1643
  }))));
1546
- var ruleStoreTestLayer = (implementation) => Layer13.succeed(RuleStore, RuleStore.of(implementation));
1547
- var testLayer11 = (implementation) => Layer13.succeed(Permissions, Permissions.of(implementation));
1644
+ var layerRuleStoreTest = (implementation) => Layer14.succeed(RuleStore, RuleStore.of(implementation));
1645
+ var layerTest11 = (implementation) => Layer14.succeed(Permissions, Permissions.of(implementation));
1548
1646
 
1549
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/skill-source.js
1647
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/skill-source.js
1550
1648
  var exports_skill_source = {};
1551
1649
  __export(exports_skill_source, {
1552
- testLayer: () => testLayer12,
1553
1650
  selectListings: () => selectListings,
1554
1651
  merge: () => merge2,
1555
1652
  makeListing: () => makeListing,
1653
+ layerTest: () => layerTest12,
1654
+ layerSkills: () => layerSkills,
1655
+ layerEmpty: () => layerEmpty,
1556
1656
  layer: () => layer6,
1557
- fromSkills: () => fromSkills,
1558
- empty: () => empty,
1559
1657
  SkillSourceError: () => SkillSourceError,
1560
1658
  SkillSource: () => SkillSource,
1659
+ Frontmatter: () => Frontmatter,
1561
1660
  DESCRIPTION_CAP: () => DESCRIPTION_CAP
1562
1661
  });
1563
- import { Context as Context13, Effect as Effect16, Function as Function6, Layer as Layer14, Schema as Schema12 } from "effect";
1662
+ import { Context as Context14, Effect as Effect17, Function as Function6, Layer as Layer15, Schema as Schema13 } from "effect";
1564
1663
  import { Tool as Tool6 } from "effect/unstable/ai";
1565
-
1566
- class SkillSourceError extends Schema12.TaggedErrorClass()("@batonfx/core/SkillSourceError", {
1567
- source: Schema12.String,
1568
- message: Schema12.String,
1569
- cause: Schema12.optionalKey(Schema12.Defect())
1664
+ var DESCRIPTION_CAP = 1024;
1665
+ var Frontmatter = Schema13.Struct({
1666
+ name: Schema13.String,
1667
+ description: Schema13.String.pipe(Schema13.check(Schema13.isMinLength(1), Schema13.isMaxLength(DESCRIPTION_CAP))),
1668
+ whenToUse: Schema13.optionalKey(Schema13.String),
1669
+ allowedTools: Schema13.optionalKey(Schema13.Array(Schema13.String)),
1670
+ disableModelInvocation: Schema13.optionalKey(Schema13.Boolean),
1671
+ userInvocable: Schema13.optionalKey(Schema13.Boolean),
1672
+ contextFork: Schema13.optionalKey(Schema13.Boolean),
1673
+ agent: Schema13.optionalKey(Schema13.String),
1674
+ model: Schema13.optionalKey(Schema13.String),
1675
+ paths: Schema13.optionalKey(Schema13.Array(Schema13.String))
1676
+ });
1677
+
1678
+ class SkillSourceError extends Schema13.TaggedErrorClass()("@batonfx/core/SkillSourceError", {
1679
+ source: Schema13.String,
1680
+ message: Schema13.String,
1681
+ cause: Schema13.optionalKey(Schema13.Defect())
1570
1682
  }) {
1571
1683
  }
1572
- var DESCRIPTION_CAP = 1024;
1573
1684
 
1574
- class SkillSource extends Context13.Service()("@batonfx/core/skill-source/SkillSource") {
1685
+ class SkillSource extends Context14.Service()("@batonfx/core/SkillSource") {
1575
1686
  }
1576
1687
  var makeListing = Function6.dual((args) => typeof args[0] !== "number", (frontmatter, descriptionCap = DESCRIPTION_CAP) => `- ${frontmatter.name}: ${frontmatter.description.slice(0, Math.max(0, descriptionCap))}`);
1577
- var fromSkills = (skills) => {
1688
+ var layerSkills = (skills) => {
1578
1689
  const all = [...skills];
1579
1690
  const byName = new Map(all.map((skill) => [skill.frontmatter.name, skill]));
1580
- return Layer14.succeed(SkillSource, SkillSource.of({
1581
- all: Effect16.succeed(all),
1582
- get: (name) => Effect16.succeed(byName.get(name))
1691
+ return Layer15.succeed(SkillSource, SkillSource.of({
1692
+ all: Effect17.succeed(all),
1693
+ get: (name) => Effect17.succeed(byName.get(name))
1583
1694
  }));
1584
1695
  };
1585
- var empty = fromSkills([]);
1586
- var testLayer12 = (implementation) => Layer14.succeed(SkillSource, SkillSource.of(implementation));
1587
- var merge2 = (sources) => ({
1588
- all: Effect16.forEach(sources, (source) => source.all).pipe(Effect16.map((groups) => {
1696
+ var layerEmpty = layerSkills([]);
1697
+ var layerTest12 = (implementation) => Layer15.succeed(SkillSource, SkillSource.of(implementation));
1698
+ var emptySource = {
1699
+ all: Effect17.succeed([]),
1700
+ get: () => Effect17.void.pipe(Effect17.as(undefined))
1701
+ };
1702
+ var merge2 = Function6.dual(2, (first, second) => ({
1703
+ all: Effect17.all([first.all, second.all]).pipe(Effect17.map((groups) => {
1589
1704
  const byName = new Map;
1590
1705
  for (const skills of groups) {
1591
1706
  for (const skill of skills)
@@ -1593,16 +1708,9 @@ var merge2 = (sources) => ({
1593
1708
  }
1594
1709
  return [...byName.values()];
1595
1710
  })),
1596
- get: (name) => Effect16.gen(function* () {
1597
- for (const source of sources.toReversed()) {
1598
- const found = yield* source.get(name);
1599
- if (found !== undefined)
1600
- return found;
1601
- }
1602
- return;
1603
- })
1604
- });
1605
- var layer6 = (sources) => Layer14.effect(SkillSource, Effect16.forEach(sources, (source) => source).pipe(Effect16.map((built) => SkillSource.of(merge2(built)))));
1711
+ get: (name) => second.get(name).pipe(Effect17.flatMap((found) => found === undefined ? first.get(name) : Effect17.succeed(found)))
1712
+ }));
1713
+ var layer6 = (sources) => Layer15.effect(SkillSource, Effect17.forEach(sources, (source) => source).pipe(Effect17.map((built) => SkillSource.of(built.reduce((first, second) => merge2(first, second), emptySource)))));
1606
1714
  var estimatedTokens = (listing) => Math.ceil(listing.length / 4);
1607
1715
  var usageRank = (skill, recentlyUsed) => {
1608
1716
  const index = recentlyUsed.indexOf(skill.frontmatter.name);
@@ -1626,23 +1734,23 @@ var selectListings = Function6.dual(3, (skills, budgetTokens, recentlyUsed) => {
1626
1734
  return selected;
1627
1735
  });
1628
1736
 
1629
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/steering.js
1737
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/steering.js
1630
1738
  var exports_steering = {};
1631
1739
  __export(exports_steering, {
1632
- testLayer: () => testLayer13,
1740
+ layerTest: () => layerTest13,
1633
1741
  layer: () => layer7,
1634
1742
  SteeringQueueFull: () => SteeringQueueFull,
1635
1743
  Steering: () => Steering
1636
1744
  });
1637
- import { Context as Context14, Effect as Effect17, Exit, Layer as Layer15, Queue, Schema as Schema13 } from "effect";
1638
- import { Prompt as Prompt7 } from "effect/unstable/ai";
1745
+ import { Context as Context15, Effect as Effect18, Exit, Layer as Layer16, Queue, Schema as Schema14 } from "effect";
1746
+ import { Prompt as Prompt8 } from "effect/unstable/ai";
1639
1747
 
1640
- class Steering extends Context14.Service()("@batonfx/core/steering") {
1748
+ class Steering extends Context15.Service()("@batonfx/core/Steering") {
1641
1749
  }
1642
1750
 
1643
- class SteeringQueueFull extends Schema13.TaggedErrorClass()("@batonfx/core/SteeringQueueFull", {
1644
- queue: Schema13.Literals(["steering", "followUp"]),
1645
- capacity: Schema13.Finite
1751
+ class SteeringQueueFull extends Schema14.TaggedErrorClass()("@batonfx/core/SteeringQueueFull", {
1752
+ queue: Schema14.Literals(["steering", "followUp"]),
1753
+ capacity: Schema14.Finite
1646
1754
  }) {
1647
1755
  }
1648
1756
  var resolvePolicy = (policy, mode) => ({
@@ -1661,222 +1769,125 @@ var queueStrategy = (strategy2) => {
1661
1769
  return "suspend";
1662
1770
  }
1663
1771
  };
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) => {
1772
+ var makeQueue = (name, policy) => (policy.capacity === undefined ? Queue.unbounded() : Queue.make({ capacity: policy.capacity, strategy: queueStrategy(policy.onFull) })).pipe(Effect18.map((queue) => ({ name, queue, policy })));
1773
+ var offer = (runtime, input) => Queue.offer(runtime.queue, input).pipe(Effect18.flatMap((offered) => {
1666
1774
  if (offered || runtime.policy.capacity === undefined || runtime.policy.onFull !== "fail")
1667
- return Effect17.void;
1775
+ return Effect18.void;
1668
1776
  return SteeringQueueFull.make({ queue: runtime.name, capacity: runtime.policy.capacity });
1669
1777
  }));
1670
- var drainOne = (queue) => Effect17.sync(() => {
1778
+ var drainOne = (queue) => Effect18.sync(() => {
1671
1779
  const taken = Queue.takeUnsafe(queue);
1672
1780
  return taken === undefined || !Exit.isSuccess(taken) ? [] : [taken.value];
1673
1781
  });
1674
1782
  var drain = (queue, mode) => mode === "all" ? Queue.clear(queue) : drainOne(queue);
1675
- var layer7 = (options = {}) => Layer15.effect(Steering, Effect17.gen(function* () {
1783
+ var layer7 = (options = {}) => Layer16.effect(Steering, Effect18.gen(function* () {
1676
1784
  const steeringQueue = yield* makeQueue("steering", resolvePolicy(options.steering, "all"));
1677
1785
  const followUpQueue = yield* makeQueue("followUp", resolvePolicy(options.followUp, "one-at-a-time"));
1678
1786
  return Steering.of({
1679
- steer: (message) => offer(steeringQueue, message),
1680
- followUp: (message) => offer(followUpQueue, message),
1787
+ steer: (input) => offer(steeringQueue, input),
1788
+ followUp: (input) => offer(followUpQueue, input),
1681
1789
  takeSteering: drain(steeringQueue.queue, steeringQueue.policy.mode),
1682
1790
  takeFollowUp: drain(followUpQueue.queue, followUpQueue.policy.mode)
1683
1791
  });
1684
1792
  }));
1685
- var testLayer13 = (implementation) => Layer15.succeed(Steering, Steering.of(implementation));
1793
+ var layerTest13 = (implementation) => Layer16.succeed(Steering, Steering.of(implementation));
1686
1794
 
1687
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent.js
1795
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent.js
1688
1796
  var exports_agent = {};
1689
1797
  __export(exports_agent, {
1690
1798
  stream: () => stream2,
1691
- provideModel: () => provideModel,
1692
1799
  make: () => make5,
1800
+ layerRuntime: () => layerRuntime,
1693
1801
  generate: () => generate,
1694
- defaultObjectPrompt: () => defaultObjectPrompt
1802
+ defaultObjectPrompt: () => defaultObjectPrompt,
1803
+ Runtime: () => Runtime
1695
1804
  });
1696
- import { Effect as Effect22, Layer as Layer17, Option as Option15, Schema as Schema19, Stream as Stream5, Types } from "effect";
1697
- import { dual as dual7 } from "effect/Function";
1698
- import { AiError as AiError5, Chat as Chat3, LanguageModel as LanguageModel6, Prompt as Prompt12, Tool as Tool11, Toolkit as Toolkit5 } from "effect/unstable/ai";
1805
+ import { Effect as Effect24, Option as Option14, Schema as Schema20, Stream as Stream5, Types } from "effect";
1806
+ import { dual as dual6 } from "effect/Function";
1807
+ import { AiError as AiError5, Chat as Chat3, LanguageModel as LanguageModel7, Prompt as Prompt12, Tool as Tool10, Toolkit as Toolkit5 } from "effect/unstable/ai";
1699
1808
 
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";
1809
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-run.js
1810
+ import { Cause as Cause4, Channel, Effect as Effect23, Equal as Equal2, Exit as Exit2, Fiber as Fiber3, HashMap as HashMap6, Option as Option13, Queue as Queue2, Ref as Ref5, Schema as Schema19, Semaphore as Semaphore3, Stream as Stream4 } from "effect";
1811
+ import { AiError as AiError4, Chat as Chat2, LanguageModel as LanguageModel6, Prompt as Prompt11, Response as Response9, Telemetry, Tokenizer as Tokenizer2, Tool as Tool9, Toolkit as Toolkit4 } from "effect/unstable/ai";
1703
1812
 
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";
1706
- import { dual as dual5 } from "effect/Function";
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
1813
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-authorization.js
1814
+ import { Cause as Cause3, Context as Context16, Effect as Effect19, Layer as Layer17, Schema as Schema15 } from "effect";
1815
+ import"effect/unstable/ai";
1816
+ class PermissionDenied extends Schema15.TaggedErrorClass()("@batonfx/core/PermissionDenied", {
1817
+ message: Schema15.String
1710
1818
  }) {
1711
1819
  }
1712
1820
 
1713
- class AuthorizationError extends Schema14.TaggedErrorClass()("@batonfx/core/AuthorizationError", { message: Schema14.String, cause: Schema14.optional(Schema14.Defect()) }) {
1821
+ class AuthorizationError extends Schema15.TaggedErrorClass()("@batonfx/core/AuthorizationError", { message: Schema15.String, cause: Schema15.optional(Schema15.Defect()) }) {
1714
1822
  }
1715
1823
 
1716
- class ToolAuthorizerService extends Context15.Service()("@batonfx/core/tool-authorization/ToolAuthorizerService") {
1824
+ class ToolAuthorizerService extends Context16.Service()("@batonfx/core/ToolAuthorizerService") {
1717
1825
  }
1718
- var deny = (message) => ({
1719
- _tag: "Deny",
1720
- error: PermissionDenied.make({ message })
1721
- });
1722
- var suspension = (request, token, stage) => ({
1826
+ var deny = (message) => ({ _tag: "Deny", error: PermissionDenied.make({ message }) });
1827
+ var authorizationError = (error) => AuthorizationError.make({ message: error.message, cause: error });
1828
+ var approvalRequired = (request) => {
1829
+ const needsApproval = request.tool?.needsApproval;
1830
+ if (needsApproval === undefined)
1831
+ return Effect19.succeed(false);
1832
+ if (typeof needsApproval === "boolean")
1833
+ return Effect19.succeed(needsApproval);
1834
+ return Effect19.suspend(() => {
1835
+ const result = needsApproval(request.call.params, {
1836
+ toolCallId: request.call.id,
1837
+ messages: request.messages
1838
+ });
1839
+ return Effect19.isEffect(result) ? result : Effect19.succeed(result);
1840
+ }).pipe(Effect19.catchCause((cause) => Cause3.hasInterrupts(cause) ? Effect19.interrupt : Effect19.succeed(true)));
1841
+ };
1842
+ var suspend = (request, token) => ({
1723
1843
  _tag: "Suspend",
1724
1844
  suspension: AgentSuspended.make({
1725
1845
  token,
1726
1846
  reason: "approval",
1727
- authorization_stage: stage,
1728
1847
  tool_call_id: request.call.id,
1729
1848
  tool_name: request.call.name,
1730
1849
  tool_params: request.call.params,
1731
- tool_call_batch: request.execution.toolCallBatch.calls,
1850
+ tool_call_batch: [request.call],
1732
1851
  active_tools: request.activeTools,
1733
1852
  activated_skills: request.activatedSkills
1734
1853
  })
1735
1854
  });
1736
- var authorizationError = (error) => AuthorizationError.make({ message: error.message, cause: error });
1737
- var approvalRequired = (request) => {
1738
- const needsApproval = request.tool?.needsApproval;
1739
- if (needsApproval === undefined)
1740
- return Effect18.succeed(false);
1741
- if (typeof needsApproval === "boolean")
1742
- return Effect18.succeed(needsApproval);
1743
- return Effect18.suspend(() => {
1744
- const result = needsApproval(request.call.params, {
1745
- toolCallId: request.call.id,
1746
- messages: request.messages
1747
- });
1748
- return Effect18.isEffect(result) ? result : Effect18.succeed(result);
1749
- }).pipe(Effect18.catchCause((cause) => Cause3.hasInterrupts(cause) ? Effect18.interrupt : Effect18.succeed(true)));
1750
- };
1751
- var evaluationRequest = (request) => ({
1752
- tool: request.call.name,
1753
- params: request.call.params,
1754
- agentName: request.execution.agentName,
1755
- turn: request.execution.turn,
1756
- toolCallId: request.call.id,
1757
- sessionId: request.execution.sessionId
1758
- });
1759
- var rememberedDecision = (request, ruleStore) => ruleStore?.rules === undefined ? Effect18.succeedNone : ruleStore.rules.pipe(Effect18.map((rules) => {
1760
- if (rules.length === 0)
1761
- return Option10.none();
1762
- const matched = matchRule({ rules }, request.call.name, request.call.params);
1763
- if (Option10.isNone(matched))
1764
- return Option10.none();
1765
- switch (matched.value.level) {
1766
- case "allow":
1767
- return Option10.some({ _tag: "Allow" });
1768
- case "deny":
1769
- return Option10.some({
1770
- _tag: "Deny",
1771
- ...matched.value.reason === undefined ? {} : { reason: matched.value.reason }
1772
- });
1773
- case "ask":
1774
- return Option10.some({ _tag: "Ask", token: `permission:${request.call.id}` });
1775
- }
1776
- }), Effect18.mapError(authorizationError));
1777
- var resolveRequiredApproval = (request, approvals) => Effect18.gen(function* () {
1778
- yield* request.onApprovalRequired;
1779
- if (approvals === undefined)
1780
- return deny("Approvals service is required for approval-gated tools");
1781
- const decision2 = yield* approvals.check(request.execution);
1782
- switch (decision2._tag) {
1783
- case "Approved":
1855
+ var make4 = (options) => ({
1856
+ authorize: (request) => Effect19.gen(function* () {
1857
+ if (!request.active || request.tool === undefined)
1858
+ return deny(`Tool ${request.call.name} is not active for turn ${request.turn}`);
1859
+ const decision2 = yield* evaluateWithRules(options.permissions, options.ruleStore, request).pipe(Effect19.mapError(authorizationError));
1860
+ if (decision2._tag === "Deny")
1861
+ return deny(decision2.reason ?? "Permission denied");
1862
+ const required = decision2._tag === "Ask" || (yield* approvalRequired(request));
1863
+ if (!required)
1784
1864
  return { _tag: "Execute" };
1785
- case "Denied":
1786
- return deny(decision2.reason ?? "Tool call denied");
1787
- case "Pending":
1788
- return suspension(request, decision2.token, "approval");
1789
- }
1790
- });
1791
- var finalApproval = (request, approvals) => approvalRequired(request).pipe(Effect18.flatMap((required) => {
1792
- if (!required)
1793
- return Effect18.succeed({ _tag: "Execute" });
1794
- return resolveRequiredApproval(request, approvals);
1795
- }));
1796
- var make4 = (options = {}) => ({
1797
- authorize: (request) => Effect18.gen(function* () {
1798
- if (!request.active || request.tool === undefined) {
1799
- return deny(`Tool ${request.call.name} is not active for turn ${request.execution.turn}`);
1800
- }
1801
- if (request.authorizationStage === "approval") {
1802
- return yield* resolveRequiredApproval(request, options.approvals);
1803
- }
1804
- const remembered = yield* rememberedDecision(request, options.ruleStore);
1805
- if (Option10.isSome(remembered) && remembered.value._tag === "Deny") {
1806
- return deny(remembered.value.reason ?? "Permission denied");
1807
- }
1808
- if (request.authorizationStage === "permission") {
1809
- const token = request.authorizationToken ?? `permission:${request.call.id}`;
1810
- if (options.permissions !== undefined) {
1811
- const current2 = yield* options.permissions.evaluate(evaluationRequest(request)).pipe(Effect18.mapError(authorizationError));
1812
- if (current2._tag === "Deny")
1813
- return deny(current2.reason ?? "Permission denied");
1814
- }
1815
- yield* request.onApprovalRequired;
1816
- if (options.permissions === undefined)
1817
- return suspension(request, token, "permission");
1818
- const answer2 = yield* options.permissions.await({
1819
- token,
1820
- tool: request.call.name,
1821
- params: request.call.params,
1822
- agentName: request.execution.agentName,
1823
- turn: request.execution.turn,
1824
- toolCallId: request.call.id
1825
- }).pipe(Effect18.mapError(authorizationError));
1826
- if (Option10.isNone(answer2))
1827
- return suspension(request, token, "permission");
1828
- if (answer2.value._tag === "Denied")
1829
- return deny(answer2.value.reason ?? "Permission denied");
1830
- if (answer2.value._tag === "Always" && options.ruleStore !== undefined) {
1831
- yield* options.ruleStore.remember({ pattern: request.call.name, level: "allow" }).pipe(Effect18.mapError(authorizationError));
1832
- }
1833
- return yield* finalApproval(request, options.approvals);
1834
- }
1835
- if (options.permissions === undefined) {
1836
- if (Option10.isSome(remembered) && remembered.value._tag === "Ask") {
1837
- yield* request.onApprovalRequired;
1838
- return suspension(request, remembered.value.token, "permission");
1839
- }
1840
- return yield* finalApproval(request, options.approvals);
1841
- }
1842
- const permissions = options.permissions;
1843
- const current = yield* permissions.evaluate(evaluationRequest(request)).pipe(Effect18.mapError(authorizationError));
1844
- if (current._tag === "Deny")
1845
- return deny(current.reason ?? "Permission denied");
1846
- if (current._tag !== "Ask" || Option10.isSome(remembered) && remembered.value._tag === "Allow") {
1847
- return yield* finalApproval(request, options.approvals);
1848
- }
1849
- const pending = {
1850
- token: current.token,
1851
- tool: request.call.name,
1852
- params: request.call.params,
1853
- agentName: request.execution.agentName,
1854
- turn: request.execution.turn,
1855
- toolCallId: request.call.id
1856
- };
1857
1865
  yield* request.onApprovalRequired;
1858
- const answer = yield* permissions.await(pending).pipe(Effect18.mapError(authorizationError));
1859
- if (Option10.isNone(answer))
1860
- return suspension(request, current.token, "permission");
1861
- switch (answer.value._tag) {
1862
- case "Denied":
1863
- return deny(answer.value.reason ?? "Permission denied");
1864
- case "Always":
1865
- if (options.ruleStore !== undefined) {
1866
- yield* options.ruleStore.remember({ pattern: request.call.name, level: "allow" }).pipe(Effect18.mapError(authorizationError));
1867
- }
1868
- return yield* finalApproval(request, options.approvals);
1866
+ const resolution = yield* options.approvals.resolve({
1867
+ _tag: "Pending",
1868
+ token: decision2._tag === "Ask" ? decision2.token : `approval:${request.call.id}`,
1869
+ call: request.call,
1870
+ agentName: request.agentName,
1871
+ turn: request.turn,
1872
+ ...request.sessionId === undefined ? {} : { sessionId: request.sessionId }
1873
+ });
1874
+ switch (resolution._tag) {
1869
1875
  case "Approved":
1870
- return yield* finalApproval(request, options.approvals);
1876
+ if (resolution.remember !== undefined)
1877
+ yield* options.ruleStore.remember(resolution.remember).pipe(Effect19.mapError(authorizationError));
1878
+ return { _tag: "Execute" };
1879
+ case "Denied":
1880
+ return deny(resolution.reason ?? "Tool call denied");
1881
+ case "Pending":
1882
+ return suspend(request, resolution.token);
1871
1883
  }
1872
1884
  })
1873
1885
  });
1874
- var fromPermissions = dual5((args) => args.length === 2 || args.length === 1 && ("evaluate" in args[0]), (permissions, options = {}) => make4({ ...options, permissions }));
1875
1886
 
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";
1878
- import { dual as dual6 } from "effect/Function";
1879
- import { Tool as Tool8, Toolkit as Toolkit3 } from "effect/unstable/ai";
1887
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/tool-registry.js
1888
+ import { Array as Array2, Effect as Effect20, HashMap as HashMap4, Option as Option10 } from "effect";
1889
+ import { dual as dual5 } from "effect/Function";
1890
+ import { Tool as Tool7, Toolkit as Toolkit3 } from "effect/unstable/ai";
1880
1891
  var makeToolkit = (entries) => {
1881
1892
  const toolkit = Toolkit3.make(...entries.map((candidate) => candidate.tool));
1882
1893
  for (const entry of entries) {
@@ -1892,89 +1903,71 @@ var makeToolkit = (entries) => {
1892
1903
  return toolkit;
1893
1904
  };
1894
1905
  var assemble = (candidates) => {
1895
- const grouped = new Map;
1896
- for (const candidate of candidates) {
1897
- const existing = grouped.get(candidate.tool.name);
1898
- if (existing === undefined)
1899
- grouped.set(candidate.tool.name, [candidate]);
1900
- else
1901
- existing.push(candidate);
1902
- }
1906
+ const grouped = Array2.groupBy(candidates, (candidate) => `tool:${candidate.tool.name}`);
1903
1907
  for (const candidate of candidates) {
1904
- const conflicts = grouped.get(candidate.tool.name);
1908
+ const conflicts = grouped[`tool:${candidate.tool.name}`];
1905
1909
  if (conflicts !== undefined && conflicts.length > 1) {
1906
- return Effect19.fail(ToolNameCollision.make({
1910
+ return Effect20.fail(ToolNameCollision.make({
1907
1911
  name: candidate.tool.name,
1908
- origins: [conflicts[0].origin, ...conflicts.slice(1).map((conflict) => conflict.origin)]
1912
+ origins: Array2.map(conflicts, (conflict) => conflict.origin)
1909
1913
  }));
1910
1914
  }
1911
1915
  }
1912
1916
  const entries = [...candidates];
1913
- return Effect19.succeed({
1917
+ return Effect20.succeed({
1914
1918
  entries,
1915
- byName: HashMap3.fromIterable(entries.map((candidate) => [candidate.tool.name, candidate])),
1919
+ byName: HashMap4.fromIterable(entries.map((candidate) => [candidate.tool.name, candidate])),
1916
1920
  toolkit: makeToolkit(entries)
1917
1921
  });
1918
1922
  };
1919
- var get = dual6(2, (registry, name) => Option11.getOrUndefined(HashMap3.get(registry.byName, name)));
1920
- var select = dual6(2, (registry, names) => {
1923
+ var get = dual5(2, (registry, name) => Option10.getOrUndefined(HashMap4.get(registry.byName, name)));
1924
+ var select = dual5(2, (registry, names) => {
1921
1925
  const entries = registry.entries.filter((entry) => names.includes(entry.tool.name));
1922
1926
  return {
1923
1927
  entries,
1924
- byName: HashMap3.fromIterable(entries.map((candidate) => [candidate.tool.name, candidate])),
1928
+ byName: HashMap4.fromIterable(entries.map((candidate) => [candidate.tool.name, candidate])),
1925
1929
  toolkit: makeToolkit(entries)
1926
1930
  };
1927
1931
  });
1928
1932
 
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";
1933
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-persistence-lock.js
1934
+ import { Context as Context17, Effect as Effect21, Layer as Layer18, RcMap, Scope as Scope3, Semaphore as Semaphore2 } from "effect";
1931
1935
  import { Chat } from "effect/unstable/ai";
1932
- var persistenceLocks = new WeakMap;
1933
- var reservePersistedChatLock = (persistence, chatId) => {
1934
- const locks = persistenceLocks.get(persistence) ?? new Map;
1935
- if (!persistenceLocks.has(persistence))
1936
- persistenceLocks.set(persistence, locks);
1937
- const existing = locks.get(chatId);
1938
- if (existing !== undefined) {
1939
- existing.users += 1;
1940
- return existing;
1941
- }
1942
- const created = { semaphore: Semaphore2.makeUnsafe(1), users: 1 };
1943
- locks.set(chatId, created);
1944
- return created;
1945
- };
1946
- var releasePersistedChatLock = (persistence, chatId, lock) => {
1947
- lock.users -= 1;
1948
- if (lock.users !== 0)
1949
- return;
1950
- const locks = persistenceLocks.get(persistence);
1951
- if (locks?.get(chatId) !== lock)
1952
- return;
1953
- locks.delete(chatId);
1954
- if (locks.size === 0)
1955
- persistenceLocks.delete(persistence);
1956
- };
1957
1936
 
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";
1937
+ class Runtime extends Context17.Service()("@batonfx/core/Runtime") {
1938
+ }
1939
+ var makeRuntime = Effect21.gen(function* () {
1940
+ const persistenceLocks = yield* RcMap.make({
1941
+ lookup: (_persistence) => RcMap.make({
1942
+ lookup: (_chatId) => Semaphore2.make(1)
1943
+ })
1944
+ });
1945
+ return Runtime.of({
1946
+ persistenceSemaphore: (persistence, chatId) => RcMap.get(persistenceLocks, persistence).pipe(Effect21.flatMap((chatLocks) => RcMap.get(chatLocks, chatId)))
1947
+ });
1948
+ });
1949
+ var layerRuntime = Layer18.effect(Runtime, makeRuntime);
1950
+
1951
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-message.js
1952
+ import { Effect as Effect22, Option as Option11, Schema as Schema17 } from "effect";
1953
+ import { Prompt as Prompt9, Response as Response6 } from "effect/unstable/ai";
1961
1954
 
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";
1955
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-skill-tool.js
1956
+ import { Schema as Schema16 } from "effect";
1957
+ import { Tool as Tool8 } from "effect/unstable/ai";
1965
1958
  var skillListingBudgetTokens = 2048;
1966
1959
  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)
1960
+ var activateSkillParameters = Schema16.Struct({ name: Schema16.String });
1961
+ var activateSkillSuccess = Schema16.Struct({
1962
+ name: Schema16.String,
1963
+ body: Schema16.String,
1964
+ allowedTools: Schema16.Array(Schema16.String)
1972
1965
  });
1973
- var activateSkillFailure = Schema15.Struct({
1974
- reason: Schema15.Literals(["not-found", "not-model-invocable"]),
1975
- message: Schema15.String
1966
+ var activateSkillFailure = Schema16.Struct({
1967
+ reason: Schema16.Literals(["not-found", "not-model-invocable"]),
1968
+ message: Schema16.String
1976
1969
  });
1977
- var activateSkillTool = Tool9.make(activateSkillToolName, {
1970
+ var activateSkillTool = Tool8.make(activateSkillToolName, {
1978
1971
  description: "Load the full body for one listed Baton skill by name before applying that skill.",
1979
1972
  parameters: activateSkillParameters,
1980
1973
  success: activateSkillSuccess,
@@ -1982,26 +1975,26 @@ var activateSkillTool = Tool9.make(activateSkillToolName, {
1982
1975
  failureMode: "return"
1983
1976
  });
1984
1977
 
1985
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-message.js
1978
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-message.js
1986
1979
  var withSystem = (instructions, prompt) => Prompt9.fromMessages([Prompt9.makeMessage("system", { content: instructions }), ...prompt.content]);
1987
1980
  var skillListingsInstructions = (listings) => `Available skills:
1988
1981
  ${listings}
1989
1982
 
1990
1983
  Call ${activateSkillToolName} with a listed skill name to load its full body before using it.`;
1991
1984
  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);
1985
+ var messageJsonStringCodec = Schema17.fromJsonString(Schema17.toCodecJson(Prompt9.Message));
1986
+ var encodeMessage = Schema17.encodeEffect(messageJsonStringCodec);
1987
+ var decodeMessage = Schema17.decodeEffect(messageJsonStringCodec);
1988
+ var detachMessage = (message) => encodeMessage(message).pipe(Effect22.flatMap(decodeMessage), Effect22.map((detached) => isMessageFromRecall(message) && message.role === "user" && detached.role === "user" ? replaceRecalledMessage(message, detached.content) : detached));
1989
+ var detachPrompt = (prompt) => Effect22.forEach(prompt.content, detachMessage).pipe(Effect22.map(Prompt9.fromMessages));
1990
+ var detachEntry = (entry) => entry._tag === "Message" || entry._tag === "Steering" ? detachMessage(entry.message).pipe(Effect22.map((message) => ({ ...entry, message }))) : Effect22.succeed(entry);
1998
1991
  var preservesRecalledMessages = (allowed, required, transformed) => {
1999
1992
  const allowedSet = new Set(allowed);
2000
1993
  const transformedMessages = recalledMessages(transformed);
2001
1994
  const transformedSet = new Set(transformedMessages);
2002
1995
  return transformedSet.size === transformedMessages.length && transformedMessages.every((message) => allowedSet.has(message)) && required.every((message) => transformedSet.has(message));
2003
1996
  };
2004
- var applyPromptChain = (chain, prompt, context) => Effect20.gen(function* () {
1997
+ var applyPromptChain = (chain, prompt, context) => Effect22.gen(function* () {
2005
1998
  let current = prompt;
2006
1999
  for (const middleware of chain) {
2007
2000
  if (middleware.transformPrompt !== undefined) {
@@ -2018,10 +2011,10 @@ var applyPromptChain = (chain, prompt, context) => Effect20.gen(function* () {
2018
2011
  }
2019
2012
  return current;
2020
2013
  });
2021
- var applyPartChain = (chain, part, context) => Effect20.gen(function* () {
2022
- let current = Option12.some(part);
2014
+ var applyPartChain = (chain, part, context) => Effect22.gen(function* () {
2015
+ let current = Option11.some(part);
2023
2016
  for (const middleware of chain) {
2024
- if (Option12.isNone(current))
2017
+ if (Option11.isNone(current))
2025
2018
  break;
2026
2019
  if (middleware.transformPart !== undefined) {
2027
2020
  current = yield* middleware.transformPart(current.value, context);
@@ -2030,18 +2023,17 @@ var applyPartChain = (chain, part, context) => Effect20.gen(function* () {
2030
2023
  return current;
2031
2024
  });
2032
2025
 
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";
2026
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-suspension.js
2027
+ import { Equal, Option as Option12, Schema as Schema18 } from "effect";
2028
+ import { Prompt as Prompt10, Response as Response7 } from "effect/unstable/ai";
2036
2029
  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))
2030
+ var suspensionMetadata = Schema18.Struct({
2031
+ token: Schema18.String,
2032
+ reason: Schema18.Literals(["tool-wait", "approval"]),
2033
+ tool_call_index: Schema18.optional(Schema18.Int.check(Schema18.isGreaterThanOrEqualTo(0))),
2034
+ tool_call_batch_ids: Schema18.Array(Schema18.String),
2035
+ active_tools: Schema18.optional(Schema18.Array(Schema18.String)),
2036
+ activated_skills: Schema18.optional(Schema18.Array(Schema18.String))
2045
2037
  });
2046
2038
  var unresolvedToolCall = (messages, toolCallId) => {
2047
2039
  const unpaired = new Map;
@@ -2072,36 +2064,51 @@ var unresolvedToolCall = (messages, toolCallId) => {
2072
2064
  }
2073
2065
  }
2074
2066
  const unresolved = [...unpaired.entries()].flatMap(([id, occurrences]) => ambiguous.has(id) ? [] : occurrences.filter(({ call }) => !call.providerExecuted));
2075
- const pending = toolCallId === undefined ? unresolved.find(({ call }) => Option13.isSome(Schema17.decodeUnknownOption(suspensionMetadata)(call.options[suspensionCheckpointOption]))) : unresolved.find(({ call }) => call.id === toolCallId);
2067
+ const pending = toolCallId === undefined ? unresolved.find(({ call }) => Option12.isSome(Schema18.decodeUnknownOption(suspensionMetadata)(call.options[suspensionCheckpointOption]))) : unresolved.find(({ call }) => call.id === toolCallId);
2076
2068
  const pendingMessage = pending === undefined ? undefined : messages[pending.messageIndex];
2069
+ const unresolvedParts = new Set(unresolved.filter(({ messageIndex }) => messageIndex === pending?.messageIndex).map(({ partIndex }) => partIndex));
2077
2070
  const toolCallBatch = pendingMessage?.role === "assistant" ? pendingMessage.content.flatMap((part) => part.type === "tool-call" && !part.providerExecuted ? [
2078
- Response8.makePart("tool-call", {
2071
+ Response7.makePart("tool-call", {
2079
2072
  id: part.id,
2080
2073
  name: part.name,
2081
2074
  params: part.params,
2082
2075
  providerExecuted: false
2083
2076
  })
2084
2077
  ] : []) : [];
2078
+ const unresolvedToolCallIndexes = pendingMessage?.role === "assistant" ? (() => {
2079
+ const indexes = [];
2080
+ let toolCallIndex = 0;
2081
+ for (const [partIndex, part] of pendingMessage.content.entries()) {
2082
+ if (part.type !== "tool-call" || part.providerExecuted)
2083
+ continue;
2084
+ if (unresolvedParts.has(partIndex))
2085
+ indexes.push(toolCallIndex);
2086
+ toolCallIndex += 1;
2087
+ }
2088
+ return indexes;
2089
+ })() : [];
2085
2090
  return pending !== undefined ? {
2086
2091
  call: pending.call,
2087
2092
  messages: messages.slice(0, pending.messageIndex),
2088
2093
  messageIndex: pending.messageIndex,
2089
2094
  partIndex: pending.partIndex,
2090
- toolCallBatch
2095
+ toolCallBatch,
2096
+ unresolvedToolCallIndexes
2091
2097
  } : undefined;
2092
2098
  };
2093
2099
  var suspensionCheckpoint = (messages) => {
2094
2100
  const unresolved = unresolvedToolCall(messages);
2095
2101
  if (unresolved === undefined)
2096
2102
  return;
2097
- const metadata = Schema17.decodeUnknownOption(suspensionMetadata)(unresolved.call.options[suspensionCheckpointOption]);
2098
- if (Option13.isNone(metadata))
2103
+ const metadata = Schema18.decodeUnknownOption(suspensionMetadata)(unresolved.call.options[suspensionCheckpointOption]);
2104
+ if (Option12.isNone(metadata))
2099
2105
  return;
2100
2106
  if (!Equal.equals(metadata.value.tool_call_batch_ids, unresolved.toolCallBatch.map((call) => call.id)))
2101
2107
  return;
2102
2108
  return {
2103
2109
  call: unresolved.call,
2104
2110
  messages: unresolved.messages,
2111
+ unresolvedToolCallIndexes: unresolved.unresolvedToolCallIndexes,
2105
2112
  suspension: AgentSuspended.make({
2106
2113
  ...metadata.value,
2107
2114
  tool_call_batch: unresolved.toolCallBatch,
@@ -2111,7 +2118,7 @@ var suspensionCheckpoint = (messages) => {
2111
2118
  })
2112
2119
  };
2113
2120
  };
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);
2121
+ var sameSuspension = (left, right) => left.token === right.token && left.reason === right.reason && 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
2122
  var suspended = (call, toolCallBatch, toolCallIndex, token, reason) => AgentSuspended.make({
2116
2123
  token,
2117
2124
  reason,
@@ -2122,10 +2129,10 @@ var suspended = (call, toolCallBatch, toolCallIndex, token, reason) => AgentSusp
2122
2129
  tool_call_batch: toolCallBatch.calls
2123
2130
  });
2124
2131
 
2125
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-tool-result.js
2126
- import { HashMap as HashMap4 } from "effect";
2127
- import { Response as Response9 } from "effect/unstable/ai";
2128
- var successResult = (call, outcome) => Response9.toolResultPart({
2132
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-tool-result.js
2133
+ import { HashMap as HashMap5 } from "effect";
2134
+ import { Response as Response8 } from "effect/unstable/ai";
2135
+ var successResult = (call, outcome) => Response8.toolResultPart({
2129
2136
  id: call.id,
2130
2137
  name: call.name,
2131
2138
  isFailure: false,
@@ -2134,7 +2141,7 @@ var successResult = (call, outcome) => Response9.toolResultPart({
2134
2141
  providerExecuted: false,
2135
2142
  preliminary: false
2136
2143
  });
2137
- var domainFailureResult = (call, outcome) => Response9.toolResultPart({
2144
+ var domainFailureResult = (call, outcome) => Response8.toolResultPart({
2138
2145
  id: call.id,
2139
2146
  name: call.name,
2140
2147
  isFailure: true,
@@ -2144,19 +2151,18 @@ var domainFailureResult = (call, outcome) => Response9.toolResultPart({
2144
2151
  preliminary: false
2145
2152
  });
2146
2153
 
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");
2154
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-run.js
2149
2155
  var classifyOtherFailure = () => "other";
2150
2156
  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
+ var progressCapacitySchema = Schema19.Finite.pipe(Schema19.check(Schema19.isInt(), Schema19.isGreaterThan(0)));
2158
+ var progressOverflowPolicySchema = Schema19.Union([
2159
+ Schema19.TaggedStruct("Backpressure", { capacity: progressCapacitySchema }),
2160
+ Schema19.TaggedStruct("Dropping", { capacity: progressCapacitySchema }),
2161
+ Schema19.TaggedStruct("Sliding", { capacity: progressCapacitySchema }),
2162
+ Schema19.TaggedStruct("Fail", { capacity: progressCapacitySchema })
2157
2163
  ]);
2158
2164
  var errorMessage = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
2159
- var isToolNameCollision = Schema18.is(ToolNameCollision);
2165
+ var isToolNameCollision = Schema19.is(ToolNameCollision);
2160
2166
  var appendInstructionFragment = (base, fragment) => {
2161
2167
  if (fragment === undefined || fragment.length === 0)
2162
2168
  return base;
@@ -2171,15 +2177,15 @@ var isTurnPolicyDecision = (input) => {
2171
2177
  return false;
2172
2178
  if (input._tag === "Continue")
2173
2179
  return true;
2174
- return input._tag === "Stop" && "reason" in input && Schema18.is(StopReason)(input.reason);
2180
+ return input._tag === "Stop" && "reason" in input && Schema19.is(StopReason)(input.reason);
2175
2181
  };
2176
- var steeringDrainedEvent = (turn, queue, messages) => ({
2182
+ var steeringDrainedEvent = (turn, queue, inputs) => ({
2177
2183
  _tag: "SteeringDrained",
2178
2184
  turn,
2179
2185
  queue,
2180
- count: messages.length
2186
+ count: inputs.length
2181
2187
  });
2182
- var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen(function* () {
2188
+ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen(function* () {
2183
2189
  if (options.history !== undefined && options.persistence !== undefined) {
2184
2190
  return yield* AgentError.make({
2185
2191
  message: "RunOptions.history and RunOptions.persistence are mutually exclusive",
@@ -2188,39 +2194,47 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2188
2194
  }
2189
2195
  const persistenceOptions = options.persistence;
2190
2196
  const resume = options.resume;
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({
2197
+ const persistenceService = yield* Effect23.serviceOption(Chat2.Persistence);
2198
+ const runtimeService = yield* Effect23.serviceOption(Runtime);
2199
+ const compactionService = yield* Effect23.serviceOption(Compaction);
2200
+ const sessionService = yield* Effect23.serviceOption(SessionStore);
2201
+ const persisted = persistenceOptions === undefined ? undefined : yield* Option13.match(persistenceService, {
2202
+ onNone: () => Effect23.fail(AgentError.make({
2196
2203
  message: "RunOptions.persistence requires Chat.Persistence in context",
2197
2204
  turn: 0
2198
2205
  })),
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), {
2206
+ onSome: (service) => Effect23.gen(function* () {
2207
+ const runtime = yield* Option13.match(runtimeService, {
2208
+ onNone: () => Effect23.fail(AgentError.make({
2209
+ message: "RunOptions.persistence requires Agent.Runtime in context",
2210
+ turn: 0
2211
+ })),
2212
+ onSome: Effect23.succeed
2213
+ });
2214
+ const semaphore = yield* runtime.persistenceSemaphore(service, persistenceOptions.chatId);
2215
+ yield* Effect23.acquireRelease(semaphore.take(1), () => semaphore.release(1), {
2202
2216
  interruptible: true
2203
2217
  });
2204
2218
  const getOptions = persistenceOptions.timeToLive === undefined ? undefined : { timeToLive: persistenceOptions.timeToLive };
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({
2219
+ return yield* resume === undefined ? service.getOrCreate(persistenceOptions.chatId, getOptions).pipe(Effect23.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error }))) : service.get(persistenceOptions.chatId, getOptions).pipe(Effect23.mapError((error) => error._tag === "ChatNotFoundError" ? ResumeMismatch.make({
2206
2220
  reason: "checkpoint-not-found",
2207
2221
  received: resume.suspension
2208
2222
  }) : AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2209
2223
  })
2210
2224
  });
2211
2225
  let recoveredHistory;
2212
- if (resume !== undefined && persisted !== undefined && Option14.isSome(compactionService) && Option14.isSome(sessionService)) {
2213
- yield* Effect21.gen(function* () {
2226
+ if (resume !== undefined && persisted !== undefined && Option13.isSome(compactionService) && Option13.isSome(sessionService)) {
2227
+ yield* Effect23.gen(function* () {
2214
2228
  const path = yield* sessionService.value.path();
2215
2229
  const checkpoint = path.at(-1);
2216
2230
  if (checkpoint?._tag !== "Compaction" || checkpoint.version !== 2)
2217
2231
  return;
2218
2232
  const history = yield* Ref5.get(persisted.history);
2219
2233
  const before = buildContext(path.slice(0, -1));
2220
- if (!Schema18.toEquivalence(Prompt11.Prompt)(before, history))
2234
+ if (!Schema19.toEquivalence(Prompt11.Prompt)(before, history))
2221
2235
  return;
2222
2236
  recoveredHistory = buildContext(path);
2223
- }).pipe(Effect21.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2237
+ }).pipe(Effect23.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2224
2238
  }
2225
2239
  let resumeChat;
2226
2240
  let validatedResume;
@@ -2228,12 +2242,12 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2228
2242
  resumeChat = persisted ?? (yield* options.history === undefined ? Chat2.empty : Chat2.fromPrompt(options.history));
2229
2243
  const received = resume.suspension;
2230
2244
  const resumeHistory = recoveredHistory ?? (yield* Ref5.get(resumeChat.history));
2231
- validatedResume = yield* Effect21.succeed(resumeHistory).pipe(Effect21.flatMap((history) => {
2245
+ validatedResume = yield* Effect23.succeed(resumeHistory).pipe(Effect23.flatMap((history) => {
2232
2246
  const expected = suspensionCheckpoint(history.content);
2233
2247
  if (expected === undefined) {
2234
2248
  return ResumeMismatch.make({ reason: "checkpoint-not-found", received });
2235
2249
  }
2236
- return sameSuspension(expected.suspension, received) ? Effect21.succeed(expected) : ResumeMismatch.make({
2250
+ return sameSuspension(expected.suspension, received) ? Effect23.succeed(expected) : ResumeMismatch.make({
2237
2251
  reason: "identity-mismatch",
2238
2252
  expected: expected.suspension,
2239
2253
  received
@@ -2241,7 +2255,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2241
2255
  }));
2242
2256
  if (recoveredHistory !== undefined && persisted !== undefined) {
2243
2257
  yield* Ref5.set(persisted.history, recoveredHistory);
2244
- yield* persisted.save.pipe(Effect21.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2258
+ yield* persisted.save.pipe(Effect23.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2245
2259
  }
2246
2260
  }
2247
2261
  const staticCandidates = (agent.toolDeclarations ?? Object.values(agent.toolkit.tools).map((tool) => ({
@@ -2260,17 +2274,17 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2260
2274
  turn: 0
2261
2275
  });
2262
2276
  }
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 })));
2277
+ const executor = yield* Effect23.serviceOption(ToolExecutor);
2278
+ const approvals = yield* Effect23.serviceOption(Approvals);
2279
+ const chain = yield* Effect23.serviceOption(ModelMiddleware).pipe(Effect23.map(Option13.match({ onNone: () => [], onSome: (service) => service })));
2266
2280
  if (options.toolOutputMaxBytes !== undefined && (!Number.isFinite(options.toolOutputMaxBytes) || options.toolOutputMaxBytes < 0)) {
2267
2281
  return yield* AgentError.make({
2268
2282
  message: "RunOptions.toolOutputMaxBytes must be a non-negative finite number",
2269
2283
  turn: 0
2270
2284
  });
2271
2285
  }
2272
- const decodedProgressPolicy = Schema18.decodeUnknownOption(progressOverflowPolicySchema)(options.toolProgress === undefined ? defaultProgressOverflowPolicy : options.toolProgress);
2273
- if (Option14.isNone(decodedProgressPolicy)) {
2286
+ const decodedProgressPolicy = Schema19.decodeUnknownOption(progressOverflowPolicySchema)(options.toolProgress === undefined ? defaultProgressOverflowPolicy : options.toolProgress);
2287
+ if (Option13.isNone(decodedProgressPolicy)) {
2274
2288
  return yield* AgentError.make({
2275
2289
  message: "RunOptions.toolProgress must select a supported policy with a positive safe-integer capacity",
2276
2290
  turn: 0
@@ -2290,11 +2304,13 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2290
2304
  });
2291
2305
  }
2292
2306
  const sessionId = options.sessionId ?? "local";
2293
- const instructionsService = yield* Effect21.serviceOption(Instructions);
2294
- const skillSourceService = yield* Effect21.serviceOption(SkillSource);
2295
- const skillRuntime = Option14.isNone(skillSourceService) ? undefined : {
2307
+ const sessionOwnerToken = options.sessionOwnerToken;
2308
+ const sessionAppendOptions = (expectedLeafId) => sessionOwnerToken === undefined ? { expectedLeafId } : { expectedLeafId, ownerToken: sessionOwnerToken };
2309
+ const instructionsService = yield* Effect23.serviceOption(Instructions);
2310
+ const skillSourceService = yield* Effect23.serviceOption(SkillSource);
2311
+ const skillRuntime = Option13.isNone(skillSourceService) ? undefined : {
2296
2312
  source: skillSourceService.value,
2297
- skills: yield* skillSourceService.value.all.pipe(Effect21.mapError((error) => AgentError.make({ message: error.message, turn: 0, cause: error })))
2313
+ skills: yield* skillSourceService.value.all.pipe(Effect23.mapError((error) => AgentError.make({ message: error.message, turn: 0, cause: error })))
2298
2314
  };
2299
2315
  const selectedSkills = skillRuntime === undefined ? [] : selectListings(skillRuntime.skills, skillListingBudgetTokens, []);
2300
2316
  const skillListings = selectedSkills.map((skill) => skill.listing).join(`
@@ -2310,75 +2326,90 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2310
2326
  }
2311
2327
  ] : []
2312
2328
  ]);
2313
- const instructionsEpoch = options.system === undefined && options.history === undefined && Option14.isSome(instructionsService) ? yield* openEpoch(instructionsService.value, { agentName: agent.name, turn: 0 }) : undefined;
2314
- const baseSystem = options.system ?? (instructionsEpoch === undefined ? agent.instructions : instructionsEpoch.baseline.length === 0 ? agent.instructions : instructionsEpoch.baseline);
2329
+ const instructionsEpoch = options.system === undefined && options.history === undefined && Option13.isSome(instructionsService) ? yield* openEpoch(instructionsService.value, { agentName: agent.name, turn: 0 }) : undefined;
2330
+ const baseSystem = options.system ?? (instructionsEpoch === undefined ? agent.instructions : instructionsEpoch.length === 0 ? agent.instructions : instructionsEpoch);
2315
2331
  const system = appendInstructionFragment(baseSystem, options.history === undefined && skillListings.length > 0 ? skillListingsInstructions(skillListings) : undefined);
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 }
2332
+ const resilienceService = yield* Effect23.serviceOption(ModelResilience);
2333
+ const modelRegistryService = yield* Effect23.serviceOption(ModelRegistry);
2334
+ const permissionsService = yield* Effect23.serviceOption(Permissions);
2335
+ const ruleStoreService = yield* Effect23.serviceOption(RuleStore);
2336
+ const authorizationService = yield* Effect23.serviceOption(ToolAuthorizerService);
2337
+ const steeringService = yield* Effect23.serviceOption(Steering);
2338
+ const memoryService = yield* Effect23.serviceOption(Memory);
2339
+ const tokenizerService = yield* Effect23.serviceOption(Tokenizer2.Tokenizer);
2340
+ const defaultRules = yield* Ref5.make([]);
2341
+ const authorizer = agent.authorization ?? Option13.getOrElse(authorizationService, () => make4({
2342
+ permissions: Option13.getOrElse(permissionsService, () => Permissions.of({ evaluate: () => Effect23.succeed({ _tag: "Allow" }) })),
2343
+ approvals: Option13.getOrElse(approvals, () => Approvals.of({ resolve: () => Effect23.succeed({ _tag: "Approved" }) })),
2344
+ ruleStore: Option13.getOrElse(ruleStoreService, () => RuleStore.of({
2345
+ rules: Ref5.get(defaultRules),
2346
+ remember: (rule) => Ref5.update(defaultRules, (rules) => [
2347
+ ...rules.filter((current) => current.pattern !== rule.pattern),
2348
+ rule
2349
+ ])
2350
+ }))
2328
2351
  }));
2329
2352
  const memoryOptions = options.memory ?? (agent.memory === undefined ? undefined : { key: agent.memory });
2330
2353
  const agentModel = agent.model;
2331
- const agentModelRegistry = agentModel === undefined ? undefined : yield* Option14.match(modelRegistryService, {
2332
- onNone: () => Effect21.fail(AgentError.make({
2354
+ const agentModelRegistry = agentModel === undefined ? undefined : yield* Option13.match(modelRegistryService, {
2355
+ onNone: () => Effect23.fail(AgentError.make({
2333
2356
  message: "Agent.model requires ModelRegistry in context",
2334
2357
  turn: 0
2335
2358
  })),
2336
- onSome: Effect21.succeed
2359
+ onSome: Effect23.succeed
2337
2360
  });
2338
2361
  const memoryRuntime = memoryOptions === undefined ? undefined : {
2339
2362
  key: memoryOptions.key,
2340
- service: yield* Option14.match(memoryService, {
2341
- onNone: () => Effect21.fail(AgentError.make({
2363
+ service: yield* Option13.match(memoryService, {
2364
+ onNone: () => Effect23.fail(AgentError.make({
2342
2365
  message: options.memory === undefined ? "Agent.memory requires Memory in context" : "RunOptions.memory requires Memory in context",
2343
2366
  turn: 0
2344
2367
  })),
2345
- onSome: Effect21.succeed
2368
+ onSome: Effect23.succeed
2346
2369
  })
2347
2370
  };
2348
2371
  const seedSystem = persisted !== undefined && system !== undefined && (yield* Ref5.get(persisted.history)).content.length === 0 ? system : undefined;
2349
2372
  const freshChat = options.history !== undefined ? Chat2.fromPrompt(options.history) : system !== undefined ? Chat2.fromPrompt([Prompt11.makeMessage("system", { content: system })]) : Chat2.empty;
2350
2373
  const chat = resumeChat ?? persisted ?? (yield* freshChat);
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* () {
2374
+ const savePersisted = (turn) => persisted === undefined ? Effect23.void : persisted.save.pipe(Effect23.mapError((error) => AgentError.make({ message: errorMessage(error), turn, cause: error })));
2375
+ const appendPending = (turn, pending) => pending.length === 0 ? Ref5.get(chat.history) : Ref5.updateAndGet(chat.history, (history) => Prompt11.concat(history, Prompt11.fromResponseParts(pending))).pipe(Effect23.tap(() => savePersisted(turn)));
2376
+ const checkpointSuspended = (turn, pending, suspension) => Effect23.gen(function* () {
2354
2377
  const withPending = yield* appendPending(turn, pending);
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)) {
2378
+ const unresolved = unresolvedToolCall(withPending.content, suspension.tool_call_id);
2379
+ if (unresolved === undefined || unresolved.call.id !== suspension.tool_call_id || unresolved.call.name !== suspension.tool_name || !Equal2.equals(unresolved.call.params, suspension.tool_params)) {
2357
2380
  return yield* AgentError.make({
2358
2381
  message: "Suspension does not match the unresolved checkpoint call",
2359
2382
  turn
2360
2383
  });
2361
2384
  }
2362
2385
  const metadata = {
2363
- token: suspension2.token,
2364
- reason: suspension2.reason,
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),
2368
- ...suspension2.active_tools === undefined ? {} : { active_tools: suspension2.active_tools },
2369
- ...suspension2.activated_skills === undefined ? {} : { activated_skills: suspension2.activated_skills }
2386
+ token: suspension.token,
2387
+ reason: suspension.reason,
2388
+ ...suspension.tool_call_index === undefined ? {} : { tool_call_index: suspension.tool_call_index },
2389
+ tool_call_batch_ids: suspension.tool_call_batch.map((call) => call.id),
2390
+ ...suspension.active_tools === undefined ? {} : { active_tools: suspension.active_tools },
2391
+ ...suspension.activated_skills === undefined ? {} : { activated_skills: suspension.activated_skills }
2370
2392
  };
2371
2393
  const messages = withPending.content.map((message, messageIndex) => {
2372
- if (messageIndex !== unresolved.messageIndex || message.role !== "assistant")
2394
+ if (message.role !== "assistant")
2373
2395
  return message;
2374
2396
  return Prompt11.makeMessage("assistant", {
2375
- content: message.content.map((part, partIndex) => partIndex === unresolved.partIndex && part.type === "tool-call" ? Prompt11.makePart("tool-call", {
2376
- id: part.id,
2377
- name: part.name,
2378
- params: part.params,
2379
- providerExecuted: part.providerExecuted,
2380
- options: { ...part.options, [suspensionCheckpointOption]: metadata }
2381
- }) : part),
2397
+ content: message.content.map((part, partIndex) => {
2398
+ if (part.type !== "tool-call")
2399
+ return part;
2400
+ const partOptions = { ...part.options };
2401
+ delete partOptions[suspensionCheckpointOption];
2402
+ if (messageIndex === unresolved.messageIndex && partIndex === unresolved.partIndex) {
2403
+ partOptions[suspensionCheckpointOption] = metadata;
2404
+ }
2405
+ return Prompt11.makePart("tool-call", {
2406
+ id: part.id,
2407
+ name: part.name,
2408
+ params: part.params,
2409
+ providerExecuted: part.providerExecuted,
2410
+ options: partOptions
2411
+ });
2412
+ }),
2382
2413
  options: message.options
2383
2414
  });
2384
2415
  });
@@ -2386,32 +2417,32 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2386
2417
  const path = yield* syncSession(turn, withPending);
2387
2418
  const parentId = path.at(-1)?.id ?? null;
2388
2419
  yield* applyCompactionResult(turn, { _tag: "Microcompact", history: checkpoint, prompt: Prompt11.empty }, parentId);
2389
- if (Option14.isNone(activeSession))
2420
+ if (Option13.isNone(activeSession))
2390
2421
  yield* savePersisted(turn);
2391
2422
  return yield* Ref5.get(chat.history);
2392
2423
  });
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));
2424
+ const checkpointPending = (turn, pending) => appendPending(turn, pending).pipe(Effect23.tap((checkpoint) => syncSession(turn, checkpoint)));
2395
2425
  const state = {
2396
2426
  text: "",
2397
2427
  turn: 0,
2398
- pending: [],
2428
+ pending: new Map,
2399
2429
  finish: undefined,
2400
2430
  usage: undefined
2401
2431
  };
2432
+ const pendingResults = () => [...state.pending.entries()].toSorted(([left], [right]) => left - right).map(([, result]) => result);
2402
2433
  const toolState = yield* Ref5.make({
2403
2434
  registry: initialRegistry,
2404
2435
  activatedSkillBodies: new Map
2405
2436
  });
2406
- const restoreActivatedSkills = (history) => Effect21.gen(function* () {
2437
+ const restoreActivatedSkills = (history) => Effect23.gen(function* () {
2407
2438
  for (const message of history.content) {
2408
2439
  if (!Array.isArray(message.content))
2409
2440
  continue;
2410
2441
  for (const part of message.content) {
2411
2442
  if (String(part.type) !== "tool-result" || String(part.name) !== activateSkillToolName || part.isFailure === true)
2412
2443
  continue;
2413
- const activation = Schema18.decodeUnknownOption(activateSkillSuccess)(part.result);
2414
- if (Option14.isNone(activation))
2444
+ const activation = Schema19.decodeUnknownOption(activateSkillSuccess)(part.result);
2445
+ if (Option13.isNone(activation))
2415
2446
  continue;
2416
2447
  if (skillRuntime === undefined) {
2417
2448
  return yield* AgentError.make({
@@ -2442,10 +2473,10 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2442
2473
  yield* Ref5.set(toolState, { registry, activatedSkillBodies });
2443
2474
  }
2444
2475
  }
2445
- }).pipe(Effect21.mapError((error) => isToolNameCollision(error) ? error : AgentError.make({ message: error.message, turn: 0, cause: error })));
2476
+ }).pipe(Effect23.mapError((error) => isToolNameCollision(error) ? error : AgentError.make({ message: error.message, turn: 0, cause: error })));
2446
2477
  if (validatedResume !== undefined)
2447
- yield* Ref5.get(chat.history).pipe(Effect21.flatMap(restoreActivatedSkills));
2448
- const activeSession = Option14.isSome(compactionService) ? sessionService : Option14.none();
2478
+ yield* Ref5.get(chat.history).pipe(Effect23.flatMap(restoreActivatedSkills));
2479
+ const activeSession = Option13.isSome(compactionService) ? sessionService : Option13.none();
2449
2480
  const sessionError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2450
2481
  const compactionError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2451
2482
  const memoryError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
@@ -2459,33 +2490,33 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2459
2490
  const [first, ...rest] = prompt.content;
2460
2491
  return first?.role === "system" ? Prompt11.fromMessages([first, memoryMessage2, ...rest]) : Prompt11.fromMessages([memoryMessage2, ...prompt.content]);
2461
2492
  };
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({
2493
+ const recallInitialPrompt = (prompt) => memoryRuntime === undefined ? Effect23.succeed(prompt) : memoryRuntime.service.recall({ key: memoryRuntime.key, turn: 0, prompt }).pipe(Effect23.mapError((error) => memoryError(0, error)), Effect23.map((items) => insertRecalledItems(prompt, items)));
2494
+ const rememberTurn = (turn, transcript, terminal, path) => memoryRuntime === undefined ? Effect23.void : memoryRuntime.service.remember({
2464
2495
  key: memoryRuntime.key,
2465
2496
  turn,
2466
- transcript: Option14.isSome(activeSession) ? buildMemoryContext(path) : projectTranscript(transcript),
2497
+ transcript: Option13.isSome(activeSession) ? buildMemoryContext(path) : projectTranscript(transcript),
2467
2498
  terminal
2468
- }).pipe(Effect21.mapError((error) => memoryError(turn, error)));
2469
- const messageEquivalence = Schema18.toEquivalence(Prompt11.Message);
2470
- const promptEquivalence2 = Schema18.toEquivalence(Prompt11.Prompt);
2499
+ }).pipe(Effect23.mapError((error) => memoryError(turn, error)));
2500
+ const messageEquivalence = Schema19.toEquivalence(Prompt11.Message);
2501
+ const promptEquivalence2 = Schema19.toEquivalence(Prompt11.Prompt);
2471
2502
  const sessionTranscriptCursor = (projection, transcript) => {
2472
2503
  if (projection.length === 0)
2473
- return Option14.some(0);
2504
+ return Option13.some(0);
2474
2505
  const matches2 = [];
2475
2506
  for (let start = 0;start <= transcript.length - projection.length; start += 1) {
2476
2507
  if (transcript.slice(0, start).every((message) => message.role === "system") && projection.every((message, index) => messageEquivalence(message, transcript[start + index]))) {
2477
2508
  matches2.push(start + projection.length);
2478
2509
  }
2479
2510
  }
2480
- return matches2.length === 1 ? Option14.some(matches2[0]) : Option14.none();
2511
+ return matches2.length === 1 ? Option13.some(matches2[0]) : Option13.none();
2481
2512
  };
2482
- const syncSession = (turn, transcript) => Option14.match(activeSession, {
2483
- onNone: () => Effect21.succeed([]),
2484
- onSome: (session) => Effect21.gen(function* () {
2513
+ const syncSession = (turn, transcript) => Option13.match(activeSession, {
2514
+ onNone: () => Effect23.succeed([]),
2515
+ onSome: (session) => Effect23.gen(function* () {
2485
2516
  let path = yield* session.path();
2486
2517
  const projection = buildContext(path);
2487
2518
  const cursor = sessionTranscriptCursor(projection.content, transcript.content);
2488
- if (Option14.isNone(cursor)) {
2519
+ if (Option13.isNone(cursor)) {
2489
2520
  const checkpoint = path.at(-1);
2490
2521
  const before = buildContext(path.slice(0, -1));
2491
2522
  if (checkpoint?._tag === "Compaction" && checkpoint.version === 2 && promptEquivalence2(before, transcript)) {
@@ -2495,24 +2526,31 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2495
2526
  }
2496
2527
  return yield* AgentError.make({
2497
2528
  message: "Session projection is not a prefix of authoritative Chat history",
2498
- turn
2529
+ turn,
2530
+ diagnostics: diagnose({
2531
+ sessionId,
2532
+ ...sessionOwnerToken === undefined ? {} : { ownerToken: sessionOwnerToken },
2533
+ durableEntryTags: path.map((entry) => entry._tag),
2534
+ projection: projection.content,
2535
+ transcript: transcript.content
2536
+ })
2499
2537
  });
2500
2538
  }
2501
2539
  let expectedLeafId = path.at(-1)?.id ?? null;
2502
2540
  for (const message of transcript.content.slice(cursor.value)) {
2503
- const appended = yield* session.append({ _tag: "Message", message }, { expectedLeafId });
2541
+ const appended = yield* session.append({ _tag: "Message", message }, sessionAppendOptions(expectedLeafId));
2504
2542
  expectedLeafId = appended.id;
2505
2543
  }
2506
2544
  if (expectedLeafId !== (path.at(-1)?.id ?? null))
2507
2545
  path = yield* session.path();
2508
2546
  return path;
2509
- }).pipe(Effect21.mapError((error) => Schema18.is(AgentError)(error) ? error : sessionError(turn, error)))
2547
+ }).pipe(Effect23.mapError((error) => Schema19.is(AgentError)(error) ? error : sessionError(turn, error)))
2510
2548
  });
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 })))
2549
+ const countTokens = (turn, prompt) => Option13.match(tokenizerService, {
2550
+ onNone: () => Effect23.succeed(Math.ceil(JSON.stringify(prompt.content).length / 4)),
2551
+ onSome: (tokenizer) => tokenizer.tokenize(prompt).pipe(Effect23.map((tokens) => tokens.length), Effect23.mapError((error) => AgentError.make({ message: errorMessage(error), turn, cause: error })))
2514
2552
  });
2515
- const compactionUsage = (turn, history, prompt) => countTokens(turn, Prompt11.concat(history, prompt)).pipe(Effect21.map((contextTokens) => ({
2553
+ const compactionUsage = (turn, history, prompt) => countTokens(turn, Prompt11.concat(history, prompt)).pipe(Effect23.map((contextTokens) => ({
2516
2554
  contextTokens,
2517
2555
  contextWindow: options.compaction?.contextWindow ?? Number.POSITIVE_INFINITY,
2518
2556
  reserveTokens: DEFAULT_RESERVE_TOKENS
@@ -2523,14 +2561,14 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2523
2561
  for (const message of Prompt11.concat(result.history, result.prompt).content) {
2524
2562
  if (typeof message.content === "string") {
2525
2563
  if (pending.size > 0) {
2526
- return Effect21.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2564
+ return Effect23.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2527
2565
  }
2528
2566
  optional.clear();
2529
2567
  continue;
2530
2568
  }
2531
2569
  const hasResult = message.content.some((part) => part.type === "tool-result");
2532
2570
  if (pending.size > 0 && !hasResult) {
2533
- return Effect21.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2571
+ return Effect23.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2534
2572
  }
2535
2573
  if (!hasResult)
2536
2574
  optional.clear();
@@ -2538,7 +2576,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2538
2576
  for (const part of message.content) {
2539
2577
  if (part.type === "tool-call") {
2540
2578
  if (responseCalls.has(part.id)) {
2541
- return Effect21.fail(AgentError.make({ message: `Compaction projection contains duplicate tool call ${part.id}`, turn }));
2579
+ return Effect23.fail(AgentError.make({ message: `Compaction projection contains duplicate tool call ${part.id}`, turn }));
2542
2580
  }
2543
2581
  responseCalls.add(part.id);
2544
2582
  if (part.providerExecuted)
@@ -2548,38 +2586,39 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2548
2586
  }
2549
2587
  if (part.type === "tool-result") {
2550
2588
  if (!pending.delete(part.id) && !optional.delete(part.id)) {
2551
- return Effect21.fail(AgentError.make({ message: `Compaction projection contains orphan tool result ${part.id}`, turn }));
2589
+ return Effect23.fail(AgentError.make({ message: `Compaction projection contains orphan tool result ${part.id}`, turn }));
2552
2590
  }
2553
2591
  }
2554
2592
  }
2555
2593
  }
2556
- return pending.size === 0 ? Effect21.void : Effect21.fail(AgentError.make({ message: "Compaction projection contains an unresolved tool call", turn }));
2594
+ return pending.size === 0 ? Effect23.void : Effect23.fail(AgentError.make({ message: "Compaction projection contains an unresolved tool call", turn }));
2557
2595
  };
2558
- const applyCompactionResult = (turn, result, parentId) => Option14.match(activeSession, {
2596
+ const applyCompactionResult = (turn, result, parentId) => Option13.match(activeSession, {
2559
2597
  onNone: () => Ref5.set(chat.history, result.history),
2560
- onSome: (session) => Effect21.gen(function* () {
2598
+ onSome: (session) => Effect23.gen(function* () {
2561
2599
  const id = yield* session.reserveEntryId;
2562
- yield* Effect21.uninterruptibleMask((restore) => restore(session.appendCheckpoint({
2600
+ yield* Effect23.uninterruptibleMask((restore) => restore(session.appendCheckpoint({
2563
2601
  id,
2564
2602
  parentId,
2565
2603
  projectedHistory: result.history,
2566
- ...result._tag === "Summarize" ? { summary: result.summary } : {}
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)))
2604
+ ...result._tag === "Summarize" ? { summary: result.summary } : {},
2605
+ ...sessionOwnerToken === undefined ? {} : { ownerToken: sessionOwnerToken }
2606
+ })).pipe(Effect23.flatMap((appended) => restore(session.path(appended.leafId))), Effect23.map(buildContext), Effect23.tap((projection) => Ref5.set(chat.history, projection)), Effect23.andThen(restore(savePersisted(turn)))));
2607
+ }).pipe(Effect23.mapError((error) => Schema19.is(AgentError)(error) ? error : sessionError(turn, error)))
2569
2608
  });
2570
- const preparePrompt = (turn, prompt, overflow) => Option14.match(compactionService, {
2571
- onNone: () => Effect21.succeed({ prompt, changed: false }),
2572
- onSome: (compaction) => Effect21.gen(function* () {
2609
+ const preparePrompt = (turn, prompt, overflow) => Option13.match(compactionService, {
2610
+ onNone: () => Effect23.succeed({ prompt, changed: false }),
2611
+ onSome: (compaction) => Effect23.gen(function* () {
2573
2612
  const history = yield* Ref5.get(chat.history);
2574
2613
  const path = yield* syncSession(turn, history);
2575
2614
  const usage = yield* compactionUsage(turn, history, prompt);
2576
2615
  const historyRecalled = recalledMessages(history);
2577
2616
  const promptRecalled = recalledMessages(prompt);
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 })));
2617
+ const detachedHistory = yield* detachPrompt(history).pipe(Effect23.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2618
+ const detachedPrompt = yield* detachPrompt(prompt).pipe(Effect23.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2619
+ const originalHistory = yield* detachPrompt(detachedHistory).pipe(Effect23.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2620
+ const originalPrompt = yield* detachPrompt(detachedPrompt).pipe(Effect23.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2621
+ const detachedPath = yield* Effect23.forEach(path, detachEntry).pipe(Effect23.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
2583
2622
  const compacted = yield* compaction.maybeCompact({
2584
2623
  agentName: agent.name,
2585
2624
  sessionId,
@@ -2590,14 +2629,14 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2590
2629
  usage,
2591
2630
  overflow,
2592
2631
  ...options.toolOutputMaxBytes === undefined ? {} : { toolOutputMaxBytes: options.toolOutputMaxBytes }
2593
- }).pipe(Effect21.mapError((error) => compactionError(turn, error)));
2594
- if (Option14.isNone(compacted))
2632
+ }).pipe(Effect23.mapError((error) => compactionError(turn, error)));
2633
+ if (Option13.isNone(compacted))
2595
2634
  return { prompt, changed: false };
2596
2635
  const changed = !Equal2.equals(originalHistory.content, compacted.value.history.content) || !Equal2.equals(originalPrompt.content, compacted.value.prompt.content);
2597
2636
  if (!changed)
2598
2637
  return { prompt, changed: false };
2599
2638
  const allowed = [...historyRecalled, ...promptRecalled];
2600
- const required = Option14.isSome(activeSession) ? promptRecalled : allowed;
2639
+ const required = Option13.isSome(activeSession) ? promptRecalled : allowed;
2601
2640
  if (!preservesRecalledMessages(allowed, required, Prompt11.concat(compacted.value.history, compacted.value.prompt))) {
2602
2641
  return yield* MiddlewareViolation.make({
2603
2642
  turn,
@@ -2609,18 +2648,20 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2609
2648
  return { prompt: compacted.value.prompt, changed: true };
2610
2649
  })
2611
2650
  });
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) => {
2651
+ const boundedSuccessResult = (call, outcome) => options.toolOutputMaxBytes === undefined ? Effect23.succeed(successResult(call, outcome)) : bound(outcome, { toolCallId: call.id, maxBytes: options.toolOutputMaxBytes }).pipe(Effect23.map((bounded2) => successResult(call, bounded2)));
2652
+ const outcomeEvent = (turn, toolCallBatch, toolCallIndex, call, outcome, droppedProgress, registry) => {
2614
2653
  const metadata = droppedProgress === 0 ? {} : { metadata: { toolProgress: { dropped: droppedProgress } } };
2654
+ const completed = (result) => Effect23.sync(() => {
2655
+ state.pending.set(toolCallIndex, result);
2656
+ return { _tag: "ToolExecutionCompleted", turn, call, result, ...metadata };
2657
+ });
2615
2658
  switch (outcome._tag) {
2616
2659
  case "Success":
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 }])));
2618
- case "DomainFailure": {
2619
- const result = domainFailureResult(call, outcome);
2620
- return Effect21.succeed(Stream4.fromIterable([{ _tag: "ToolExecutionCompleted", turn, call, result, ...metadata }]));
2621
- }
2660
+ return (isSkillActivationCall(call, registry) ? Effect23.succeed(successResult(call, outcome)) : boundedSuccessResult(call, outcome)).pipe(Effect23.flatMap(completed));
2661
+ case "DomainFailure":
2662
+ return completed(domainFailureResult(call, outcome));
2622
2663
  case "Suspend":
2623
- return Effect21.succeed(failSuspended(call, toolCallBatch, toolCallIndex, outcome.token, "tool-wait"));
2664
+ return Effect23.fail(suspended(call, toolCallBatch, toolCallIndex, outcome.token, "tool-wait"));
2624
2665
  }
2625
2666
  };
2626
2667
  const defaultExecute = (request, registry) => {
@@ -2628,11 +2669,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2628
2669
  if (registered?.dispatch === "Static") {
2629
2670
  return executeToolkit(staticToolkit, request);
2630
2671
  }
2631
- return registered === undefined ? Effect21.fail(FrameworkFailure.make({
2672
+ return registered === undefined ? Effect23.fail(FrameworkFailure.make({
2632
2673
  stage: "missing-handler",
2633
2674
  tool: request.call.name,
2634
2675
  message: `Tool ${request.call.name} is not registered`
2635
- })) : Effect21.fail(FrameworkFailure.make({
2676
+ })) : Effect23.fail(FrameworkFailure.make({
2636
2677
  stage: "missing-handler",
2637
2678
  tool: request.call.name,
2638
2679
  message: `Activated skill tool ${request.call.name} requires ToolExecutor`
@@ -2649,11 +2690,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2649
2690
  return Queue2.sliding(progressPolicy.capacity);
2650
2691
  }
2651
2692
  };
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);
2693
+ const executeApproved = (turn, call, request, registry) => Stream4.concat(Stream4.fromIterable([{ _tag: "ToolExecutionStarted", turn, call }]), Stream4.unwrap(Effect23.gen(function* () {
2694
+ const progressQueue = yield* Effect23.acquireRelease(makeProgressQueue(), Queue2.shutdown);
2654
2695
  const droppedProgress = yield* Ref5.make(0);
2655
2696
  const emitSemaphore = yield* Semaphore3.make(1);
2656
- const signal = yield* Effect21.abortSignal;
2697
+ const signal = yield* Effect23.abortSignal;
2657
2698
  const context = ToolContext.of({
2658
2699
  signal,
2659
2700
  sessionId,
@@ -2665,9 +2706,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2665
2706
  ...progress.message === undefined ? {} : { message: progress.message },
2666
2707
  ...progress.data === undefined ? {} : { data: progress.data }
2667
2708
  };
2668
- return emitSemaphore.withPermit(Effect21.gen(function* () {
2709
+ return emitSemaphore.withPermit(Effect23.gen(function* () {
2669
2710
  if (progressPolicy._tag === "Sliding") {
2670
- const dropped = yield* Effect21.sync(() => {
2711
+ const dropped = yield* Effect23.sync(() => {
2671
2712
  const full = Queue2.isFullUnsafe(progressQueue);
2672
2713
  Queue2.offerUnsafe(progressQueue, event);
2673
2714
  return full;
@@ -2680,16 +2721,16 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2680
2721
  if (progressPolicy._tag === "Dropping" && !offered) {
2681
2722
  yield* Ref5.update(droppedProgress, (count) => count + 1);
2682
2723
  } else if (progressPolicy._tag === "Fail" && !offered) {
2683
- yield* Queue2.fail(progressQueue, ProgressOverflowError.make({ turn, toolCallId: call.id, capacity: progressPolicy.capacity }));
2724
+ yield* Queue2.fail(progressQueue, ProgressOverflow.make({ turn, toolCallId: call.id, capacity: progressPolicy.capacity }));
2684
2725
  }
2685
2726
  }));
2686
2727
  }
2687
2728
  });
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)))))));
2729
+ const execution = isSkillActivationCall(call, registry) ? activateSkillOutcome(turn, call) : Option13.isNone(executor) ? defaultExecute(request, registry) : executor.value.execute(request).pipe(Effect23.mapError((error) => Schema19.is(RemoteRetryMisconfigured)(error) ? AgentError.make({ message: error.message, turn, cause: error }) : error));
2730
+ const fiber = yield* Effect23.uninterruptibleMask((restore) => restore(execution.pipe(Effect23.provideService(ToolContext, context))).pipe(Effect23.flatMap((outcome) => Ref5.get(droppedProgress).pipe(Effect23.flatMap((dropped) => outcomeEvent(turn, request.toolCallBatch, request.toolCallIndex, call, outcome, dropped, registry)))))).pipe(Effect23.ensuring(Queue2.end(progressQueue).pipe(Effect23.asVoid)), Effect23.forkScoped({ startImmediately: true }));
2731
+ return Stream4.concat(Stream4.fromQueue(progressQueue), Stream4.fromEffect(Fiber3.join(fiber)));
2691
2732
  })));
2692
- const activateSkillOutcome = (turn, call) => Effect21.gen(function* () {
2733
+ const activateSkillOutcome = (turn, call) => Effect23.gen(function* () {
2693
2734
  if (skillRuntime === undefined) {
2694
2735
  return yield* FrameworkFailure.make({
2695
2736
  stage: "missing-handler",
@@ -2697,8 +2738,8 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2697
2738
  message: "SkillSource is not available"
2698
2739
  });
2699
2740
  }
2700
- const params = Schema18.decodeUnknownOption(activateSkillParameters)(call.params);
2701
- if (Option14.isNone(params)) {
2741
+ const params = Schema19.decodeUnknownOption(activateSkillParameters)(call.params);
2742
+ if (Option13.isNone(params)) {
2702
2743
  return yield* FrameworkFailure.make({
2703
2744
  stage: "decode-input",
2704
2745
  tool: call.name,
@@ -2739,9 +2780,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2739
2780
  allowedTools: [...skill.frontmatter.allowedTools ?? []]
2740
2781
  };
2741
2782
  return { _tag: "Success", result: output, encodedResult: output };
2742
- }).pipe(Effect21.mapError((error) => isToolNameCollision(error) || Schema18.is(FrameworkFailure)(error) ? error : skillError(turn, error)));
2783
+ }).pipe(Effect23.mapError((error) => isToolNameCollision(error) || Schema19.is(FrameworkFailure)(error) ? error : skillError(turn, error)));
2743
2784
  const authorizationError2 = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2744
- const toolCallEvents = (turn, toolCallBatch, toolCallIndex, call, messages, registry, authorizationStage, authorizationToken) => {
2785
+ const toolCallEvents = (turn, toolCallBatch, toolCallIndex, call, messages, registry) => {
2745
2786
  const request = { call, toolCallBatch, turn, toolCallIndex, agentName: agent.name, sessionId };
2746
2787
  const candidate = get(registry, call.name);
2747
2788
  if (candidate === undefined)
@@ -2751,22 +2792,22 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2751
2792
  message: `Tool ${call.name} is not active for turn ${turn}`
2752
2793
  }));
2753
2794
  const activeTools = registry.entries.map((entry) => entry.tool.name);
2754
- return Stream4.unwrap(Effect21.gen(function* () {
2795
+ return Stream4.unwrap(Effect23.gen(function* () {
2755
2796
  const activatedSkills = [...(yield* Ref5.get(toolState)).activatedSkillBodies.keys()];
2756
2797
  const approvalEvents = yield* Queue2.bounded(1);
2757
2798
  const fiber = yield* authorizer.authorize({
2758
2799
  call,
2800
+ agentName: agent.name,
2801
+ turn,
2802
+ sessionId,
2759
2803
  tool: candidate.tool,
2760
2804
  active: true,
2761
2805
  activeTools,
2762
2806
  activatedSkills,
2763
- ...authorizationStage === undefined ? {} : { authorizationStage },
2764
- ...authorizationToken === undefined ? {} : { authorizationToken },
2765
2807
  messages,
2766
- execution: request,
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 }));
2769
- return Stream4.concat(Stream4.fromQueue(approvalEvents), Stream4.fromEffect(Fiber.join(fiber)).pipe(Stream4.flatMap((decision2) => {
2808
+ onApprovalRequired: Queue2.offer(approvalEvents, { _tag: "ApprovalRequested", turn, call }).pipe(Effect23.asVoid)
2809
+ }).pipe(Effect23.mapError((error) => authorizationError2(turn, error)), Effect23.ensuring(Queue2.end(approvalEvents).pipe(Effect23.asVoid)), Effect23.forkScoped({ startImmediately: true }));
2810
+ return Stream4.concat(Stream4.fromQueue(approvalEvents), Stream4.fromEffect(Fiber3.join(fiber)).pipe(Stream4.flatMap((decision2) => {
2770
2811
  switch (decision2._tag) {
2771
2812
  case "Execute":
2772
2813
  return executeApproved(turn, call, request, registry);
@@ -2780,7 +2821,6 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2780
2821
  return Stream4.fail(AgentSuspended.make({
2781
2822
  token: decision2.suspension.token,
2782
2823
  reason: "approval",
2783
- authorization_stage: decision2.suspension.authorization_stage ?? "approval",
2784
2824
  tool_call_index: toolCallIndex,
2785
2825
  tool_call_id: call.id,
2786
2826
  tool_name: call.name,
@@ -2793,8 +2833,8 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2793
2833
  })));
2794
2834
  }));
2795
2835
  };
2796
- const captureFinishPart = (part) => Effect21.gen(function* () {
2797
- const span = yield* Effect21.currentSpan;
2836
+ const captureFinishPart = (part) => Effect23.gen(function* () {
2837
+ const span = yield* Effect23.currentSpan;
2798
2838
  state.finish = {
2799
2839
  usage: state.finish === undefined ? part.usage : addUsage(state.finish.usage, part.usage),
2800
2840
  reason: part.reason
@@ -2808,9 +2848,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2808
2848
  },
2809
2849
  response: { finishReasons: [part.reason] }
2810
2850
  });
2811
- }).pipe(Effect21.orDie);
2812
- const captureStructuredUsage = (content) => Effect21.gen(function* () {
2813
- const span = yield* Effect21.currentSpan;
2851
+ }).pipe(Effect23.orDie);
2852
+ const captureStructuredUsage = (content) => Effect23.gen(function* () {
2853
+ const span = yield* Effect23.currentSpan;
2814
2854
  for (const part of content) {
2815
2855
  if (part.type === "finish") {
2816
2856
  state.usage = state.usage === undefined ? part.usage : addUsage(state.usage, part.usage);
@@ -2824,17 +2864,17 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2824
2864
  });
2825
2865
  }
2826
2866
  }
2827
- }).pipe(Effect21.orDie);
2828
- const withModelResilience = (effect) => Option14.match(resilienceService, {
2867
+ }).pipe(Effect23.orDie);
2868
+ const withModelResilience = (effect) => Option13.match(resilienceService, {
2829
2869
  onNone: () => effect,
2830
- onSome: (resilience) => Effect21.flatMap(LanguageModel5.LanguageModel, (model) => effect.pipe(Effect21.provideService(LanguageModel5.LanguageModel, apply(model, {
2870
+ onSome: (resilience) => Effect23.flatMap(LanguageModel6.LanguageModel, (model) => effect.pipe(Effect23.provideService(LanguageModel6.LanguageModel, apply(model, {
2831
2871
  ...resilience,
2832
2872
  classify: (error) => classifyFailure(model, error) === "context-overflow" ? "terminal" : resilience.classify(error)
2833
2873
  }))))
2834
2874
  });
2835
2875
  const withAgentModel = (effect) => agentModelRegistry === undefined || agentModel === undefined ? effect : agentModelRegistry.operate(agentModel, effect);
2836
2876
  function provideAgentModel(stream2) {
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 }))));
2877
+ return agentModelRegistry === undefined || agentModel === undefined ? stream2 : agentModelRegistry.stream(agentModel, stream2).pipe(Stream4.catchTag("@batonfx/core/LanguageModelNotRegistered", (error) => Stream4.fail(AgentError.make({ message: errorMessage(error), turn: state.turn, cause: error }))));
2838
2878
  }
2839
2879
  const partEvents = (turn, part) => {
2840
2880
  if (part.type === "error") {
@@ -2851,33 +2891,29 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2851
2891
  }
2852
2892
  return modelPart;
2853
2893
  };
2854
- const recordPending = (event) => Effect21.sync(() => {
2855
- if (event._tag === "ToolExecutionCompleted")
2856
- state.pending.push(event.result);
2857
- });
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({
2894
+ const transformPart = (turn, part) => applyPartChain(chain, part, { agentName: agent.name, turn }).pipe(Effect23.flatMap(Option13.match({
2895
+ onSome: (transformed) => Effect23.succeed(Option13.some(transformed)),
2896
+ onNone: () => part.type === "tool-call" ? Effect23.fail(MiddlewareViolation.make({
2861
2897
  turn,
2862
2898
  detail: "ModelMiddleware dropped a tool-call part"
2863
- })) : Effect21.succeed(Option14.none())
2899
+ })) : Effect23.succeed(Option13.none())
2864
2900
  })));
2865
2901
  const validateToolCallId = (idState, part) => {
2866
2902
  if (part.type !== "tool-call")
2867
- return Effect21.void;
2903
+ return Effect23.void;
2868
2904
  return Ref5.modify(idState, (current) => {
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 }));
2905
+ const existingFirstIndex = HashMap6.get(current.firstIndexes, part.id);
2906
+ const duplicate = Option13.map(existingFirstIndex, (index) => DuplicateToolCallId.make({ id: part.id, firstIndex: index, duplicateIndex: current.nextIndex }));
2871
2907
  return [
2872
2908
  duplicate,
2873
2909
  {
2874
2910
  nextIndex: current.nextIndex + 1,
2875
- firstIndexes: Option14.isSome(existingFirstIndex) ? current.firstIndexes : HashMap5.set(current.firstIndexes, part.id, current.nextIndex)
2911
+ firstIndexes: Option13.isSome(existingFirstIndex) ? current.firstIndexes : HashMap6.set(current.firstIndexes, part.id, current.nextIndex)
2876
2912
  }
2877
2913
  ];
2878
- }).pipe(Effect21.flatMap(Option14.match({
2879
- onNone: () => Effect21.void,
2880
- onSome: Effect21.fail
2914
+ }).pipe(Effect23.flatMap(Option13.match({
2915
+ onNone: () => Effect23.void,
2916
+ onSome: Effect23.fail
2881
2917
  })));
2882
2918
  };
2883
2919
  const modelTurn = (turn, prompt, registry, overrides) => {
@@ -2889,32 +2925,35 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2889
2925
  let preparedState;
2890
2926
  const singleFailure = (cause) => {
2891
2927
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
2892
- return reason !== undefined && Cause4.isFailReason(reason) ? Option14.some(reason.error) : Option14.none();
2928
+ return reason !== undefined && Cause4.isFailReason(reason) ? Option13.some(reason.error) : Option13.none();
2893
2929
  };
2894
2930
  const retryableOverflow = (cause, hasEmitted) => {
2895
2931
  const failure2 = singleFailure(cause);
2896
- return retryOverflow && !hasEmitted && Option14.isSome(failure2) && classifyFailure2(failure2.value) === "context-overflow" && Option14.isSome(compactionService);
2932
+ if (Option13.isNone(failure2))
2933
+ return false;
2934
+ const classifiedFailure = Schema19.is(AgentError)(failure2.value) && failure2.value.cause !== undefined ? failure2.value.cause : failure2.value;
2935
+ return retryOverflow && !hasEmitted && Option13.isSome(compactionService) && classifyFailure2(classifiedFailure) === "context-overflow";
2897
2936
  };
2898
2937
  return Stream4.fromChannel(Channel.acquireUseRelease(Ref5.make({
2899
2938
  nextIndex: 0,
2900
- firstIndexes: HashMap5.empty()
2901
- }), (toolCallIds) => Stream4.unwrap(Effect21.gen(function* () {
2902
- const activeModel = yield* LanguageModel5.LanguageModel;
2939
+ firstIndexes: HashMap6.empty()
2940
+ }), (toolCallIds) => Stream4.unwrap(Effect23.gen(function* () {
2941
+ const activeModel = yield* LanguageModel6.LanguageModel;
2903
2942
  classifyFailure2 = (error) => classifyFailure(activeModel, error);
2904
2943
  const prepared = yield* preparePrompt(turn, activePrompt, compactOverflow);
2905
2944
  if (compactOverflow && !prepared.changed && overflowCause !== undefined) {
2906
- return yield* Effect21.failCause(overflowCause);
2945
+ return yield* Effect23.failCause(overflowCause);
2907
2946
  }
2908
2947
  const preparedPrompt = prepared.prompt;
2909
2948
  const history = yield* Ref5.get(chat.history);
2910
2949
  preparedState = { history, preparedPrompt };
2911
2950
  const responsePrompt = Prompt11.concat(history, preparedPrompt);
2912
2951
  const messages = responsePrompt.content;
2913
- const rawParts = LanguageModel5.streamText({
2952
+ const rawParts = LanguageModel6.streamText({
2914
2953
  prompt: responsePrompt,
2915
2954
  toolkit: activeRegistry.toolkit,
2916
2955
  disableToolCallResolution: true
2917
- }).pipe(Stream4.tap(() => Effect21.sync(() => {
2956
+ }).pipe(Stream4.mapEffect((part) => part.type === "error" ? Effect23.fail(isToolNameCollision(part.error) ? part.error : AgentError.make({ message: errorMessage(part.error), turn, cause: part.error })) : Effect23.succeed(part)), Stream4.tap(() => Effect23.sync(() => {
2918
2957
  emitted = true;
2919
2958
  })), Stream4.catchCause((cause) => {
2920
2959
  if (Cause4.hasInterrupts(cause) || Cause4.hasDies(cause))
@@ -2922,18 +2961,21 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2922
2961
  if (retryableOverflow(cause, emitted))
2923
2962
  return Stream4.failCause(cause);
2924
2963
  const error = singleFailure(cause);
2925
- if (Option14.isNone(error))
2964
+ if (Option13.isNone(error))
2926
2965
  return Stream4.failCause(cause);
2927
- return Stream4.make(Response10.makePart("error", { error: error.value }));
2966
+ if (Schema19.is(AgentError)(error.value) || isToolNameCollision(error.value)) {
2967
+ return Stream4.fail(error.value);
2968
+ }
2969
+ return Stream4.make(Response9.makePart("error", { error: error.value }));
2928
2970
  }));
2929
- return rawParts.pipe(Stream4.mapEffect((part) => transformPart(turn, part)), Stream4.flatMap(Option14.match({ onNone: () => Stream4.empty, onSome: Stream4.make })), Stream4.map((part) => ({
2971
+ return rawParts.pipe(Stream4.mapEffect((part) => transformPart(turn, part)), Stream4.flatMap(Option13.match({ onNone: () => Stream4.empty, onSome: Stream4.make })), Stream4.map((part) => ({
2930
2972
  part,
2931
2973
  messages,
2932
- accept: validateToolCallId(toolCallIds, part).pipe(Effect21.andThen(Effect21.sync(() => {
2974
+ accept: validateToolCallId(toolCallIds, part).pipe(Effect23.andThen(Effect23.sync(() => {
2933
2975
  transformedParts.push(part);
2934
2976
  })))
2935
2977
  })));
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) => {
2978
+ })).pipe(Stream4.toChannel), (_, exit) => preparedState === undefined || Exit2.isFailure(exit) && retryableOverflow(exit.cause, emitted) ? Effect23.void : Ref5.set(chat.history, Prompt11.concat(Prompt11.concat(preparedState.history, preparedState.preparedPrompt), Prompt11.fromResponseParts(transformedParts))).pipe(Effect23.andThen(persisted === undefined ? Effect23.void : persisted.save), Effect23.orDie, Effect23.asVoid))).pipe(Stream4.catchCause((cause) => {
2937
2979
  if (Cause4.hasInterrupts(cause) || Cause4.hasDies(cause))
2938
2980
  return Stream4.failCause(cause);
2939
2981
  if (retryableOverflow(cause, emitted)) {
@@ -2942,15 +2984,15 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2942
2984
  return Stream4.failCause(cause);
2943
2985
  }), Stream4.catchCause((cause) => {
2944
2986
  const failure2 = singleFailure(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);
2987
+ return Option13.isSome(failure2) && AiError4.isAiError(failure2.value) ? Stream4.fail(AgentError.make({ message: errorMessage(failure2.value), turn, cause: failure2.value })) : Stream4.failCause(cause);
2946
2988
  }));
2947
2989
  };
2948
- const parts = Stream4.unwrap(applyPromptChain(chain, Prompt11.make(prompt), { agentName: agent.name, turn }).pipe(Effect21.map((transformedPrompt) => {
2990
+ const parts = Stream4.unwrap(applyPromptChain(chain, Prompt11.make(prompt), { agentName: agent.name, turn }).pipe(Effect23.map((transformedPrompt) => {
2949
2991
  let nextToolCallIndex = 0;
2950
2992
  const calls = new Array;
2951
2993
  const executions = new Array;
2952
2994
  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 }) => {
2995
+ const accepted = attempt(transformedPrompt, true).pipe(Stream4.mapEffect(({ accept, part, messages }) => accept.pipe(Effect23.as({ part, messages }))), Stream4.map(({ part, messages }) => {
2954
2996
  const toolCallIndex = nextToolCallIndex;
2955
2997
  if (part.type === "tool-call" && part.providerExecuted !== true) {
2956
2998
  const call = part;
@@ -2965,12 +3007,12 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2965
3007
  Object.freeze(toolCallBatch);
2966
3008
  const concurrency = agent.toolExecution?.concurrency ?? 1;
2967
3009
  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));
3010
+ return concurrency === 1 ? executionStreams.pipe(Stream4.flatMap(({ call, messages, toolCallIndex }) => toolCallEvents(turn, toolCallBatch, toolCallIndex, call, messages, activeRegistry))) : executionStreams.pipe(Stream4.mapEffect(({ call, messages, toolCallIndex }) => Stream4.runCollect(toolCallEvents(turn, toolCallBatch, toolCallIndex, call, messages, activeRegistry)), { concurrency }), Stream4.flatMap(Stream4.fromIterable));
2969
3011
  }));
2970
3012
  })));
2971
- const resilientParts = Option14.match(resilienceService, {
3013
+ const resilientParts = Option13.match(resilienceService, {
2972
3014
  onNone: () => parts,
2973
- onSome: (resilience) => Stream4.unwrap(LanguageModel5.LanguageModel.pipe(Effect21.map((model) => parts.pipe(Stream4.provideService(LanguageModel5.LanguageModel, apply(model, {
3015
+ onSome: (resilience) => Stream4.unwrap(LanguageModel6.LanguageModel.pipe(Effect23.map((model) => parts.pipe(Stream4.provideService(LanguageModel6.LanguageModel, apply(model, {
2974
3016
  ...resilience,
2975
3017
  classify: (error) => classifyFailure(model, error) === "context-overflow" ? "terminal" : resilience.classify(error)
2976
3018
  }))))))
@@ -2990,30 +3032,30 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
2990
3032
  transcript,
2991
3033
  ...state.usage === undefined ? {} : { usage: state.usage }
2992
3034
  });
2993
- const structuredFinalEvents = (structuredTurn, config) => Stream4.fromEffect(Effect21.gen(function* () {
3035
+ const structuredFinalEvents = (structuredTurn, config) => Stream4.fromEffect(Effect23.gen(function* () {
2994
3036
  const transformedPrompt = yield* applyPromptChain(chain, Prompt11.make(config.objectPrompt), {
2995
3037
  agentName: agent.name,
2996
3038
  turn: structuredTurn
2997
3039
  });
2998
3040
  const history = yield* Ref5.get(chat.history);
2999
- const response = yield* LanguageModel5.generateObject({
3041
+ const response = yield* LanguageModel6.generateObject({
3000
3042
  prompt: Prompt11.concat(history, transformedPrompt),
3001
3043
  schema: config.schema,
3002
3044
  objectName: config.objectName,
3003
3045
  toolChoice: "none"
3004
- }).pipe(withModelResilience, withAgentModel, Effect21.catchCause((cause) => {
3046
+ }).pipe(withModelResilience, withAgentModel, Effect23.catchCause((cause) => {
3005
3047
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
3006
- return reason !== undefined && Cause4.isFailReason(reason) ? Effect21.fail(AgentError.make({
3048
+ return reason !== undefined && Cause4.isFailReason(reason) ? Effect23.fail(AgentError.make({
3007
3049
  message: errorMessage(reason.error),
3008
3050
  turn: structuredTurn,
3009
3051
  cause: reason.error
3010
- })) : Effect21.failCause(cause);
3052
+ })) : Effect23.failCause(cause);
3011
3053
  }));
3012
3054
  yield* captureStructuredUsage(response.content);
3013
3055
  const transcript = Prompt11.concat(Prompt11.concat(history, transformedPrompt), Prompt11.fromResponseParts(response.content));
3014
3056
  const path = yield* syncSession(structuredTurn, history);
3015
3057
  yield* applyCompactionResult(structuredTurn, { _tag: "Microcompact", history: transcript, prompt: Prompt11.empty }, path.at(-1)?.id ?? null);
3016
- if (Option14.isNone(activeSession))
3058
+ if (Option13.isNone(activeSession))
3017
3059
  yield* savePersisted(structuredTurn);
3018
3060
  const structuredOutput = {
3019
3061
  _tag: "StructuredOutput",
@@ -3023,17 +3065,17 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
3023
3065
  };
3024
3066
  return [structuredOutput, terminalCompletedEvent(structuredTurn, transcript)];
3025
3067
  })).pipe(Stream4.flatMap((events) => Stream4.fromIterable(events)));
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([]),
3068
+ const promptFromSteeringInputs = (inputs) => inputs.reduce((prompt, input) => Prompt11.concat(prompt, input.prompt), Prompt11.empty);
3069
+ const takeSteering = () => Option13.match(steeringService, {
3070
+ onNone: () => Effect23.succeed([]),
3029
3071
  onSome: (service) => service.takeSteering
3030
3072
  });
3031
- const takeFollowUp = () => Option14.match(steeringService, {
3032
- onNone: () => Effect21.succeed([]),
3073
+ const takeFollowUp = () => Option13.match(steeringService, {
3074
+ onNone: () => Effect23.succeed([]),
3033
3075
  onSome: (service) => service.takeFollowUp
3034
3076
  });
3035
- const afterTurn = (turn) => Effect21.gen(function* () {
3036
- const pending = state.pending;
3077
+ const afterTurn = (turn) => Effect23.gen(function* () {
3078
+ const pending = pendingResults();
3037
3079
  const transcript = yield* checkpointPending(turn, pending);
3038
3080
  const path = yield* syncSession(turn, transcript);
3039
3081
  yield* rememberTurn(turn, transcript, pending.length === 0, path);
@@ -3043,7 +3085,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
3043
3085
  if (followUp.length > 0) {
3044
3086
  return {
3045
3087
  events: Stream4.fromIterable([completed, steeringDrainedEvent(turn, "followUp", followUp)]),
3046
- next: { prompt: promptFromSteeringMessages(followUp) }
3088
+ next: { prompt: promptFromSteeringInputs(followUp) }
3047
3089
  };
3048
3090
  }
3049
3091
  if (structured !== undefined) {
@@ -3064,7 +3106,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
3064
3106
  });
3065
3107
  if (!isTurnPolicyDecision(evaluated)) {
3066
3108
  return yield* TurnPolicyError.make({
3067
- message: "TurnPolicy returned an invalid decision; reasonless Stop decisions must be adapted with TurnPolicy.fromLegacy",
3109
+ message: "TurnPolicy returned an invalid decision; Stop decisions must include a reason",
3068
3110
  cause: evaluated
3069
3111
  });
3070
3112
  }
@@ -3086,9 +3128,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
3086
3128
  })))
3087
3129
  };
3088
3130
  }
3089
- state.pending = [];
3131
+ state.pending.clear();
3090
3132
  const steering = yield* takeSteering();
3091
- const basePrompt = steering.length === 0 ? Prompt11.empty : promptFromSteeringMessages(steering);
3133
+ const basePrompt = steering.length === 0 ? Prompt11.empty : promptFromSteeringInputs(steering);
3092
3134
  const prompt = decision2.overrides?.instructions === undefined ? basePrompt : withSystem(decision2.overrides.instructions, basePrompt);
3093
3135
  return {
3094
3136
  events: Stream4.fromIterable(steering.length === 0 ? [completed] : [completed, steeringDrainedEvent(turn, "steering", steering)]),
@@ -3102,7 +3144,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
3102
3144
  const runTurn = (turn, prompt, overrides) => {
3103
3145
  let next;
3104
3146
  let structuredTurn;
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) => {
3147
+ const currentTurn = Stream4.fromIterable([{ _tag: "TurnStarted", turn }]).pipe(Stream4.concat(resetTurnState(turn)), Stream4.concat(Stream4.unwrap(Ref5.get(toolState).pipe(Effect23.map(({ registry }) => modelTurn(turn, prompt, registry, overrides))))), Stream4.concat(Stream4.unwrap(afterTurn(turn).pipe(Effect23.map((result) => {
3106
3148
  next = result.next;
3107
3149
  structuredTurn = result.structuredTurn;
3108
3150
  return result.events;
@@ -3116,10 +3158,10 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
3116
3158
  };
3117
3159
  const resumeStream = (checkpoint) => {
3118
3160
  let next;
3119
- const currentTurn = resetTurnState(0).pipe(Stream4.concat(Stream4.unwrap(Ref5.get(toolState).pipe(Effect21.map((tools) => {
3120
- const suspension2 = checkpoint.suspension;
3121
- const registry = suspension2.authorization_stage === undefined && suspension2.active_tools === undefined ? tools.registry : select(tools.registry, suspension2.active_tools ?? []);
3122
- const calls = suspension2.tool_call_batch.map((call) => Response10.makePart("tool-call", {
3161
+ const currentTurn = resetTurnState(0).pipe(Stream4.concat(Stream4.unwrap(Ref5.get(toolState).pipe(Effect23.map((tools) => {
3162
+ const suspension = checkpoint.suspension;
3163
+ const registry = suspension.active_tools === undefined ? tools.registry : select(tools.registry, suspension.active_tools);
3164
+ const calls = suspension.tool_call_batch.map((call) => Response9.makePart("tool-call", {
3123
3165
  id: call.id,
3124
3166
  name: call.name,
3125
3167
  params: call.params,
@@ -3127,15 +3169,18 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
3127
3169
  metadata: call.metadata
3128
3170
  }));
3129
3171
  const toolCallBatch = { calls };
3130
- const startIndex = suspension2.tool_call_index ?? 0;
3131
- if (calls[startIndex] === undefined) {
3172
+ const suspendedIndex = suspension.tool_call_index ?? 0;
3173
+ if (calls[suspendedIndex] === undefined) {
3132
3174
  return Stream4.fail(AgentError.make({ message: "Suspension tool call index is outside its batch", turn: 0 }));
3133
3175
  }
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);
3176
+ const executions = Stream4.fromIterable(checkpoint.unresolvedToolCallIndexes.map((toolCallIndex) => ({
3177
+ call: calls[toolCallIndex],
3178
+ toolCallIndex
3179
+ })));
3180
+ const execute = ({ call, toolCallIndex }) => toolCallEvents(0, toolCallBatch, toolCallIndex, call, checkpoint.messages, registry);
3136
3181
  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) => {
3182
+ return concurrency === 1 ? executions.pipe(Stream4.flatMap(execute)) : executions.pipe(Stream4.mapEffect((execution) => Stream4.runCollect(execute(execution)), { concurrency }), Stream4.flatMap(Stream4.fromIterable));
3183
+ })))), Stream4.concat(Stream4.unwrap(afterTurn(0).pipe(Effect23.map((result) => {
3139
3184
  next = result.next;
3140
3185
  return result.events;
3141
3186
  })))), Stream4.withSpan("Baton.Agent.turn", { attributes: { "baton.turn": 0 } }));
@@ -3146,22 +3191,22 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect21.gen
3146
3191
  const runStream = validatedResume === undefined ? runTurn(0, initialPrompt) : resumeStream(validatedResume);
3147
3192
  return runStream.pipe(Stream4.catchCause((cause) => {
3148
3193
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
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))));
3194
+ if (reason !== undefined && Cause4.isFailReason(reason) && Schema19.is(DuplicateToolCallId)(reason.error)) {
3195
+ return Stream4.unwrap(checkpointPending(state.turn, pendingResults()).pipe(Effect23.map(() => Stream4.failCause(cause))));
3151
3196
  }
3152
- if (reason !== undefined && Cause4.isFailReason(reason) && Schema18.is(AgentSuspended)(reason.error)) {
3153
- const suspension2 = reason.error;
3154
- return Stream4.unwrap(Effect21.gen(function* () {
3155
- const checkpoint = yield* checkpointSuspended(state.turn, state.pending, suspension2);
3197
+ if (reason !== undefined && Cause4.isFailReason(reason) && Schema19.is(AgentSuspended)(reason.error)) {
3198
+ const suspension = reason.error;
3199
+ return Stream4.unwrap(Effect23.gen(function* () {
3200
+ const checkpoint = yield* checkpointSuspended(state.turn, pendingResults(), suspension);
3156
3201
  yield* syncSession(state.turn, checkpoint);
3157
3202
  return Stream4.concat(Stream4.fromIterable([turnCompletedEvent(state.turn, checkpoint)]), Stream4.failCause(cause));
3158
3203
  }));
3159
3204
  }
3160
3205
  return Stream4.failCause(cause);
3161
3206
  }));
3162
- })).pipe(Stream4.withSpan("Baton.Agent.run", { attributes: { "baton.agent.name": agent.name } }), (run) => agent[ModelLayerTypeId] === undefined ? run : run.pipe(Stream4.provide(agent[ModelLayerTypeId])));
3207
+ })).pipe(Stream4.withSpan("Baton.Agent.run", { attributes: { "baton.agent.name": agent.name } }));
3163
3208
 
3164
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent.js
3209
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent.js
3165
3210
  var AgentTypeId = Symbol.for("@batonfx/core/Agent");
3166
3211
  function make5(options) {
3167
3212
  const declaredTools = "tools" in options && Array.isArray(options.tools) ? options.tools : undefined;
@@ -3199,32 +3244,20 @@ function make5(options) {
3199
3244
  };
3200
3245
  }
3201
3246
  var defaultObjectPrompt = "Return the final structured output for the task above.";
3202
- var provideModel = dual7(2, (agent, layer8) => ({
3203
- ...agent,
3204
- policy: agent.policy,
3205
- ...agent.authorization === undefined ? {} : {
3206
- authorization: agent.authorization
3207
- },
3208
- [AgentTypeId]: {
3209
- tools: (value) => value,
3210
- requirements: (value) => value
3211
- },
3212
- [ModelLayerTypeId]: layer8
3247
+ var stream2 = dual6(2, (agent, options) => streamInternal(agent, options, options.output === undefined ? undefined : {
3248
+ schema: options.output.schema,
3249
+ objectName: options.output.name ?? "output",
3250
+ objectPrompt: options.output.prompt ?? defaultObjectPrompt
3213
3251
  }));
3214
- var stream2 = dual7(2, (agent, options) => streamInternal(agent, options, options.schema === undefined ? undefined : {
3215
- schema: options.schema,
3216
- objectName: options.objectName ?? "output",
3217
- objectPrompt: options.objectPrompt ?? defaultObjectPrompt
3218
- }));
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 }))
3252
+ var generateText = (agent, options) => Stream5.runLast(streamInternal(agent, options, undefined)).pipe(Effect24.flatMap(Option14.match({
3253
+ onNone: () => Effect24.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 })),
3254
+ onSome: (event) => event._tag === "Completed" ? Effect24.succeed({ text: event.text, turns: event.turns, transcript: event.transcript }) : Effect24.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 }))
3222
3255
  })));
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({
3256
+ var generateObjectResult = (agent, options, structured) => Stream5.runFold(streamInternal(agent, options, structured), () => ({ value: Option14.none(), completed: Option14.none() }), (acc, event) => event._tag === "StructuredOutput" ? { ...acc, value: Option14.some(event.value) } : event._tag === "Completed" ? { ...acc, completed: Option14.some(event) } : acc).pipe(Effect24.flatMap(({ value, completed }) => Option14.match(completed, {
3257
+ onNone: () => Effect24.fail(AgentError.make({ message: "Agent object run ended without a Completed event", turn: 0 })),
3258
+ onSome: (event) => Option14.match(value, {
3259
+ onNone: () => Effect24.fail(AgentError.make({ message: "Agent object run ended without a StructuredOutput event", turn: 0 })),
3260
+ onSome: (typedValue) => Effect24.succeed({
3228
3261
  text: event.text,
3229
3262
  turns: event.turns,
3230
3263
  transcript: event.transcript,
@@ -3232,42 +3265,46 @@ var generateObjectResult = (agent, options) => Stream5.runFold(stream2(agent, op
3232
3265
  })
3233
3266
  })
3234
3267
  })));
3235
- var generate = dual7(2, (agent, options) => options.schema === undefined ? generateText(agent, options) : generateObjectResult(agent, options));
3268
+ var generate = dual6(2, (agent, options) => options.output === undefined ? generateText(agent, options) : generateObjectResult(agent, options, {
3269
+ schema: options.output.schema,
3270
+ objectName: options.output.name ?? "output",
3271
+ objectPrompt: options.output.prompt ?? defaultObjectPrompt
3272
+ }));
3236
3273
 
3237
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/agent-tool.js
3274
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/agent-tool.js
3238
3275
  var exports_agent_tool = {};
3239
3276
  __export(exports_agent_tool, {
3240
3277
  asTool: () => asTool
3241
3278
  });
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 });
3279
+ import { Cause as Cause5, Effect as Effect25, Function as Function7, Schema as Schema21 } from "effect";
3280
+ import { Prompt as Prompt13, Tool as Tool11, Toolkit as Toolkit6 } from "effect/unstable/ai";
3281
+ var defaultParameters = Schema21.Struct({ prompt: Schema21.String });
3245
3282
  var errorMessage2 = (error) => {
3246
- if (Schema20.is(AgentSuspended)(error)) {
3283
+ if (Schema21.is(AgentSuspended)(error)) {
3247
3284
  return `suspended on ${error.tool_name}: ${error.reason}`;
3248
3285
  }
3249
- if (Schema20.is(AgentError)(error)) {
3286
+ if (Schema21.is(AgentError)(error)) {
3250
3287
  return `failed on turn ${error.turn}: ${error.message}`;
3251
3288
  }
3252
- if (Schema20.is(ResumeMismatch)(error)) {
3289
+ if (Schema21.is(ResumeMismatch)(error)) {
3253
3290
  return `resume mismatch: ${error.reason}`;
3254
3291
  }
3255
- if (Schema20.is(TurnLimitExceeded)(error)) {
3292
+ if (Schema21.is(TurnLimitExceeded)(error)) {
3256
3293
  return `turn limit exceeded at turn ${error.turn}`;
3257
3294
  }
3258
- if (Schema20.is(TurnPolicyStopped)(error)) {
3295
+ if (Schema21.is(TurnPolicyStopped)(error)) {
3259
3296
  return `policy stopped at turn ${error.turn}: ${error.reason._tag}`;
3260
3297
  }
3261
- if (Schema20.is(TurnPolicyError)(error)) {
3298
+ if (Schema21.is(TurnPolicyError)(error)) {
3262
3299
  return `turn policy failed: ${error.message}`;
3263
3300
  }
3264
- if (Schema20.is(MiddlewareViolation)(error)) {
3301
+ if (Schema21.is(MiddlewareViolation)(error)) {
3265
3302
  return `middleware violation on turn ${error.turn}: ${error.detail}`;
3266
3303
  }
3267
- if (Schema20.is(DuplicateToolCallId)(error)) {
3304
+ if (Schema21.is(DuplicateToolCallId)(error)) {
3268
3305
  return `duplicate tool-call ID '${error.id}' at position ${error.duplicateIndex} (first at ${error.firstIndex})`;
3269
3306
  }
3270
- if (Schema20.is(ToolNameCollision)(error)) {
3307
+ if (Schema21.is(ToolNameCollision)(error)) {
3271
3308
  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(", ")})`;
3272
3309
  }
3273
3310
  return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
@@ -3277,35 +3314,35 @@ var lazyHandled = (toolkit, name, handler) => ({
3277
3314
  tools: toolkit.tools,
3278
3315
  handle: (toolName, params) => toolkit.toHandlers({
3279
3316
  [name]: handler
3280
- }).pipe(Effect23.flatMap((handlers) => toolkit.pipe(Effect23.provide(handlers))), Effect23.flatMap((handled) => handled.handle(toolName, params)))
3317
+ }).pipe(Effect25.flatMap((handlers) => toolkit.pipe(Effect25.provide(handlers))), Effect25.flatMap((handled) => handled.handle(toolName, params)))
3281
3318
  });
3282
3319
  var asTool = Function7.dual((args) => args.length !== 1 || ("name" in args[0]), (agent, options = {}) => {
3283
3320
  const name = options.name ?? agent.name;
3284
3321
  const parameters = options.parameters ?? defaultParameters;
3285
- const success2 = options.success ?? Schema20.String;
3322
+ const success2 = options.success ?? Schema21.String;
3286
3323
  const toPrompt = options.toPrompt ?? ((params) => params.prompt);
3287
3324
  const fromResult = options.fromResult ?? ((result) => result.text);
3288
- const tool = Tool12.make(name, {
3325
+ const tool = Tool11.make(name, {
3289
3326
  ...options.description === undefined ? {} : { description: options.description },
3290
3327
  parameters,
3291
3328
  success: success2,
3292
- failure: Schema20.String,
3329
+ failure: Schema21.String,
3293
3330
  failureMode: "return"
3294
3331
  });
3295
3332
  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) => {
3333
+ const handler = (params) => Effect25.gen(function* () {
3334
+ const prompt = yield* Effect25.try({ try: () => toPrompt(params), catch: errorMessage2 });
3335
+ const result = yield* generate(agent, { prompt }).pipe(Effect25.catchCause((cause) => {
3299
3336
  if (Cause5.hasInterrupts(cause))
3300
- return Effect23.interrupt;
3301
- return Effect23.fail(causeMessage(agent.name, cause));
3337
+ return Effect25.interrupt;
3338
+ return Effect25.fail(causeMessage(agent.name, cause));
3302
3339
  }));
3303
- return yield* Effect23.try({ try: () => fromResult(result), catch: errorMessage2 });
3340
+ return yield* Effect25.try({ try: () => fromResult(result), catch: errorMessage2 });
3304
3341
  });
3305
3342
  return lazyHandled(toolkit, name, handler);
3306
3343
  });
3307
3344
 
3308
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/guardrail.js
3345
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/guardrail.js
3309
3346
  var exports_guardrail = {};
3310
3347
  __export(exports_guardrail, {
3311
3348
  validateInput: () => validateInput,
@@ -3313,8 +3350,8 @@ __export(exports_guardrail, {
3313
3350
  redactInput: () => redactInput,
3314
3351
  filterOutput: () => filterOutput
3315
3352
  });
3316
- import { Effect as Effect24, Option as Option16 } from "effect";
3317
- import { Prompt as Prompt14, Response as Response11 } from "effect/unstable/ai";
3353
+ import { Effect as Effect26, Option as Option15 } from "effect";
3354
+ import { Prompt as Prompt14, Response as Response10 } from "effect/unstable/ai";
3318
3355
  var replacement = (options) => options.replacement ?? "[redacted]";
3319
3356
  var redactText = (text, options) => text.replace(options.pattern, replacement(options));
3320
3357
  var redactUserPart = (part, options) => part.type === "text" ? Prompt14.makePart("text", { text: redactText(part.text, options), options: part.options }) : part;
@@ -3363,19 +3400,19 @@ var redactPromptText = (prompt, options) => Prompt14.fromMessages(prompt.content
3363
3400
  }
3364
3401
  }));
3365
3402
  var validateInput = (check) => ({
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 }))
3403
+ transformPrompt: (prompt, context) => check(prompt, context).pipe(Effect26.flatMap(Option15.match({
3404
+ onNone: () => Effect26.succeed(prompt),
3405
+ onSome: (reason) => Effect26.fail(AgentError.make({ message: `Input guardrail blocked: ${reason}`, turn: context.turn }))
3369
3406
  })))
3370
3407
  });
3371
3408
  var redactInput = (options) => ({
3372
- transformPrompt: (prompt) => Effect24.succeed(redactPromptText(prompt, options))
3409
+ transformPrompt: (prompt) => Effect26.succeed(redactPromptText(prompt, options))
3373
3410
  });
3374
3411
  var redactOutput = (options) => ({
3375
3412
  transformPart: (part) => {
3376
3413
  if (part.type !== "text-delta")
3377
- return Effect24.succeed(Option16.some(part));
3378
- return Effect24.succeed(Option16.some(Response11.makePart("text-delta", {
3414
+ return Effect26.succeed(Option15.some(part));
3415
+ return Effect26.succeed(Option15.some(Response10.makePart("text-delta", {
3379
3416
  id: part.id,
3380
3417
  delta: redactText(part.delta, options),
3381
3418
  metadata: part.metadata
@@ -3383,23 +3420,23 @@ var redactOutput = (options) => ({
3383
3420
  }
3384
3421
  });
3385
3422
  var filterOutput = (keep) => ({
3386
- transformPart: (part, context) => Effect24.succeed(part.type === "tool-call" || keep(part, context) ? Option16.some(part) : Option16.none())
3423
+ transformPart: (part, context) => Effect26.succeed(part.type === "tool-call" || keep(part, context) ? Option15.some(part) : Option15.none())
3387
3424
  });
3388
3425
 
3389
- // ../../node_modules/.bun/@batonfx+core@0.7.0/node_modules/@batonfx/core/dist/handoff.js
3426
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/handoff.js
3390
3427
  var exports_handoff = {};
3391
3428
  __export(exports_handoff, {
3392
3429
  transferTool: () => transferTool,
3393
3430
  supervisor: () => supervisor,
3394
3431
  fanOut: () => fanOut
3395
3432
  });
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 });
3433
+ import { Array as Array3, Effect as Effect27, Function as Function8, Schema as Schema22 } from "effect";
3434
+ import { AiError as AiError6, LanguageModel as LanguageModel8, Prompt as Prompt15, Tool as Tool12, Toolkit as Toolkit7 } from "effect/unstable/ai";
3435
+ var defaultTransferParameters = Schema22.Struct({ prompt: Schema22.String });
3399
3436
  var transferName = (agentName) => `transfer_to_${agentName}`;
3400
3437
  var positiveConcurrency = (value) => {
3401
3438
  const concurrency = value ?? 4;
3402
- return Number.isInteger(concurrency) && concurrency > 0 ? Effect25.succeed(concurrency) : Effect25.fail(AgentError.make({
3439
+ return Number.isInteger(concurrency) && concurrency > 0 ? Effect27.succeed(concurrency) : Effect27.fail(AgentError.make({
3403
3440
  message: "Handoff.fanOut concurrency must be a positive integer",
3404
3441
  turn: 0
3405
3442
  }));
@@ -3417,7 +3454,7 @@ var mergeHandled = (toolkits) => {
3417
3454
  tools,
3418
3455
  handle: (name, params) => {
3419
3456
  const entry = entries.get(String(name));
3420
- return entry === undefined ? Effect25.fail(AiError6.make({
3457
+ return entry === undefined ? Effect27.fail(AiError6.make({
3421
3458
  module: "Handoff",
3422
3459
  method: `${String(name)}.handle`,
3423
3460
  reason: AiError6.ToolNotFoundError.make({
@@ -3437,7 +3474,7 @@ var transferTool = Function8.dual((args) => args.length !== 1 || ("name" in args
3437
3474
  ...options.toPrompt === undefined ? {} : { toPrompt: options.toPrompt },
3438
3475
  ...options.fromResult === undefined ? {} : { fromResult: options.fromResult }
3439
3476
  }));
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) => {
3477
+ var fanOut = Function8.dual((args) => args.length !== 1 || globalThis.Array.isArray(args[0]), (children, options = {}) => positiveConcurrency(options.concurrency).pipe(Effect27.flatMap((concurrency) => Effect27.forEach(children, (child) => {
3441
3478
  const runOptions = {
3442
3479
  ...child.options,
3443
3480
  prompt: child.prompt
@@ -3457,16 +3494,16 @@ var supervisor = (options) => {
3457
3494
  return {
3458
3495
  agent: {
3459
3496
  ...agent,
3460
- toolDeclarations: transferTools.flatMap((transfer, index) => Object.values(transfer.tools).map((tool) => ({
3497
+ toolDeclarations: Array3.zip(specialists, transferTools).flatMap(([specialist, transfer]) => Object.values(transfer.tools).map((tool) => ({
3461
3498
  tool,
3462
- origin: { _tag: "Handoff", specialist: options.specialists[index].name }
3499
+ origin: { _tag: "Handoff", specialist: specialist.name }
3463
3500
  })))
3464
3501
  },
3465
3502
  toolkit
3466
3503
  };
3467
3504
  };
3468
3505
 
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";
3506
+ // ../../node_modules/.bun/@batonfx+core@0.9.1/node_modules/@batonfx/core/dist/index.js
3507
+ import { AiError as AiError7, Chat as Chat4, EmbeddingModel, IdGenerator, LanguageModel as LanguageModel9, Model as Model2, Prompt as Prompt16, Response as Response11, ResponseIdTracker, Telemetry as Telemetry2, Tokenizer as Tokenizer3, Tool as Tool13, Toolkit as Toolkit8 } from "effect/unstable/ai";
3471
3508
 
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 };
3509
+ 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, Response11 as Response, ResponseIdTracker, Telemetry2 as Telemetry, Tokenizer3 as Tokenizer, Tool13 as Tool, Toolkit8 as Toolkit };