@relayfx/sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ import {
3
3
  __export
4
4
  } from "./index-nb39b5ae.js";
5
5
 
6
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/turn-policy.js
6
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/turn-policy.js
7
7
  var exports_turn_policy = {};
8
8
  __export(exports_turn_policy, {
9
9
  untilToolCall: () => untilToolCall,
@@ -72,7 +72,7 @@ var both = dual(2, (first, second) => ({
72
72
  }));
73
73
  var defaultPolicy = forever;
74
74
 
75
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent-event.js
75
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-event.js
76
76
  var exports_agent_event = {};
77
77
  __export(exports_agent_event, {
78
78
  addUsage: () => addUsage,
@@ -87,31 +87,289 @@ __export(exports_agent_event, {
87
87
  AgentSuspended: () => AgentSuspended,
88
88
  AgentError: () => AgentError
89
89
  });
90
- import { Function, Schema as Schema3 } from "effect";
91
- import { Prompt as Prompt3, Response as Response2, Tool } from "effect/unstable/ai";
90
+ import { Function, Schema as Schema4 } from "effect";
91
+ import { Prompt as Prompt3, Response as Response3, Tool } from "effect/unstable/ai";
92
92
 
93
- // ../../node_modules/.bun/@batonfx+core@0.9.0/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({
93
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/model-telemetry.js
94
+ var exports_model_telemetry = {};
95
+ __export(exports_model_telemetry, {
96
+ layerNoop: () => layerNoop,
97
+ generateId: () => generateId,
98
+ classifyFailureCategory: () => classifyFailureCategory,
99
+ ModelRetryScheduled: () => ModelRetryScheduled,
100
+ ModelRetryReason: () => ModelRetryReason,
101
+ ModelFirstOutputKind: () => ModelFirstOutputKind,
102
+ ModelFailureClassification: () => ModelFailureClassification,
103
+ ModelFailureCategory: () => ModelFailureCategory,
104
+ ModelCost: () => ModelCost,
105
+ ModelCallStarted: () => ModelCallStarted,
106
+ ModelCallPurpose: () => ModelCallPurpose,
107
+ ModelCallFailed: () => ModelCallFailed,
108
+ ModelCallCompleted: () => ModelCallCompleted,
109
+ ModelAttemptStarted: () => ModelAttemptStarted,
110
+ ModelAttemptFirstOutput: () => ModelAttemptFirstOutput,
111
+ ModelAttemptFailed: () => ModelAttemptFailed,
112
+ ModelAttemptCompleted: () => ModelAttemptCompleted,
113
+ Event: () => Event,
114
+ DeliveryFailed: () => DeliveryFailed,
115
+ DeliveryBatch: () => DeliveryBatch,
116
+ Delivery: () => Delivery,
117
+ CurrentSummaryCall: () => CurrentSummaryCall,
118
+ CurrentPurpose: () => CurrentPurpose,
119
+ CurrentInstrumentation: () => CurrentInstrumentation,
120
+ CurrentCompactionId: () => CurrentCompactionId,
121
+ CompactionTrigger: () => CompactionTrigger,
122
+ CompactionStarted: () => CompactionStarted,
123
+ CompactionKind: () => CompactionKind,
124
+ CompactionFailed: () => CompactionFailed,
125
+ CompactionCompleted: () => CompactionCompleted,
126
+ CompactionCommit: () => CompactionCommit
127
+ });
128
+ import { Cause, Context, Effect as Effect2, Layer as Layer2, Option, Schema as Schema2 } from "effect";
129
+ import { AiError, IdGenerator, LanguageModel as LanguageModel2, Response as Response2 } from "effect/unstable/ai";
130
+ var ModelCallPurpose = Schema2.Literals(["conversation", "structured-output", "compaction-summary"]);
131
+ var ModelFailureCategory = Schema2.Literals([
132
+ "authentication",
133
+ "rate-limit",
134
+ "transport",
135
+ "provider-response",
136
+ "stream-decode",
137
+ "context-overflow",
138
+ "invalid-tool-call",
139
+ "token-budget",
140
+ "timeout",
141
+ "cancellation",
142
+ "unknown"
143
+ ]);
144
+ var ModelFailureClassification = Schema2.Literals(["transient", "terminal"]);
145
+ var ModelRetryReason = Schema2.Literals(["provider-resilience", "invalid-tool-call-correction"]);
146
+ var ModelFirstOutputKind = Schema2.Literals(["reasoning", "text", "tool-call"]);
147
+ var ModelCost = Schema2.Struct({
148
+ amount: Schema2.Finite,
149
+ currency: Schema2.String
150
+ });
151
+ var CompactionTrigger = Schema2.Literals(["threshold", "overflow"]);
152
+ var CompactionKind = Schema2.Literals(["microcompact", "summarize", "unchanged"]);
153
+ var attemptOrdinal = Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(0));
154
+ var ModelCallStarted = Schema2.Struct({
155
+ _tag: Schema2.tag("ModelCallStarted"),
156
+ deliveryId: Schema2.String,
157
+ turn: Schema2.Finite,
158
+ modelCallId: Schema2.String,
159
+ purpose: ModelCallPurpose,
160
+ provider: Schema2.optionalKey(Schema2.String),
161
+ model: Schema2.optionalKey(Schema2.String),
162
+ compactionId: Schema2.optionalKey(Schema2.String),
163
+ startedAt: Schema2.Finite
164
+ });
165
+ var ModelAttemptStarted = Schema2.Struct({
166
+ _tag: Schema2.tag("ModelAttemptStarted"),
167
+ deliveryId: Schema2.String,
168
+ turn: Schema2.Finite,
169
+ modelCallId: Schema2.String,
170
+ modelAttemptId: Schema2.String,
171
+ attempt: attemptOrdinal,
172
+ startedAt: Schema2.Finite
173
+ });
174
+ var ModelAttemptFirstOutput = Schema2.Struct({
175
+ _tag: Schema2.tag("ModelAttemptFirstOutput"),
176
+ deliveryId: Schema2.String,
177
+ turn: Schema2.Finite,
178
+ modelCallId: Schema2.String,
179
+ modelAttemptId: Schema2.String,
180
+ attempt: attemptOrdinal,
181
+ kind: ModelFirstOutputKind,
182
+ at: Schema2.Finite
183
+ });
184
+ var ModelAttemptCompleted = Schema2.Struct({
185
+ _tag: Schema2.tag("ModelAttemptCompleted"),
186
+ deliveryId: Schema2.String,
187
+ turn: Schema2.Finite,
188
+ modelCallId: Schema2.String,
189
+ modelAttemptId: Schema2.String,
190
+ attempt: attemptOrdinal,
191
+ completedAt: Schema2.Finite,
192
+ usage: Schema2.optionalKey(Response2.Usage),
193
+ usageAt: Schema2.optionalKey(Schema2.Finite),
194
+ finishReason: Schema2.optionalKey(Response2.FinishReason),
195
+ requestId: Schema2.optionalKey(Schema2.String),
196
+ responseModel: Schema2.optionalKey(Schema2.String),
197
+ serviceTier: Schema2.optionalKey(Schema2.String),
198
+ cost: Schema2.optionalKey(ModelCost)
199
+ });
200
+ var ModelAttemptFailed = Schema2.Struct({
201
+ _tag: Schema2.tag("ModelAttemptFailed"),
202
+ deliveryId: Schema2.String,
203
+ turn: Schema2.Finite,
204
+ modelCallId: Schema2.String,
205
+ modelAttemptId: Schema2.String,
206
+ attempt: attemptOrdinal,
207
+ failedAt: Schema2.Finite,
208
+ category: ModelFailureCategory,
209
+ classification: ModelFailureClassification
210
+ });
211
+ var ModelRetryScheduled = Schema2.Struct({
212
+ _tag: Schema2.tag("ModelRetryScheduled"),
213
+ deliveryId: Schema2.String,
214
+ turn: Schema2.Finite,
215
+ modelCallId: Schema2.String,
216
+ attempt: attemptOrdinal,
217
+ reason: ModelRetryReason,
218
+ category: ModelFailureCategory,
219
+ delayMillis: Schema2.Finite,
220
+ at: Schema2.Finite
221
+ });
222
+ var ModelCallCompleted = Schema2.Struct({
223
+ _tag: Schema2.tag("ModelCallCompleted"),
224
+ deliveryId: Schema2.String,
225
+ turn: Schema2.Finite,
226
+ modelCallId: Schema2.String,
227
+ purpose: ModelCallPurpose,
228
+ attempts: attemptOrdinal,
229
+ completedAt: Schema2.Finite,
230
+ usage: Schema2.optionalKey(Response2.Usage),
231
+ finishReason: Schema2.optionalKey(Response2.FinishReason)
232
+ });
233
+ var ModelCallFailed = Schema2.Struct({
234
+ _tag: Schema2.tag("ModelCallFailed"),
235
+ deliveryId: Schema2.String,
236
+ turn: Schema2.Finite,
237
+ modelCallId: Schema2.String,
238
+ purpose: ModelCallPurpose,
239
+ attempts: attemptOrdinal,
240
+ failedAt: Schema2.Finite,
241
+ category: ModelFailureCategory
242
+ });
243
+ var CompactionStarted = Schema2.Struct({
244
+ _tag: Schema2.tag("CompactionStarted"),
245
+ deliveryId: Schema2.String,
246
+ turn: Schema2.Finite,
247
+ compactionId: Schema2.String,
248
+ trigger: CompactionTrigger,
249
+ startedAt: Schema2.Finite,
250
+ contextTokensBefore: Schema2.optionalKey(Schema2.Finite),
251
+ entriesBefore: Schema2.optionalKey(Schema2.Finite)
252
+ });
253
+ var CompactionCompleted = Schema2.Struct({
254
+ _tag: Schema2.tag("CompactionCompleted"),
255
+ deliveryId: Schema2.String,
256
+ turn: Schema2.Finite,
257
+ compactionId: Schema2.String,
258
+ kind: CompactionKind,
259
+ completedAt: Schema2.Finite,
260
+ summaryModelCallId: Schema2.optionalKey(Schema2.String)
261
+ });
262
+ var CompactionFailed = Schema2.Struct({
263
+ _tag: Schema2.tag("CompactionFailed"),
264
+ deliveryId: Schema2.String,
265
+ turn: Schema2.Finite,
266
+ compactionId: Schema2.String,
267
+ failedAt: Schema2.Finite
268
+ });
269
+ var Event = Schema2.Union([
270
+ ModelCallStarted,
271
+ ModelAttemptStarted,
272
+ ModelAttemptFirstOutput,
273
+ ModelAttemptCompleted,
274
+ ModelAttemptFailed,
275
+ ModelRetryScheduled,
276
+ ModelCallCompleted,
277
+ ModelCallFailed,
278
+ CompactionStarted,
279
+ CompactionCompleted,
280
+ CompactionFailed
281
+ ]);
282
+ var DeliveryBatch = Schema2.Struct({
106
283
  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)
284
+ events: Schema2.Array(Event)
285
+ });
286
+ var CompactionCommit = Schema2.Struct({
287
+ compactionId: Schema2.String,
288
+ checkpointId: Schema2.String,
289
+ summaryModelCallId: Schema2.optionalKey(Schema2.String),
290
+ contextTokensBefore: Schema2.optionalKey(Schema2.Finite),
291
+ contextTokensAfter: Schema2.optionalKey(Schema2.Finite),
292
+ entriesBefore: Schema2.optionalKey(Schema2.Finite),
293
+ entriesAfter: Schema2.optionalKey(Schema2.Finite)
294
+ });
295
+
296
+ class DeliveryFailed extends Schema2.TaggedErrorClass()("@batonfx/core/DeliveryFailed", {
297
+ message: Schema2.String,
298
+ cause: Schema2.optionalKey(Schema2.Defect())
299
+ }) {
300
+ }
301
+
302
+ class Delivery extends Context.Service()("@batonfx/core/Delivery") {
303
+ }
304
+ var layerNoop = Layer2.succeed(Delivery, Delivery.of({ deliver: () => Effect2.void }));
305
+ var classifyFailureCategory = (error) => {
306
+ if (Cause.isTimeoutError(error))
307
+ return "timeout";
308
+ if (!AiError.isAiError(error))
309
+ return "unknown";
310
+ switch (error.reason._tag) {
311
+ case "AuthenticationError":
312
+ return "authentication";
313
+ case "RateLimitError":
314
+ return "rate-limit";
315
+ case "QuotaExhaustedError":
316
+ return "token-budget";
317
+ case "NetworkError":
318
+ return "transport";
319
+ case "ContentPolicyError":
320
+ case "InternalProviderError":
321
+ case "InvalidRequestError":
322
+ case "InvalidUserInputError":
323
+ case "UnsupportedSchemaError":
324
+ return "provider-response";
325
+ case "InvalidOutputError":
326
+ case "StructuredOutputError":
327
+ return "stream-decode";
328
+ case "InvalidToolResultError":
329
+ case "ToolConfigurationError":
330
+ case "ToolNotFoundError":
331
+ case "ToolParameterValidationError":
332
+ case "ToolResultEncodingError":
333
+ case "ToolkitRequiredError":
334
+ return "invalid-tool-call";
335
+ case "UnknownError":
336
+ return "unknown";
337
+ }
338
+ };
339
+ var CurrentInstrumentation = Context.Reference("@batonfx/core/ModelTelemetry/CurrentInstrumentation", { defaultValue: () => {
340
+ return;
341
+ } });
342
+ var CurrentPurpose = Context.Reference("@batonfx/core/ModelTelemetry/CurrentPurpose", { defaultValue: () => "conversation" });
343
+ var CurrentCompactionId = Context.Reference("@batonfx/core/ModelTelemetry/CurrentCompactionId", { defaultValue: () => {
344
+ return;
345
+ } });
346
+ var CurrentSummaryCall = Context.Reference("@batonfx/core/ModelTelemetry/CurrentSummaryCall", { defaultValue: () => {
347
+ return;
348
+ } });
349
+ var generateId = Effect2.flatMap(Effect2.serviceOption(IdGenerator.IdGenerator), (service) => Option.getOrElse(service, () => IdGenerator.defaultIdGenerator).generateId());
350
+
351
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/session-sync.js
352
+ import { Schema as Schema3 } from "effect";
353
+ import { Prompt as Prompt2 } from "effect/unstable/ai";
354
+ var Divergence = Schema3.Struct({
355
+ index: Schema3.Finite,
356
+ durableRole: Schema3.optionalKey(Schema3.String),
357
+ authoritativeRole: Schema3.optionalKey(Schema3.String),
358
+ durablePartTypes: Schema3.Array(Schema3.String),
359
+ authoritativePartTypes: Schema3.Array(Schema3.String),
360
+ durableDigest: Schema3.optionalKey(Schema3.String),
361
+ authoritativeDigest: Schema3.optionalKey(Schema3.String)
362
+ });
363
+ var Diagnostics = Schema3.Struct({
364
+ sessionId: Schema3.String,
365
+ ownerToken: Schema3.optionalKey(Schema3.String),
366
+ durableEntryCount: Schema3.Finite,
367
+ durableMessageCount: Schema3.Finite,
368
+ authoritativeMessageCount: Schema3.Finite,
369
+ alignmentCount: Schema3.Finite,
370
+ commonPrefixLength: Schema3.Finite,
371
+ lastDurableEntryTag: Schema3.optionalKey(Schema3.String),
372
+ firstDivergence: Schema3.optionalKey(Divergence)
115
373
  });
116
374
  var digest = (value) => {
117
375
  let hash = 2166136261;
@@ -122,9 +380,28 @@ var digest = (value) => {
122
380
  return (hash >>> 0).toString(16).padStart(8, "0");
123
381
  };
124
382
  var partTypes = (message) => typeof message.content === "string" ? ["text"] : message.content.map((part) => part.type);
383
+ var sameOptions = (left, right) => JSON.stringify(left.options ?? {}) === JSON.stringify(right.options ?? {});
384
+ var coalesceParts = (parts) => {
385
+ const merged = [];
386
+ for (const part of parts) {
387
+ const previous = merged[merged.length - 1];
388
+ if (part.type === "text" && previous !== undefined && previous.type === "text" && sameOptions(previous, part)) {
389
+ merged[merged.length - 1] = { ...previous, text: previous.text + part.text };
390
+ continue;
391
+ }
392
+ merged.push(part);
393
+ }
394
+ return merged;
395
+ };
396
+ var coalesceAdjacentText = (message) => {
397
+ if (typeof message.content === "string" || message.content.length < 2)
398
+ return message;
399
+ const coalesced = coalesceParts(message.content);
400
+ return coalesced.length === message.content.length ? message : { ...message, content: coalesced };
401
+ };
125
402
  var messageDigest = (message) => digest(JSON.stringify(message));
126
403
  var diagnose = (input) => {
127
- const equals = Schema2.toEquivalence(Prompt2.Message);
404
+ const equals = Schema3.toEquivalence(Prompt2.Message);
128
405
  let alignmentCount = 0;
129
406
  if (input.projection.length === 0)
130
407
  alignmentCount = 1;
@@ -162,9 +439,9 @@ var diagnose = (input) => {
162
439
  };
163
440
  };
164
441
 
165
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent-event.js
442
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-event.js
166
443
  var addUsageField = (left, right) => left === undefined && right === undefined ? undefined : (left ?? 0) + (right ?? 0);
167
- var addUsage = Function.dual(2, (left, right) => Response2.Usage.make({
444
+ var addUsage = Function.dual(2, (left, right) => Response3.Usage.make({
168
445
  inputTokens: {
169
446
  uncached: addUsageField(left.inputTokens.uncached, right.inputTokens.uncached),
170
447
  total: addUsageField(left.inputTokens.total, right.inputTokens.total),
@@ -178,94 +455,94 @@ var addUsage = Function.dual(2, (left, right) => Response2.Usage.make({
178
455
  }
179
456
  }));
180
457
 
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)
458
+ class AgentError extends Schema4.TaggedErrorClass()("@batonfx/core/AgentError", {
459
+ message: Schema4.String,
460
+ turn: Schema4.Finite,
461
+ cause: Schema4.optionalKey(Schema4.Defect()),
462
+ diagnostics: Schema4.optionalKey(Diagnostics)
186
463
  }) {
187
464
  }
188
465
 
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
466
+ class TurnLimitExceeded extends Schema4.TaggedErrorClass()("@batonfx/core/TurnLimitExceeded", {
467
+ turn: Schema4.Finite,
468
+ limit: Schema4.Finite,
469
+ pending: Schema4.Array(Schema4.Struct({
470
+ tool_call_id: Schema4.String,
471
+ tool_name: Schema4.String
195
472
  }))
196
473
  }) {
197
474
  }
198
475
 
199
- class TurnPolicyStopped extends Schema3.TaggedErrorClass()("@batonfx/core/TurnPolicyStopped", {
200
- turn: Schema3.Finite,
476
+ class TurnPolicyStopped extends Schema4.TaggedErrorClass()("@batonfx/core/TurnPolicyStopped", {
477
+ turn: Schema4.Finite,
201
478
  reason: StopReason,
202
- pending: Schema3.Array(Schema3.Struct({
203
- tool_call_id: Schema3.String,
204
- tool_name: Schema3.String
479
+ pending: Schema4.Array(Schema4.Struct({
480
+ tool_call_id: Schema4.String,
481
+ tool_name: Schema4.String
205
482
  }))
206
483
  }) {
207
484
  }
208
485
 
209
- class MiddlewareViolation extends Schema3.TaggedErrorClass()("@batonfx/core/MiddlewareViolation", {
210
- turn: Schema3.Finite,
211
- detail: Schema3.String
486
+ class MiddlewareViolation extends Schema4.TaggedErrorClass()("@batonfx/core/MiddlewareViolation", {
487
+ turn: Schema4.Finite,
488
+ detail: Schema4.String
212
489
  }) {
213
490
  }
214
491
 
215
- class DuplicateToolCallId extends Schema3.TaggedErrorClass()("@batonfx/core/DuplicateToolCallId", {
216
- id: Schema3.String,
217
- firstIndex: Schema3.Finite,
218
- duplicateIndex: Schema3.Finite
492
+ class DuplicateToolCallId extends Schema4.TaggedErrorClass()("@batonfx/core/DuplicateToolCallId", {
493
+ id: Schema4.String,
494
+ firstIndex: Schema4.Finite,
495
+ duplicateIndex: Schema4.Finite
219
496
  }) {
220
497
  }
221
498
 
222
- class ProgressOverflow extends Schema3.TaggedErrorClass()("@batonfx/core/ProgressOverflow", {
223
- turn: Schema3.Finite,
224
- toolCallId: Schema3.String,
225
- capacity: Schema3.Finite
499
+ class ProgressOverflow extends Schema4.TaggedErrorClass()("@batonfx/core/ProgressOverflow", {
500
+ turn: Schema4.Finite,
501
+ toolCallId: Schema4.String,
502
+ capacity: Schema4.Finite
226
503
  }) {
227
504
  }
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 })
505
+ var ToolOrigin = Schema4.Union([
506
+ Schema4.TaggedStruct("Static", { agent: Schema4.String }),
507
+ Schema4.TaggedStruct("Builtin", { builtin: Schema4.Literal("activate_skill") }),
508
+ Schema4.TaggedStruct("Skill", { skill: Schema4.String }),
509
+ Schema4.TaggedStruct("Handoff", { specialist: Schema4.String })
233
510
  ]);
234
511
 
235
- class ToolNameCollision extends Schema3.TaggedErrorClass()("@batonfx/core/ToolNameCollision", {
236
- name: Schema3.String,
237
- origins: Schema3.NonEmptyArray(ToolOrigin)
512
+ class ToolNameCollision extends Schema4.TaggedErrorClass()("@batonfx/core/ToolNameCollision", {
513
+ name: Schema4.String,
514
+ origins: Schema4.NonEmptyArray(ToolOrigin)
238
515
  }) {
239
516
  }
240
517
 
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,
254
- metadata: Response2.ProviderMetadata
518
+ class AgentSuspended extends Schema4.TaggedErrorClass()("@batonfx/core/AgentSuspended", {
519
+ token: Schema4.String,
520
+ reason: Schema4.Literals(["tool-wait", "approval"]),
521
+ tool_call_index: Schema4.optional(Schema4.Int.check(Schema4.isGreaterThanOrEqualTo(0))),
522
+ tool_call_id: Schema4.String,
523
+ tool_name: Schema4.String,
524
+ tool_params: Schema4.Unknown,
525
+ tool_call_batch: Schema4.Array(Schema4.Struct({
526
+ type: Schema4.Literal("tool-call"),
527
+ id: Schema4.String,
528
+ name: Schema4.String,
529
+ params: Schema4.Unknown,
530
+ providerExecuted: Schema4.Boolean,
531
+ metadata: Response3.ProviderMetadata
255
532
  })),
256
- active_tools: Schema3.optional(Schema3.Array(Schema3.String)),
257
- activated_skills: Schema3.optional(Schema3.Array(Schema3.String))
533
+ active_tools: Schema4.optional(Schema4.Array(Schema4.String)),
534
+ activated_skills: Schema4.optional(Schema4.Array(Schema4.String))
258
535
  }) {
259
536
  }
260
537
 
261
- class ResumeMismatch extends Schema3.TaggedErrorClass()("@batonfx/core/ResumeMismatch", {
262
- reason: Schema3.Literals(["checkpoint-not-found", "identity-mismatch"]),
263
- expected: Schema3.optional(AgentSuspended),
538
+ class ResumeMismatch extends Schema4.TaggedErrorClass()("@batonfx/core/ResumeMismatch", {
539
+ reason: Schema4.Literals(["checkpoint-not-found", "identity-mismatch"]),
540
+ expected: Schema4.optional(AgentSuspended),
264
541
  received: AgentSuspended
265
542
  }) {
266
543
  }
267
544
 
268
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/memory.js
545
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/memory.js
269
546
  var exports_memory = {};
270
547
  __export(exports_memory, {
271
548
  replaceRecalledMessage: () => replaceRecalledMessage,
@@ -274,18 +551,18 @@ __export(exports_memory, {
274
551
  messageFromRecall: () => messageFromRecall,
275
552
  merge: () => merge,
276
553
  layerTest: () => layerTest,
277
- layerNoop: () => layerNoop,
554
+ layerNoop: () => layerNoop2,
278
555
  itemFromPromptPart: () => itemFromPromptPart,
279
556
  isMessageFromRecall: () => isMessageFromRecall,
280
557
  MemoryError: () => MemoryError,
281
558
  Memory: () => Memory
282
559
  });
283
- import { Context, Effect as Effect2, Layer as Layer2, Option, Schema as Schema4 } from "effect";
560
+ import { Context as Context2, Effect as Effect3, Layer as Layer3, Option as Option2, Schema as Schema5 } from "effect";
284
561
  import { dual as dual2 } from "effect/Function";
285
562
  import { Prompt as Prompt4 } from "effect/unstable/ai";
286
563
  var provenanceOption = "@batonfx/core/memory";
287
564
  var recallLineage = new WeakMap;
288
- var itemFromPromptPart = Option.liftPredicate((part) => part.type === "text" || part.type === "file");
565
+ var itemFromPromptPart = Option2.liftPredicate((part) => part.type === "text" || part.type === "file");
289
566
  var isMessageFromRecall = (message) => {
290
567
  const provenance = message.options[provenanceOption];
291
568
  return typeof provenance === "object" && provenance !== null && !Array.isArray(provenance) && "origin" in provenance && provenance.origin === "memoryRecall";
@@ -311,27 +588,27 @@ var projectTranscript = (transcript) => {
311
588
  return content.length === transcript.content.length ? transcript : Prompt4.fromMessages(content);
312
589
  };
313
590
 
314
- class MemoryError extends Schema4.TaggedErrorClass()("@batonfx/core/MemoryError", {
315
- message: Schema4.String
591
+ class MemoryError extends Schema5.TaggedErrorClass()("@batonfx/core/MemoryError", {
592
+ message: Schema5.String
316
593
  }) {
317
594
  }
318
595
 
319
- class Memory extends Context.Service()("@batonfx/core/Memory") {
596
+ class Memory extends Context2.Service()("@batonfx/core/Memory") {
320
597
  }
321
598
  var noop = {
322
- recall: () => Effect2.succeed([]),
323
- remember: () => Effect2.void,
324
- forget: () => Effect2.void
599
+ recall: () => Effect3.succeed([]),
600
+ remember: () => Effect3.void,
601
+ forget: () => Effect3.void
325
602
  };
326
603
  var merge = dual2(2, (first, second) => ({
327
- recall: (input) => Effect2.all([first.recall(input), second.recall(input)]).pipe(Effect2.map(([firstItems, secondItems]) => [...firstItems, ...secondItems])),
328
- remember: (input) => Effect2.all([first.remember(input), second.remember(input)], { discard: true }),
329
- forget: (input) => Effect2.all([first.forget(input), second.forget(input)], { discard: true })
604
+ recall: (input) => Effect3.all([first.recall(input), second.recall(input)]).pipe(Effect3.map(([firstItems, secondItems]) => [...firstItems, ...secondItems])),
605
+ remember: (input) => Effect3.all([first.remember(input), second.remember(input)], { discard: true }),
606
+ forget: (input) => Effect3.all([first.forget(input), second.forget(input)], { discard: true })
330
607
  }));
331
- var layerNoop = Layer2.succeed(Memory, Memory.of(noop));
332
- var layerTest = (implementation) => Layer2.succeed(Memory, Memory.of(implementation));
608
+ var layerNoop2 = Layer3.succeed(Memory, Memory.of(noop));
609
+ var layerTest = (implementation) => Layer3.succeed(Memory, Memory.of(implementation));
333
610
 
334
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/model-registry.js
611
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/model-registry.js
335
612
  var exports_model_registry = {};
336
613
  __export(exports_model_registry, {
337
614
  stream: () => stream,
@@ -347,29 +624,73 @@ __export(exports_model_registry, {
347
624
  ModelRegistry: () => ModelRegistry,
348
625
  LanguageModelNotRegistered: () => LanguageModelNotRegistered
349
626
  });
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";
351
- import { LanguageModel as LanguageModel2, Model } from "effect/unstable/ai";
627
+ import { Context as Context3, Effect as Effect4, Fiber, Function as Function2, HashMap, Layer as Layer4, Option as Option3, Ref, Schema as Schema6, Scope, Semaphore, Stream } from "effect";
628
+ import { LanguageModel as LanguageModel3, Model } from "effect/unstable/ai";
629
+
630
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/context-overflow.js
631
+ var exports_context_overflow = {};
632
+ __export(exports_context_overflow, {
633
+ classify: () => classify
634
+ });
635
+ import { AiError as AiError2 } from "effect/unstable/ai";
636
+ var overflowEvidence = /context_length_exceeded|context_window_exceeded|context_window_overflow|input_too_long|maximum context length|context (?:window|length) (?:was |has been )?exceeded|exceeds? (?:the )?(?:context window|maximum number of tokens|model'?s? maximum context)|input (?:is )?too (?:long|large)|prompt is too long|too many (?:input )?tokens/i;
637
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
638
+ var overflowEligibleReasons = new Set(["InvalidRequestError", "UnknownError", "InvalidOutputError"]);
639
+ var textFields = ["message", "description", "code", "errorCode", "errorType", "error_code", "error_type"];
640
+ var nestedFields = ["error", "reason", "cause"];
641
+ var evidence = (value, depth) => {
642
+ if (depth > 4 || value === null || value === undefined)
643
+ return "";
644
+ if (typeof value === "string")
645
+ return value;
646
+ if (AiError2.isAiError(value)) {
647
+ return overflowEligibleReasons.has(value.reason._tag) ? `${value.message} ${evidence(value.reason, depth + 1)}` : "";
648
+ }
649
+ if (!isRecord(value))
650
+ return "";
651
+ const parts = [];
652
+ for (const field of textFields) {
653
+ const candidate = value[field];
654
+ if (typeof candidate === "string")
655
+ parts.push(candidate);
656
+ }
657
+ for (const field of nestedFields) {
658
+ if (field in value)
659
+ parts.push(evidence(value[field], depth + 1));
660
+ }
661
+ if (isRecord(value.metadata)) {
662
+ for (const entry of Object.values(value.metadata))
663
+ parts.push(evidence(entry, depth + 1));
664
+ }
665
+ return parts.join(" ");
666
+ };
667
+ var classify = (error) => overflowEvidence.test(evidence(error, 0)) ? "context-overflow" : "other";
668
+
669
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/model-registry.js
352
670
  var FailureClassifierTypeId = Symbol.for("@batonfx/core/model-registry/FailureClassifier");
353
- var classifyFailure = Function2.dual(2, (model, error) => model[FailureClassifierTypeId]?.(error) ?? "other");
671
+ var classifyFailure = Function2.dual(2, (model, error) => {
672
+ const classified = model[FailureClassifierTypeId]?.(error);
673
+ return classified !== undefined && classified !== "other" ? classified : classify(error);
674
+ });
354
675
  var attachFailureClassifier = (registration, context) => {
355
676
  if (registration.classifyFailure === undefined)
356
677
  return context;
357
- const model = Context2.get(context, LanguageModel2.LanguageModel);
678
+ const model = Context3.get(context, LanguageModel3.LanguageModel);
358
679
  const classified = {
359
680
  ...model,
360
681
  [FailureClassifierTypeId]: registration.classifyFailure
361
682
  };
362
- return Context2.add(context, LanguageModel2.LanguageModel, classified);
683
+ return Context3.add(context, LanguageModel3.LanguageModel, classified);
363
684
  };
364
685
 
365
- class LanguageModelNotRegistered extends Schema5.TaggedErrorClass()("@batonfx/core/LanguageModelNotRegistered", {
366
- provider: Schema5.String,
367
- model: Schema5.String,
368
- registration_key: Schema5.optionalKey(Schema5.String)
686
+ class LanguageModelNotRegistered extends Schema6.TaggedErrorClass()("@batonfx/core/LanguageModelNotRegistered", {
687
+ provider: Schema6.String,
688
+ model: Schema6.String,
689
+ registration_key: Schema6.optionalKey(Schema6.String)
369
690
  }) {
370
691
  }
371
692
 
372
- class ModelRegistry extends Context2.Service()("@batonfx/core/ModelRegistry") {
693
+ class ModelRegistry extends Context3.Service()("@batonfx/core/ModelRegistry") {
373
694
  }
374
695
  var selectionKey = (selection) => JSON.stringify([selection.provider, selection.model, selection.registrationKey ?? null]);
375
696
  var upsertRegistration = (registry, entry) => {
@@ -379,8 +700,8 @@ var upsertRegistration = (registry, entry) => {
379
700
  keys: HashMap.has(registry.byKey, key) ? registry.keys : [...registry.keys, key]
380
701
  };
381
702
  };
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) => ({
703
+ var findRegistration = (registry, selection) => HashMap.get(registry.byKey, selectionKey(selection)).pipe(Option3.getOrUndefined);
704
+ var registration = (input) => Model.make(input.provider, input.model, input.layer).captureRequirements.pipe(Effect4.map((layer) => ({
384
705
  provider: input.provider,
385
706
  model: input.model,
386
707
  layer,
@@ -388,28 +709,28 @@ var registration = (input) => Model.make(input.provider, input.model, input.laye
388
709
  ...input.metadata === undefined ? {} : { metadata: input.metadata },
389
710
  ...input.classifyFailure === undefined ? {} : { classifyFailure: input.classifyFailure }
390
711
  })));
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, {
712
+ var makeLayer = (initialRegistrations, options) => Layer4.effect(ModelRegistry, Effect4.gen(function* () {
713
+ const memoMap = yield* Layer4.makeMemoMap;
714
+ const scope = yield* Effect4.scope;
715
+ const makeEntry = Effect4.fnUntraced(function* (candidate) {
716
+ const fiber = yield* Effect4.cached(Effect4.forkIn(Layer4.buildWithMemoMap(candidate.layer, memoMap, scope), scope, {
396
717
  startImmediately: true
397
718
  }));
398
- const context = Effect3.uninterruptible(fiber).pipe(Effect3.flatMap(Fiber.join));
719
+ const context = Effect4.uninterruptible(fiber).pipe(Effect4.flatMap(Fiber.join));
399
720
  return { registration: candidate, context };
400
721
  });
401
- const initialEntries = yield* Effect3.forEach(initialRegistrations, makeEntry);
722
+ const initialEntries = yield* Effect4.forEach(initialRegistrations, makeEntry);
402
723
  const registry = yield* Ref.make(initialEntries.reduce(upsertRegistration, {
403
724
  byKey: HashMap.empty(),
404
725
  keys: []
405
726
  }));
406
727
  const semaphore = options?.maxConcurrentModelCalls === undefined ? undefined : yield* Semaphore.make(options.maxConcurrentModelCalls);
407
- const register = Effect3.fn("ModelRegistry.register")(function* (input) {
728
+ const register = Effect4.fn("ModelRegistry.register")(function* (input) {
408
729
  const entry = yield* makeEntry(input.registration);
409
730
  yield* Ref.update(registry, (items) => upsertRegistration(items, entry));
410
731
  });
411
- const registrations = Ref.get(registry).pipe(Effect3.map((items) => items.keys.map((key) => HashMap.getUnsafe(items.byKey, key).registration)));
412
- const operate = Effect3.fn("ModelRegistry.operate")(function* (selection, effect) {
732
+ const registrations = Ref.get(registry).pipe(Effect4.map((items) => items.keys.map((key) => HashMap.getUnsafe(items.byKey, key).registration)));
733
+ const operate = Effect4.fn("ModelRegistry.operate")(function* (selection, effect) {
413
734
  const items = yield* Ref.get(registry);
414
735
  const entry = findRegistration(items, selection);
415
736
  if (entry === undefined) {
@@ -419,10 +740,10 @@ var makeLayer = (initialRegistrations, options) => Layer3.effect(ModelRegistry,
419
740
  ...selection.registrationKey === undefined ? {} : { registration_key: selection.registrationKey }
420
741
  });
421
742
  }
422
- const provided = entry.context.pipe(Effect3.flatMap((context) => effect.pipe(Effect3.provide(attachFailureClassifier(entry.registration, context)))));
743
+ const provided = entry.context.pipe(Effect4.flatMap((context) => effect.pipe(Effect4.provide(attachFailureClassifier(entry.registration, context)))));
423
744
  return yield* semaphore === undefined ? provided : semaphore.withPermits(1)(provided);
424
745
  });
425
- const stream = (selection, operation) => Stream.unwrap(Effect3.gen(function* () {
746
+ const stream = (selection, operation) => Stream.unwrap(Effect4.gen(function* () {
426
747
  const items = yield* Ref.get(registry);
427
748
  const entry = findRegistration(items, selection);
428
749
  if (entry === undefined) {
@@ -433,7 +754,7 @@ var makeLayer = (initialRegistrations, options) => Layer3.effect(ModelRegistry,
433
754
  });
434
755
  }
435
756
  if (semaphore !== undefined) {
436
- yield* Effect3.acquireRelease(semaphore.take(1), () => semaphore.release(1), { interruptible: true });
757
+ yield* Effect4.acquireRelease(semaphore.take(1), () => semaphore.release(1), { interruptible: true });
437
758
  }
438
759
  const context = attachFailureClassifier(entry.registration, yield* entry.context);
439
760
  return operation.pipe(Stream.provideContext(context));
@@ -445,43 +766,43 @@ var makeLayer = (initialRegistrations, options) => Layer3.effect(ModelRegistry,
445
766
  stream
446
767
  });
447
768
  }));
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)))));
769
+ var layer = Function2.dual((args) => args.length === 0 || args.length > 1 || Array.isArray(args[0]), (registrations = [], options) => Layer4.unwrap(Effect4.all(registrations).pipe(Effect4.map((initialRegistrations) => makeLayer(initialRegistrations, options)))));
770
+ var layerCombined = Function2.dual((args) => args.length !== 1 || Array.isArray(args[0]), (registries, options) => Layer4.unwrap(Effect4.forEach(registries, (registry) => Layer4.build(registry).pipe(Effect4.flatMap((context) => Context3.get(context, ModelRegistry).registrations))).pipe(Effect4.map((groups) => makeLayer(groups.flat(), options)))));
450
771
  var layerMemory = layer;
451
- var layerTest2 = (implementation) => Layer3.succeed(ModelRegistry, ModelRegistry.of(implementation));
452
- var register = Effect3.fn("ModelRegistry.register.call")(function* (input) {
772
+ var layerTest2 = (implementation) => Layer4.succeed(ModelRegistry, ModelRegistry.of(implementation));
773
+ var register = Effect4.fn("ModelRegistry.register.call")(function* (input) {
453
774
  const service = yield* ModelRegistry;
454
775
  return yield* service.register(input);
455
776
  });
456
- var registrations = Effect3.fn("ModelRegistry.registrations.call")(function* () {
777
+ var registrations = Effect4.fn("ModelRegistry.registrations.call")(function* () {
457
778
  const service = yield* ModelRegistry;
458
779
  return yield* service.registrations;
459
780
  });
460
- var operate = Function2.dual(2, (selection, effect) => Effect3.gen(function* () {
781
+ var operate = Function2.dual(2, (selection, effect) => Effect4.gen(function* () {
461
782
  const service = yield* ModelRegistry;
462
783
  return yield* service.operate(selection, effect);
463
784
  }));
464
- var stream = Function2.dual(2, (selection, operation) => Stream.unwrap(ModelRegistry.pipe(Effect3.map((service) => service.stream(selection, operation)))));
785
+ var stream = Function2.dual(2, (selection, operation) => Stream.unwrap(ModelRegistry.pipe(Effect4.map((service) => service.stream(selection, operation)))));
465
786
 
466
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/tool-context.js
787
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-context.js
467
788
  var exports_tool_context = {};
468
789
  __export(exports_tool_context, {
469
790
  layerTest: () => layerTest3,
470
791
  layerDefault: () => layerDefault,
471
792
  ToolContext: () => ToolContext
472
793
  });
473
- import { Context as Context3, Effect as Effect4, Layer as Layer4 } from "effect";
794
+ import { Context as Context4, Effect as Effect5, Layer as Layer5 } from "effect";
474
795
 
475
- class ToolContext extends Context3.Service()("@batonfx/core/ToolContext") {
796
+ class ToolContext extends Context4.Service()("@batonfx/core/ToolContext") {
476
797
  }
477
- var layerDefault = Layer4.sync(ToolContext, () => ToolContext.of({
798
+ var layerDefault = Layer5.sync(ToolContext, () => ToolContext.of({
478
799
  signal: new AbortController().signal,
479
- emit: () => Effect4.void,
800
+ emit: () => Effect5.void,
480
801
  sessionId: "local"
481
802
  }));
482
- var layerTest3 = (implementation) => Layer4.succeed(ToolContext, ToolContext.of(implementation));
803
+ var layerTest3 = (implementation) => Layer5.succeed(ToolContext, ToolContext.of(implementation));
483
804
 
484
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/tool-executor.js
805
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-executor.js
485
806
  var exports_tool_executor = {};
486
807
  __export(exports_tool_executor, {
487
808
  sandbox: () => sandbox,
@@ -499,16 +820,16 @@ __export(exports_tool_executor, {
499
820
  FrameworkStage: () => FrameworkStage,
500
821
  FrameworkFailure: () => FrameworkFailure
501
822
  });
502
- import { Context as Context4, Effect as Effect7, Layer as Layer5, Option as Option3, Schema as Schema7, Stream as Stream2 } from "effect";
503
- import { AiError as AiError2, Response as Response3, Tool as Tool4, Toolkit } from "effect/unstable/ai";
823
+ import { Context as Context5, Effect as Effect8, Layer as Layer6, Option as Option4, Schema as Schema8, Stream as Stream2 } from "effect";
824
+ import { AiError as AiError4, Response as Response4, Tool as Tool4, Toolkit } from "effect/unstable/ai";
504
825
 
505
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/tool-placement.js
506
- import { Effect as Effect6, Schedule } from "effect";
826
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-placement.js
827
+ import { Effect as Effect7, Schedule } from "effect";
507
828
  import { Tool as Tool3 } from "effect/unstable/ai";
508
829
 
509
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/tool-result-codec.js
510
- import { Effect as Effect5, Schema as Schema6 } from "effect";
511
- import { AiError, Tool as Tool2 } from "effect/unstable/ai";
830
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-result-codec.js
831
+ import { Effect as Effect6, Schema as Schema7 } from "effect";
832
+ import { AiError as AiError3, Tool as Tool2 } from "effect/unstable/ai";
512
833
  var resultMessage = (result) => {
513
834
  if (typeof result === "string")
514
835
  return result;
@@ -525,20 +846,20 @@ var schemaMessage = (error) => error instanceof Error ? error.message : typeof e
525
846
  var frameworkFailure = (stage, tool, error) => FrameworkFailure.make({ stage, tool, message: schemaMessage(error) });
526
847
  var encodeSuccess = (tool, result) => {
527
848
  const schema = tool.successSchema;
528
- return Schema6.encodeUnknownEffect(schema)(result).pipe(Effect5.map((encodedResult) => ({ _tag: "Success", result, encodedResult })), Effect5.mapError((error) => frameworkFailure("encode-success", tool.name, error)));
849
+ return Schema7.encodeUnknownEffect(schema)(result).pipe(Effect6.map((encodedResult) => ({ _tag: "Success", result, encodedResult })), Effect6.mapError((error) => frameworkFailure("encode-success", tool.name, error)));
529
850
  };
530
851
  var encodeDomainFailure = (tool, failure) => {
531
852
  const schema = tool.failureSchema;
532
- return Schema6.encodeUnknownEffect(schema)(failure).pipe(Effect5.map((encodedFailure) => ({ _tag: "DomainFailure", failure, encodedFailure })), Effect5.mapError((error) => frameworkFailure("encode-domain-failure", tool.name, error)));
853
+ return Schema7.encodeUnknownEffect(schema)(failure).pipe(Effect6.map((encodedFailure) => ({ _tag: "DomainFailure", failure, encodedFailure })), Effect6.mapError((error) => frameworkFailure("encode-domain-failure", tool.name, error)));
533
854
  };
534
- var encodeDomainCandidate = (tool, failure) => !Schema6.is(tool.failureSchema)(failure) ? Effect5.fail(frameworkFailure("handler", tool.name, failure)) : encodeDomainFailure(tool, failure);
855
+ var encodeDomainCandidate = (tool, failure) => !Schema7.is(tool.failureSchema)(failure) ? Effect6.fail(frameworkFailure("handler", tool.name, failure)) : encodeDomainFailure(tool, failure);
535
856
  var decodeInput = (tool, input) => {
536
857
  const schema = tool.parametersSchema;
537
- return Schema6.decodeUnknownEffect(schema)(input).pipe(Effect5.asVoid, Effect5.mapError((error) => frameworkFailure("decode-input", tool.name, error)));
858
+ return Schema7.decodeUnknownEffect(schema)(input).pipe(Effect6.asVoid, Effect6.mapError((error) => frameworkFailure("decode-input", tool.name, error)));
538
859
  };
539
860
  var decodeSuccess = (tool, result) => {
540
861
  const schema = tool.successSchema;
541
- return Schema6.decodeUnknownEffect(schema)(result).pipe(Effect5.mapError((error) => frameworkFailure("encode-success", tool.name, error)), Effect5.flatMap((decoded) => encodeSuccess(tool, decoded)));
862
+ return Schema7.decodeUnknownEffect(schema)(result).pipe(Effect6.mapError((error) => frameworkFailure("encode-success", tool.name, error)), Effect6.flatMap((decoded) => encodeSuccess(tool, decoded)));
542
863
  };
543
864
  var aiFrameworkFailure = (tool, error) => {
544
865
  switch (error.reason._tag) {
@@ -551,8 +872,8 @@ var aiFrameworkFailure = (tool, error) => {
551
872
  case "ToolResultEncodingError": {
552
873
  if (tool.failureMode === "error")
553
874
  return frameworkFailure("encode-success", tool.name, error);
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);
875
+ const isSuccess = Schema7.isSchema(tool.successSchema) && Schema7.is(tool.successSchema)(error.reason.toolResult);
876
+ const isDomainFailure = Schema7.isSchema(tool.failureSchema) && Schema7.is(tool.failureSchema)(error.reason.toolResult);
556
877
  return frameworkFailure(isSuccess === isDomainFailure ? "handler" : isDomainFailure ? "encode-domain-failure" : "encode-success", tool.name, error);
557
878
  }
558
879
  default:
@@ -571,26 +892,26 @@ var toolResultCodec = {
571
892
  schemaMessage
572
893
  };
573
894
 
574
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/tool-placement.js
895
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-placement.js
575
896
  var placementOutcomeFromResponse = (placement, tool, response) => {
576
897
  if (typeof response !== "object" || response === null || !("_tag" in response)) {
577
- return Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Placement returned an invalid response"));
898
+ return Effect7.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Placement returned an invalid response"));
578
899
  }
579
900
  switch (response._tag) {
580
901
  case "DomainFailure":
581
- return "failure" in response ? toolResultCodec.encodeDomainFailure(tool, response.failure) : Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "DomainFailure response is missing failure"));
902
+ return "failure" in response ? toolResultCodec.encodeDomainFailure(tool, response.failure) : Effect7.fail(toolResultCodec.frameworkFailure("placement", tool.name, "DomainFailure response is missing failure"));
582
903
  case "Suspend":
583
- return "token" in response && typeof response.token === "string" ? Effect6.succeed({ _tag: "Suspend", token: response.token }) : Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Suspend response is missing a string token"));
904
+ return "token" in response && typeof response.token === "string" ? Effect7.succeed({ _tag: "Suspend", token: response.token }) : Effect7.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Suspend response is missing a string token"));
584
905
  case "Success":
585
- return "result" in response ? toolResultCodec.decodeSuccess(tool, response.result).pipe(Effect6.mapError((error) => FrameworkFailure.make({ ...error, message: `${placement} result: ${error.message}` }))) : Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Success response is missing result"));
906
+ return "result" in response ? toolResultCodec.decodeSuccess(tool, response.result).pipe(Effect7.mapError((error) => FrameworkFailure.make({ ...error, message: `${placement} result: ${error.message}` }))) : Effect7.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Success response is missing result"));
586
907
  default:
587
- return Effect6.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Placement returned an unknown response tag"));
908
+ return Effect7.fail(toolResultCodec.frameworkFailure("placement", tool.name, "Placement returned an unknown response tag"));
588
909
  }
589
910
  };
590
911
  var placementOutcome = { fromResponse: placementOutcomeFromResponse };
591
912
 
592
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/tool-executor.js
593
- var FrameworkStage = Schema7.Literals([
913
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-executor.js
914
+ var FrameworkStage = Schema8.Literals([
594
915
  "decode-input",
595
916
  "handler",
596
917
  "encode-success",
@@ -601,44 +922,44 @@ var FrameworkStage = Schema7.Literals([
601
922
  "authorization"
602
923
  ]);
603
924
 
604
- class FrameworkFailure extends Schema7.TaggedErrorClass()("@batonfx/core/FrameworkFailure", {
925
+ class FrameworkFailure extends Schema8.TaggedErrorClass()("@batonfx/core/FrameworkFailure", {
605
926
  stage: FrameworkStage,
606
- tool: Schema7.String,
607
- message: Schema7.String
927
+ tool: Schema8.String,
928
+ message: Schema8.String
608
929
  }) {
609
930
  }
610
931
 
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
932
+ class RemoteRetryMisconfigured extends Schema8.TaggedErrorClass()("@batonfx/core/RemoteRetryMisconfigured", {
933
+ reason: Schema8.Literals(["invalid-max-retries", "missing-operation-key", "changed-operation-key"]),
934
+ message: Schema8.String
614
935
  }) {
615
936
  }
616
937
 
617
- class ToolExecutor extends Context4.Service()("@batonfx/core/ToolExecutor") {
938
+ class ToolExecutor extends Context5.Service()("@batonfx/core/ToolExecutor") {
618
939
  }
619
940
  var findTool = (tools, name) => tools[name];
620
941
  var executeWithToolkit = (toolkit, request) => {
621
942
  const tool = findTool(toolkit.tools, request.call.name);
622
943
  if (tool === undefined) {
623
- return Effect7.fail(toolResultCodec.frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
944
+ return Effect8.fail(toolResultCodec.frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
624
945
  }
625
946
  const handleFailure = (error) => {
626
- if (Schema7.is(FrameworkFailure)(error))
627
- return Effect7.fail(error);
628
- if (AiError2.isAiError(error))
629
- return Effect7.fail(toolResultCodec.aiFrameworkFailure(tool, error));
947
+ if (Schema8.is(FrameworkFailure)(error))
948
+ return Effect8.fail(error);
949
+ if (AiError4.isAiError(error))
950
+ return Effect8.fail(toolResultCodec.aiFrameworkFailure(tool, error));
630
951
  return toolResultCodec.encodeDomainCandidate(tool, error);
631
952
  };
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) => {
633
- if (Option3.isNone(option)) {
634
- return Effect7.fail(toolResultCodec.frameworkFailure("handler", tool.name, "Tool handler did not produce a final result"));
953
+ return toolkit.handle(request.call.name, request.call.params).pipe(Effect8.flatMap((results) => results.pipe(Stream2.filter((item) => item.preliminary === false), Stream2.runLast)), Effect8.flatMap((option) => {
954
+ if (Option4.isNone(option)) {
955
+ return Effect8.fail(toolResultCodec.frameworkFailure("handler", tool.name, "Tool handler did not produce a final result"));
635
956
  }
636
957
  const result = option.value;
637
958
  if (!result.isFailure) {
638
- return Effect7.succeed({ _tag: "Success", result: result.result, encodedResult: result.encodedResult });
959
+ return Effect8.succeed({ _tag: "Success", result: result.result, encodedResult: result.encodedResult });
639
960
  }
640
- return AiError2.isAiError(result.result) ? Effect7.fail(toolResultCodec.aiFrameworkFailure(tool, result.result)) : toolResultCodec.encodeDomainFailure(tool, result.result);
641
- }), Effect7.catchIf(() => true, handleFailure, handleFailure));
961
+ return AiError4.isAiError(result.result) ? Effect8.fail(toolResultCodec.aiFrameworkFailure(tool, result.result)) : toolResultCodec.encodeDomainFailure(tool, result.result);
962
+ }), Effect8.catchIf(() => true, handleFailure, handleFailure));
642
963
  };
643
964
  function executeToolkit(toolkitOrRequest, request) {
644
965
  if (request === undefined) {
@@ -649,10 +970,10 @@ function executeToolkit(toolkitOrRequest, request) {
649
970
  return pipeable;
650
971
  }
651
972
  const toolkit = toolkitOrRequest;
652
- return ("handle" in toolkit ? Effect7.succeed(toolkit) : toolkit).pipe(Effect7.flatMap((handled) => executeWithToolkit(handled, request)));
973
+ return ("handle" in toolkit ? Effect8.succeed(toolkit) : toolkit).pipe(Effect8.flatMap((handled) => executeWithToolkit(handled, request)));
653
974
  }
654
975
  function layerToolkit(toolkit) {
655
- return Layer5.effect(ToolExecutor, ("handle" in toolkit ? Effect7.succeed(toolkit) : toolkit).pipe(Effect7.map((handled) => ToolExecutor.of({
976
+ return Layer6.effect(ToolExecutor, ("handle" in toolkit ? Effect8.succeed(toolkit) : toolkit).pipe(Effect8.map((handled) => ToolExecutor.of({
656
977
  execute: (request) => executeWithToolkit(handled, request)
657
978
  }))));
658
979
  }
@@ -671,37 +992,37 @@ var placementRoute = (placement, options) => {
671
992
  execute: (request) => {
672
993
  const tool = findTool(options.toolkit.tools, request.call.name);
673
994
  if (tool === undefined) {
674
- return Effect7.fail(toolResultCodec.frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
995
+ return Effect8.fail(toolResultCodec.frameworkFailure("missing-handler", request.call.name, `Tool ${request.call.name} is not registered`));
675
996
  }
676
- return toolResultCodec.decodeInput(tool, request.call.params).pipe(Effect7.flatMap(() => {
997
+ return toolResultCodec.decodeInput(tool, request.call.params).pipe(Effect8.flatMap(() => {
677
998
  const effect = options.execute({ ...request, placement, tool });
678
999
  return effect;
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)));
1000
+ }), Effect8.mapError((error) => Schema8.is(FrameworkFailure)(error) || Schema8.is(RemoteRetryMisconfigured)(error) ? error : toolResultCodec.frameworkFailure("placement", request.call.name, error)), Effect8.flatMap((response) => placementOutcome.fromResponse(placement, tool, response)));
680
1001
  }
681
1002
  });
682
1003
  };
683
1004
  var remoteRetryError = (reason, message) => RemoteRetryMisconfigured.make({ reason, message });
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);
685
- var retryRemote = (options, request) => Effect7.suspend(() => {
1005
+ var validateOperationKey = (operationKey) => typeof operationKey !== "string" || operationKey.trim().length === 0 ? Effect8.fail(remoteRetryError("missing-operation-key", "Remote retry operation key must be non-empty")) : Effect8.succeed(operationKey);
1006
+ var retryRemote = (options, request) => Effect8.suspend(() => {
686
1007
  if (!Number.isFinite(options.maxRetries) || !Number.isInteger(options.maxRetries) || options.maxRetries < 0) {
687
- return Effect7.fail(remoteRetryError("invalid-max-retries", "Remote retry maxRetries must be a non-negative finite integer"));
1008
+ return Effect8.fail(remoteRetryError("invalid-max-retries", "Remote retry maxRetries must be a non-negative finite integer"));
688
1009
  }
689
1010
  const operationKey = typeof options.operationKey === "function" ? options.operationKey(request) : undefined;
690
- return validateOperationKey(operationKey).pipe(Effect7.flatMap((stableKey) => {
1011
+ return validateOperationKey(operationKey).pipe(Effect8.flatMap((stableKey) => {
691
1012
  let attempt = 0;
692
- const executeAttempt = Effect7.suspend(() => {
1013
+ const executeAttempt = Effect8.suspend(() => {
693
1014
  const currentKey = attempt === 0 ? stableKey : options.operationKey(request);
694
1015
  attempt += 1;
695
- return validateOperationKey(currentKey).pipe(Effect7.match({
1016
+ return validateOperationKey(currentKey).pipe(Effect8.match({
696
1017
  onFailure: (error) => error,
697
1018
  onSuccess: (validatedKey) => validatedKey
698
- }), Effect7.flatMap((validatedKey) => typeof validatedKey !== "string" ? Effect7.succeed(validatedKey) : validatedKey === stableKey ? options.execute({ ...request, operationKey: stableKey }) : Effect7.succeed(remoteRetryError("changed-operation-key", "Remote retry operation key changed between attempts"))));
1019
+ }), Effect8.flatMap((validatedKey) => typeof validatedKey !== "string" ? Effect8.succeed(validatedKey) : validatedKey === stableKey ? options.execute({ ...request, operationKey: stableKey }) : Effect8.succeed(remoteRetryError("changed-operation-key", "Remote retry operation key changed between attempts"))));
699
1020
  });
700
- return Effect7.retry(executeAttempt, {
1021
+ return Effect8.retry(executeAttempt, {
701
1022
  schedule: options.schedule,
702
1023
  times: options.maxRetries,
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)));
1024
+ while: (error) => !Schema8.is(AgentError)(error) && !Schema8.is(FrameworkFailure)(error) && !Schema8.is(RemoteRetryMisconfigured)(error)
1025
+ }).pipe(Effect8.flatMap((result) => Schema8.is(RemoteRetryMisconfigured)(result) ? Effect8.fail(result) : Effect8.succeed(result)));
705
1026
  }));
706
1027
  });
707
1028
  var client = (options) => placementRoute("client", options);
@@ -717,20 +1038,20 @@ function routeToolkit(toolkit) {
717
1038
  tools: Object.keys(handled.tools),
718
1039
  execute: (request) => executeWithToolkit(handled, request)
719
1040
  });
720
- return "handle" in toolkit ? makeRoute(toolkit) : toolkit.pipe(Effect7.map(makeRoute));
1041
+ return "handle" in toolkit ? makeRoute(toolkit) : toolkit.pipe(Effect8.map(makeRoute));
721
1042
  }
722
- var routeInputEffect = (input) => Effect7.isEffect(input) ? input : Effect7.succeed(input);
1043
+ var routeInputEffect = (input) => Effect8.isEffect(input) ? input : Effect8.succeed(input);
723
1044
  function layerRouter(routes) {
724
- return Layer5.effect(ToolExecutor, Effect7.all(Array.from(routes, routeInputEffect)).pipe(Effect7.map((resolved) => ToolExecutor.of({
1045
+ return Layer6.effect(ToolExecutor, Effect8.all(Array.from(routes, routeInputEffect)).pipe(Effect8.map((resolved) => ToolExecutor.of({
725
1046
  execute: (request) => {
726
1047
  const matched = resolved.find((candidate) => candidate.matches(request));
727
- return matched === undefined ? Effect7.fail(toolResultCodec.frameworkFailure("route", request.call.name, `Tool ${request.call.name} has no matching route`)) : matched.execute(request);
1048
+ return matched === undefined ? Effect8.fail(toolResultCodec.frameworkFailure("route", request.call.name, `Tool ${request.call.name} has no matching route`)) : matched.execute(request);
728
1049
  }
729
1050
  }))));
730
1051
  }
731
- var layerTest4 = (implementation) => Layer5.succeed(ToolExecutor, ToolExecutor.of(implementation));
1052
+ var layerTest4 = (implementation) => Layer6.succeed(ToolExecutor, ToolExecutor.of(implementation));
732
1053
 
733
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/approvals.js
1054
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/approvals.js
734
1055
  var exports_approvals = {};
735
1056
  __export(exports_approvals, {
736
1057
  layerTest: () => layerTest5,
@@ -738,39 +1059,41 @@ __export(exports_approvals, {
738
1059
  layerAutoApprove: () => layerAutoApprove,
739
1060
  Approvals: () => Approvals
740
1061
  });
741
- import { Context as Context5, Effect as Effect8, Layer as Layer6 } from "effect";
1062
+ import { Context as Context6, Effect as Effect9, Layer as Layer7 } from "effect";
742
1063
 
743
- class Approvals extends Context5.Service()("@batonfx/core/Approvals") {
1064
+ class Approvals extends Context6.Service()("@batonfx/core/Approvals") {
744
1065
  }
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));
1066
+ var layerAutoApprove = Layer7.succeed(Approvals, Approvals.of({ resolve: () => Effect9.succeed({ _tag: "Approved" }) }));
1067
+ var layerDenyAll = Layer7.succeed(Approvals, Approvals.of({ resolve: () => Effect9.succeed({ _tag: "Denied" }) }));
1068
+ var layerTest5 = (implementation) => Layer7.succeed(Approvals, Approvals.of(implementation));
748
1069
 
749
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/session.js
1070
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/session.js
750
1071
  var exports_session = {};
751
1072
  __export(exports_session, {
752
1073
  layerTest: () => layerTest6,
753
1074
  layerMemory: () => layerMemory2,
1075
+ checkpointMatches: () => checkpointMatches,
754
1076
  buildMemoryContext: () => buildMemoryContext,
755
1077
  buildContext: () => buildContext,
756
1078
  SessionStoreError: () => SessionStoreError,
757
1079
  SessionStore: () => SessionStore,
758
1080
  SessionConflict: () => SessionConflict
759
1081
  });
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";
1082
+ import { Context as Context7, Effect as Effect10, HashMap as HashMap2, Layer as Layer8, Option as Option5, Ref as Ref2, Schema as Schema9 } from "effect";
1083
+ import { dual as dual3 } from "effect/Function";
761
1084
  import { Prompt as Prompt5 } from "effect/unstable/ai";
762
- class SessionStoreError extends Schema8.TaggedErrorClass()("@batonfx/core/SessionStoreError", {
763
- message: Schema8.String
1085
+ class SessionStoreError extends Schema9.TaggedErrorClass()("@batonfx/core/SessionStoreError", {
1086
+ message: Schema9.String
764
1087
  }) {
765
1088
  }
766
1089
 
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
1090
+ class SessionConflict extends Schema9.TaggedErrorClass()("@batonfx/core/SessionConflict", {
1091
+ reason: Schema9.Literals(["stale-leaf", "checkpoint-id-reused", "checkpoint-not-on-active-path", "fenced"]),
1092
+ message: Schema9.String
770
1093
  }) {
771
1094
  }
772
1095
 
773
- class SessionStore extends Context6.Service()("@batonfx/core/SessionStore") {
1096
+ class SessionStore extends Context7.Service()("@batonfx/core/SessionStore") {
774
1097
  }
775
1098
  var initialState = {
776
1099
  entries: HashMap2.empty(),
@@ -783,8 +1106,8 @@ var failure = (message) => ({
783
1106
  _tag: "Failure",
784
1107
  error: SessionStoreError.make({ message })
785
1108
  });
786
- var effectFromResult = (result) => result._tag === "Failure" ? Effect9.fail(result.error) : Effect9.succeed(result.value);
787
- var effectFromAppendResult = (result) => result._tag === "@batonfx/core/SessionConflict" ? Effect9.fail(result) : effectFromResult(result);
1109
+ var effectFromResult = (result) => result._tag === "Failure" ? Effect10.fail(result.error) : Effect10.succeed(result.value);
1110
+ var effectFromAppendResult = (result) => result._tag === "@batonfx/core/SessionConflict" ? Effect10.fail(result) : effectFromResult(result);
788
1111
  var entryFromInput = (input, id, parentId) => {
789
1112
  const base = {
790
1113
  id,
@@ -819,7 +1142,7 @@ var pathFromState = (state, leaf) => {
819
1142
  if (entries.length > state.order.length)
820
1143
  return failure(`Session path for leaf ${leaf} contains a cycle`);
821
1144
  const entry = HashMap2.get(state.entries, cursor);
822
- if (Option4.isNone(entry))
1145
+ if (Option5.isNone(entry))
823
1146
  return failure(`Session entry ${cursor} does not exist`);
824
1147
  const value = entry.value;
825
1148
  entries.push(value);
@@ -865,11 +1188,22 @@ var appendState = (state, input, options) => {
865
1188
  }
866
1189
  ];
867
1190
  };
868
- var promptEquivalence = Schema8.toEquivalence(Prompt5.Prompt);
869
- var checkpointMatches = (entry, prepared) => entry.parentId === prepared.parentId && entry.summary === prepared.summary && promptEquivalence(entry.projectedHistory, prepared.projectedHistory);
1191
+ var promptEquivalence = Schema9.toEquivalence(Prompt5.Prompt);
1192
+ var telemetryEquivalence = Schema9.toEquivalence(Schema9.Array(Event));
1193
+ var commitEquivalence = Schema9.toEquivalence(CompactionCommit);
1194
+ var checkpointMatches = dual3(2, (entry, prepared) => entry.id === prepared.id && entry.parentId === prepared.parentId && entry.summary === prepared.summary && promptEquivalence(entry.projectedHistory, prepared.projectedHistory) && telemetryEquivalence(entry.telemetry, prepared.telemetry) && (entry.compactionCommit === undefined ? prepared.compactionCommit === undefined : prepared.compactionCommit !== undefined && commitEquivalence(entry.compactionCommit, prepared.compactionCommit)));
870
1195
  var appendCheckpointState = (state, prepared) => {
1196
+ if (prepared.compactionCommit !== undefined && prepared.compactionCommit.checkpointId !== prepared.id) {
1197
+ return [
1198
+ SessionConflict.make({
1199
+ reason: "checkpoint-id-reused",
1200
+ message: `Compaction commit checkpoint id ${prepared.compactionCommit.checkpointId} does not match ${prepared.id}`
1201
+ }),
1202
+ state
1203
+ ];
1204
+ }
871
1205
  const existing = HashMap2.get(state.entries, prepared.id);
872
- if (Option4.isSome(existing)) {
1206
+ if (Option5.isSome(existing)) {
873
1207
  const entry = existing.value;
874
1208
  if (entry._tag !== "Compaction" || entry.version !== 2 || !checkpointMatches(entry, prepared)) {
875
1209
  return [
@@ -913,6 +1247,8 @@ var appendCheckpointState = (state, prepared) => {
913
1247
  id: prepared.id,
914
1248
  parentId: prepared.parentId,
915
1249
  projectedHistory: prepared.projectedHistory,
1250
+ telemetry: prepared.telemetry,
1251
+ ...prepared.compactionCommit === undefined ? {} : { compactionCommit: prepared.compactionCommit },
916
1252
  ...prepared.summary === undefined ? {} : { summary: prepared.summary }
917
1253
  };
918
1254
  return [
@@ -926,7 +1262,7 @@ var appendCheckpointState = (state, prepared) => {
926
1262
  ];
927
1263
  };
928
1264
  var setLeafState = (state, id) => {
929
- if (id !== null && Option4.isNone(HashMap2.get(state.entries, id)))
1265
+ if (id !== null && Option5.isNone(HashMap2.get(state.entries, id)))
930
1266
  return [failure(`Session entry ${id} does not exist`), state];
931
1267
  return [success(undefined), { ...state, leaf: id }];
932
1268
  };
@@ -1010,45 +1346,45 @@ var buildMemoryContext = (path) => {
1010
1346
  });
1011
1347
  return projectTranscript(Prompt5.fromMessages(messages));
1012
1348
  };
1013
- var layerMemory2 = Layer7.effect(SessionStore, Ref2.make(initialState).pipe(Effect9.map((state) => SessionStore.of({
1349
+ var layerMemory2 = Layer8.effect(SessionStore, Ref2.make(initialState).pipe(Effect10.map((state) => SessionStore.of({
1014
1350
  reserveEntryId: Ref2.modify(state, (current) => [
1015
1351
  String(current.counter),
1016
1352
  { ...current, counter: current.counter + 1 }
1017
1353
  ]),
1018
- append: (entry, options) => Ref2.modify(state, (current) => appendState(current, entry, options)).pipe(Effect9.flatMap(effectFromAppendResult)),
1019
- appendCheckpoint: (checkpoint) => Ref2.modify(state, (current) => appendCheckpointState(current, checkpoint)).pipe(Effect9.flatMap((result) => result._tag === "@batonfx/core/SessionConflict" ? Effect9.fail(result) : Effect9.succeed(result))),
1020
- path: (leaf) => Ref2.get(state).pipe(Effect9.flatMap((current) => leaf === undefined && current.leaf === null ? Effect9.succeed([]) : effectFromResult(pathFromState(current, leaf ?? current.leaf ?? "")))),
1021
- setLeaf: (id) => Ref2.modify(state, (current) => setLeafState(current, id)).pipe(Effect9.flatMap(effectFromResult)),
1022
- leaf: Ref2.get(state).pipe(Effect9.map((current) => current.leaf))
1354
+ append: (entry, options) => Ref2.modify(state, (current) => appendState(current, entry, options)).pipe(Effect10.flatMap(effectFromAppendResult)),
1355
+ appendCheckpoint: (checkpoint) => Ref2.modify(state, (current) => appendCheckpointState(current, checkpoint)).pipe(Effect10.flatMap((result) => result._tag === "@batonfx/core/SessionConflict" ? Effect10.fail(result) : Effect10.succeed(result))),
1356
+ path: (leaf) => Ref2.get(state).pipe(Effect10.flatMap((current) => leaf === undefined && current.leaf === null ? Effect10.succeed([]) : effectFromResult(pathFromState(current, leaf ?? current.leaf ?? "")))),
1357
+ setLeaf: (id) => Ref2.modify(state, (current) => setLeafState(current, id)).pipe(Effect10.flatMap(effectFromResult)),
1358
+ leaf: Ref2.get(state).pipe(Effect10.map((current) => current.leaf))
1023
1359
  }))));
1024
- var layerTest6 = (implementation) => Layer7.succeed(SessionStore, SessionStore.of(implementation));
1360
+ var layerTest6 = (implementation) => Layer8.succeed(SessionStore, SessionStore.of(implementation));
1025
1361
 
1026
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/tool-output.js
1362
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-output.js
1027
1363
  var exports_tool_output = {};
1028
1364
  __export(exports_tool_output, {
1029
1365
  layerTest: () => layerTest7,
1030
- layerNoop: () => layerNoop2,
1366
+ layerNoop: () => layerNoop3,
1031
1367
  layerMemory: () => layerMemory3,
1032
1368
  bound: () => bound,
1033
1369
  ToolOutputStore: () => ToolOutputStore,
1034
1370
  ToolOutputError: () => ToolOutputError
1035
1371
  });
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") {
1372
+ import { Cause as Cause2, Context as Context8, Effect as Effect11, Function as Function3, HashMap as HashMap3, Layer as Layer9, Option as Option6, Ref as Ref3, Schema as Schema10 } from "effect";
1373
+ class ToolOutputStore extends Context8.Service()("@batonfx/core/ToolOutputStore") {
1038
1374
  }
1039
1375
 
1040
- class ToolOutputError extends Schema9.TaggedErrorClass()("@batonfx/core/ToolOutputError", {
1041
- message: Schema9.String
1376
+ class ToolOutputError extends Schema10.TaggedErrorClass()("@batonfx/core/ToolOutputError", {
1377
+ message: Schema10.String
1042
1378
  }) {
1043
1379
  }
1044
- var layerNoop2 = Layer8.succeed(ToolOutputStore, ToolOutputStore.of({ put: () => Effect10.succeed(Option5.none()) }));
1045
- var layerMemory3 = Layer8.effect(ToolOutputStore, Ref3.make({ next: 0, records: HashMap3.empty() }).pipe(Effect10.map((state) => ToolOutputStore.of({
1380
+ var layerNoop3 = Layer9.succeed(ToolOutputStore, ToolOutputStore.of({ put: () => Effect11.succeed(Option6.none()) }));
1381
+ var layerMemory3 = Layer9.effect(ToolOutputStore, Ref3.make({ next: 0, records: HashMap3.empty() }).pipe(Effect11.map((state) => ToolOutputStore.of({
1046
1382
  put: (toolCallId, content) => Ref3.modify(state, ({ next, records }) => {
1047
1383
  const id = `mem:tool-output-${next + 1}`;
1048
- return [Option5.some(id), { next: next + 1, records: HashMap3.set(records, id, { toolCallId, content }) }];
1384
+ return [Option6.some(id), { next: next + 1, records: HashMap3.set(records, id, { toolCallId, content }) }];
1049
1385
  })
1050
1386
  }))));
1051
- var layerTest7 = (implementation) => Layer8.succeed(ToolOutputStore, ToolOutputStore.of(implementation));
1387
+ var layerTest7 = (implementation) => Layer9.succeed(ToolOutputStore, ToolOutputStore.of(implementation));
1052
1388
  var encoder = new TextEncoder;
1053
1389
  var decoder = new TextDecoder;
1054
1390
  var serialized = (value) => {
@@ -1073,11 +1409,11 @@ var bounded = (inline, outputPaths) => {
1073
1409
  return { _tag: "Success", result: output, encodedResult: output, outputPaths };
1074
1410
  };
1075
1411
  var boundedFromOriginal = (encoded, bytes, maxBytes, outputPaths) => bounded({ truncated: true, bytes, maxBytes, preview: preview(encoded, maxBytes) }, outputPaths);
1076
- var optionalStore = (store, toolCallId, result) => store.put(toolCallId, { result: result.result, encodedResult: result.encodedResult }).pipe(Effect10.catchCause((cause) => {
1077
- const unrecoverable = cause.reasons.filter((reason) => Cause.isDieReason(reason) || Cause.isInterruptReason(reason));
1078
- return unrecoverable.length === 0 ? Effect10.succeed(Option5.none()) : Effect10.failCause(Cause.fromReasons(unrecoverable));
1412
+ var optionalStore = (store, toolCallId, result) => store.put(toolCallId, { result: result.result, encodedResult: result.encodedResult }).pipe(Effect11.catchCause((cause) => {
1413
+ const unrecoverable = cause.reasons.filter((reason) => Cause2.isDieReason(reason) || Cause2.isInterruptReason(reason));
1414
+ return unrecoverable.length === 0 ? Effect11.succeed(Option6.none()) : Effect11.failCause(Cause2.fromReasons(unrecoverable));
1079
1415
  }));
1080
- var bound = Function3.dual(2, (result, options) => Effect10.gen(function* () {
1416
+ var bound = Function3.dual(2, (result, options) => Effect11.gen(function* () {
1081
1417
  if (isToolOutput(result.encodedResult)) {
1082
1418
  const output = result.encodedResult;
1083
1419
  const outputPaths = output.outputPaths ?? [];
@@ -1090,18 +1426,19 @@ var bound = Function3.dual(2, (result, options) => Effect10.gen(function* () {
1090
1426
  const bytes = encoder.encode(encoded).byteLength;
1091
1427
  if (bytes <= options.maxBytes)
1092
1428
  return { ...result, outputPaths: [] };
1093
- const maybeStore = yield* Effect10.serviceOption(ToolOutputStore);
1094
- if (Option5.isNone(maybeStore))
1429
+ const maybeStore = yield* Effect11.serviceOption(ToolOutputStore);
1430
+ if (Option6.isNone(maybeStore))
1095
1431
  return boundedFromOriginal(encoded, bytes, options.maxBytes, []);
1096
1432
  const path = yield* optionalStore(maybeStore.value, options.toolCallId, result);
1097
- if (Option5.isNone(path))
1433
+ if (Option6.isNone(path))
1098
1434
  return boundedFromOriginal(encoded, bytes, options.maxBytes, []);
1099
1435
  return boundedFromOriginal(encoded, bytes, options.maxBytes, [path.value]);
1100
1436
  }));
1101
1437
 
1102
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/compaction.js
1438
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/compaction.js
1103
1439
  var exports_compaction = {};
1104
1440
  __export(exports_compaction, {
1441
+ withLifecycle: () => withLifecycle,
1105
1442
  truncate: () => truncate,
1106
1443
  toolOutputBound: () => toolOutputBound,
1107
1444
  structuredSummary: () => structuredSummary,
@@ -1118,35 +1455,71 @@ __export(exports_compaction, {
1118
1455
  Compaction: () => Compaction,
1119
1456
  AgentSummary: () => AgentSummary
1120
1457
  });
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";
1458
+ import { Context as Context10, Effect as Effect14, Function as Function5, Layer as Layer11, Option as Option8, Schema as Schema11 } from "effect";
1459
+ import { LanguageModel as LanguageModel6, Prompt as Prompt6, Tokenizer, Toolkit as Toolkit2 } from "effect/unstable/ai";
1460
+
1461
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/compaction-telemetry.js
1462
+ import { Clock, Effect as Effect12, Exit, Function as Function4, Option as Option7 } from "effect";
1463
+ import { LanguageModel as LanguageModel4 } from "effect/unstable/ai";
1464
+ var resultKind = (result) => Option7.isNone(result) ? "unchanged" : result.value._tag === "Summarize" ? "summarize" : "microcompact";
1465
+ var withCompactionLifecycle = Function4.dual(3, (work, input, usage) => Effect12.gen(function* () {
1466
+ const instrumentation = yield* CurrentInstrumentation;
1467
+ if (instrumentation === undefined)
1468
+ return yield* work;
1469
+ const turn = input.turn;
1470
+ const compactionId = input.compactionId;
1471
+ const startedAt = yield* Clock.currentTimeMillis;
1472
+ yield* instrumentation.emit({
1473
+ _tag: "CompactionStarted",
1474
+ turn,
1475
+ compactionId,
1476
+ trigger: input.overflow ? "overflow" : "threshold",
1477
+ startedAt,
1478
+ contextTokensBefore: usage.contextTokens,
1479
+ entriesBefore: input.history.content.length + input.prompt.content.length
1480
+ });
1481
+ const summaryCell = { current: undefined };
1482
+ return yield* work.pipe(Effect12.provideService(CurrentCompactionId, compactionId), Effect12.provideService(CurrentPurpose, "compaction-summary"), Effect12.provideService(CurrentSummaryCall, summaryCell), Effect12.onExit((exit) => Effect12.flatMap(Clock.currentTimeMillis, (at) => Exit.isSuccess(exit) ? instrumentation.emit({
1483
+ _tag: "CompactionCompleted",
1484
+ turn,
1485
+ compactionId,
1486
+ kind: resultKind(exit.value),
1487
+ completedAt: at,
1488
+ ...summaryCell.current === undefined ? {} : { summaryModelCallId: summaryCell.current }
1489
+ }) : instrumentation.emit({ _tag: "CompactionFailed", turn, compactionId, failedAt: at }))));
1490
+ }));
1491
+ var summaryLanguageModel = Effect12.gen(function* () {
1492
+ const instrumentation = yield* CurrentInstrumentation;
1493
+ const model = yield* LanguageModel4.LanguageModel;
1494
+ return instrumentation === undefined ? model : instrumentation.wrap(model);
1495
+ });
1123
1496
 
1124
- // ../../node_modules/.bun/@batonfx+core@0.9.0/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";
1497
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/summary-model.js
1498
+ import { Context as Context9, Deferred, Effect as Effect13, Fiber as Fiber2, Layer as Layer10, Scope as Scope2 } from "effect";
1499
+ import { LanguageModel as LanguageModel5 } from "effect/unstable/ai";
1127
1500
  var makeSummaryModelProvider = (model) => {
1128
1501
  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);
1502
+ return (effect) => Effect13.contextWith((context) => {
1503
+ const memoMap = Context9.getOrUndefined(context, Layer10.CurrentMemoMap);
1504
+ const scope = Context9.getOrUndefined(context, Scope2.Scope);
1132
1505
  if (memoMap === undefined || scope === undefined) {
1133
- return Effect11.scoped(Layer9.build(model).pipe(Effect11.flatMap((modelContext) => effect.pipe(Effect11.provide(modelContext)))));
1506
+ return Effect13.scoped(Layer10.build(model).pipe(Effect13.flatMap((modelContext) => effect.pipe(Effect13.provide(modelContext)))));
1134
1507
  }
1135
- const sharedFiber = Effect11.uninterruptible(Effect11.sync(() => {
1508
+ const sharedFiber = Effect13.uninterruptible(Effect13.sync(() => {
1136
1509
  const existing = fibers.get(scope);
1137
1510
  if (existing !== undefined)
1138
1511
  return [existing, false];
1139
1512
  const created = Deferred.makeUnsafe();
1140
1513
  fibers.set(scope, created);
1141
1514
  return [created, true];
1142
- }).pipe(Effect11.flatMap(([deferred, start]) => start ? Effect11.forkIn(Layer9.buildWithMemoMap(model, memoMap, scope), scope, {
1515
+ }).pipe(Effect13.flatMap(([deferred, start]) => start ? Effect13.forkIn(Layer10.buildWithMemoMap(model, memoMap, scope), scope, {
1143
1516
  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))));
1517
+ }).pipe(Effect13.tap((fiber) => Deferred.succeed(deferred, fiber)), Effect13.as(deferred)) : Effect13.succeed(deferred))));
1518
+ return sharedFiber.pipe(Effect13.flatMap(Deferred.await), Effect13.flatMap(Fiber2.join), Effect13.flatMap((modelContext) => effect.pipe(Effect13.provide(modelContext))));
1146
1519
  });
1147
1520
  };
1148
1521
 
1149
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/compaction.js
1522
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/compaction.js
1150
1523
  var DEFAULT_RESERVE_TOKENS = 16384;
1151
1524
  var DEFAULT_KEEP_RECENT_TOKENS = 20000;
1152
1525
  var SUMMARY_TEMPLATE = `Summarize the conversation so another agent can continue seamlessly.
@@ -1164,21 +1537,22 @@ Use Markdown with these sections:
1164
1537
  ## Critical Context
1165
1538
 
1166
1539
  Do not mention that context was compacted.`;
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)
1540
+ var AgentSummary = Schema11.Struct({
1541
+ goal: Schema11.String,
1542
+ facts: Schema11.Array(Schema11.String),
1543
+ decisions: Schema11.Array(Schema11.String),
1544
+ openQuestions: Schema11.Array(Schema11.String),
1545
+ toolFindings: Schema11.Array(Schema11.String)
1173
1546
  });
1547
+ var withLifecycle = (request) => (work) => withCompactionLifecycle(work, request, request.usage);
1174
1548
 
1175
- class CompactionError extends Schema10.TaggedErrorClass()("@batonfx/core/CompactionError", {
1176
- message: Schema10.String,
1177
- cause: Schema10.optionalKey(Schema10.Defect())
1549
+ class CompactionError extends Schema11.TaggedErrorClass()("@batonfx/core/CompactionError", {
1550
+ message: Schema11.String,
1551
+ cause: Schema11.optionalKey(Schema11.Defect())
1178
1552
  }) {
1179
1553
  }
1180
1554
 
1181
- class Compaction extends Context9.Service()("@batonfx/core/Compaction") {
1555
+ class Compaction extends Context10.Service()("@batonfx/core/Compaction") {
1182
1556
  }
1183
1557
  var serialized2 = (value) => {
1184
1558
  const json = JSON.stringify(value);
@@ -1214,7 +1588,7 @@ var isPromptToolResult = (part) => part.type === "tool-result";
1214
1588
  var messageHasToolCall = (message) => typeof message.content !== "string" && message.content.some((part) => part.type === "tool-call");
1215
1589
  var isToolMessage = (entry) => entry?._tag === "Message" && entry.message.role === "tool";
1216
1590
  var isAssistantToolCallEntry = (entry) => entry?._tag === "Message" && entry.message.role === "assistant" && messageHasToolCall(entry.message);
1217
- var compactToolPart = (part, maxBytes) => Effect12.gen(function* () {
1591
+ var compactToolPart = (part, maxBytes) => Effect14.gen(function* () {
1218
1592
  if (part.isFailure)
1219
1593
  return [part, false];
1220
1594
  const success2 = { _tag: "Success", result: part.result, encodedResult: part.result };
@@ -1231,7 +1605,7 @@ var compactToolPart = (part, maxBytes) => Effect12.gen(function* () {
1231
1605
  true
1232
1606
  ];
1233
1607
  });
1234
- var microcompactPrompt = (prompt, maxBytes) => Effect12.gen(function* () {
1608
+ var microcompactPrompt = (prompt, maxBytes) => Effect14.gen(function* () {
1235
1609
  let changed = false;
1236
1610
  const messages = [];
1237
1611
  for (const message of prompt.content) {
@@ -1295,24 +1669,24 @@ var defaultStrategy = (options = {}) => {
1295
1669
  cut: (entries, keepRecentTokens) => {
1296
1670
  const index = safeCutIndex(entries, keepRecentTokens);
1297
1671
  if (index <= 0 || index >= entries.length)
1298
- return Option6.none();
1672
+ return Option8.none();
1299
1673
  const recent = entries.slice(index);
1300
1674
  const first = recent[0];
1301
- return first === undefined ? Option6.none() : Option6.some({ firstKeptEntryId: first.id, head: entries.slice(0, index), recent });
1675
+ return first === undefined ? Option8.none() : Option8.some({ firstKeptEntryId: first.id, head: entries.slice(0, index), recent });
1302
1676
  },
1303
1677
  summarize: (plan, request) => {
1304
- const effect = Effect12.gen(function* () {
1678
+ const effect = Effect14.gen(function* () {
1305
1679
  const head = buildContext(plan.head);
1306
1680
  const [compactedHead] = request.toolOutputMaxBytes === undefined ? [head, false] : yield* microcompactPrompt(head, request.toolOutputMaxBytes);
1307
1681
  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 })));
1682
+ const model = yield* summaryLanguageModel;
1683
+ return yield* model.generateText({ prompt, toolkit: Toolkit2.empty, toolChoice: "none" }).pipe(Effect14.map((response) => response.text), Effect14.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1310
1684
  });
1311
1685
  return provideSummaryModel === undefined ? effect : provideSummaryModel(effect);
1312
1686
  }
1313
1687
  };
1314
1688
  };
1315
- var strategy = Function4.dual((args) => args.length !== 1 || Array.isArray(args[0]), (parts, base = defaultStrategy()) => parts.reduce((current, part) => ({
1689
+ var strategy = Function5.dual((args) => args.length !== 1 || Array.isArray(args[0]), (parts, base = defaultStrategy()) => parts.reduce((current, part) => ({
1316
1690
  shouldCompact: part.shouldCompact ?? current.shouldCompact,
1317
1691
  cut: part.cut ?? current.cut,
1318
1692
  summarize: part.summarize ?? current.summarize,
@@ -1329,79 +1703,81 @@ var structuredSummary = (options = {}) => {
1329
1703
  const provideSummaryModel = options.summaryModel === undefined ? undefined : makeSummaryModelProvider(options.summaryModel);
1330
1704
  return {
1331
1705
  summarize: (plan, request) => {
1332
- const effect = Effect12.gen(function* () {
1706
+ const effect = Effect14.gen(function* () {
1333
1707
  const head = buildContext(plan.head);
1334
1708
  const [compactedHead] = request.toolOutputMaxBytes === undefined ? [head, false] : yield* microcompactPrompt(head, request.toolOutputMaxBytes);
1335
1709
  const prompt = summaryPrompt(options.summaryPrompt ?? SUMMARY_TEMPLATE, compactedHead);
1336
- const model = yield* LanguageModel4.LanguageModel;
1710
+ const model = yield* summaryLanguageModel;
1337
1711
  return yield* model.generateObject({
1338
1712
  prompt,
1339
1713
  schema: AgentSummary,
1340
1714
  objectName: options.objectName ?? "AgentSummary",
1341
1715
  toolChoice: "none"
1342
- }).pipe(Effect12.map((response) => renderAgentSummary(response.value)), Effect12.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1716
+ }).pipe(Effect14.map((response) => renderAgentSummary(response.value)), Effect14.mapError((error) => CompactionError.make({ message: String(error), cause: error })));
1343
1717
  });
1344
1718
  return provideSummaryModel === undefined ? effect : provideSummaryModel(effect);
1345
1719
  }
1346
1720
  };
1347
1721
  };
1348
- var make2 = Function4.dual((args) => args.length !== 1 || ("shouldCompact" in args[0]), (compactionStrategy, options = {}) => ({
1349
- maybeCompact: (input) => Effect12.gen(function* () {
1722
+ var make2 = Function5.dual((args) => args.length !== 1 || ("shouldCompact" in args[0]), (compactionStrategy, options = {}) => ({
1723
+ maybeCompact: (input) => Effect14.suspend(() => {
1350
1724
  const usage = normalizeUsage(input.usage, options);
1351
1725
  const shouldCompact = input.overflow || compactionStrategy.shouldCompact(usage);
1352
1726
  if (!shouldCompact)
1353
- return Option6.none();
1354
- let history = input.history;
1355
- let prompt = input.prompt;
1356
- let changed = false;
1357
- const toolOutputMaxBytes = input.toolOutputMaxBytes ?? compactionStrategy.toolOutputMaxBytes;
1358
- if (toolOutputMaxBytes !== undefined) {
1359
- const [compactedHistoryPrompt, historyChanged] = yield* microcompactPrompt(history, toolOutputMaxBytes);
1360
- const [compactedPrompt, promptChanged] = yield* microcompactPrompt(prompt, toolOutputMaxBytes);
1361
- history = compactedHistoryPrompt;
1362
- prompt = compactedPrompt;
1363
- changed = historyChanged || promptChanged;
1364
- if (changed && fits(history, prompt, usage))
1365
- return Option6.some(makeMicrocompact(history, prompt));
1366
- }
1367
- const plan = compactionStrategy.cut(input.path ?? [], compactionStrategy.keepRecentTokens ?? options.keepRecentTokens ?? DEFAULT_KEEP_RECENT_TOKENS);
1368
- if (Option6.isNone(plan))
1369
- return changed ? Option6.some(makeMicrocompact(history, prompt)) : Option6.none();
1370
- const summary = yield* compactionStrategy.summarize(plan.value, {
1371
- ...input,
1372
- history,
1373
- prompt,
1374
- usage,
1375
- ...toolOutputMaxBytes === undefined ? {} : { toolOutputMaxBytes }
1376
- });
1377
- const recent = buildContext(plan.value.recent);
1378
- const [compactedRecent] = toolOutputMaxBytes === undefined ? [recent, false] : yield* microcompactPrompt(recent, toolOutputMaxBytes);
1379
- return Option6.some({
1380
- _tag: "Summarize",
1381
- history: compactedHistory(summary, plan.value.head, compactedRecent),
1382
- prompt,
1383
- summary,
1384
- firstKeptEntryId: plan.value.firstKeptEntryId
1385
- });
1727
+ return Effect14.succeed(Option8.none());
1728
+ return withCompactionLifecycle(compact(compactionStrategy, input, usage, options), input, usage);
1386
1729
  })
1387
1730
  }));
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))));
1731
+ var compact = (compactionStrategy, input, usage, options) => Effect14.gen(function* () {
1732
+ let history = input.history;
1733
+ let prompt = input.prompt;
1734
+ let changed = false;
1735
+ const toolOutputMaxBytes = input.toolOutputMaxBytes ?? compactionStrategy.toolOutputMaxBytes;
1736
+ if (toolOutputMaxBytes !== undefined) {
1737
+ const [compactedHistoryPrompt, historyChanged] = yield* microcompactPrompt(history, toolOutputMaxBytes);
1738
+ const [compactedPrompt, promptChanged] = yield* microcompactPrompt(prompt, toolOutputMaxBytes);
1739
+ history = compactedHistoryPrompt;
1740
+ prompt = compactedPrompt;
1741
+ changed = historyChanged || promptChanged;
1742
+ if (changed && fits(history, prompt, usage))
1743
+ return Option8.some(makeMicrocompact(history, prompt));
1744
+ }
1745
+ const plan = compactionStrategy.cut(input.path ?? [], compactionStrategy.keepRecentTokens ?? options.keepRecentTokens ?? DEFAULT_KEEP_RECENT_TOKENS);
1746
+ if (Option8.isNone(plan))
1747
+ return changed ? Option8.some(makeMicrocompact(history, prompt)) : Option8.none();
1748
+ const summary = yield* compactionStrategy.summarize(plan.value, {
1749
+ ...input,
1750
+ history,
1751
+ prompt,
1752
+ usage,
1753
+ ...toolOutputMaxBytes === undefined ? {} : { toolOutputMaxBytes }
1754
+ });
1755
+ const recent = buildContext(plan.value.recent);
1756
+ const [compactedRecent] = toolOutputMaxBytes === undefined ? [recent, false] : yield* microcompactPrompt(recent, toolOutputMaxBytes);
1757
+ return Option8.some({
1758
+ _tag: "Summarize",
1759
+ history: compactedHistory(summary, plan.value.head, compactedRecent),
1760
+ prompt,
1761
+ summary,
1762
+ firstKeptEntryId: plan.value.firstKeptEntryId
1763
+ });
1764
+ });
1765
+ var layer2 = Function5.dual((args) => args.length !== 1 || !("shouldCompact" in args[0]), (options = {}, providedStrategy = options.strategy ?? defaultStrategy(options)) => Layer11.succeed(Compaction, Compaction.of(make2(providedStrategy, options))));
1389
1766
  var truncate = (maxTokens) => ({
1390
- maybeCompact: (input) => Effect12.gen(function* () {
1767
+ maybeCompact: (input) => Effect14.gen(function* () {
1391
1768
  const usage = input.usage;
1392
1769
  if (!input.overflow && !(Number.isFinite(usage.contextWindow) && usage.contextTokens > usage.contextWindow - usage.reserveTokens)) {
1393
- return Option6.none();
1770
+ return Option8.none();
1394
1771
  }
1395
- const tokenizer = yield* Effect12.serviceOption(Tokenizer.Tokenizer);
1396
- if (Option6.isNone(tokenizer))
1397
- return Option6.none();
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));
1772
+ const tokenizer = yield* Effect14.serviceOption(Tokenizer.Tokenizer);
1773
+ if (Option8.isNone(tokenizer))
1774
+ return Option8.none();
1775
+ return yield* tokenizer.value.truncate(Prompt6.concat(input.history, input.prompt), maxTokens).pipe(Effect14.map((prompt) => Option8.some(makeMicrocompact(Prompt6.empty, prompt))), Effect14.mapError((error) => CompactionError.make({ message: String(error), cause: error })), withCompactionLifecycle(input, usage));
1400
1776
  })
1401
1777
  });
1402
- var layerTest8 = (implementation) => Layer10.succeed(Compaction, Compaction.of(implementation));
1778
+ var layerTest8 = (implementation) => Layer11.succeed(Compaction, Compaction.of(implementation));
1403
1779
 
1404
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/instructions.js
1780
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/instructions.js
1405
1781
  var exports_instructions = {};
1406
1782
  __export(exports_instructions, {
1407
1783
  staticSource: () => staticSource,
@@ -1410,43 +1786,43 @@ __export(exports_instructions, {
1410
1786
  layer: () => layer3,
1411
1787
  Instructions: () => Instructions
1412
1788
  });
1413
- import { Context as Context10, Effect as Effect13, Layer as Layer11, Option as Option7 } from "effect";
1414
- import { dual as dual3 } from "effect/Function";
1415
- class Instructions extends Context10.Service()("@batonfx/core/Instructions") {
1789
+ import { Context as Context11, Effect as Effect15, Layer as Layer12, Option as Option9 } from "effect";
1790
+ import { dual as dual4 } from "effect/Function";
1791
+ class Instructions extends Context11.Service()("@batonfx/core/Instructions") {
1416
1792
  }
1417
- var staticSource = dual3(2, (id, text) => ({
1793
+ var staticSource = dual4(2, (id, text) => ({
1418
1794
  id,
1419
- render: () => Effect13.succeed(text.length === 0 ? Option7.none() : Option7.some(text))
1795
+ render: () => Effect15.succeed(text.length === 0 ? Option9.none() : Option9.some(text))
1420
1796
  }));
1421
- var openEpoch = dual3(2, (instructions, context) => Effect13.gen(function* () {
1797
+ var openEpoch = dual4(2, (instructions, context) => Effect15.gen(function* () {
1422
1798
  const baseline = [];
1423
1799
  for (const source of instructions.sources) {
1424
1800
  const rendered = yield* source.render(context);
1425
- if (Option7.isSome(rendered))
1801
+ if (Option9.isSome(rendered))
1426
1802
  baseline.push(rendered.value);
1427
1803
  }
1428
1804
  return baseline.join(`
1429
1805
 
1430
1806
  `);
1431
1807
  }));
1432
- var layer3 = (sources) => Layer11.succeed(Instructions, Instructions.of({ sources: [...sources] }));
1433
- var layerTest9 = (implementation) => Layer11.succeed(Instructions, Instructions.of(implementation));
1808
+ var layer3 = (sources) => Layer12.succeed(Instructions, Instructions.of({ sources: [...sources] }));
1809
+ var layerTest9 = (implementation) => Layer12.succeed(Instructions, Instructions.of(implementation));
1434
1810
 
1435
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/model-middleware.js
1811
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/model-middleware.js
1436
1812
  var exports_model_middleware = {};
1437
1813
  __export(exports_model_middleware, {
1438
1814
  layerIdentity: () => layerIdentity,
1439
1815
  layer: () => layer4,
1440
1816
  ModelMiddleware: () => ModelMiddleware
1441
1817
  });
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") {
1818
+ import { Context as Context12, Effect as Effect16, Layer as Layer13, Option as Option10 } from "effect";
1819
+ import { Prompt as Prompt7, Response as Response5 } from "effect/unstable/ai";
1820
+ class ModelMiddleware extends Context12.Service()("@batonfx/core/ModelMiddleware") {
1445
1821
  }
1446
- var layerIdentity = Layer12.succeed(ModelMiddleware, []);
1447
- var layer4 = (middleware) => Layer12.succeed(ModelMiddleware, middleware);
1822
+ var layerIdentity = Layer13.succeed(ModelMiddleware, []);
1823
+ var layer4 = (middleware) => Layer13.succeed(ModelMiddleware, middleware);
1448
1824
 
1449
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/model-resilience.js
1825
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/model-resilience.js
1450
1826
  var exports_model_resilience = {};
1451
1827
  __export(exports_model_resilience, {
1452
1828
  none: () => none,
@@ -1457,49 +1833,49 @@ __export(exports_model_resilience, {
1457
1833
  apply: () => apply,
1458
1834
  ModelResilience: () => ModelResilience
1459
1835
  });
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";
1836
+ import { Cause as Cause3, Context as Context13, Effect as Effect17, Function as Function6, Layer as Layer14, Result, Schedule as Schedule2, Schema as Schema12, Stream as Stream3 } from "effect";
1837
+ import { AiError as AiError5, LanguageModel as LanguageModel7, Response as Response6, Tool as Tool5 } from "effect/unstable/ai";
1462
1838
 
1463
- class ModelResilience extends Context12.Service()("@batonfx/core/ModelResilience") {
1839
+ class ModelResilience extends Context13.Service()("@batonfx/core/ModelResilience") {
1464
1840
  }
1465
- var defaultClassify = (error) => AiError3.isAiError(error) && error.isRetryable ? "transient" : "terminal";
1841
+ var defaultClassify = (error) => AiError5.isAiError(error) && error.isRetryable ? "transient" : "terminal";
1466
1842
  var none = { classify: () => "terminal", retrySchedule: Schedule2.recurs(0) };
1467
1843
  var make3 = (input) => ({
1468
1844
  classify: input?.classify ?? defaultClassify,
1469
1845
  retrySchedule: input?.retrySchedule ?? none.retrySchedule
1470
1846
  });
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) => {
1847
+ var layer5 = (input) => Layer14.succeed(ModelResilience, ModelResilience.of(make3(input)));
1848
+ var layerTest10 = (implementation) => Layer14.succeed(ModelResilience, ModelResilience.of(implementation));
1849
+ var retryEffect = (effect, resilience) => Effect17.suspend(effect).pipe(Effect17.map((value) => Result.succeed(value)), Effect17.catchCause((cause) => {
1474
1850
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
1475
- return reason === undefined || !Cause2.isFailReason(reason) ? Effect15.succeed(Result.fail(cause)) : Effect15.fail(reason.error);
1476
- }), Effect15.retry({
1851
+ return reason === undefined || !Cause3.isFailReason(reason) ? Effect17.succeed(Result.fail(cause)) : Effect17.fail(reason.error);
1852
+ }), Effect17.retry({
1477
1853
  schedule: resilience.retrySchedule,
1478
1854
  while: (error) => resilience.classify(error) === "transient"
1479
- }), Effect15.flatMap((result) => Result.isFailure(result) ? Effect15.failCause(result.failure) : Effect15.succeed(result.success)));
1855
+ }), Effect17.flatMap((result) => Result.isFailure(result) ? Effect17.failCause(result.failure) : Effect17.succeed(result.success)));
1480
1856
  var retryStreamSchedule = (resilience) => resilience.retrySchedule.pipe(Schedule2.while(({ input }) => resilience.classify(input) === "transient"));
1481
1857
  var retryStream = (stream2, onEmittedFailure, resilience) => Stream3.suspend(() => {
1482
1858
  let emitted = false;
1483
- return stream2().pipe(Stream3.map((value) => Result.succeed(value)), Stream3.tap(() => Effect15.sync(() => {
1859
+ return stream2().pipe(Stream3.map((value) => Result.succeed(value)), Stream3.tap(() => Effect17.sync(() => {
1484
1860
  emitted = true;
1485
1861
  })), Stream3.catchCause((cause) => {
1486
1862
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
1487
- if (reason === undefined || !Cause2.isFailReason(reason))
1863
+ if (reason === undefined || !Cause3.isFailReason(reason))
1488
1864
  return Stream3.succeed(Result.fail(cause));
1489
1865
  return emitted ? Stream3.succeed(Result.succeed(onEmittedFailure(reason.error))) : Stream3.fail(reason.error);
1490
1866
  }));
1491
1867
  }).pipe(Stream3.retry(retryStreamSchedule(resilience)), Stream3.flatMap((result) => Result.isFailure(result) ? Stream3.failCause(result.failure) : Stream3.succeed(result.success)));
1492
- var apply = Function5.dual(2, (model, resilience) => ({
1868
+ var apply = Function6.dual(2, (model, resilience) => ({
1493
1869
  ...model,
1494
1870
  generateText: (options) => retryEffect(() => model.generateText(options), resilience),
1495
1871
  generateObject: (options) => {
1496
1872
  const generate = model.generateObject;
1497
1873
  return retryEffect(() => generate(options), resilience);
1498
1874
  },
1499
- streamText: (options) => retryStream(() => model.streamText(options), (error) => Response5.makePart("error", { error }), resilience)
1875
+ streamText: (options) => retryStream(() => model.streamText(options), (error) => Response6.makePart("error", { error }), resilience)
1500
1876
  }));
1501
1877
 
1502
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/permissions.js
1878
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/permissions.js
1503
1879
  var exports_permissions = {};
1504
1880
  __export(exports_permissions, {
1505
1881
  matches: () => matches,
@@ -1515,18 +1891,18 @@ __export(exports_permissions, {
1515
1891
  Permissions: () => Permissions,
1516
1892
  PermissionError: () => PermissionError
1517
1893
  });
1518
- import { Context as Context13, Effect as Effect16, Layer as Layer14, Option as Option9, Ref as Ref4, Schema as Schema12 } from "effect";
1519
- import { dual as dual4 } from "effect/Function";
1894
+ import { Context as Context14, Effect as Effect18, Layer as Layer15, Option as Option11, Ref as Ref4, Schema as Schema13 } from "effect";
1895
+ import { dual as dual5 } from "effect/Function";
1520
1896
 
1521
- class PermissionError extends Schema12.TaggedErrorClass()("@batonfx/core/PermissionError", {
1522
- message: Schema12.String
1897
+ class PermissionError extends Schema13.TaggedErrorClass()("@batonfx/core/PermissionError", {
1898
+ message: Schema13.String
1523
1899
  }) {
1524
1900
  }
1525
1901
 
1526
- class Permissions extends Context13.Service()("@batonfx/core/Permissions") {
1902
+ class Permissions extends Context14.Service()("@batonfx/core/Permissions") {
1527
1903
  }
1528
1904
 
1529
- class RuleStore extends Context13.Service()("@batonfx/core/RuleStore") {
1905
+ class RuleStore extends Context14.Service()("@batonfx/core/RuleStore") {
1530
1906
  }
1531
1907
  var escapeRegExp = (value) => value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
1532
1908
  var glob = (pattern) => new RegExp(`^${pattern.split("*").map(escapeRegExp).join(".*")}$`);
@@ -1589,7 +1965,7 @@ var matchesProjection = (pattern, tool, projection, failClosed) => {
1589
1965
  const paramsPattern = glob(pattern.slice(separator + 1));
1590
1966
  return projection.candidates.some((candidate) => paramsPattern.test(candidate));
1591
1967
  };
1592
- var matches = dual4(3, (pattern, tool, params) => matchesProjection(pattern, tool, project(params), false));
1968
+ var matches = dual5(3, (pattern, tool, params) => matchesProjection(pattern, tool, project(params), false));
1593
1969
  var matchingRule = (ruleset, tool, params) => {
1594
1970
  const projection = project(params);
1595
1971
  let matched;
@@ -1599,8 +1975,8 @@ var matchingRule = (ruleset, tool, params) => {
1599
1975
  }
1600
1976
  return matched;
1601
1977
  };
1602
- var matchRule = dual4(3, (ruleset, tool, params) => Option9.fromNullishOr(matchingRule(ruleset, tool, params)));
1603
- var evaluate = dual4(3, (ruleset, tool, params) => matchingRule(ruleset, tool, params)?.level ?? ruleset.fallback ?? "ask");
1978
+ var matchRule = dual5(3, (ruleset, tool, params) => Option11.fromNullishOr(matchingRule(ruleset, tool, params)));
1979
+ var evaluate = dual5(3, (ruleset, tool, params) => matchingRule(ruleset, tool, params)?.level ?? ruleset.fallback ?? "ask");
1604
1980
  var tokenFor = (request) => `permission:${request.call.id}`;
1605
1981
  var decisionFor = (ruleset, request) => {
1606
1982
  const rule = matchingRule(ruleset, request.call.name, request.call.params);
@@ -1614,7 +1990,7 @@ var decisionFor = (ruleset, request) => {
1614
1990
  return { _tag: "Ask", token: tokenFor(request) };
1615
1991
  }
1616
1992
  };
1617
- var evaluateWithRules = dual4(3, (base, store, request) => Effect16.gen(function* () {
1993
+ var evaluateWithRules = dual5(3, (base, store, request) => Effect18.gen(function* () {
1618
1994
  const baseDecision = yield* base.evaluate(request);
1619
1995
  if (baseDecision._tag === "Deny")
1620
1996
  return baseDecision;
@@ -1631,20 +2007,20 @@ var evaluateWithRules = dual4(3, (base, store, request) => Effect16.gen(function
1631
2007
  return { _tag: "Ask", token: tokenFor(request) };
1632
2008
  }
1633
2009
  }));
1634
- var layerRuleset = (ruleset) => Layer14.succeed(Permissions, Permissions.of({
1635
- evaluate: (request) => Effect16.succeed(decisionFor(ruleset, request))
2010
+ var layerRuleset = (ruleset) => Layer15.succeed(Permissions, Permissions.of({
2011
+ evaluate: (request) => Effect18.succeed(decisionFor(ruleset, request))
1636
2012
  }));
1637
- var layerAllowAll = Layer14.succeed(Permissions, Permissions.of({
1638
- evaluate: () => Effect16.succeed({ _tag: "Allow" })
2013
+ var layerAllowAll = Layer15.succeed(Permissions, Permissions.of({
2014
+ evaluate: () => Effect18.succeed({ _tag: "Allow" })
1639
2015
  }));
1640
- var layerRuleStoreMemory = (initialRules = []) => Layer14.effect(RuleStore, Ref4.make(initialRules).pipe(Effect16.map((rules) => RuleStore.of({
2016
+ var layerRuleStoreMemory = (initialRules = []) => Layer15.effect(RuleStore, Ref4.make(initialRules).pipe(Effect18.map((rules) => RuleStore.of({
1641
2017
  remember: (rule) => Ref4.update(rules, (current) => [...current.filter((existing) => existing.pattern !== rule.pattern), rule]),
1642
2018
  rules: Ref4.get(rules)
1643
2019
  }))));
1644
- var layerRuleStoreTest = (implementation) => Layer14.succeed(RuleStore, RuleStore.of(implementation));
1645
- var layerTest11 = (implementation) => Layer14.succeed(Permissions, Permissions.of(implementation));
2020
+ var layerRuleStoreTest = (implementation) => Layer15.succeed(RuleStore, RuleStore.of(implementation));
2021
+ var layerTest11 = (implementation) => Layer15.succeed(Permissions, Permissions.of(implementation));
1646
2022
 
1647
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/skill-source.js
2023
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/skill-source.js
1648
2024
  var exports_skill_source = {};
1649
2025
  __export(exports_skill_source, {
1650
2026
  selectListings: () => selectListings,
@@ -1659,48 +2035,48 @@ __export(exports_skill_source, {
1659
2035
  Frontmatter: () => Frontmatter,
1660
2036
  DESCRIPTION_CAP: () => DESCRIPTION_CAP
1661
2037
  });
1662
- import { Context as Context14, Effect as Effect17, Function as Function6, Layer as Layer15, Schema as Schema13 } from "effect";
2038
+ import { Context as Context15, Effect as Effect19, Function as Function7, Layer as Layer16, Schema as Schema14 } from "effect";
1663
2039
  import { Tool as Tool6 } from "effect/unstable/ai";
1664
2040
  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())
2041
+ var Frontmatter = Schema14.Struct({
2042
+ name: Schema14.String,
2043
+ description: Schema14.String.pipe(Schema14.check(Schema14.isMinLength(1), Schema14.isMaxLength(DESCRIPTION_CAP))),
2044
+ whenToUse: Schema14.optionalKey(Schema14.String),
2045
+ allowedTools: Schema14.optionalKey(Schema14.Array(Schema14.String)),
2046
+ disableModelInvocation: Schema14.optionalKey(Schema14.Boolean),
2047
+ userInvocable: Schema14.optionalKey(Schema14.Boolean),
2048
+ contextFork: Schema14.optionalKey(Schema14.Boolean),
2049
+ agent: Schema14.optionalKey(Schema14.String),
2050
+ model: Schema14.optionalKey(Schema14.String),
2051
+ paths: Schema14.optionalKey(Schema14.Array(Schema14.String))
2052
+ });
2053
+
2054
+ class SkillSourceError extends Schema14.TaggedErrorClass()("@batonfx/core/SkillSourceError", {
2055
+ source: Schema14.String,
2056
+ message: Schema14.String,
2057
+ cause: Schema14.optionalKey(Schema14.Defect())
1682
2058
  }) {
1683
2059
  }
1684
2060
 
1685
- class SkillSource extends Context14.Service()("@batonfx/core/SkillSource") {
2061
+ class SkillSource extends Context15.Service()("@batonfx/core/SkillSource") {
1686
2062
  }
1687
- var makeListing = Function6.dual((args) => typeof args[0] !== "number", (frontmatter, descriptionCap = DESCRIPTION_CAP) => `- ${frontmatter.name}: ${frontmatter.description.slice(0, Math.max(0, descriptionCap))}`);
2063
+ var makeListing = Function7.dual((args) => typeof args[0] !== "number", (frontmatter, descriptionCap = DESCRIPTION_CAP) => `- ${frontmatter.name}: ${frontmatter.description.slice(0, Math.max(0, descriptionCap))}`);
1688
2064
  var layerSkills = (skills) => {
1689
2065
  const all = [...skills];
1690
2066
  const byName = new Map(all.map((skill) => [skill.frontmatter.name, skill]));
1691
- return Layer15.succeed(SkillSource, SkillSource.of({
1692
- all: Effect17.succeed(all),
1693
- get: (name) => Effect17.succeed(byName.get(name))
2067
+ return Layer16.succeed(SkillSource, SkillSource.of({
2068
+ all: Effect19.succeed(all),
2069
+ get: (name) => Effect19.succeed(byName.get(name))
1694
2070
  }));
1695
2071
  };
1696
2072
  var layerEmpty = layerSkills([]);
1697
- var layerTest12 = (implementation) => Layer15.succeed(SkillSource, SkillSource.of(implementation));
2073
+ var layerTest12 = (implementation) => Layer16.succeed(SkillSource, SkillSource.of(implementation));
1698
2074
  var emptySource = {
1699
- all: Effect17.succeed([]),
1700
- get: () => Effect17.void.pipe(Effect17.as(undefined))
2075
+ all: Effect19.succeed([]),
2076
+ get: () => Effect19.void.pipe(Effect19.as(undefined))
1701
2077
  };
1702
- var merge2 = Function6.dual(2, (first, second) => ({
1703
- all: Effect17.all([first.all, second.all]).pipe(Effect17.map((groups) => {
2078
+ var merge2 = Function7.dual(2, (first, second) => ({
2079
+ all: Effect19.all([first.all, second.all]).pipe(Effect19.map((groups) => {
1704
2080
  const byName = new Map;
1705
2081
  for (const skills of groups) {
1706
2082
  for (const skill of skills)
@@ -1708,15 +2084,15 @@ var merge2 = Function6.dual(2, (first, second) => ({
1708
2084
  }
1709
2085
  return [...byName.values()];
1710
2086
  })),
1711
- get: (name) => second.get(name).pipe(Effect17.flatMap((found) => found === undefined ? first.get(name) : Effect17.succeed(found)))
2087
+ get: (name) => second.get(name).pipe(Effect19.flatMap((found) => found === undefined ? first.get(name) : Effect19.succeed(found)))
1712
2088
  }));
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)))));
2089
+ var layer6 = (sources) => Layer16.effect(SkillSource, Effect19.forEach(sources, (source) => source).pipe(Effect19.map((built) => SkillSource.of(built.reduce((first, second) => merge2(first, second), emptySource)))));
1714
2090
  var estimatedTokens = (listing) => Math.ceil(listing.length / 4);
1715
2091
  var usageRank = (skill, recentlyUsed) => {
1716
2092
  const index = recentlyUsed.indexOf(skill.frontmatter.name);
1717
2093
  return index === -1 ? -1 : index;
1718
2094
  };
1719
- var selectListings = Function6.dual(3, (skills, budgetTokens, recentlyUsed) => {
2095
+ var selectListings = Function7.dual(3, (skills, budgetTokens, recentlyUsed) => {
1720
2096
  if (budgetTokens <= 0)
1721
2097
  return [];
1722
2098
  const selected = skills.filter((skill) => skill.frontmatter.disableModelInvocation !== true && estimatedTokens(skill.listing) <= budgetTokens);
@@ -1734,7 +2110,7 @@ var selectListings = Function6.dual(3, (skills, budgetTokens, recentlyUsed) => {
1734
2110
  return selected;
1735
2111
  });
1736
2112
 
1737
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/steering.js
2113
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/steering.js
1738
2114
  var exports_steering = {};
1739
2115
  __export(exports_steering, {
1740
2116
  layerTest: () => layerTest13,
@@ -1742,15 +2118,15 @@ __export(exports_steering, {
1742
2118
  SteeringQueueFull: () => SteeringQueueFull,
1743
2119
  Steering: () => Steering
1744
2120
  });
1745
- import { Context as Context15, Effect as Effect18, Exit, Layer as Layer16, Queue, Schema as Schema14 } from "effect";
2121
+ import { Context as Context16, Effect as Effect20, Exit as Exit2, Layer as Layer17, Queue, Schema as Schema15 } from "effect";
1746
2122
  import { Prompt as Prompt8 } from "effect/unstable/ai";
1747
2123
 
1748
- class Steering extends Context15.Service()("@batonfx/core/Steering") {
2124
+ class Steering extends Context16.Service()("@batonfx/core/Steering") {
1749
2125
  }
1750
2126
 
1751
- class SteeringQueueFull extends Schema14.TaggedErrorClass()("@batonfx/core/SteeringQueueFull", {
1752
- queue: Schema14.Literals(["steering", "followUp"]),
1753
- capacity: Schema14.Finite
2127
+ class SteeringQueueFull extends Schema15.TaggedErrorClass()("@batonfx/core/SteeringQueueFull", {
2128
+ queue: Schema15.Literals(["steering", "followUp"]),
2129
+ capacity: Schema15.Finite
1754
2130
  }) {
1755
2131
  }
1756
2132
  var resolvePolicy = (policy, mode) => ({
@@ -1769,18 +2145,18 @@ var queueStrategy = (strategy2) => {
1769
2145
  return "suspend";
1770
2146
  }
1771
2147
  };
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) => {
2148
+ var makeQueue = (name, policy) => (policy.capacity === undefined ? Queue.unbounded() : Queue.make({ capacity: policy.capacity, strategy: queueStrategy(policy.onFull) })).pipe(Effect20.map((queue) => ({ name, queue, policy })));
2149
+ var offer = (runtime, input) => Queue.offer(runtime.queue, input).pipe(Effect20.flatMap((offered) => {
1774
2150
  if (offered || runtime.policy.capacity === undefined || runtime.policy.onFull !== "fail")
1775
- return Effect18.void;
2151
+ return Effect20.void;
1776
2152
  return SteeringQueueFull.make({ queue: runtime.name, capacity: runtime.policy.capacity });
1777
2153
  }));
1778
- var drainOne = (queue) => Effect18.sync(() => {
2154
+ var drainOne = (queue) => Effect20.sync(() => {
1779
2155
  const taken = Queue.takeUnsafe(queue);
1780
- return taken === undefined || !Exit.isSuccess(taken) ? [] : [taken.value];
2156
+ return taken === undefined || !Exit2.isSuccess(taken) ? [] : [taken.value];
1781
2157
  });
1782
2158
  var drain = (queue, mode) => mode === "all" ? Queue.clear(queue) : drainOne(queue);
1783
- var layer7 = (options = {}) => Layer16.effect(Steering, Effect18.gen(function* () {
2159
+ var layer7 = (options = {}) => Layer17.effect(Steering, Effect20.gen(function* () {
1784
2160
  const steeringQueue = yield* makeQueue("steering", resolvePolicy(options.steering, "all"));
1785
2161
  const followUpQueue = yield* makeQueue("followUp", resolvePolicy(options.followUp, "one-at-a-time"));
1786
2162
  return Steering.of({
@@ -1790,9 +2166,9 @@ var layer7 = (options = {}) => Layer16.effect(Steering, Effect18.gen(function* (
1790
2166
  takeFollowUp: drain(followUpQueue.queue, followUpQueue.policy.mode)
1791
2167
  });
1792
2168
  }));
1793
- var layerTest13 = (implementation) => Layer16.succeed(Steering, Steering.of(implementation));
2169
+ var layerTest13 = (implementation) => Layer17.succeed(Steering, Steering.of(implementation));
1794
2170
 
1795
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent.js
2171
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent.js
1796
2172
  var exports_agent = {};
1797
2173
  __export(exports_agent, {
1798
2174
  stream: () => stream2,
@@ -1802,42 +2178,297 @@ __export(exports_agent, {
1802
2178
  defaultObjectPrompt: () => defaultObjectPrompt,
1803
2179
  Runtime: () => Runtime
1804
2180
  });
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";
2181
+ import { Effect as Effect27, Option as Option17, Schema as Schema21, Stream as Stream6, Types } from "effect";
2182
+ import { dual as dual7 } from "effect/Function";
2183
+ import { AiError as AiError8, Chat as Chat3, LanguageModel as LanguageModel10, Prompt as Prompt12, Tool as Tool10, Toolkit as Toolkit5 } from "effect/unstable/ai";
1808
2184
 
1809
- // ../../node_modules/.bun/@batonfx+core@0.9.0/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";
2185
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-run.js
2186
+ import { Cause as Cause6, Channel, Effect as Effect26, Equal as Equal2, Exit as Exit4, Fiber as Fiber3, HashMap as HashMap6, Option as Option16, Queue as Queue2, Ref as Ref5, Schema as Schema20, Semaphore as Semaphore3, Stream as Stream5 } from "effect";
2187
+ import { AiError as AiError7, Chat as Chat2, LanguageModel as LanguageModel9, Prompt as Prompt11, Response as Response11, Telemetry, Tokenizer as Tokenizer2, Tool as Tool9, Toolkit as Toolkit4 } from "effect/unstable/ai";
1812
2188
 
1813
- // ../../node_modules/.bun/@batonfx+core@0.9.0/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";
2189
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/model-instrumentation.js
2190
+ import { Cause as Cause4, Clock as Clock2, Duration, Effect as Effect21, Exit as Exit3, Function as Function8, Option as Option12, Schedule as Schedule3, Stream as Stream4 } from "effect";
2191
+ import { AiError as AiError6, LanguageModel as LanguageModel8, Model as Model2, Response as Response7 } from "effect/unstable/ai";
2192
+ var makeIdentityCell = () => ({ current: undefined });
2193
+ var InstrumentedTypeId = Symbol.for("@batonfx/core/model-instrumentation/Instrumented");
2194
+ var memoized = (compute) => {
2195
+ const cache = new Map;
2196
+ return (error) => {
2197
+ const cached = cache.get(error);
2198
+ if (cached !== undefined)
2199
+ return cached;
2200
+ const result = compute(error);
2201
+ cache.set(error, result);
2202
+ return result;
2203
+ };
2204
+ };
2205
+ var singleFailure = (cause) => {
2206
+ const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
2207
+ return reason !== undefined && Cause4.isFailReason(reason) ? Option12.some(reason.error) : Option12.none();
2208
+ };
2209
+ var firstOutputKind = (part) => {
2210
+ switch (part.type) {
2211
+ case "reasoning-start":
2212
+ case "reasoning-delta":
2213
+ case "reasoning":
2214
+ return "reasoning";
2215
+ case "text-start":
2216
+ case "text-delta":
2217
+ case "text":
2218
+ return "text";
2219
+ case "tool-params-start":
2220
+ case "tool-call":
2221
+ return "tool-call";
2222
+ default:
2223
+ return;
2224
+ }
2225
+ };
2226
+ var recordResponsePart = (context, attempt, part) => {
2227
+ if (part.type === "response-metadata") {
2228
+ attempt.state.requestId = part.id;
2229
+ attempt.state.responseModel = part.modelId;
2230
+ }
2231
+ if (part.type === "finish") {
2232
+ attempt.state.usage = part.usage;
2233
+ attempt.state.finishReason = part.reason;
2234
+ }
2235
+ if (part.type === "error") {
2236
+ attempt.state.errorCategory = context.categorize(part.error);
2237
+ }
2238
+ };
2239
+ var observeStreamPart = (context, attempt, part) => Effect21.gen(function* () {
2240
+ recordResponsePart(context, attempt, part);
2241
+ if (part.type === "finish") {
2242
+ attempt.state.usageAt = yield* Clock2.currentTimeMillis;
2243
+ }
2244
+ const kind = firstOutputKind(part);
2245
+ if (kind === undefined || attempt.state.firstOutputs.has(kind))
2246
+ return;
2247
+ attempt.state.firstOutputs.add(kind);
2248
+ const at = yield* Clock2.currentTimeMillis;
2249
+ yield* context.options.emit({
2250
+ _tag: "ModelAttemptFirstOutput",
2251
+ turn: context.options.turn,
2252
+ modelCallId: context.modelCallId,
2253
+ modelAttemptId: attempt.modelAttemptId,
2254
+ attempt: attempt.attempt,
2255
+ kind,
2256
+ at
2257
+ });
2258
+ });
2259
+ var attemptCompleted = (context, attempt) => Effect21.flatMap(Clock2.currentTimeMillis, (completedAt) => context.options.emit({
2260
+ _tag: "ModelAttemptCompleted",
2261
+ turn: context.options.turn,
2262
+ modelCallId: context.modelCallId,
2263
+ modelAttemptId: attempt.modelAttemptId,
2264
+ attempt: attempt.attempt,
2265
+ completedAt,
2266
+ ...attempt.state.usage === undefined ? {} : { usage: attempt.state.usage },
2267
+ ...attempt.state.usageAt === undefined ? {} : { usageAt: attempt.state.usageAt },
2268
+ ...attempt.state.finishReason === undefined ? {} : { finishReason: attempt.state.finishReason },
2269
+ ...attempt.state.requestId === undefined ? {} : { requestId: attempt.state.requestId },
2270
+ ...attempt.state.responseModel === undefined ? {} : { responseModel: attempt.state.responseModel }
2271
+ }));
2272
+ var attemptFailed = (context, attempt, category, classification) => Effect21.flatMap(Clock2.currentTimeMillis, (failedAt) => context.options.emit({
2273
+ _tag: "ModelAttemptFailed",
2274
+ turn: context.options.turn,
2275
+ modelCallId: context.modelCallId,
2276
+ modelAttemptId: attempt.modelAttemptId,
2277
+ attempt: attempt.attempt,
2278
+ failedAt,
2279
+ category,
2280
+ classification
2281
+ }));
2282
+ var attemptExit = (context, attempt, exit) => {
2283
+ if (attempt.state.errorCategory !== undefined) {
2284
+ return attemptFailed(context, attempt, attempt.state.errorCategory, "terminal");
2285
+ }
2286
+ if (Exit3.isSuccess(exit)) {
2287
+ context.state.usage = attempt.state.usage ?? context.state.usage;
2288
+ context.state.finishReason = attempt.state.finishReason ?? context.state.finishReason;
2289
+ return attemptCompleted(context, attempt);
2290
+ }
2291
+ if (Cause4.hasInterrupts(exit.cause))
2292
+ return attemptFailed(context, attempt, "cancellation", "terminal");
2293
+ const failure2 = singleFailure(exit.cause);
2294
+ if (Option12.isNone(failure2))
2295
+ return attemptFailed(context, attempt, "unknown", "terminal");
2296
+ return attemptFailed(context, attempt, context.categorize(failure2.value), context.classify(failure2.value));
2297
+ };
2298
+ var beginAttempt = (context) => Effect21.gen(function* () {
2299
+ const attempt = context.state.attempts;
2300
+ context.state.attempts += 1;
2301
+ const modelAttemptId = yield* generateId;
2302
+ if (context.options.identity !== undefined) {
2303
+ context.options.identity.current = { modelCallId: context.modelCallId, modelAttemptId, attempt };
2304
+ }
2305
+ const startedAt = yield* Clock2.currentTimeMillis;
2306
+ yield* context.options.emit({
2307
+ _tag: "ModelAttemptStarted",
2308
+ turn: context.options.turn,
2309
+ modelCallId: context.modelCallId,
2310
+ modelAttemptId,
2311
+ attempt,
2312
+ startedAt
2313
+ });
2314
+ return {
2315
+ modelAttemptId,
2316
+ attempt,
2317
+ state: {
2318
+ firstOutputs: new Set,
2319
+ usage: undefined,
2320
+ usageAt: undefined,
2321
+ finishReason: undefined,
2322
+ requestId: undefined,
2323
+ responseModel: undefined,
2324
+ errorCategory: undefined
2325
+ }
2326
+ };
2327
+ });
2328
+ var attemptEffect = (context, run) => Effect21.flatMap(beginAttempt(context), (attempt) => run().pipe(Effect21.tap((response) => Effect21.forEach(response.content, (part) => observeStreamPart(context, attempt, part), { discard: true })), Effect21.onExit((exit) => attemptExit(context, attempt, exit))));
2329
+ var attemptStream = (context, run) => Stream4.unwrap(Effect21.map(beginAttempt(context), (attempt) => run().pipe(Stream4.tap((part) => observeStreamPart(context, attempt, part)), Stream4.onExit((exit) => attemptExit(context, attempt, exit)))));
2330
+ var attemptModel = (model, context) => ({
2331
+ ...model,
2332
+ generateText: (options) => attemptEffect(context, () => model.generateText(options)),
2333
+ generateObject: (options) => attemptEffect(context, () => model.generateObject(options)),
2334
+ streamText: (options) => attemptStream(context, () => model.streamText(options))
2335
+ });
2336
+ var tappedResilience = (context, resilience) => ({
2337
+ classify: context.classify,
2338
+ retrySchedule: resilience.retrySchedule.pipe(Schedule3.while(({ input }) => context.classify(input) === "transient"), Schedule3.tap((metadata) => Effect21.flatMap(Clock2.currentTimeMillis, (at) => context.options.emit({
2339
+ _tag: "ModelRetryScheduled",
2340
+ turn: context.options.turn,
2341
+ modelCallId: context.modelCallId,
2342
+ attempt: context.state.attempts - 1,
2343
+ reason: "provider-resilience",
2344
+ category: context.categorize(metadata.input),
2345
+ delayMillis: Duration.toMillis(metadata.duration),
2346
+ at
2347
+ }))))
2348
+ });
2349
+ var beginCall = (model, options) => Effect21.gen(function* () {
2350
+ const modelCallId = yield* generateId;
2351
+ const purpose = yield* CurrentPurpose;
2352
+ const compactionId = yield* CurrentCompactionId;
2353
+ const provider = yield* Effect21.serviceOption(Model2.ProviderName);
2354
+ const modelName = yield* Effect21.serviceOption(Model2.ModelName);
2355
+ const startedAt = yield* Clock2.currentTimeMillis;
2356
+ yield* options.emit({
2357
+ _tag: "ModelCallStarted",
2358
+ turn: options.turn,
2359
+ modelCallId,
2360
+ purpose,
2361
+ ...Option12.isSome(provider) ? { provider: provider.value } : {},
2362
+ ...Option12.isSome(modelName) ? { model: modelName.value } : {},
2363
+ ...compactionId === undefined ? {} : { compactionId },
2364
+ startedAt
2365
+ });
2366
+ if (compactionId !== undefined) {
2367
+ const summaryCell = yield* CurrentSummaryCall;
2368
+ if (summaryCell !== undefined) {
2369
+ if (summaryCell.current !== undefined)
2370
+ return yield* Effect21.die(new Error("A compaction pass issued multiple summary model calls"));
2371
+ summaryCell.current = modelCallId;
2372
+ }
2373
+ }
2374
+ const providerClassification = memoized((error) => classifyFailure(model, error));
2375
+ const context = {
2376
+ options,
2377
+ modelCallId,
2378
+ purpose,
2379
+ categorize: memoized((error) => providerClassification(error) === "context-overflow" ? "context-overflow" : classifyFailureCategory(error)),
2380
+ classify: memoized((error) => providerClassification(error) === "context-overflow" ? "terminal" : options.resilience === undefined ? "terminal" : options.resilience.classify(error)),
2381
+ state: { attempts: 0, usage: undefined, finishReason: undefined, errorCategory: undefined }
2382
+ };
2383
+ const attempts = attemptModel(model, context);
2384
+ const stack = options.resilience === undefined ? attempts : apply(attempts, tappedResilience(context, options.resilience));
2385
+ return { context, stack };
2386
+ });
2387
+ var observeCallPart = (context, part) => {
2388
+ if (part.type === "finish") {
2389
+ context.state.usage = part.usage;
2390
+ context.state.finishReason = part.reason;
2391
+ }
2392
+ if (part.type === "error") {
2393
+ context.state.errorCategory = context.categorize(part.error);
2394
+ }
2395
+ };
2396
+ var callCompleted = (context) => Effect21.flatMap(Clock2.currentTimeMillis, (completedAt) => context.options.emit({
2397
+ _tag: "ModelCallCompleted",
2398
+ turn: context.options.turn,
2399
+ modelCallId: context.modelCallId,
2400
+ purpose: context.purpose,
2401
+ attempts: context.state.attempts,
2402
+ completedAt,
2403
+ ...context.state.usage === undefined ? {} : { usage: context.state.usage },
2404
+ ...context.state.finishReason === undefined ? {} : { finishReason: context.state.finishReason }
2405
+ }));
2406
+ var callFailed = (context, category) => Effect21.flatMap(Clock2.currentTimeMillis, (failedAt) => context.options.emit({
2407
+ _tag: "ModelCallFailed",
2408
+ turn: context.options.turn,
2409
+ modelCallId: context.modelCallId,
2410
+ purpose: context.purpose,
2411
+ attempts: context.state.attempts,
2412
+ failedAt,
2413
+ category
2414
+ }));
2415
+ var callExit = (context, exit) => {
2416
+ if (context.state.errorCategory !== undefined)
2417
+ return callFailed(context, context.state.errorCategory);
2418
+ if (Exit3.isSuccess(exit))
2419
+ return callCompleted(context);
2420
+ if (Cause4.hasInterrupts(exit.cause))
2421
+ return callFailed(context, "cancellation");
2422
+ const failure2 = singleFailure(exit.cause);
2423
+ return callFailed(context, Option12.isNone(failure2) ? "unknown" : context.categorize(failure2.value));
2424
+ };
2425
+ var callEffect = (model, options, invoke) => Effect21.flatMap(beginCall(model, options), ({ context, stack }) => invoke(stack).pipe(Effect21.tap((response) => Effect21.sync(() => {
2426
+ for (const part of response.content)
2427
+ observeCallPart(context, part);
2428
+ })), Effect21.onExit((exit) => callExit(context, exit))));
2429
+ var callStream = (model, options, invoke) => Stream4.unwrap(Effect21.map(beginCall(model, options), ({ context, stack }) => invoke(stack).pipe(Stream4.tap((part) => Effect21.sync(() => observeCallPart(context, part))), Stream4.onExit((exit) => callExit(context, exit)))));
2430
+ var instrument = Function8.dual(2, (model, options) => {
2431
+ const marker = model[InstrumentedTypeId];
2432
+ if (marker !== undefined) {
2433
+ return marker.emit === options.emit ? model : instrument(marker.base, options);
2434
+ }
2435
+ return {
2436
+ ...model,
2437
+ [InstrumentedTypeId]: { emit: options.emit, base: model },
2438
+ generateText: (generateOptions) => callEffect(model, options, (stack) => stack.generateText(generateOptions)),
2439
+ generateObject: (generateOptions) => callEffect(model, options, (stack) => stack.generateObject(generateOptions)),
2440
+ streamText: (streamOptions) => callStream(model, options, (stack) => stack.streamText(streamOptions))
2441
+ };
2442
+ });
2443
+
2444
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-authorization.js
2445
+ import { Cause as Cause5, Context as Context17, Effect as Effect22, Layer as Layer18, Schema as Schema16 } from "effect";
1815
2446
  import"effect/unstable/ai";
1816
- class PermissionDenied extends Schema15.TaggedErrorClass()("@batonfx/core/PermissionDenied", {
1817
- message: Schema15.String
2447
+ class PermissionDenied extends Schema16.TaggedErrorClass()("@batonfx/core/PermissionDenied", {
2448
+ message: Schema16.String
1818
2449
  }) {
1819
2450
  }
1820
2451
 
1821
- class AuthorizationError extends Schema15.TaggedErrorClass()("@batonfx/core/AuthorizationError", { message: Schema15.String, cause: Schema15.optional(Schema15.Defect()) }) {
2452
+ class AuthorizationError extends Schema16.TaggedErrorClass()("@batonfx/core/AuthorizationError", { message: Schema16.String, cause: Schema16.optional(Schema16.Defect()) }) {
1822
2453
  }
1823
2454
 
1824
- class ToolAuthorizerService extends Context16.Service()("@batonfx/core/ToolAuthorizerService") {
2455
+ class ToolAuthorizerService extends Context17.Service()("@batonfx/core/ToolAuthorizerService") {
1825
2456
  }
1826
2457
  var deny = (message) => ({ _tag: "Deny", error: PermissionDenied.make({ message }) });
1827
2458
  var authorizationError = (error) => AuthorizationError.make({ message: error.message, cause: error });
1828
2459
  var approvalRequired = (request) => {
1829
2460
  const needsApproval = request.tool?.needsApproval;
1830
2461
  if (needsApproval === undefined)
1831
- return Effect19.succeed(false);
2462
+ return Effect22.succeed(false);
1832
2463
  if (typeof needsApproval === "boolean")
1833
- return Effect19.succeed(needsApproval);
1834
- return Effect19.suspend(() => {
2464
+ return Effect22.succeed(needsApproval);
2465
+ return Effect22.suspend(() => {
1835
2466
  const result = needsApproval(request.call.params, {
1836
2467
  toolCallId: request.call.id,
1837
2468
  messages: request.messages
1838
2469
  });
1839
- return Effect19.isEffect(result) ? result : Effect19.succeed(result);
1840
- }).pipe(Effect19.catchCause((cause) => Cause3.hasInterrupts(cause) ? Effect19.interrupt : Effect19.succeed(true)));
2470
+ return Effect22.isEffect(result) ? result : Effect22.succeed(result);
2471
+ }).pipe(Effect22.catchCause((cause) => Cause5.hasInterrupts(cause) ? Effect22.interrupt : Effect22.succeed(true)));
1841
2472
  };
1842
2473
  var suspend = (request, token) => ({
1843
2474
  _tag: "Suspend",
@@ -1853,10 +2484,10 @@ var suspend = (request, token) => ({
1853
2484
  })
1854
2485
  });
1855
2486
  var make4 = (options) => ({
1856
- authorize: (request) => Effect19.gen(function* () {
2487
+ authorize: (request) => Effect22.gen(function* () {
1857
2488
  if (!request.active || request.tool === undefined)
1858
2489
  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));
2490
+ const decision2 = yield* evaluateWithRules(options.permissions, options.ruleStore, request).pipe(Effect22.mapError(authorizationError));
1860
2491
  if (decision2._tag === "Deny")
1861
2492
  return deny(decision2.reason ?? "Permission denied");
1862
2493
  const required = decision2._tag === "Ask" || (yield* approvalRequired(request));
@@ -1874,7 +2505,7 @@ var make4 = (options) => ({
1874
2505
  switch (resolution._tag) {
1875
2506
  case "Approved":
1876
2507
  if (resolution.remember !== undefined)
1877
- yield* options.ruleStore.remember(resolution.remember).pipe(Effect19.mapError(authorizationError));
2508
+ yield* options.ruleStore.remember(resolution.remember).pipe(Effect22.mapError(authorizationError));
1878
2509
  return { _tag: "Execute" };
1879
2510
  case "Denied":
1880
2511
  return deny(resolution.reason ?? "Tool call denied");
@@ -1884,9 +2515,9 @@ var make4 = (options) => ({
1884
2515
  })
1885
2516
  });
1886
2517
 
1887
- // ../../node_modules/.bun/@batonfx+core@0.9.0/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";
2518
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/tool-registry.js
2519
+ import { Array as Array2, Effect as Effect23, HashMap as HashMap4, Option as Option13 } from "effect";
2520
+ import { dual as dual6 } from "effect/Function";
1890
2521
  import { Tool as Tool7, Toolkit as Toolkit3 } from "effect/unstable/ai";
1891
2522
  var makeToolkit = (entries) => {
1892
2523
  const toolkit = Toolkit3.make(...entries.map((candidate) => candidate.tool));
@@ -1907,21 +2538,21 @@ var assemble = (candidates) => {
1907
2538
  for (const candidate of candidates) {
1908
2539
  const conflicts = grouped[`tool:${candidate.tool.name}`];
1909
2540
  if (conflicts !== undefined && conflicts.length > 1) {
1910
- return Effect20.fail(ToolNameCollision.make({
2541
+ return Effect23.fail(ToolNameCollision.make({
1911
2542
  name: candidate.tool.name,
1912
2543
  origins: Array2.map(conflicts, (conflict) => conflict.origin)
1913
2544
  }));
1914
2545
  }
1915
2546
  }
1916
2547
  const entries = [...candidates];
1917
- return Effect20.succeed({
2548
+ return Effect23.succeed({
1918
2549
  entries,
1919
2550
  byName: HashMap4.fromIterable(entries.map((candidate) => [candidate.tool.name, candidate])),
1920
2551
  toolkit: makeToolkit(entries)
1921
2552
  });
1922
2553
  };
1923
- var get = dual5(2, (registry, name) => Option10.getOrUndefined(HashMap4.get(registry.byName, name)));
1924
- var select = dual5(2, (registry, names) => {
2554
+ var get = dual6(2, (registry, name) => Option13.getOrUndefined(HashMap4.get(registry.byName, name)));
2555
+ var select = dual6(2, (registry, names) => {
1925
2556
  const entries = registry.entries.filter((entry) => names.includes(entry.tool.name));
1926
2557
  return {
1927
2558
  entries,
@@ -1930,42 +2561,42 @@ var select = dual5(2, (registry, names) => {
1930
2561
  };
1931
2562
  });
1932
2563
 
1933
- // ../../node_modules/.bun/@batonfx+core@0.9.0/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";
2564
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-persistence-lock.js
2565
+ import { Context as Context18, Effect as Effect24, Layer as Layer19, RcMap, Scope as Scope3, Semaphore as Semaphore2 } from "effect";
1935
2566
  import { Chat } from "effect/unstable/ai";
1936
2567
 
1937
- class Runtime extends Context17.Service()("@batonfx/core/Runtime") {
2568
+ class Runtime extends Context18.Service()("@batonfx/core/Runtime") {
1938
2569
  }
1939
- var makeRuntime = Effect21.gen(function* () {
2570
+ var makeRuntime = Effect24.gen(function* () {
1940
2571
  const persistenceLocks = yield* RcMap.make({
1941
2572
  lookup: (_persistence) => RcMap.make({
1942
2573
  lookup: (_chatId) => Semaphore2.make(1)
1943
2574
  })
1944
2575
  });
1945
2576
  return Runtime.of({
1946
- persistenceSemaphore: (persistence, chatId) => RcMap.get(persistenceLocks, persistence).pipe(Effect21.flatMap((chatLocks) => RcMap.get(chatLocks, chatId)))
2577
+ persistenceSemaphore: (persistence, chatId) => RcMap.get(persistenceLocks, persistence).pipe(Effect24.flatMap((chatLocks) => RcMap.get(chatLocks, chatId)))
1947
2578
  });
1948
2579
  });
1949
- var layerRuntime = Layer18.effect(Runtime, makeRuntime);
2580
+ var layerRuntime = Layer19.effect(Runtime, makeRuntime);
1950
2581
 
1951
- // ../../node_modules/.bun/@batonfx+core@0.9.0/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";
2582
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-message.js
2583
+ import { Effect as Effect25, Option as Option14, Schema as Schema18 } from "effect";
2584
+ import { Prompt as Prompt9, Response as Response8 } from "effect/unstable/ai";
1954
2585
 
1955
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent-skill-tool.js
1956
- import { Schema as Schema16 } from "effect";
2586
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-skill-tool.js
2587
+ import { Schema as Schema17 } from "effect";
1957
2588
  import { Tool as Tool8 } from "effect/unstable/ai";
1958
2589
  var skillListingBudgetTokens = 2048;
1959
2590
  var activateSkillToolName = "activate_skill";
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)
1965
- });
1966
- var activateSkillFailure = Schema16.Struct({
1967
- reason: Schema16.Literals(["not-found", "not-model-invocable"]),
1968
- message: Schema16.String
2591
+ var activateSkillParameters = Schema17.Struct({ name: Schema17.String });
2592
+ var activateSkillSuccess = Schema17.Struct({
2593
+ name: Schema17.String,
2594
+ body: Schema17.String,
2595
+ allowedTools: Schema17.Array(Schema17.String)
2596
+ });
2597
+ var activateSkillFailure = Schema17.Struct({
2598
+ reason: Schema17.Literals(["not-found", "not-model-invocable"]),
2599
+ message: Schema17.String
1969
2600
  });
1970
2601
  var activateSkillTool = Tool8.make(activateSkillToolName, {
1971
2602
  description: "Load the full body for one listed Baton skill by name before applying that skill.",
@@ -1975,26 +2606,26 @@ var activateSkillTool = Tool8.make(activateSkillToolName, {
1975
2606
  failureMode: "return"
1976
2607
  });
1977
2608
 
1978
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent-message.js
2609
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-message.js
1979
2610
  var withSystem = (instructions, prompt) => Prompt9.fromMessages([Prompt9.makeMessage("system", { content: instructions }), ...prompt.content]);
1980
2611
  var skillListingsInstructions = (listings) => `Available skills:
1981
2612
  ${listings}
1982
2613
 
1983
2614
  Call ${activateSkillToolName} with a listed skill name to load its full body before using it.`;
1984
2615
  var recalledMessages = (prompt) => prompt.content.filter(isMessageFromRecall).map(recalledMessageIdentity);
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);
2616
+ var messageJsonStringCodec = Schema18.fromJsonString(Schema18.toCodecJson(Prompt9.Message));
2617
+ var encodeMessage = Schema18.encodeEffect(messageJsonStringCodec);
2618
+ var decodeMessage = Schema18.decodeEffect(messageJsonStringCodec);
2619
+ var detachMessage = (message) => encodeMessage(message).pipe(Effect25.flatMap(decodeMessage), Effect25.map((detached) => isMessageFromRecall(message) && message.role === "user" && detached.role === "user" ? replaceRecalledMessage(message, detached.content) : detached));
2620
+ var detachPrompt = (prompt) => Effect25.forEach(prompt.content, detachMessage).pipe(Effect25.map(Prompt9.fromMessages));
2621
+ var detachEntry = (entry) => entry._tag === "Message" || entry._tag === "Steering" ? detachMessage(entry.message).pipe(Effect25.map((message) => ({ ...entry, message }))) : Effect25.succeed(entry);
1991
2622
  var preservesRecalledMessages = (allowed, required, transformed) => {
1992
2623
  const allowedSet = new Set(allowed);
1993
2624
  const transformedMessages = recalledMessages(transformed);
1994
2625
  const transformedSet = new Set(transformedMessages);
1995
2626
  return transformedSet.size === transformedMessages.length && transformedMessages.every((message) => allowedSet.has(message)) && required.every((message) => transformedSet.has(message));
1996
2627
  };
1997
- var applyPromptChain = (chain, prompt, context) => Effect22.gen(function* () {
2628
+ var applyPromptChain = (chain, prompt, context) => Effect25.gen(function* () {
1998
2629
  let current = prompt;
1999
2630
  for (const middleware of chain) {
2000
2631
  if (middleware.transformPrompt !== undefined) {
@@ -2011,10 +2642,10 @@ var applyPromptChain = (chain, prompt, context) => Effect22.gen(function* () {
2011
2642
  }
2012
2643
  return current;
2013
2644
  });
2014
- var applyPartChain = (chain, part, context) => Effect22.gen(function* () {
2015
- let current = Option11.some(part);
2645
+ var applyPartChain = (chain, part, context) => Effect25.gen(function* () {
2646
+ let current = Option14.some(part);
2016
2647
  for (const middleware of chain) {
2017
- if (Option11.isNone(current))
2648
+ if (Option14.isNone(current))
2018
2649
  break;
2019
2650
  if (middleware.transformPart !== undefined) {
2020
2651
  current = yield* middleware.transformPart(current.value, context);
@@ -2023,17 +2654,17 @@ var applyPartChain = (chain, part, context) => Effect22.gen(function* () {
2023
2654
  return current;
2024
2655
  });
2025
2656
 
2026
- // ../../node_modules/.bun/@batonfx+core@0.9.0/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";
2657
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-suspension.js
2658
+ import { Equal, Option as Option15, Schema as Schema19 } from "effect";
2659
+ import { Prompt as Prompt10, Response as Response9 } from "effect/unstable/ai";
2029
2660
  var suspensionCheckpointOption = "@batonfx/core/suspension";
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))
2661
+ var suspensionMetadata = Schema19.Struct({
2662
+ token: Schema19.String,
2663
+ reason: Schema19.Literals(["tool-wait", "approval"]),
2664
+ tool_call_index: Schema19.optional(Schema19.Int.check(Schema19.isGreaterThanOrEqualTo(0))),
2665
+ tool_call_batch_ids: Schema19.Array(Schema19.String),
2666
+ active_tools: Schema19.optional(Schema19.Array(Schema19.String)),
2667
+ activated_skills: Schema19.optional(Schema19.Array(Schema19.String))
2037
2668
  });
2038
2669
  var unresolvedToolCall = (messages, toolCallId) => {
2039
2670
  const unpaired = new Map;
@@ -2064,11 +2695,11 @@ var unresolvedToolCall = (messages, toolCallId) => {
2064
2695
  }
2065
2696
  }
2066
2697
  const unresolved = [...unpaired.entries()].flatMap(([id, occurrences]) => ambiguous.has(id) ? [] : occurrences.filter(({ call }) => !call.providerExecuted));
2067
- const pending = toolCallId === undefined ? unresolved.find(({ call }) => Option12.isSome(Schema18.decodeUnknownOption(suspensionMetadata)(call.options[suspensionCheckpointOption]))) : unresolved.find(({ call }) => call.id === toolCallId);
2698
+ const pending = toolCallId === undefined ? unresolved.find(({ call }) => Option15.isSome(Schema19.decodeUnknownOption(suspensionMetadata)(call.options[suspensionCheckpointOption]))) : unresolved.find(({ call }) => call.id === toolCallId);
2068
2699
  const pendingMessage = pending === undefined ? undefined : messages[pending.messageIndex];
2069
2700
  const unresolvedParts = new Set(unresolved.filter(({ messageIndex }) => messageIndex === pending?.messageIndex).map(({ partIndex }) => partIndex));
2070
2701
  const toolCallBatch = pendingMessage?.role === "assistant" ? pendingMessage.content.flatMap((part) => part.type === "tool-call" && !part.providerExecuted ? [
2071
- Response7.makePart("tool-call", {
2702
+ Response9.makePart("tool-call", {
2072
2703
  id: part.id,
2073
2704
  name: part.name,
2074
2705
  params: part.params,
@@ -2100,8 +2731,8 @@ var suspensionCheckpoint = (messages) => {
2100
2731
  const unresolved = unresolvedToolCall(messages);
2101
2732
  if (unresolved === undefined)
2102
2733
  return;
2103
- const metadata = Schema18.decodeUnknownOption(suspensionMetadata)(unresolved.call.options[suspensionCheckpointOption]);
2104
- if (Option12.isNone(metadata))
2734
+ const metadata = Schema19.decodeUnknownOption(suspensionMetadata)(unresolved.call.options[suspensionCheckpointOption]);
2735
+ if (Option15.isNone(metadata))
2105
2736
  return;
2106
2737
  if (!Equal.equals(metadata.value.tool_call_batch_ids, unresolved.toolCallBatch.map((call) => call.id)))
2107
2738
  return;
@@ -2129,10 +2760,10 @@ var suspended = (call, toolCallBatch, toolCallIndex, token, reason) => AgentSusp
2129
2760
  tool_call_batch: toolCallBatch.calls
2130
2761
  });
2131
2762
 
2132
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent-tool-result.js
2763
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-tool-result.js
2133
2764
  import { HashMap as HashMap5 } from "effect";
2134
- import { Response as Response8 } from "effect/unstable/ai";
2135
- var successResult = (call, outcome) => Response8.toolResultPart({
2765
+ import { Response as Response10 } from "effect/unstable/ai";
2766
+ var successResult = (call, outcome) => Response10.toolResultPart({
2136
2767
  id: call.id,
2137
2768
  name: call.name,
2138
2769
  isFailure: false,
@@ -2141,7 +2772,7 @@ var successResult = (call, outcome) => Response8.toolResultPart({
2141
2772
  providerExecuted: false,
2142
2773
  preliminary: false
2143
2774
  });
2144
- var domainFailureResult = (call, outcome) => Response8.toolResultPart({
2775
+ var domainFailureResult = (call, outcome) => Response10.toolResultPart({
2145
2776
  id: call.id,
2146
2777
  name: call.name,
2147
2778
  isFailure: true,
@@ -2151,18 +2782,18 @@ var domainFailureResult = (call, outcome) => Response8.toolResultPart({
2151
2782
  preliminary: false
2152
2783
  });
2153
2784
 
2154
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent-run.js
2155
- var classifyOtherFailure = () => "other";
2785
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-run.js
2786
+ var classifyOtherFailure = (error) => classify(error);
2156
2787
  var defaultProgressOverflowPolicy = { _tag: "Backpressure", capacity: 64 };
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 })
2788
+ var progressCapacitySchema = Schema20.Finite.pipe(Schema20.check(Schema20.isInt(), Schema20.isGreaterThan(0)));
2789
+ var progressOverflowPolicySchema = Schema20.Union([
2790
+ Schema20.TaggedStruct("Backpressure", { capacity: progressCapacitySchema }),
2791
+ Schema20.TaggedStruct("Dropping", { capacity: progressCapacitySchema }),
2792
+ Schema20.TaggedStruct("Sliding", { capacity: progressCapacitySchema }),
2793
+ Schema20.TaggedStruct("Fail", { capacity: progressCapacitySchema })
2163
2794
  ]);
2164
2795
  var errorMessage = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
2165
- var isToolNameCollision = Schema19.is(ToolNameCollision);
2796
+ var isToolNameCollision = Schema20.is(ToolNameCollision);
2166
2797
  var appendInstructionFragment = (base, fragment) => {
2167
2798
  if (fragment === undefined || fragment.length === 0)
2168
2799
  return base;
@@ -2177,7 +2808,7 @@ var isTurnPolicyDecision = (input) => {
2177
2808
  return false;
2178
2809
  if (input._tag === "Continue")
2179
2810
  return true;
2180
- return input._tag === "Stop" && "reason" in input && Schema19.is(StopReason)(input.reason);
2811
+ return input._tag === "Stop" && "reason" in input && Schema20.is(StopReason)(input.reason);
2181
2812
  };
2182
2813
  var steeringDrainedEvent = (turn, queue, inputs) => ({
2183
2814
  _tag: "SteeringDrained",
@@ -2185,7 +2816,7 @@ var steeringDrainedEvent = (turn, queue, inputs) => ({
2185
2816
  queue,
2186
2817
  count: inputs.length
2187
2818
  });
2188
- var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen(function* () {
2819
+ var streamInternal = (agent, options, structured) => Stream5.unwrap(Effect26.gen(function* () {
2189
2820
  if (options.history !== undefined && options.persistence !== undefined) {
2190
2821
  return yield* AgentError.make({
2191
2822
  message: "RunOptions.history and RunOptions.persistence are mutually exclusive",
@@ -2194,47 +2825,47 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2194
2825
  }
2195
2826
  const persistenceOptions = options.persistence;
2196
2827
  const resume = options.resume;
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({
2828
+ const persistenceService = yield* Effect26.serviceOption(Chat2.Persistence);
2829
+ const runtimeService = yield* Effect26.serviceOption(Runtime);
2830
+ const compactionService = yield* Effect26.serviceOption(Compaction);
2831
+ const sessionService = yield* Effect26.serviceOption(SessionStore);
2832
+ const persisted = persistenceOptions === undefined ? undefined : yield* Option16.match(persistenceService, {
2833
+ onNone: () => Effect26.fail(AgentError.make({
2203
2834
  message: "RunOptions.persistence requires Chat.Persistence in context",
2204
2835
  turn: 0
2205
2836
  })),
2206
- onSome: (service) => Effect23.gen(function* () {
2207
- const runtime = yield* Option13.match(runtimeService, {
2208
- onNone: () => Effect23.fail(AgentError.make({
2837
+ onSome: (service) => Effect26.gen(function* () {
2838
+ const runtime = yield* Option16.match(runtimeService, {
2839
+ onNone: () => Effect26.fail(AgentError.make({
2209
2840
  message: "RunOptions.persistence requires Agent.Runtime in context",
2210
2841
  turn: 0
2211
2842
  })),
2212
- onSome: Effect23.succeed
2843
+ onSome: Effect26.succeed
2213
2844
  });
2214
2845
  const semaphore = yield* runtime.persistenceSemaphore(service, persistenceOptions.chatId);
2215
- yield* Effect23.acquireRelease(semaphore.take(1), () => semaphore.release(1), {
2846
+ yield* Effect26.acquireRelease(semaphore.take(1), () => semaphore.release(1), {
2216
2847
  interruptible: true
2217
2848
  });
2218
2849
  const getOptions = persistenceOptions.timeToLive === undefined ? undefined : { timeToLive: persistenceOptions.timeToLive };
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({
2850
+ return yield* resume === undefined ? service.getOrCreate(persistenceOptions.chatId, getOptions).pipe(Effect26.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error }))) : service.get(persistenceOptions.chatId, getOptions).pipe(Effect26.mapError((error) => error._tag === "ChatNotFoundError" ? ResumeMismatch.make({
2220
2851
  reason: "checkpoint-not-found",
2221
2852
  received: resume.suspension
2222
2853
  }) : AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2223
2854
  })
2224
2855
  });
2225
2856
  let recoveredHistory;
2226
- if (resume !== undefined && persisted !== undefined && Option13.isSome(compactionService) && Option13.isSome(sessionService)) {
2227
- yield* Effect23.gen(function* () {
2857
+ if (resume !== undefined && persisted !== undefined && Option16.isSome(compactionService) && Option16.isSome(sessionService)) {
2858
+ yield* Effect26.gen(function* () {
2228
2859
  const path = yield* sessionService.value.path();
2229
2860
  const checkpoint = path.at(-1);
2230
2861
  if (checkpoint?._tag !== "Compaction" || checkpoint.version !== 2)
2231
2862
  return;
2232
2863
  const history = yield* Ref5.get(persisted.history);
2233
2864
  const before = buildContext(path.slice(0, -1));
2234
- if (!Schema19.toEquivalence(Prompt11.Prompt)(before, history))
2865
+ if (!Schema20.toEquivalence(Prompt11.Prompt)(before, history))
2235
2866
  return;
2236
2867
  recoveredHistory = buildContext(path);
2237
- }).pipe(Effect23.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2868
+ }).pipe(Effect26.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2238
2869
  }
2239
2870
  let resumeChat;
2240
2871
  let validatedResume;
@@ -2242,12 +2873,12 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2242
2873
  resumeChat = persisted ?? (yield* options.history === undefined ? Chat2.empty : Chat2.fromPrompt(options.history));
2243
2874
  const received = resume.suspension;
2244
2875
  const resumeHistory = recoveredHistory ?? (yield* Ref5.get(resumeChat.history));
2245
- validatedResume = yield* Effect23.succeed(resumeHistory).pipe(Effect23.flatMap((history) => {
2876
+ validatedResume = yield* Effect26.succeed(resumeHistory).pipe(Effect26.flatMap((history) => {
2246
2877
  const expected = suspensionCheckpoint(history.content);
2247
2878
  if (expected === undefined) {
2248
2879
  return ResumeMismatch.make({ reason: "checkpoint-not-found", received });
2249
2880
  }
2250
- return sameSuspension(expected.suspension, received) ? Effect23.succeed(expected) : ResumeMismatch.make({
2881
+ return sameSuspension(expected.suspension, received) ? Effect26.succeed(expected) : ResumeMismatch.make({
2251
2882
  reason: "identity-mismatch",
2252
2883
  expected: expected.suspension,
2253
2884
  received
@@ -2255,7 +2886,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2255
2886
  }));
2256
2887
  if (recoveredHistory !== undefined && persisted !== undefined) {
2257
2888
  yield* Ref5.set(persisted.history, recoveredHistory);
2258
- yield* persisted.save.pipe(Effect23.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2889
+ yield* persisted.save.pipe(Effect26.mapError((error) => AgentError.make({ message: errorMessage(error), turn: 0, cause: error })));
2259
2890
  }
2260
2891
  }
2261
2892
  const staticCandidates = (agent.toolDeclarations ?? Object.values(agent.toolkit.tools).map((tool) => ({
@@ -2274,17 +2905,17 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2274
2905
  turn: 0
2275
2906
  });
2276
2907
  }
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 })));
2908
+ const executor = yield* Effect26.serviceOption(ToolExecutor);
2909
+ const approvals = yield* Effect26.serviceOption(Approvals);
2910
+ const chain = yield* Effect26.serviceOption(ModelMiddleware).pipe(Effect26.map(Option16.match({ onNone: () => [], onSome: (service) => service })));
2280
2911
  if (options.toolOutputMaxBytes !== undefined && (!Number.isFinite(options.toolOutputMaxBytes) || options.toolOutputMaxBytes < 0)) {
2281
2912
  return yield* AgentError.make({
2282
2913
  message: "RunOptions.toolOutputMaxBytes must be a non-negative finite number",
2283
2914
  turn: 0
2284
2915
  });
2285
2916
  }
2286
- const decodedProgressPolicy = Schema19.decodeUnknownOption(progressOverflowPolicySchema)(options.toolProgress === undefined ? defaultProgressOverflowPolicy : options.toolProgress);
2287
- if (Option13.isNone(decodedProgressPolicy)) {
2917
+ const decodedProgressPolicy = Schema20.decodeUnknownOption(progressOverflowPolicySchema)(options.toolProgress === undefined ? defaultProgressOverflowPolicy : options.toolProgress);
2918
+ if (Option16.isNone(decodedProgressPolicy)) {
2288
2919
  return yield* AgentError.make({
2289
2920
  message: "RunOptions.toolProgress must select a supported policy with a positive safe-integer capacity",
2290
2921
  turn: 0
@@ -2306,11 +2937,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2306
2937
  const sessionId = options.sessionId ?? "local";
2307
2938
  const sessionOwnerToken = options.sessionOwnerToken;
2308
2939
  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 : {
2940
+ const instructionsService = yield* Effect26.serviceOption(Instructions);
2941
+ const skillSourceService = yield* Effect26.serviceOption(SkillSource);
2942
+ const skillRuntime = Option16.isNone(skillSourceService) ? undefined : {
2312
2943
  source: skillSourceService.value,
2313
- skills: yield* skillSourceService.value.all.pipe(Effect23.mapError((error) => AgentError.make({ message: error.message, turn: 0, cause: error })))
2944
+ skills: yield* skillSourceService.value.all.pipe(Effect26.mapError((error) => AgentError.make({ message: error.message, turn: 0, cause: error })))
2314
2945
  };
2315
2946
  const selectedSkills = skillRuntime === undefined ? [] : selectListings(skillRuntime.skills, skillListingBudgetTokens, []);
2316
2947
  const skillListings = selectedSkills.map((skill) => skill.listing).join(`
@@ -2326,22 +2957,50 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2326
2957
  }
2327
2958
  ] : []
2328
2959
  ]);
2329
- const instructionsEpoch = options.system === undefined && options.history === undefined && Option13.isSome(instructionsService) ? yield* openEpoch(instructionsService.value, { agentName: agent.name, turn: 0 }) : undefined;
2960
+ const instructionsEpoch = options.system === undefined && options.history === undefined && Option16.isSome(instructionsService) ? yield* openEpoch(instructionsService.value, { agentName: agent.name, turn: 0 }) : undefined;
2330
2961
  const baseSystem = options.system ?? (instructionsEpoch === undefined ? agent.instructions : instructionsEpoch.length === 0 ? agent.instructions : instructionsEpoch);
2331
2962
  const system = appendInstructionFragment(baseSystem, options.history === undefined && skillListings.length > 0 ? skillListingsInstructions(skillListings) : undefined);
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);
2963
+ const resilienceService = yield* Effect26.serviceOption(ModelResilience);
2964
+ const deliveryService = yield* Effect26.serviceOption(Delivery);
2965
+ const telemetryRunId = yield* generateId;
2966
+ let telemetrySequence = 0;
2967
+ const pendingTelemetry = [];
2968
+ const undeliveredTelemetry = [];
2969
+ const emitTelemetry = (payload) => Effect26.sync(() => {
2970
+ const event = { ...payload, deliveryId: `${telemetryRunId}:${telemetrySequence++}` };
2971
+ pendingTelemetry.push(event);
2972
+ undeliveredTelemetry.push(event);
2973
+ });
2974
+ const flushTelemetry = () => pendingTelemetry.splice(0, pendingTelemetry.length);
2975
+ const deliverPending = () => {
2976
+ if (Option16.isNone(deliveryService) || undeliveredTelemetry.length === 0)
2977
+ return Effect26.void;
2978
+ const snapshot = Object.freeze([...undeliveredTelemetry]);
2979
+ return deliveryService.value.deliver({ sessionId, events: snapshot }).pipe(Effect26.onError(() => Effect26.sync(() => {
2980
+ pendingTelemetry.splice(0, pendingTelemetry.length);
2981
+ })), Effect26.tap(() => Effect26.sync(() => {
2982
+ undeliveredTelemetry.splice(0, snapshot.length);
2983
+ })));
2984
+ };
2985
+ const telemetryIdentity = makeIdentityCell();
2986
+ const instrumentModel = (model, turn) => instrument(model, {
2987
+ emit: emitTelemetry,
2988
+ turn,
2989
+ identity: telemetryIdentity,
2990
+ ...Option16.isSome(resilienceService) ? { resilience: resilienceService.value } : {}
2991
+ });
2992
+ const modelRegistryService = yield* Effect26.serviceOption(ModelRegistry);
2993
+ const permissionsService = yield* Effect26.serviceOption(Permissions);
2994
+ const ruleStoreService = yield* Effect26.serviceOption(RuleStore);
2995
+ const authorizationService = yield* Effect26.serviceOption(ToolAuthorizerService);
2996
+ const steeringService = yield* Effect26.serviceOption(Steering);
2997
+ const memoryService = yield* Effect26.serviceOption(Memory);
2998
+ const tokenizerService = yield* Effect26.serviceOption(Tokenizer2.Tokenizer);
2340
2999
  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({
3000
+ const authorizer = agent.authorization ?? Option16.getOrElse(authorizationService, () => make4({
3001
+ permissions: Option16.getOrElse(permissionsService, () => Permissions.of({ evaluate: () => Effect26.succeed({ _tag: "Allow" }) })),
3002
+ approvals: Option16.getOrElse(approvals, () => Approvals.of({ resolve: () => Effect26.succeed({ _tag: "Approved" }) })),
3003
+ ruleStore: Option16.getOrElse(ruleStoreService, () => RuleStore.of({
2345
3004
  rules: Ref5.get(defaultRules),
2346
3005
  remember: (rule) => Ref5.update(defaultRules, (rules) => [
2347
3006
  ...rules.filter((current) => current.pattern !== rule.pattern),
@@ -2351,29 +3010,29 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2351
3010
  }));
2352
3011
  const memoryOptions = options.memory ?? (agent.memory === undefined ? undefined : { key: agent.memory });
2353
3012
  const agentModel = agent.model;
2354
- const agentModelRegistry = agentModel === undefined ? undefined : yield* Option13.match(modelRegistryService, {
2355
- onNone: () => Effect23.fail(AgentError.make({
3013
+ const agentModelRegistry = agentModel === undefined ? undefined : yield* Option16.match(modelRegistryService, {
3014
+ onNone: () => Effect26.fail(AgentError.make({
2356
3015
  message: "Agent.model requires ModelRegistry in context",
2357
3016
  turn: 0
2358
3017
  })),
2359
- onSome: Effect23.succeed
3018
+ onSome: Effect26.succeed
2360
3019
  });
2361
3020
  const memoryRuntime = memoryOptions === undefined ? undefined : {
2362
3021
  key: memoryOptions.key,
2363
- service: yield* Option13.match(memoryService, {
2364
- onNone: () => Effect23.fail(AgentError.make({
3022
+ service: yield* Option16.match(memoryService, {
3023
+ onNone: () => Effect26.fail(AgentError.make({
2365
3024
  message: options.memory === undefined ? "Agent.memory requires Memory in context" : "RunOptions.memory requires Memory in context",
2366
3025
  turn: 0
2367
3026
  })),
2368
- onSome: Effect23.succeed
3027
+ onSome: Effect26.succeed
2369
3028
  })
2370
3029
  };
2371
3030
  const seedSystem = persisted !== undefined && system !== undefined && (yield* Ref5.get(persisted.history)).content.length === 0 ? system : undefined;
2372
3031
  const freshChat = options.history !== undefined ? Chat2.fromPrompt(options.history) : system !== undefined ? Chat2.fromPrompt([Prompt11.makeMessage("system", { content: system })]) : Chat2.empty;
2373
3032
  const chat = resumeChat ?? persisted ?? (yield* freshChat);
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* () {
3033
+ const savePersisted = (turn) => persisted === undefined ? Effect26.void : persisted.save.pipe(Effect26.mapError((error) => AgentError.make({ message: errorMessage(error), turn, cause: error })));
3034
+ const appendPending = (turn, pending) => pending.length === 0 ? Ref5.get(chat.history) : Ref5.updateAndGet(chat.history, (history) => Prompt11.concat(history, Prompt11.fromResponseParts(pending))).pipe(Effect26.tap(() => savePersisted(turn)));
3035
+ const checkpointSuspended = (turn, pending, suspension) => Effect26.gen(function* () {
2377
3036
  const withPending = yield* appendPending(turn, pending);
2378
3037
  const unresolved = unresolvedToolCall(withPending.content, suspension.tool_call_id);
2379
3038
  if (unresolved === undefined || unresolved.call.id !== suspension.tool_call_id || unresolved.call.name !== suspension.tool_name || !Equal2.equals(unresolved.call.params, suspension.tool_params)) {
@@ -2417,11 +3076,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2417
3076
  const path = yield* syncSession(turn, withPending);
2418
3077
  const parentId = path.at(-1)?.id ?? null;
2419
3078
  yield* applyCompactionResult(turn, { _tag: "Microcompact", history: checkpoint, prompt: Prompt11.empty }, parentId);
2420
- if (Option13.isNone(activeSession))
3079
+ if (Option16.isNone(activeSession))
2421
3080
  yield* savePersisted(turn);
2422
3081
  return yield* Ref5.get(chat.history);
2423
3082
  });
2424
- const checkpointPending = (turn, pending) => appendPending(turn, pending).pipe(Effect23.tap((checkpoint) => syncSession(turn, checkpoint)));
3083
+ const checkpointPending = (turn, pending) => appendPending(turn, pending).pipe(Effect26.tap((checkpoint) => syncSession(turn, checkpoint)));
2425
3084
  const state = {
2426
3085
  text: "",
2427
3086
  turn: 0,
@@ -2434,15 +3093,15 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2434
3093
  registry: initialRegistry,
2435
3094
  activatedSkillBodies: new Map
2436
3095
  });
2437
- const restoreActivatedSkills = (history) => Effect23.gen(function* () {
3096
+ const restoreActivatedSkills = (history) => Effect26.gen(function* () {
2438
3097
  for (const message of history.content) {
2439
3098
  if (!Array.isArray(message.content))
2440
3099
  continue;
2441
3100
  for (const part of message.content) {
2442
3101
  if (String(part.type) !== "tool-result" || String(part.name) !== activateSkillToolName || part.isFailure === true)
2443
3102
  continue;
2444
- const activation = Schema19.decodeUnknownOption(activateSkillSuccess)(part.result);
2445
- if (Option13.isNone(activation))
3103
+ const activation = Schema20.decodeUnknownOption(activateSkillSuccess)(part.result);
3104
+ if (Option16.isNone(activation))
2446
3105
  continue;
2447
3106
  if (skillRuntime === undefined) {
2448
3107
  return yield* AgentError.make({
@@ -2473,10 +3132,10 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2473
3132
  yield* Ref5.set(toolState, { registry, activatedSkillBodies });
2474
3133
  }
2475
3134
  }
2476
- }).pipe(Effect23.mapError((error) => isToolNameCollision(error) ? error : AgentError.make({ message: error.message, turn: 0, cause: error })));
3135
+ }).pipe(Effect26.mapError((error) => isToolNameCollision(error) ? error : AgentError.make({ message: error.message, turn: 0, cause: error })));
2477
3136
  if (validatedResume !== undefined)
2478
- yield* Ref5.get(chat.history).pipe(Effect23.flatMap(restoreActivatedSkills));
2479
- const activeSession = Option13.isSome(compactionService) ? sessionService : Option13.none();
3137
+ yield* Ref5.get(chat.history).pipe(Effect26.flatMap(restoreActivatedSkills));
3138
+ const activeSession = Option16.isSome(compactionService) ? sessionService : Option16.none();
2480
3139
  const sessionError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2481
3140
  const compactionError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2482
3141
  const memoryError = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
@@ -2490,33 +3149,34 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2490
3149
  const [first, ...rest] = prompt.content;
2491
3150
  return first?.role === "system" ? Prompt11.fromMessages([first, memoryMessage2, ...rest]) : Prompt11.fromMessages([memoryMessage2, ...prompt.content]);
2492
3151
  };
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({
3152
+ const recallInitialPrompt = (prompt) => memoryRuntime === undefined ? Effect26.succeed(prompt) : memoryRuntime.service.recall({ key: memoryRuntime.key, turn: 0, prompt }).pipe(Effect26.mapError((error) => memoryError(0, error)), Effect26.map((items) => insertRecalledItems(prompt, items)));
3153
+ const rememberTurn = (turn, transcript, terminal, path) => memoryRuntime === undefined ? Effect26.void : memoryRuntime.service.remember({
2495
3154
  key: memoryRuntime.key,
2496
3155
  turn,
2497
- transcript: Option13.isSome(activeSession) ? buildMemoryContext(path) : projectTranscript(transcript),
3156
+ transcript: Option16.isSome(activeSession) ? buildMemoryContext(path) : projectTranscript(transcript),
2498
3157
  terminal
2499
- }).pipe(Effect23.mapError((error) => memoryError(turn, error)));
2500
- const messageEquivalence = Schema19.toEquivalence(Prompt11.Message);
2501
- const promptEquivalence2 = Schema19.toEquivalence(Prompt11.Prompt);
3158
+ }).pipe(Effect26.mapError((error) => memoryError(turn, error)));
3159
+ const messageEquivalence = Schema20.toEquivalence(Prompt11.Message);
3160
+ const promptEquivalence2 = Schema20.toEquivalence(Prompt11.Prompt);
3161
+ const canonicalEquivalence = (left, right) => messageEquivalence(coalesceAdjacentText(left), coalesceAdjacentText(right));
2502
3162
  const sessionTranscriptCursor = (projection, transcript) => {
2503
3163
  if (projection.length === 0)
2504
- return Option13.some(0);
3164
+ return Option16.some(0);
2505
3165
  const matches2 = [];
2506
3166
  for (let start = 0;start <= transcript.length - projection.length; start += 1) {
2507
- if (transcript.slice(0, start).every((message) => message.role === "system") && projection.every((message, index) => messageEquivalence(message, transcript[start + index]))) {
3167
+ if (transcript.slice(0, start).every((message) => message.role === "system") && projection.every((message, index) => canonicalEquivalence(message, transcript[start + index]))) {
2508
3168
  matches2.push(start + projection.length);
2509
3169
  }
2510
3170
  }
2511
- return matches2.length === 1 ? Option13.some(matches2[0]) : Option13.none();
3171
+ return matches2.length === 1 ? Option16.some(matches2[0]) : Option16.none();
2512
3172
  };
2513
- const syncSession = (turn, transcript) => Option13.match(activeSession, {
2514
- onNone: () => Effect23.succeed([]),
2515
- onSome: (session) => Effect23.gen(function* () {
3173
+ const syncSession = (turn, transcript) => Option16.match(activeSession, {
3174
+ onNone: () => Effect26.succeed([]),
3175
+ onSome: (session) => Effect26.gen(function* () {
2516
3176
  let path = yield* session.path();
2517
3177
  const projection = buildContext(path);
2518
3178
  const cursor = sessionTranscriptCursor(projection.content, transcript.content);
2519
- if (Option13.isNone(cursor)) {
3179
+ if (Option16.isNone(cursor)) {
2520
3180
  const checkpoint = path.at(-1);
2521
3181
  const before = buildContext(path.slice(0, -1));
2522
3182
  if (checkpoint?._tag === "Compaction" && checkpoint.version === 2 && promptEquivalence2(before, transcript)) {
@@ -2544,13 +3204,13 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2544
3204
  if (expectedLeafId !== (path.at(-1)?.id ?? null))
2545
3205
  path = yield* session.path();
2546
3206
  return path;
2547
- }).pipe(Effect23.mapError((error) => Schema19.is(AgentError)(error) ? error : sessionError(turn, error)))
3207
+ }).pipe(Effect26.mapError((error) => Schema20.is(AgentError)(error) ? error : sessionError(turn, error)))
2548
3208
  });
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 })))
3209
+ const countTokens = (turn, prompt) => Option16.match(tokenizerService, {
3210
+ onNone: () => Effect26.succeed(Math.ceil(JSON.stringify(prompt.content).length / 4)),
3211
+ onSome: (tokenizer) => tokenizer.tokenize(prompt).pipe(Effect26.map((tokens) => tokens.length), Effect26.mapError((error) => AgentError.make({ message: errorMessage(error), turn, cause: error })))
2552
3212
  });
2553
- const compactionUsage = (turn, history, prompt) => countTokens(turn, Prompt11.concat(history, prompt)).pipe(Effect23.map((contextTokens) => ({
3213
+ const compactionUsage = (turn, history, prompt) => countTokens(turn, Prompt11.concat(history, prompt)).pipe(Effect26.map((contextTokens) => ({
2554
3214
  contextTokens,
2555
3215
  contextWindow: options.compaction?.contextWindow ?? Number.POSITIVE_INFINITY,
2556
3216
  reserveTokens: DEFAULT_RESERVE_TOKENS
@@ -2561,14 +3221,14 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2561
3221
  for (const message of Prompt11.concat(result.history, result.prompt).content) {
2562
3222
  if (typeof message.content === "string") {
2563
3223
  if (pending.size > 0) {
2564
- return Effect23.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
3224
+ return Effect26.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2565
3225
  }
2566
3226
  optional.clear();
2567
3227
  continue;
2568
3228
  }
2569
3229
  const hasResult = message.content.some((part) => part.type === "tool-result");
2570
3230
  if (pending.size > 0 && !hasResult) {
2571
- return Effect23.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
3231
+ return Effect26.fail(AgentError.make({ message: "Compaction projection separates a tool call from its result", turn }));
2572
3232
  }
2573
3233
  if (!hasResult)
2574
3234
  optional.clear();
@@ -2576,7 +3236,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2576
3236
  for (const part of message.content) {
2577
3237
  if (part.type === "tool-call") {
2578
3238
  if (responseCalls.has(part.id)) {
2579
- return Effect23.fail(AgentError.make({ message: `Compaction projection contains duplicate tool call ${part.id}`, turn }));
3239
+ return Effect26.fail(AgentError.make({ message: `Compaction projection contains duplicate tool call ${part.id}`, turn }));
2580
3240
  }
2581
3241
  responseCalls.add(part.id);
2582
3242
  if (part.providerExecuted)
@@ -2586,40 +3246,69 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2586
3246
  }
2587
3247
  if (part.type === "tool-result") {
2588
3248
  if (!pending.delete(part.id) && !optional.delete(part.id)) {
2589
- return Effect23.fail(AgentError.make({ message: `Compaction projection contains orphan tool result ${part.id}`, turn }));
3249
+ return Effect26.fail(AgentError.make({ message: `Compaction projection contains orphan tool result ${part.id}`, turn }));
2590
3250
  }
2591
3251
  }
2592
3252
  }
2593
3253
  }
2594
- return pending.size === 0 ? Effect23.void : Effect23.fail(AgentError.make({ message: "Compaction projection contains an unresolved tool call", turn }));
3254
+ return pending.size === 0 ? Effect26.void : Effect26.fail(AgentError.make({ message: "Compaction projection contains an unresolved tool call", turn }));
2595
3255
  };
2596
- const applyCompactionResult = (turn, result, parentId) => Option13.match(activeSession, {
2597
- onNone: () => Ref5.set(chat.history, result.history),
2598
- onSome: (session) => Effect23.gen(function* () {
3256
+ const applyCompactionResult = (turn, result, parentId, commitData) => Option16.match(activeSession, {
3257
+ onNone: () => deliverPending().pipe(Effect26.andThen(Ref5.set(chat.history, result.history))),
3258
+ onSome: (session) => Effect26.gen(function* () {
2599
3259
  const id = yield* session.reserveEntryId;
2600
- yield* Effect23.uninterruptibleMask((restore) => restore(session.appendCheckpoint({
3260
+ const telemetry = Object.freeze([...undeliveredTelemetry]);
3261
+ const completed = commitData === undefined ? undefined : telemetry.findLast((event) => event._tag === "CompactionCompleted" && event.compactionId === commitData.compactionId);
3262
+ if (commitData !== undefined && completed === undefined) {
3263
+ return yield* AgentError.make({
3264
+ message: `Changed custom compaction ${commitData.compactionId} did not emit CompactionCompleted`,
3265
+ turn
3266
+ });
3267
+ }
3268
+ const compactionCommit = commitData === undefined ? undefined : {
3269
+ ...commitData,
3270
+ checkpointId: id,
3271
+ ...completed?.summaryModelCallId === undefined ? {} : { summaryModelCallId: completed.summaryModelCallId }
3272
+ };
3273
+ yield* Effect26.uninterruptibleMask((restore) => restore(session.appendCheckpoint({
2601
3274
  id,
2602
3275
  parentId,
2603
3276
  projectedHistory: result.history,
3277
+ telemetry,
3278
+ ...compactionCommit === undefined ? {} : { compactionCommit },
2604
3279
  ...result._tag === "Summarize" ? { summary: result.summary } : {},
2605
3280
  ...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)))
3281
+ }).pipe(Effect26.filterOrFail((appended) => checkpointMatches(appended.checkpoint, {
3282
+ id,
3283
+ parentId,
3284
+ projectedHistory: result.history,
3285
+ telemetry,
3286
+ ...compactionCommit === undefined ? {} : { compactionCommit },
3287
+ ...result._tag === "Summarize" ? { summary: result.summary } : {}
3288
+ }), () => SessionConflict.make({
3289
+ reason: "checkpoint-id-reused",
3290
+ message: `Session returned a non-matching checkpoint ${id}`
3291
+ })))).pipe(Effect26.tap(() => Effect26.sync(() => {
3292
+ undeliveredTelemetry.splice(0, telemetry.length);
3293
+ })), Effect26.flatMap((appended) => restore(session.path(appended.leafId))), Effect26.map(buildContext), Effect26.tap((projection) => Ref5.set(chat.history, projection)), Effect26.andThen(restore(savePersisted(turn)))));
3294
+ }).pipe(Effect26.mapError((error) => Schema20.is(AgentError)(error) ? error : sessionError(turn, error)))
2608
3295
  });
2609
- const preparePrompt = (turn, prompt, overflow) => Option13.match(compactionService, {
2610
- onNone: () => Effect23.succeed({ prompt, changed: false }),
2611
- onSome: (compaction) => Effect23.gen(function* () {
3296
+ const preparePrompt = (turn, prompt, overflow) => Option16.match(compactionService, {
3297
+ onNone: () => Effect26.succeed({ prompt, changed: false }),
3298
+ onSome: (compaction) => Effect26.gen(function* () {
2612
3299
  const history = yield* Ref5.get(chat.history);
2613
3300
  const path = yield* syncSession(turn, history);
2614
3301
  const usage = yield* compactionUsage(turn, history, prompt);
2615
3302
  const historyRecalled = recalledMessages(history);
2616
3303
  const promptRecalled = recalledMessages(prompt);
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 })));
2622
- const compacted = yield* compaction.maybeCompact({
3304
+ const detachedHistory = yield* detachPrompt(history).pipe(Effect26.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
3305
+ const detachedPrompt = yield* detachPrompt(prompt).pipe(Effect26.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
3306
+ const originalHistory = yield* detachPrompt(detachedHistory).pipe(Effect26.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
3307
+ const originalPrompt = yield* detachPrompt(detachedPrompt).pipe(Effect26.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
3308
+ const detachedPath = yield* Effect26.forEach(path, detachEntry).pipe(Effect26.mapError((error) => AgentError.make({ message: error.message, turn, cause: error })));
3309
+ const compactionId = yield* generateId;
3310
+ const compacted = yield* Effect26.scoped(compaction.maybeCompact({
3311
+ compactionId,
2623
3312
  agentName: agent.name,
2624
3313
  sessionId,
2625
3314
  turn,
@@ -2629,14 +3318,14 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2629
3318
  usage,
2630
3319
  overflow,
2631
3320
  ...options.toolOutputMaxBytes === undefined ? {} : { toolOutputMaxBytes: options.toolOutputMaxBytes }
2632
- }).pipe(Effect23.mapError((error) => compactionError(turn, error)));
2633
- if (Option13.isNone(compacted))
3321
+ })).pipe(Effect26.mapError((error) => compactionError(turn, error)));
3322
+ if (Option16.isNone(compacted))
2634
3323
  return { prompt, changed: false };
2635
3324
  const changed = !Equal2.equals(originalHistory.content, compacted.value.history.content) || !Equal2.equals(originalPrompt.content, compacted.value.prompt.content);
2636
3325
  if (!changed)
2637
3326
  return { prompt, changed: false };
2638
3327
  const allowed = [...historyRecalled, ...promptRecalled];
2639
- const required = Option13.isSome(activeSession) ? promptRecalled : allowed;
3328
+ const required = Option16.isSome(activeSession) ? promptRecalled : allowed;
2640
3329
  if (!preservesRecalledMessages(allowed, required, Prompt11.concat(compacted.value.history, compacted.value.prompt))) {
2641
3330
  return yield* MiddlewareViolation.make({
2642
3331
  turn,
@@ -2644,24 +3333,32 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2644
3333
  });
2645
3334
  }
2646
3335
  yield* validateCompactionProjection(turn, compacted.value);
2647
- yield* applyCompactionResult(turn, compacted.value, path.at(-1)?.id ?? null);
3336
+ const after = Prompt11.concat(compacted.value.history, compacted.value.prompt);
3337
+ const contextTokensAfter = yield* Effect26.option(countTokens(turn, after));
3338
+ yield* applyCompactionResult(turn, compacted.value, path.at(-1)?.id ?? null, {
3339
+ compactionId,
3340
+ contextTokensBefore: usage.contextTokens,
3341
+ ...Option16.isSome(contextTokensAfter) ? { contextTokensAfter: contextTokensAfter.value } : {},
3342
+ entriesBefore: Prompt11.concat(history, prompt).content.length,
3343
+ entriesAfter: after.content.length
3344
+ });
2648
3345
  return { prompt: compacted.value.prompt, changed: true };
2649
3346
  })
2650
3347
  });
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)));
3348
+ const boundedSuccessResult = (call, outcome) => options.toolOutputMaxBytes === undefined ? Effect26.succeed(successResult(call, outcome)) : bound(outcome, { toolCallId: call.id, maxBytes: options.toolOutputMaxBytes }).pipe(Effect26.map((bounded2) => successResult(call, bounded2)));
2652
3349
  const outcomeEvent = (turn, toolCallBatch, toolCallIndex, call, outcome, droppedProgress, registry) => {
2653
3350
  const metadata = droppedProgress === 0 ? {} : { metadata: { toolProgress: { dropped: droppedProgress } } };
2654
- const completed = (result) => Effect23.sync(() => {
3351
+ const completed = (result) => Effect26.sync(() => {
2655
3352
  state.pending.set(toolCallIndex, result);
2656
3353
  return { _tag: "ToolExecutionCompleted", turn, call, result, ...metadata };
2657
3354
  });
2658
3355
  switch (outcome._tag) {
2659
3356
  case "Success":
2660
- return (isSkillActivationCall(call, registry) ? Effect23.succeed(successResult(call, outcome)) : boundedSuccessResult(call, outcome)).pipe(Effect23.flatMap(completed));
3357
+ return (isSkillActivationCall(call, registry) ? Effect26.succeed(successResult(call, outcome)) : boundedSuccessResult(call, outcome)).pipe(Effect26.flatMap(completed));
2661
3358
  case "DomainFailure":
2662
3359
  return completed(domainFailureResult(call, outcome));
2663
3360
  case "Suspend":
2664
- return Effect23.fail(suspended(call, toolCallBatch, toolCallIndex, outcome.token, "tool-wait"));
3361
+ return Effect26.fail(suspended(call, toolCallBatch, toolCallIndex, outcome.token, "tool-wait"));
2665
3362
  }
2666
3363
  };
2667
3364
  const defaultExecute = (request, registry) => {
@@ -2669,11 +3366,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2669
3366
  if (registered?.dispatch === "Static") {
2670
3367
  return executeToolkit(staticToolkit, request);
2671
3368
  }
2672
- return registered === undefined ? Effect23.fail(FrameworkFailure.make({
3369
+ return registered === undefined ? Effect26.fail(FrameworkFailure.make({
2673
3370
  stage: "missing-handler",
2674
3371
  tool: request.call.name,
2675
3372
  message: `Tool ${request.call.name} is not registered`
2676
- })) : Effect23.fail(FrameworkFailure.make({
3373
+ })) : Effect26.fail(FrameworkFailure.make({
2677
3374
  stage: "missing-handler",
2678
3375
  tool: request.call.name,
2679
3376
  message: `Activated skill tool ${request.call.name} requires ToolExecutor`
@@ -2690,11 +3387,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2690
3387
  return Queue2.sliding(progressPolicy.capacity);
2691
3388
  }
2692
3389
  };
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);
3390
+ const executeApproved = (turn, call, request, registry) => Stream5.concat(Stream5.fromIterable([{ _tag: "ToolExecutionStarted", turn, call }]), Stream5.unwrap(Effect26.gen(function* () {
3391
+ const progressQueue = yield* Effect26.acquireRelease(makeProgressQueue(), Queue2.shutdown);
2695
3392
  const droppedProgress = yield* Ref5.make(0);
2696
3393
  const emitSemaphore = yield* Semaphore3.make(1);
2697
- const signal = yield* Effect23.abortSignal;
3394
+ const signal = yield* Effect26.abortSignal;
2698
3395
  const context = ToolContext.of({
2699
3396
  signal,
2700
3397
  sessionId,
@@ -2706,9 +3403,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2706
3403
  ...progress.message === undefined ? {} : { message: progress.message },
2707
3404
  ...progress.data === undefined ? {} : { data: progress.data }
2708
3405
  };
2709
- return emitSemaphore.withPermit(Effect23.gen(function* () {
3406
+ return emitSemaphore.withPermit(Effect26.gen(function* () {
2710
3407
  if (progressPolicy._tag === "Sliding") {
2711
- const dropped = yield* Effect23.sync(() => {
3408
+ const dropped = yield* Effect26.sync(() => {
2712
3409
  const full = Queue2.isFullUnsafe(progressQueue);
2713
3410
  Queue2.offerUnsafe(progressQueue, event);
2714
3411
  return full;
@@ -2726,11 +3423,11 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2726
3423
  }));
2727
3424
  }
2728
3425
  });
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)));
3426
+ const execution = isSkillActivationCall(call, registry) ? activateSkillOutcome(turn, call) : Option16.isNone(executor) ? defaultExecute(request, registry) : executor.value.execute(request).pipe(Effect26.mapError((error) => Schema20.is(RemoteRetryMisconfigured)(error) ? AgentError.make({ message: error.message, turn, cause: error }) : error));
3427
+ const fiber = yield* Effect26.uninterruptibleMask((restore) => restore(execution.pipe(Effect26.provideService(ToolContext, context))).pipe(Effect26.flatMap((outcome) => Ref5.get(droppedProgress).pipe(Effect26.flatMap((dropped) => outcomeEvent(turn, request.toolCallBatch, request.toolCallIndex, call, outcome, dropped, registry)))))).pipe(Effect26.ensuring(Queue2.end(progressQueue).pipe(Effect26.asVoid)), Effect26.forkScoped({ startImmediately: true }));
3428
+ return Stream5.concat(Stream5.fromQueue(progressQueue), Stream5.fromEffect(Fiber3.join(fiber)));
2732
3429
  })));
2733
- const activateSkillOutcome = (turn, call) => Effect23.gen(function* () {
3430
+ const activateSkillOutcome = (turn, call) => Effect26.gen(function* () {
2734
3431
  if (skillRuntime === undefined) {
2735
3432
  return yield* FrameworkFailure.make({
2736
3433
  stage: "missing-handler",
@@ -2738,8 +3435,8 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2738
3435
  message: "SkillSource is not available"
2739
3436
  });
2740
3437
  }
2741
- const params = Schema19.decodeUnknownOption(activateSkillParameters)(call.params);
2742
- if (Option13.isNone(params)) {
3438
+ const params = Schema20.decodeUnknownOption(activateSkillParameters)(call.params);
3439
+ if (Option16.isNone(params)) {
2743
3440
  return yield* FrameworkFailure.make({
2744
3441
  stage: "decode-input",
2745
3442
  tool: call.name,
@@ -2780,19 +3477,19 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2780
3477
  allowedTools: [...skill.frontmatter.allowedTools ?? []]
2781
3478
  };
2782
3479
  return { _tag: "Success", result: output, encodedResult: output };
2783
- }).pipe(Effect23.mapError((error) => isToolNameCollision(error) || Schema19.is(FrameworkFailure)(error) ? error : skillError(turn, error)));
3480
+ }).pipe(Effect26.mapError((error) => isToolNameCollision(error) || Schema20.is(FrameworkFailure)(error) ? error : skillError(turn, error)));
2784
3481
  const authorizationError2 = (turn, error) => AgentError.make({ message: error.message, turn, cause: error });
2785
3482
  const toolCallEvents = (turn, toolCallBatch, toolCallIndex, call, messages, registry) => {
2786
3483
  const request = { call, toolCallBatch, turn, toolCallIndex, agentName: agent.name, sessionId };
2787
3484
  const candidate = get(registry, call.name);
2788
3485
  if (candidate === undefined)
2789
- return Stream4.fail(FrameworkFailure.make({
3486
+ return Stream5.fail(FrameworkFailure.make({
2790
3487
  stage: "authorization",
2791
3488
  tool: call.name,
2792
3489
  message: `Tool ${call.name} is not active for turn ${turn}`
2793
3490
  }));
2794
3491
  const activeTools = registry.entries.map((entry) => entry.tool.name);
2795
- return Stream4.unwrap(Effect23.gen(function* () {
3492
+ return Stream5.unwrap(Effect26.gen(function* () {
2796
3493
  const activatedSkills = [...(yield* Ref5.get(toolState)).activatedSkillBodies.keys()];
2797
3494
  const approvalEvents = yield* Queue2.bounded(1);
2798
3495
  const fiber = yield* authorizer.authorize({
@@ -2805,20 +3502,20 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2805
3502
  activeTools,
2806
3503
  activatedSkills,
2807
3504
  messages,
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) => {
3505
+ onApprovalRequired: Queue2.offer(approvalEvents, { _tag: "ApprovalRequested", turn, call }).pipe(Effect26.asVoid)
3506
+ }).pipe(Effect26.mapError((error) => authorizationError2(turn, error)), Effect26.ensuring(Queue2.end(approvalEvents).pipe(Effect26.asVoid)), Effect26.forkScoped({ startImmediately: true }));
3507
+ return Stream5.concat(Stream5.fromQueue(approvalEvents), Stream5.fromEffect(Fiber3.join(fiber)).pipe(Stream5.flatMap((decision2) => {
2811
3508
  switch (decision2._tag) {
2812
3509
  case "Execute":
2813
3510
  return executeApproved(turn, call, request, registry);
2814
3511
  case "Deny":
2815
- return Stream4.fail(FrameworkFailure.make({
3512
+ return Stream5.fail(FrameworkFailure.make({
2816
3513
  stage: "authorization",
2817
3514
  tool: call.name,
2818
3515
  message: decision2.error.message
2819
3516
  }));
2820
3517
  case "Suspend":
2821
- return Stream4.fail(AgentSuspended.make({
3518
+ return Stream5.fail(AgentSuspended.make({
2822
3519
  token: decision2.suspension.token,
2823
3520
  reason: "approval",
2824
3521
  tool_call_index: toolCallIndex,
@@ -2833,8 +3530,8 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2833
3530
  })));
2834
3531
  }));
2835
3532
  };
2836
- const captureFinishPart = (part) => Effect23.gen(function* () {
2837
- const span = yield* Effect23.currentSpan;
3533
+ const captureFinishPart = (part) => Effect26.gen(function* () {
3534
+ const span = yield* Effect26.currentSpan;
2838
3535
  state.finish = {
2839
3536
  usage: state.finish === undefined ? part.usage : addUsage(state.finish.usage, part.usage),
2840
3537
  reason: part.reason
@@ -2848,9 +3545,9 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2848
3545
  },
2849
3546
  response: { finishReasons: [part.reason] }
2850
3547
  });
2851
- }).pipe(Effect23.orDie);
2852
- const captureStructuredUsage = (content) => Effect23.gen(function* () {
2853
- const span = yield* Effect23.currentSpan;
3548
+ }).pipe(Effect26.orDie);
3549
+ const captureStructuredUsage = (content) => Effect26.gen(function* () {
3550
+ const span = yield* Effect26.currentSpan;
2854
3551
  for (const part of content) {
2855
3552
  if (part.type === "finish") {
2856
3553
  state.usage = state.usage === undefined ? part.usage : addUsage(state.usage, part.usage);
@@ -2864,129 +3561,147 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2864
3561
  });
2865
3562
  }
2866
3563
  }
2867
- }).pipe(Effect23.orDie);
2868
- const withModelResilience = (effect) => Option13.match(resilienceService, {
2869
- onNone: () => effect,
2870
- onSome: (resilience) => Effect23.flatMap(LanguageModel6.LanguageModel, (model) => effect.pipe(Effect23.provideService(LanguageModel6.LanguageModel, apply(model, {
2871
- ...resilience,
2872
- classify: (error) => classifyFailure(model, error) === "context-overflow" ? "terminal" : resilience.classify(error)
2873
- }))))
2874
- });
3564
+ }).pipe(Effect26.orDie);
3565
+ const withModelTelemetry = (turn, purpose) => (effect) => Effect26.flatMap(LanguageModel9.LanguageModel, (model) => effect.pipe(Effect26.provideService(LanguageModel9.LanguageModel, instrumentModel(model, turn)), Effect26.provideService(CurrentPurpose, purpose)));
2875
3566
  const withAgentModel = (effect) => agentModelRegistry === undefined || agentModel === undefined ? effect : agentModelRegistry.operate(agentModel, effect);
2876
3567
  function provideAgentModel(stream2) {
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 }))));
3568
+ return agentModelRegistry === undefined || agentModel === undefined ? stream2 : agentModelRegistry.stream(agentModel, stream2).pipe(Stream5.catchTag("@batonfx/core/LanguageModelNotRegistered", (error) => Stream5.fail(AgentError.make({ message: errorMessage(error), turn: state.turn, cause: error }))));
2878
3569
  }
2879
3570
  const partEvents = (turn, part) => {
2880
3571
  if (part.type === "error") {
2881
3572
  if (isToolNameCollision(part.error))
2882
- return Stream4.fail(part.error);
2883
- return Stream4.fail(AgentError.make({ message: errorMessage(part.error), turn, cause: part.error }));
3573
+ return Stream5.fail(part.error);
3574
+ return Stream5.fail(AgentError.make({ message: errorMessage(part.error), turn, cause: part.error }));
2884
3575
  }
2885
- const modelPart = Stream4.fromIterable([{ _tag: "ModelPart", turn, part }]);
3576
+ const identity = telemetryIdentity.current;
3577
+ if (identity === undefined) {
3578
+ return Stream5.fromEffect(Effect26.die(new Error("ModelPart produced outside an instrumented model attempt")));
3579
+ }
3580
+ const modelPart = Stream5.fromIterable([
3581
+ {
3582
+ _tag: "ModelPart",
3583
+ turn,
3584
+ modelCallId: identity.modelCallId,
3585
+ modelAttemptId: identity.modelAttemptId,
3586
+ attempt: identity.attempt,
3587
+ part
3588
+ }
3589
+ ]);
2886
3590
  if (part.type === "text-delta") {
2887
3591
  state.text = `${state.text}${part.delta}`;
2888
3592
  }
2889
3593
  if (part.type === "finish") {
2890
- return modelPart.pipe(Stream4.tap(() => captureFinishPart(part)));
3594
+ return modelPart.pipe(Stream5.tap(() => captureFinishPart(part)));
2891
3595
  }
2892
3596
  return modelPart;
2893
3597
  };
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({
3598
+ const transformPart = (turn, part) => applyPartChain(chain, part, { agentName: agent.name, turn }).pipe(Effect26.flatMap(Option16.match({
3599
+ onSome: (transformed) => Effect26.succeed(Option16.some(transformed)),
3600
+ onNone: () => part.type === "tool-call" ? Effect26.fail(MiddlewareViolation.make({
2897
3601
  turn,
2898
3602
  detail: "ModelMiddleware dropped a tool-call part"
2899
- })) : Effect23.succeed(Option13.none())
3603
+ })) : Effect26.succeed(Option16.none())
2900
3604
  })));
2901
3605
  const validateToolCallId = (idState, part) => {
2902
3606
  if (part.type !== "tool-call")
2903
- return Effect23.void;
3607
+ return Effect26.void;
2904
3608
  return Ref5.modify(idState, (current) => {
2905
3609
  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 }));
3610
+ const duplicate = Option16.map(existingFirstIndex, (index) => DuplicateToolCallId.make({ id: part.id, firstIndex: index, duplicateIndex: current.nextIndex }));
2907
3611
  return [
2908
3612
  duplicate,
2909
3613
  {
2910
3614
  nextIndex: current.nextIndex + 1,
2911
- firstIndexes: Option13.isSome(existingFirstIndex) ? current.firstIndexes : HashMap6.set(current.firstIndexes, part.id, current.nextIndex)
3615
+ firstIndexes: Option16.isSome(existingFirstIndex) ? current.firstIndexes : HashMap6.set(current.firstIndexes, part.id, current.nextIndex)
2912
3616
  }
2913
3617
  ];
2914
- }).pipe(Effect23.flatMap(Option13.match({
2915
- onNone: () => Effect23.void,
2916
- onSome: Effect23.fail
3618
+ }).pipe(Effect26.flatMap(Option16.match({
3619
+ onNone: () => Effect26.void,
3620
+ onSome: Effect26.fail
2917
3621
  })));
2918
3622
  };
2919
3623
  const modelTurn = (turn, prompt, registry, overrides) => {
2920
3624
  const activeRegistry = overrides?.activeTools === undefined ? registry : select(registry, overrides.activeTools);
3625
+ const instrumentTurnStream = (stream2) => Stream5.unwrap(LanguageModel9.LanguageModel.pipe(Effect26.map((model) => stream2.pipe(Stream5.provideService(LanguageModel9.LanguageModel, instrumentModel(model, turn)), Stream5.provideService(CurrentInstrumentation, {
3626
+ emit: emitTelemetry,
3627
+ wrap: (summaryModel) => instrumentModel(summaryModel, turn)
3628
+ })))));
2921
3629
  const attempt = (activePrompt, retryOverflow, compactOverflow = false, overflowCause) => {
2922
3630
  let emitted = false;
2923
3631
  let classifyFailure2 = classifyOtherFailure;
2924
3632
  const transformedParts = new Array;
2925
3633
  let preparedState;
2926
- const singleFailure = (cause) => {
3634
+ const singleFailure2 = (cause) => {
2927
3635
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
2928
- return reason !== undefined && Cause4.isFailReason(reason) ? Option13.some(reason.error) : Option13.none();
3636
+ return reason !== undefined && Cause6.isFailReason(reason) ? Option16.some(reason.error) : Option16.none();
2929
3637
  };
2930
3638
  const retryableOverflow = (cause, hasEmitted) => {
2931
- const failure2 = singleFailure(cause);
2932
- return retryOverflow && !hasEmitted && Option13.isSome(failure2) && classifyFailure2(failure2.value) === "context-overflow" && Option13.isSome(compactionService);
3639
+ const failure2 = singleFailure2(cause);
3640
+ if (Option16.isNone(failure2))
3641
+ return false;
3642
+ const classifiedFailure = Schema20.is(AgentError)(failure2.value) && failure2.value.cause !== undefined ? failure2.value.cause : failure2.value;
3643
+ return retryOverflow && !hasEmitted && Option16.isSome(compactionService) && classifyFailure2(classifiedFailure) === "context-overflow";
2933
3644
  };
2934
- return Stream4.fromChannel(Channel.acquireUseRelease(Ref5.make({
3645
+ return Stream5.fromChannel(Channel.acquireUseRelease(Ref5.make({
2935
3646
  nextIndex: 0,
2936
3647
  firstIndexes: HashMap6.empty()
2937
- }), (toolCallIds) => Stream4.unwrap(Effect23.gen(function* () {
2938
- const activeModel = yield* LanguageModel6.LanguageModel;
3648
+ }), (toolCallIds) => Stream5.unwrap(Effect26.gen(function* () {
3649
+ const activeModel = yield* LanguageModel9.LanguageModel;
2939
3650
  classifyFailure2 = (error) => classifyFailure(activeModel, error);
2940
3651
  const prepared = yield* preparePrompt(turn, activePrompt, compactOverflow);
2941
3652
  if (compactOverflow && !prepared.changed && overflowCause !== undefined) {
2942
- return yield* Effect23.failCause(overflowCause);
3653
+ return yield* Effect26.failCause(overflowCause);
2943
3654
  }
2944
- const preparedPrompt = prepared.prompt;
3655
+ const coalescedContent = prepared.prompt.content.map(coalesceAdjacentText);
3656
+ const preparedPrompt = coalescedContent.some((message, index) => message !== prepared.prompt.content[index]) ? Prompt11.fromMessages(coalescedContent) : prepared.prompt;
2945
3657
  const history = yield* Ref5.get(chat.history);
2946
3658
  preparedState = { history, preparedPrompt };
2947
3659
  const responsePrompt = Prompt11.concat(history, preparedPrompt);
2948
3660
  const messages = responsePrompt.content;
2949
- const rawParts = LanguageModel6.streamText({
3661
+ const rawParts = LanguageModel9.streamText({
2950
3662
  prompt: responsePrompt,
2951
3663
  toolkit: activeRegistry.toolkit,
2952
3664
  disableToolCallResolution: true
2953
- }).pipe(Stream4.tap(() => Effect23.sync(() => {
3665
+ }).pipe(Stream5.mapEffect((part) => part.type === "error" ? Effect26.fail(isToolNameCollision(part.error) ? part.error : AgentError.make({ message: errorMessage(part.error), turn, cause: part.error })) : Effect26.succeed(part)), Stream5.tap(() => Effect26.sync(() => {
2954
3666
  emitted = true;
2955
- })), Stream4.catchCause((cause) => {
2956
- if (Cause4.hasInterrupts(cause) || Cause4.hasDies(cause))
2957
- return Stream4.failCause(cause);
3667
+ })), Stream5.catchCause((cause) => {
3668
+ if (Cause6.hasInterrupts(cause) || Cause6.hasDies(cause))
3669
+ return Stream5.failCause(cause);
2958
3670
  if (retryableOverflow(cause, emitted))
2959
- return Stream4.failCause(cause);
2960
- const error = singleFailure(cause);
2961
- if (Option13.isNone(error))
2962
- return Stream4.failCause(cause);
2963
- return Stream4.make(Response9.makePart("error", { error: error.value }));
3671
+ return Stream5.failCause(cause);
3672
+ const error = singleFailure2(cause);
3673
+ if (Option16.isNone(error))
3674
+ return Stream5.failCause(cause);
3675
+ if (Schema20.is(AgentError)(error.value) || isToolNameCollision(error.value)) {
3676
+ return Stream5.fail(error.value);
3677
+ }
3678
+ return Stream5.make(Response11.makePart("error", { error: error.value }));
2964
3679
  }));
2965
- return rawParts.pipe(Stream4.mapEffect((part) => transformPart(turn, part)), Stream4.flatMap(Option13.match({ onNone: () => Stream4.empty, onSome: Stream4.make })), Stream4.map((part) => ({
3680
+ return rawParts.pipe(Stream5.mapEffect((part) => transformPart(turn, part)), Stream5.flatMap(Option16.match({ onNone: () => Stream5.empty, onSome: Stream5.make })), Stream5.map((part) => ({
2966
3681
  part,
2967
3682
  messages,
2968
- accept: validateToolCallId(toolCallIds, part).pipe(Effect23.andThen(Effect23.sync(() => {
3683
+ accept: validateToolCallId(toolCallIds, part).pipe(Effect26.andThen(Effect26.sync(() => {
2969
3684
  transformedParts.push(part);
2970
3685
  })))
2971
3686
  })));
2972
- })).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) => {
2973
- if (Cause4.hasInterrupts(cause) || Cause4.hasDies(cause))
2974
- return Stream4.failCause(cause);
3687
+ })).pipe(Stream5.toChannel), (_, exit) => preparedState === undefined || Exit4.isFailure(exit) && retryableOverflow(exit.cause, emitted) ? Effect26.void : Ref5.set(chat.history, Prompt11.concat(Prompt11.concat(preparedState.history, preparedState.preparedPrompt), Prompt11.fromResponseParts(transformedParts))).pipe(Effect26.andThen(persisted === undefined ? Effect26.void : persisted.save), Effect26.orDie, Effect26.asVoid))).pipe(Stream5.catchCause((cause) => {
3688
+ if (Cause6.hasInterrupts(cause) || Cause6.hasDies(cause))
3689
+ return Stream5.failCause(cause);
2975
3690
  if (retryableOverflow(cause, emitted)) {
2976
3691
  return attempt(preparedState?.preparedPrompt ?? activePrompt, false, true, cause);
2977
3692
  }
2978
- return Stream4.failCause(cause);
2979
- }), Stream4.catchCause((cause) => {
2980
- const failure2 = singleFailure(cause);
2981
- return Option13.isSome(failure2) && AiError4.isAiError(failure2.value) ? Stream4.fail(AgentError.make({ message: errorMessage(failure2.value), turn, cause: failure2.value })) : Stream4.failCause(cause);
3693
+ return Stream5.failCause(cause);
3694
+ }), Stream5.catchCause((cause) => {
3695
+ const failure2 = singleFailure2(cause);
3696
+ return Option16.isSome(failure2) && AiError7.isAiError(failure2.value) ? Stream5.fail(AgentError.make({ message: errorMessage(failure2.value), turn, cause: failure2.value })) : Stream5.failCause(cause);
2982
3697
  }));
2983
3698
  };
2984
- const parts = Stream4.unwrap(applyPromptChain(chain, Prompt11.make(prompt), { agentName: agent.name, turn }).pipe(Effect23.map((transformedPrompt) => {
3699
+ const parts = Stream5.unwrap(applyPromptChain(chain, Prompt11.make(prompt), { agentName: agent.name, turn }).pipe(Effect26.map((transformedPrompt) => {
2985
3700
  let nextToolCallIndex = 0;
2986
3701
  const calls = new Array;
2987
3702
  const executions = new Array;
2988
3703
  const toolCallBatch = { calls };
2989
- const accepted = attempt(transformedPrompt, true).pipe(Stream4.mapEffect(({ accept, part, messages }) => accept.pipe(Effect23.as({ part, messages }))), Stream4.map(({ part, messages }) => {
3704
+ const accepted = instrumentTurnStream(attempt(transformedPrompt, true)).pipe(Stream5.mapEffect(({ accept, part, messages }) => accept.pipe(Effect26.as({ part, messages }))), Stream5.map(({ part, messages }) => {
2990
3705
  const toolCallIndex = nextToolCallIndex;
2991
3706
  if (part.type === "tool-call" && part.providerExecuted !== true) {
2992
3707
  const call = part;
@@ -2995,23 +3710,16 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
2995
3710
  executions.push({ call, messages, toolCallIndex });
2996
3711
  }
2997
3712
  return { part, messages, toolCallIndex };
2998
- }), Stream4.flatMap(({ part }) => partEvents(turn, part)));
2999
- return Stream4.concat(accepted, Stream4.suspend(() => {
3713
+ }), Stream5.flatMap(({ part }) => partEvents(turn, part)));
3714
+ return Stream5.concat(accepted, Stream5.suspend(() => {
3000
3715
  Object.freeze(calls);
3001
3716
  Object.freeze(toolCallBatch);
3002
3717
  const concurrency = agent.toolExecution?.concurrency ?? 1;
3003
- const executionStreams = Stream4.fromIterable(executions);
3004
- 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));
3718
+ const executionStreams = Stream5.fromIterable(executions);
3719
+ return concurrency === 1 ? executionStreams.pipe(Stream5.flatMap(({ call, messages, toolCallIndex }) => toolCallEvents(turn, toolCallBatch, toolCallIndex, call, messages, activeRegistry))) : executionStreams.pipe(Stream5.mapEffect(({ call, messages, toolCallIndex }) => Stream5.runCollect(toolCallEvents(turn, toolCallBatch, toolCallIndex, call, messages, activeRegistry)), { concurrency }), Stream5.flatMap(Stream5.fromIterable));
3005
3720
  }));
3006
3721
  })));
3007
- const resilientParts = Option13.match(resilienceService, {
3008
- onNone: () => parts,
3009
- onSome: (resilience) => Stream4.unwrap(LanguageModel6.LanguageModel.pipe(Effect23.map((model) => parts.pipe(Stream4.provideService(LanguageModel6.LanguageModel, apply(model, {
3010
- ...resilience,
3011
- classify: (error) => classifyFailure(model, error) === "context-overflow" ? "terminal" : resilience.classify(error)
3012
- }))))))
3013
- });
3014
- return overrides?.model === undefined ? provideAgentModel(resilientParts) : resilientParts.pipe(Stream4.provide(overrides.model));
3722
+ return overrides?.model === undefined ? provideAgentModel(parts) : parts.pipe(Stream5.provide(overrides.model));
3015
3723
  };
3016
3724
  const turnCompletedEvent = (turn, transcript) => ({
3017
3725
  _tag: "TurnCompleted",
@@ -3026,49 +3734,54 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
3026
3734
  transcript,
3027
3735
  ...state.usage === undefined ? {} : { usage: state.usage }
3028
3736
  });
3029
- const structuredFinalEvents = (structuredTurn, config) => Stream4.fromEffect(Effect23.gen(function* () {
3737
+ const structuredFinalEvents = (structuredTurn, config) => Stream5.fromEffect(Effect26.gen(function* () {
3030
3738
  const transformedPrompt = yield* applyPromptChain(chain, Prompt11.make(config.objectPrompt), {
3031
3739
  agentName: agent.name,
3032
3740
  turn: structuredTurn
3033
3741
  });
3034
3742
  const history = yield* Ref5.get(chat.history);
3035
- const response = yield* LanguageModel6.generateObject({
3743
+ const response = yield* LanguageModel9.generateObject({
3036
3744
  prompt: Prompt11.concat(history, transformedPrompt),
3037
3745
  schema: config.schema,
3038
3746
  objectName: config.objectName,
3039
3747
  toolChoice: "none"
3040
- }).pipe(withModelResilience, withAgentModel, Effect23.catchCause((cause) => {
3748
+ }).pipe(withModelTelemetry(structuredTurn, "structured-output"), withAgentModel, Effect26.catchCause((cause) => {
3041
3749
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
3042
- return reason !== undefined && Cause4.isFailReason(reason) ? Effect23.fail(AgentError.make({
3750
+ return reason !== undefined && Cause6.isFailReason(reason) ? Effect26.fail(AgentError.make({
3043
3751
  message: errorMessage(reason.error),
3044
3752
  turn: structuredTurn,
3045
3753
  cause: reason.error
3046
- })) : Effect23.failCause(cause);
3754
+ })) : Effect26.failCause(cause);
3047
3755
  }));
3048
3756
  yield* captureStructuredUsage(response.content);
3757
+ const structuredIdentity = telemetryIdentity.current;
3758
+ if (structuredIdentity === undefined) {
3759
+ return yield* Effect26.die(new Error("Structured output model attempt identity is missing"));
3760
+ }
3049
3761
  const transcript = Prompt11.concat(Prompt11.concat(history, transformedPrompt), Prompt11.fromResponseParts(response.content));
3050
3762
  const path = yield* syncSession(structuredTurn, history);
3051
3763
  yield* applyCompactionResult(structuredTurn, { _tag: "Microcompact", history: transcript, prompt: Prompt11.empty }, path.at(-1)?.id ?? null);
3052
- if (Option13.isNone(activeSession))
3764
+ if (Option16.isNone(activeSession))
3053
3765
  yield* savePersisted(structuredTurn);
3054
3766
  const structuredOutput = {
3055
3767
  _tag: "StructuredOutput",
3056
3768
  turn: structuredTurn,
3769
+ ...structuredIdentity,
3057
3770
  value: response.value,
3058
3771
  content: response.content
3059
3772
  };
3060
3773
  return [structuredOutput, terminalCompletedEvent(structuredTurn, transcript)];
3061
- })).pipe(Stream4.flatMap((events) => Stream4.fromIterable(events)));
3774
+ })).pipe(Stream5.flatMap((events) => Stream5.fromIterable(events)));
3062
3775
  const promptFromSteeringInputs = (inputs) => inputs.reduce((prompt, input) => Prompt11.concat(prompt, input.prompt), Prompt11.empty);
3063
- const takeSteering = () => Option13.match(steeringService, {
3064
- onNone: () => Effect23.succeed([]),
3776
+ const takeSteering = () => Option16.match(steeringService, {
3777
+ onNone: () => Effect26.succeed([]),
3065
3778
  onSome: (service) => service.takeSteering
3066
3779
  });
3067
- const takeFollowUp = () => Option13.match(steeringService, {
3068
- onNone: () => Effect23.succeed([]),
3780
+ const takeFollowUp = () => Option16.match(steeringService, {
3781
+ onNone: () => Effect26.succeed([]),
3069
3782
  onSome: (service) => service.takeFollowUp
3070
3783
  });
3071
- const afterTurn = (turn) => Effect23.gen(function* () {
3784
+ const afterTurn = (turn) => Effect26.gen(function* () {
3072
3785
  const pending = pendingResults();
3073
3786
  const transcript = yield* checkpointPending(turn, pending);
3074
3787
  const path = yield* syncSession(turn, transcript);
@@ -3078,19 +3791,19 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
3078
3791
  const followUp = yield* takeFollowUp();
3079
3792
  if (followUp.length > 0) {
3080
3793
  return {
3081
- events: Stream4.fromIterable([completed, steeringDrainedEvent(turn, "followUp", followUp)]),
3794
+ events: Stream5.fromIterable([completed, steeringDrainedEvent(turn, "followUp", followUp)]),
3082
3795
  next: { prompt: promptFromSteeringInputs(followUp) }
3083
3796
  };
3084
3797
  }
3085
3798
  if (structured !== undefined) {
3086
3799
  return {
3087
- events: Stream4.fromIterable([completed]),
3800
+ events: Stream5.fromIterable([completed]),
3088
3801
  structuredTurn: turn + 1
3089
3802
  };
3090
3803
  }
3091
3804
  yield* savePersisted(turn);
3092
3805
  return {
3093
- events: Stream4.fromIterable([completed, terminalCompletedEvent(turn, transcript)])
3806
+ events: Stream5.fromIterable([completed, terminalCompletedEvent(turn, transcript)])
3094
3807
  };
3095
3808
  }
3096
3809
  const evaluated = yield* agent.policy.decide({
@@ -3111,7 +3824,7 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
3111
3824
  tool_name: result.name
3112
3825
  }));
3113
3826
  return {
3114
- events: Stream4.concat(Stream4.fromIterable([completed]), Stream4.fail(decision2.reason._tag === "TurnLimit" ? TurnLimitExceeded.make({
3827
+ events: Stream5.concat(Stream5.fromIterable([completed]), Stream5.fail(decision2.reason._tag === "TurnLimit" ? TurnLimitExceeded.make({
3115
3828
  turn: turn + 1,
3116
3829
  limit: decision2.reason.limit,
3117
3830
  pending: pendingCalls
@@ -3127,35 +3840,35 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
3127
3840
  const basePrompt = steering.length === 0 ? Prompt11.empty : promptFromSteeringInputs(steering);
3128
3841
  const prompt = decision2.overrides?.instructions === undefined ? basePrompt : withSystem(decision2.overrides.instructions, basePrompt);
3129
3842
  return {
3130
- events: Stream4.fromIterable(steering.length === 0 ? [completed] : [completed, steeringDrainedEvent(turn, "steering", steering)]),
3843
+ events: Stream5.fromIterable(steering.length === 0 ? [completed] : [completed, steeringDrainedEvent(turn, "steering", steering)]),
3131
3844
  next: { prompt, ...decision2.overrides === undefined ? {} : { overrides: decision2.overrides } }
3132
3845
  };
3133
3846
  });
3134
- const resetTurnState = (turn) => Stream4.sync(() => {
3847
+ const resetTurnState = (turn) => Stream5.sync(() => {
3135
3848
  state.turn = turn;
3136
3849
  state.finish = undefined;
3137
- }).pipe(Stream4.drain);
3850
+ }).pipe(Stream5.drain);
3138
3851
  const runTurn = (turn, prompt, overrides) => {
3139
3852
  let next;
3140
3853
  let structuredTurn;
3141
- 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) => {
3854
+ const currentTurn = Stream5.fromIterable([{ _tag: "TurnStarted", turn }]).pipe(Stream5.concat(resetTurnState(turn)), Stream5.concat(Stream5.unwrap(Ref5.get(toolState).pipe(Effect26.map(({ registry }) => modelTurn(turn, prompt, registry, overrides))))), Stream5.concat(Stream5.unwrap(afterTurn(turn).pipe(Effect26.map((result) => {
3142
3855
  next = result.next;
3143
3856
  structuredTurn = result.structuredTurn;
3144
3857
  return result.events;
3145
- })))), Stream4.withSpan("Baton.Agent.turn", { attributes: { "baton.turn": turn } }));
3146
- return Stream4.concat(currentTurn, Stream4.suspend(() => {
3858
+ })))), Stream5.withSpan("Baton.Agent.turn", { attributes: { "baton.turn": turn } }));
3859
+ return Stream5.concat(currentTurn, Stream5.suspend(() => {
3147
3860
  if (structuredTurn !== undefined && structured !== undefined) {
3148
- return structuredFinalEvents(structuredTurn, structured).pipe(Stream4.withSpan("Baton.Agent.turn", { attributes: { "baton.turn": structuredTurn } }));
3861
+ return structuredFinalEvents(structuredTurn, structured).pipe(Stream5.withSpan("Baton.Agent.turn", { attributes: { "baton.turn": structuredTurn } }));
3149
3862
  }
3150
- return next === undefined ? Stream4.empty : runTurn(turn + 1, next.prompt, next.overrides);
3863
+ return next === undefined ? Stream5.empty : runTurn(turn + 1, next.prompt, next.overrides);
3151
3864
  }));
3152
3865
  };
3153
3866
  const resumeStream = (checkpoint) => {
3154
3867
  let next;
3155
- const currentTurn = resetTurnState(0).pipe(Stream4.concat(Stream4.unwrap(Ref5.get(toolState).pipe(Effect23.map((tools) => {
3868
+ const currentTurn = resetTurnState(0).pipe(Stream5.concat(Stream5.unwrap(Ref5.get(toolState).pipe(Effect26.map((tools) => {
3156
3869
  const suspension = checkpoint.suspension;
3157
3870
  const registry = suspension.active_tools === undefined ? tools.registry : select(tools.registry, suspension.active_tools);
3158
- const calls = suspension.tool_call_batch.map((call) => Response9.makePart("tool-call", {
3871
+ const calls = suspension.tool_call_batch.map((call) => Response11.makePart("tool-call", {
3159
3872
  id: call.id,
3160
3873
  name: call.name,
3161
3874
  params: call.params,
@@ -3165,42 +3878,51 @@ var streamInternal = (agent, options, structured) => Stream4.unwrap(Effect23.gen
3165
3878
  const toolCallBatch = { calls };
3166
3879
  const suspendedIndex = suspension.tool_call_index ?? 0;
3167
3880
  if (calls[suspendedIndex] === undefined) {
3168
- return Stream4.fail(AgentError.make({ message: "Suspension tool call index is outside its batch", turn: 0 }));
3881
+ return Stream5.fail(AgentError.make({ message: "Suspension tool call index is outside its batch", turn: 0 }));
3169
3882
  }
3170
- const executions = Stream4.fromIterable(checkpoint.unresolvedToolCallIndexes.map((toolCallIndex) => ({
3883
+ const executions = Stream5.fromIterable(checkpoint.unresolvedToolCallIndexes.map((toolCallIndex) => ({
3171
3884
  call: calls[toolCallIndex],
3172
3885
  toolCallIndex
3173
3886
  })));
3174
3887
  const execute = ({ call, toolCallIndex }) => toolCallEvents(0, toolCallBatch, toolCallIndex, call, checkpoint.messages, registry);
3175
3888
  const concurrency = agent.toolExecution?.concurrency ?? 1;
3176
- return concurrency === 1 ? executions.pipe(Stream4.flatMap(execute)) : executions.pipe(Stream4.mapEffect((execution) => Stream4.runCollect(execute(execution)), { concurrency }), Stream4.flatMap(Stream4.fromIterable));
3177
- })))), Stream4.concat(Stream4.unwrap(afterTurn(0).pipe(Effect23.map((result) => {
3889
+ return concurrency === 1 ? executions.pipe(Stream5.flatMap(execute)) : executions.pipe(Stream5.mapEffect((execution) => Stream5.runCollect(execute(execution)), { concurrency }), Stream5.flatMap(Stream5.fromIterable));
3890
+ })))), Stream5.concat(Stream5.unwrap(afterTurn(0).pipe(Effect26.map((result) => {
3178
3891
  next = result.next;
3179
3892
  return result.events;
3180
- })))), Stream4.withSpan("Baton.Agent.turn", { attributes: { "baton.turn": 0 } }));
3181
- return Stream4.concat(currentTurn, Stream4.suspend(() => next === undefined ? Stream4.empty : runTurn(1, next.prompt, next.overrides)));
3893
+ })))), Stream5.withSpan("Baton.Agent.turn", { attributes: { "baton.turn": 0 } }));
3894
+ return Stream5.concat(currentTurn, Stream5.suspend(() => next === undefined ? Stream5.empty : runTurn(1, next.prompt, next.overrides)));
3182
3895
  };
3183
3896
  const baseInitialPrompt = seedSystem === undefined ? Prompt11.make(options.prompt) : withSystem(seedSystem, Prompt11.make(options.prompt));
3184
3897
  const initialPrompt = options.resume === undefined ? yield* recallInitialPrompt(baseInitialPrompt) : baseInitialPrompt;
3185
3898
  const runStream = validatedResume === undefined ? runTurn(0, initialPrompt) : resumeStream(validatedResume);
3186
- return runStream.pipe(Stream4.catchCause((cause) => {
3899
+ const guardedStream = runStream.pipe(Stream5.catchCause((cause) => {
3187
3900
  const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
3188
- if (reason !== undefined && Cause4.isFailReason(reason) && Schema19.is(DuplicateToolCallId)(reason.error)) {
3189
- return Stream4.unwrap(checkpointPending(state.turn, pendingResults()).pipe(Effect23.map(() => Stream4.failCause(cause))));
3901
+ if (reason !== undefined && Cause6.isFailReason(reason) && Schema20.is(DuplicateToolCallId)(reason.error)) {
3902
+ return Stream5.unwrap(checkpointPending(state.turn, pendingResults()).pipe(Effect26.map(() => Stream5.failCause(cause))));
3190
3903
  }
3191
- if (reason !== undefined && Cause4.isFailReason(reason) && Schema19.is(AgentSuspended)(reason.error)) {
3904
+ if (reason !== undefined && Cause6.isFailReason(reason) && Schema20.is(AgentSuspended)(reason.error)) {
3192
3905
  const suspension = reason.error;
3193
- return Stream4.unwrap(Effect23.gen(function* () {
3906
+ return Stream5.unwrap(Effect26.gen(function* () {
3194
3907
  const checkpoint = yield* checkpointSuspended(state.turn, pendingResults(), suspension);
3195
3908
  yield* syncSession(state.turn, checkpoint);
3196
- return Stream4.concat(Stream4.fromIterable([turnCompletedEvent(state.turn, checkpoint)]), Stream4.failCause(cause));
3909
+ return Stream5.concat(Stream5.fromIterable([turnCompletedEvent(state.turn, checkpoint)]), Stream5.failCause(cause));
3197
3910
  }));
3198
3911
  }
3199
- return Stream4.failCause(cause);
3912
+ return Stream5.failCause(cause);
3913
+ }));
3914
+ return guardedStream.pipe(Stream5.provideService(CurrentInstrumentation, undefined), Stream5.provideService(CurrentPurpose, "conversation"), Stream5.provideService(CurrentCompactionId, undefined), Stream5.provideService(CurrentSummaryCall, undefined), Stream5.mapEffect((event) => deliverPending().pipe(Effect26.map(() => [...flushTelemetry(), event]))), Stream5.flattenIterable, Stream5.concat(Stream5.unwrap(deliverPending().pipe(Effect26.map(() => Stream5.fromIterable(flushTelemetry()))))), Stream5.catchCause((cause) => {
3915
+ if (Cause6.hasInterrupts(cause))
3916
+ return Stream5.failCause(cause);
3917
+ const reason = cause.reasons.length === 1 ? cause.reasons[0] : undefined;
3918
+ if (reason !== undefined && Cause6.isFailReason(reason) && Schema20.is(DeliveryFailed)(reason.error)) {
3919
+ return Stream5.failCause(cause);
3920
+ }
3921
+ return Stream5.unwrap(deliverPending().pipe(Effect26.map(() => Stream5.concat(Stream5.fromIterable(flushTelemetry()), Stream5.failCause(cause)))));
3200
3922
  }));
3201
- })).pipe(Stream4.withSpan("Baton.Agent.run", { attributes: { "baton.agent.name": agent.name } }));
3923
+ })).pipe(Stream5.withSpan("Baton.Agent.run", { attributes: { "baton.agent.name": agent.name } }));
3202
3924
 
3203
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent.js
3925
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent.js
3204
3926
  var AgentTypeId = Symbol.for("@batonfx/core/Agent");
3205
3927
  function make5(options) {
3206
3928
  const declaredTools = "tools" in options && Array.isArray(options.tools) ? options.tools : undefined;
@@ -3238,20 +3960,20 @@ function make5(options) {
3238
3960
  };
3239
3961
  }
3240
3962
  var defaultObjectPrompt = "Return the final structured output for the task above.";
3241
- var stream2 = dual6(2, (agent, options) => streamInternal(agent, options, options.output === undefined ? undefined : {
3963
+ var stream2 = dual7(2, (agent, options) => streamInternal(agent, options, options.output === undefined ? undefined : {
3242
3964
  schema: options.output.schema,
3243
3965
  objectName: options.output.name ?? "output",
3244
3966
  objectPrompt: options.output.prompt ?? defaultObjectPrompt
3245
3967
  }));
3246
- var generateText = (agent, options) => Stream5.runLast(streamInternal(agent, options, undefined)).pipe(Effect24.flatMap(Option14.match({
3247
- onNone: () => Effect24.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 })),
3248
- 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 }))
3968
+ var generateText = (agent, options) => Stream6.runLast(streamInternal(agent, options, undefined)).pipe(Effect27.flatMap(Option17.match({
3969
+ onNone: () => Effect27.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 })),
3970
+ onSome: (event) => event._tag === "Completed" ? Effect27.succeed({ text: event.text, turns: event.turns, transcript: event.transcript }) : Effect27.fail(AgentError.make({ message: "Agent run ended without a Completed event", turn: 0 }))
3249
3971
  })));
3250
- 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, {
3251
- onNone: () => Effect24.fail(AgentError.make({ message: "Agent object run ended without a Completed event", turn: 0 })),
3252
- onSome: (event) => Option14.match(value, {
3253
- onNone: () => Effect24.fail(AgentError.make({ message: "Agent object run ended without a StructuredOutput event", turn: 0 })),
3254
- onSome: (typedValue) => Effect24.succeed({
3972
+ var generateObjectResult = (agent, options, structured) => Stream6.runFold(streamInternal(agent, options, structured), () => ({ value: Option17.none(), completed: Option17.none() }), (acc, event) => event._tag === "StructuredOutput" ? { ...acc, value: Option17.some(event.value) } : event._tag === "Completed" ? { ...acc, completed: Option17.some(event) } : acc).pipe(Effect27.flatMap(({ value, completed }) => Option17.match(completed, {
3973
+ onNone: () => Effect27.fail(AgentError.make({ message: "Agent object run ended without a Completed event", turn: 0 })),
3974
+ onSome: (event) => Option17.match(value, {
3975
+ onNone: () => Effect27.fail(AgentError.make({ message: "Agent object run ended without a StructuredOutput event", turn: 0 })),
3976
+ onSome: (typedValue) => Effect27.succeed({
3255
3977
  text: event.text,
3256
3978
  turns: event.turns,
3257
3979
  transcript: event.transcript,
@@ -3259,84 +3981,84 @@ var generateObjectResult = (agent, options, structured) => Stream5.runFold(strea
3259
3981
  })
3260
3982
  })
3261
3983
  })));
3262
- var generate = dual6(2, (agent, options) => options.output === undefined ? generateText(agent, options) : generateObjectResult(agent, options, {
3984
+ var generate = dual7(2, (agent, options) => options.output === undefined ? generateText(agent, options) : generateObjectResult(agent, options, {
3263
3985
  schema: options.output.schema,
3264
3986
  objectName: options.output.name ?? "output",
3265
3987
  objectPrompt: options.output.prompt ?? defaultObjectPrompt
3266
3988
  }));
3267
3989
 
3268
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/agent-tool.js
3990
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/agent-tool.js
3269
3991
  var exports_agent_tool = {};
3270
3992
  __export(exports_agent_tool, {
3271
3993
  asTool: () => asTool
3272
3994
  });
3273
- import { Cause as Cause5, Effect as Effect25, Function as Function7, Schema as Schema21 } from "effect";
3995
+ import { Cause as Cause7, Effect as Effect28, Function as Function9, Schema as Schema22 } from "effect";
3274
3996
  import { Prompt as Prompt13, Tool as Tool11, Toolkit as Toolkit6 } from "effect/unstable/ai";
3275
- var defaultParameters = Schema21.Struct({ prompt: Schema21.String });
3997
+ var defaultParameters = Schema22.Struct({ prompt: Schema22.String });
3276
3998
  var errorMessage2 = (error) => {
3277
- if (Schema21.is(AgentSuspended)(error)) {
3999
+ if (Schema22.is(AgentSuspended)(error)) {
3278
4000
  return `suspended on ${error.tool_name}: ${error.reason}`;
3279
4001
  }
3280
- if (Schema21.is(AgentError)(error)) {
4002
+ if (Schema22.is(AgentError)(error)) {
3281
4003
  return `failed on turn ${error.turn}: ${error.message}`;
3282
4004
  }
3283
- if (Schema21.is(ResumeMismatch)(error)) {
4005
+ if (Schema22.is(ResumeMismatch)(error)) {
3284
4006
  return `resume mismatch: ${error.reason}`;
3285
4007
  }
3286
- if (Schema21.is(TurnLimitExceeded)(error)) {
4008
+ if (Schema22.is(TurnLimitExceeded)(error)) {
3287
4009
  return `turn limit exceeded at turn ${error.turn}`;
3288
4010
  }
3289
- if (Schema21.is(TurnPolicyStopped)(error)) {
4011
+ if (Schema22.is(TurnPolicyStopped)(error)) {
3290
4012
  return `policy stopped at turn ${error.turn}: ${error.reason._tag}`;
3291
4013
  }
3292
- if (Schema21.is(TurnPolicyError)(error)) {
4014
+ if (Schema22.is(TurnPolicyError)(error)) {
3293
4015
  return `turn policy failed: ${error.message}`;
3294
4016
  }
3295
- if (Schema21.is(MiddlewareViolation)(error)) {
4017
+ if (Schema22.is(MiddlewareViolation)(error)) {
3296
4018
  return `middleware violation on turn ${error.turn}: ${error.detail}`;
3297
4019
  }
3298
- if (Schema21.is(DuplicateToolCallId)(error)) {
4020
+ if (Schema22.is(DuplicateToolCallId)(error)) {
3299
4021
  return `duplicate tool-call ID '${error.id}' at position ${error.duplicateIndex} (first at ${error.firstIndex})`;
3300
4022
  }
3301
- if (Schema21.is(ToolNameCollision)(error)) {
4023
+ if (Schema22.is(ToolNameCollision)(error)) {
3302
4024
  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(", ")})`;
3303
4025
  }
3304
4026
  return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
3305
4027
  };
3306
- var causeMessage = (agentName, cause) => `sub-agent '${agentName}' could not complete: ${errorMessage2(Cause5.squash(cause))}`;
4028
+ var causeMessage = (agentName, cause) => `sub-agent '${agentName}' could not complete: ${errorMessage2(Cause7.squash(cause))}`;
3307
4029
  var lazyHandled = (toolkit, name, handler) => ({
3308
4030
  tools: toolkit.tools,
3309
4031
  handle: (toolName, params) => toolkit.toHandlers({
3310
4032
  [name]: handler
3311
- }).pipe(Effect25.flatMap((handlers) => toolkit.pipe(Effect25.provide(handlers))), Effect25.flatMap((handled) => handled.handle(toolName, params)))
4033
+ }).pipe(Effect28.flatMap((handlers) => toolkit.pipe(Effect28.provide(handlers))), Effect28.flatMap((handled) => handled.handle(toolName, params)))
3312
4034
  });
3313
- var asTool = Function7.dual((args) => args.length !== 1 || ("name" in args[0]), (agent, options = {}) => {
4035
+ var asTool = Function9.dual((args) => args.length !== 1 || ("name" in args[0]), (agent, options = {}) => {
3314
4036
  const name = options.name ?? agent.name;
3315
4037
  const parameters = options.parameters ?? defaultParameters;
3316
- const success2 = options.success ?? Schema21.String;
4038
+ const success2 = options.success ?? Schema22.String;
3317
4039
  const toPrompt = options.toPrompt ?? ((params) => params.prompt);
3318
4040
  const fromResult = options.fromResult ?? ((result) => result.text);
3319
4041
  const tool = Tool11.make(name, {
3320
4042
  ...options.description === undefined ? {} : { description: options.description },
3321
4043
  parameters,
3322
4044
  success: success2,
3323
- failure: Schema21.String,
4045
+ failure: Schema22.String,
3324
4046
  failureMode: "return"
3325
4047
  });
3326
4048
  const toolkit = Toolkit6.make(tool);
3327
- const handler = (params) => Effect25.gen(function* () {
3328
- const prompt = yield* Effect25.try({ try: () => toPrompt(params), catch: errorMessage2 });
3329
- const result = yield* generate(agent, { prompt }).pipe(Effect25.catchCause((cause) => {
3330
- if (Cause5.hasInterrupts(cause))
3331
- return Effect25.interrupt;
3332
- return Effect25.fail(causeMessage(agent.name, cause));
4049
+ const handler = (params) => Effect28.gen(function* () {
4050
+ const prompt = yield* Effect28.try({ try: () => toPrompt(params), catch: errorMessage2 });
4051
+ const result = yield* generate(agent, { prompt }).pipe(Effect28.catchCause((cause) => {
4052
+ if (Cause7.hasInterrupts(cause))
4053
+ return Effect28.interrupt;
4054
+ return Effect28.fail(causeMessage(agent.name, cause));
3333
4055
  }));
3334
- return yield* Effect25.try({ try: () => fromResult(result), catch: errorMessage2 });
4056
+ return yield* Effect28.try({ try: () => fromResult(result), catch: errorMessage2 });
3335
4057
  });
3336
4058
  return lazyHandled(toolkit, name, handler);
3337
4059
  });
3338
4060
 
3339
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/guardrail.js
4061
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/guardrail.js
3340
4062
  var exports_guardrail = {};
3341
4063
  __export(exports_guardrail, {
3342
4064
  validateInput: () => validateInput,
@@ -3344,8 +4066,8 @@ __export(exports_guardrail, {
3344
4066
  redactInput: () => redactInput,
3345
4067
  filterOutput: () => filterOutput
3346
4068
  });
3347
- import { Effect as Effect26, Option as Option15 } from "effect";
3348
- import { Prompt as Prompt14, Response as Response10 } from "effect/unstable/ai";
4069
+ import { Effect as Effect29, Option as Option18 } from "effect";
4070
+ import { Prompt as Prompt14, Response as Response12 } from "effect/unstable/ai";
3349
4071
  var replacement = (options) => options.replacement ?? "[redacted]";
3350
4072
  var redactText = (text, options) => text.replace(options.pattern, replacement(options));
3351
4073
  var redactUserPart = (part, options) => part.type === "text" ? Prompt14.makePart("text", { text: redactText(part.text, options), options: part.options }) : part;
@@ -3394,19 +4116,19 @@ var redactPromptText = (prompt, options) => Prompt14.fromMessages(prompt.content
3394
4116
  }
3395
4117
  }));
3396
4118
  var validateInput = (check) => ({
3397
- transformPrompt: (prompt, context) => check(prompt, context).pipe(Effect26.flatMap(Option15.match({
3398
- onNone: () => Effect26.succeed(prompt),
3399
- onSome: (reason) => Effect26.fail(AgentError.make({ message: `Input guardrail blocked: ${reason}`, turn: context.turn }))
4119
+ transformPrompt: (prompt, context) => check(prompt, context).pipe(Effect29.flatMap(Option18.match({
4120
+ onNone: () => Effect29.succeed(prompt),
4121
+ onSome: (reason) => Effect29.fail(AgentError.make({ message: `Input guardrail blocked: ${reason}`, turn: context.turn }))
3400
4122
  })))
3401
4123
  });
3402
4124
  var redactInput = (options) => ({
3403
- transformPrompt: (prompt) => Effect26.succeed(redactPromptText(prompt, options))
4125
+ transformPrompt: (prompt) => Effect29.succeed(redactPromptText(prompt, options))
3404
4126
  });
3405
4127
  var redactOutput = (options) => ({
3406
4128
  transformPart: (part) => {
3407
4129
  if (part.type !== "text-delta")
3408
- return Effect26.succeed(Option15.some(part));
3409
- return Effect26.succeed(Option15.some(Response10.makePart("text-delta", {
4130
+ return Effect29.succeed(Option18.some(part));
4131
+ return Effect29.succeed(Option18.some(Response12.makePart("text-delta", {
3410
4132
  id: part.id,
3411
4133
  delta: redactText(part.delta, options),
3412
4134
  metadata: part.metadata
@@ -3414,23 +4136,23 @@ var redactOutput = (options) => ({
3414
4136
  }
3415
4137
  });
3416
4138
  var filterOutput = (keep) => ({
3417
- transformPart: (part, context) => Effect26.succeed(part.type === "tool-call" || keep(part, context) ? Option15.some(part) : Option15.none())
4139
+ transformPart: (part, context) => Effect29.succeed(part.type === "tool-call" || keep(part, context) ? Option18.some(part) : Option18.none())
3418
4140
  });
3419
4141
 
3420
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/handoff.js
4142
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/handoff.js
3421
4143
  var exports_handoff = {};
3422
4144
  __export(exports_handoff, {
3423
4145
  transferTool: () => transferTool,
3424
4146
  supervisor: () => supervisor,
3425
4147
  fanOut: () => fanOut
3426
4148
  });
3427
- import { Array as Array3, Effect as Effect27, Function as Function8, Schema as Schema22 } from "effect";
3428
- import { AiError as AiError6, LanguageModel as LanguageModel8, Prompt as Prompt15, Tool as Tool12, Toolkit as Toolkit7 } from "effect/unstable/ai";
3429
- var defaultTransferParameters = Schema22.Struct({ prompt: Schema22.String });
4149
+ import { Array as Array3, Effect as Effect30, Function as Function10, Schema as Schema23 } from "effect";
4150
+ import { AiError as AiError9, LanguageModel as LanguageModel11, Prompt as Prompt15, Tool as Tool12, Toolkit as Toolkit7 } from "effect/unstable/ai";
4151
+ var defaultTransferParameters = Schema23.Struct({ prompt: Schema23.String });
3430
4152
  var transferName = (agentName) => `transfer_to_${agentName}`;
3431
4153
  var positiveConcurrency = (value) => {
3432
4154
  const concurrency = value ?? 4;
3433
- return Number.isInteger(concurrency) && concurrency > 0 ? Effect27.succeed(concurrency) : Effect27.fail(AgentError.make({
4155
+ return Number.isInteger(concurrency) && concurrency > 0 ? Effect30.succeed(concurrency) : Effect30.fail(AgentError.make({
3434
4156
  message: "Handoff.fanOut concurrency must be a positive integer",
3435
4157
  turn: 0
3436
4158
  }));
@@ -3448,10 +4170,10 @@ var mergeHandled = (toolkits) => {
3448
4170
  tools,
3449
4171
  handle: (name, params) => {
3450
4172
  const entry = entries.get(String(name));
3451
- return entry === undefined ? Effect27.fail(AiError6.make({
4173
+ return entry === undefined ? Effect30.fail(AiError9.make({
3452
4174
  module: "Handoff",
3453
4175
  method: `${String(name)}.handle`,
3454
- reason: AiError6.ToolNotFoundError.make({
4176
+ reason: AiError9.ToolNotFoundError.make({
3455
4177
  toolName: String(name),
3456
4178
  availableTools: Object.keys(tools)
3457
4179
  })
@@ -3460,7 +4182,7 @@ var mergeHandled = (toolkits) => {
3460
4182
  };
3461
4183
  };
3462
4184
  var toolkitFromHandled = (toolkit) => Toolkit7.make(...Object.values(toolkit.tools));
3463
- var transferTool = Function8.dual((args) => args.length !== 1 || ("name" in args[0]), (target, options = {}) => asTool(target, {
4185
+ var transferTool = Function10.dual((args) => args.length !== 1 || ("name" in args[0]), (target, options = {}) => asTool(target, {
3464
4186
  name: options.nameOverride ?? transferName(target.name),
3465
4187
  description: options.description ?? `Transfer to ${target.name}`,
3466
4188
  ...options.parameters === undefined ? {} : { parameters: options.parameters },
@@ -3468,7 +4190,7 @@ var transferTool = Function8.dual((args) => args.length !== 1 || ("name" in args
3468
4190
  ...options.toPrompt === undefined ? {} : { toPrompt: options.toPrompt },
3469
4191
  ...options.fromResult === undefined ? {} : { fromResult: options.fromResult }
3470
4192
  }));
3471
- 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) => {
4193
+ var fanOut = Function10.dual((args) => args.length !== 1 || globalThis.Array.isArray(args[0]), (children, options = {}) => positiveConcurrency(options.concurrency).pipe(Effect30.flatMap((concurrency) => Effect30.forEach(children, (child) => {
3472
4194
  const runOptions = {
3473
4195
  ...child.options,
3474
4196
  prompt: child.prompt
@@ -3497,7 +4219,7 @@ var supervisor = (options) => {
3497
4219
  };
3498
4220
  };
3499
4221
 
3500
- // ../../node_modules/.bun/@batonfx+core@0.9.0/node_modules/@batonfx/core/dist/index.js
3501
- 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";
4222
+ // ../../node_modules/.bun/@batonfx+core@0.11.3+74997d64abff4185/node_modules/@batonfx/core/dist/index.js
4223
+ import { AiError as AiError10, Chat as Chat4, EmbeddingModel, IdGenerator as IdGenerator2, LanguageModel as LanguageModel12, Model as Model3, Prompt as Prompt16, Response as Response13, ResponseIdTracker, Telemetry as Telemetry2, Tokenizer as Tokenizer3, Tool as Tool13, Toolkit as Toolkit8 } from "effect/unstable/ai";
3502
4224
 
3503
- 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 };
4225
+ export { exports_model_telemetry, exports_turn_policy, exports_agent_event, exports_memory, exports_context_overflow, 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, AiError10 as AiError, Chat4 as Chat, EmbeddingModel, IdGenerator2 as IdGenerator, Model3 as Model, Prompt16 as Prompt, Response13 as Response, ResponseIdTracker, Telemetry2 as Telemetry, Tokenizer3 as Tokenizer, Tool13 as Tool, Toolkit8 as Toolkit };