1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! `AgentEvent` — streaming events emitted by the Engine.
use crate::interface::model::Usage;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::PathBuf;
mod compact;
pub use compact::{CompactCause, CompactOutcome};
/// How a turn's `usage` divides: its agent's own model calls, the calls made
/// on its side (compaction, memory, web search and extraction), and its
/// delegates' (sub-agents, team members, theirs included).
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
)]
pub struct UsageBreakdown {
pub own: crate::interface::model::Usage,
pub side: crate::interface::model::Usage,
pub delegates: crate::interface::model::Usage,
}
/// How much of the context window a session is using, after a turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct ContextUsage {
/// What the last model call was sent, as the provider counted it:
/// input plus both cache figures.
pub tokens: u64,
/// Where automatic compaction starts.
pub compact_threshold: u64,
/// The model's context window.
pub window: u64,
}
/// A user message that arrived while a turn was running.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueuedUserMessage {
pub message_id: String,
pub content: String,
}
/// Events emitted by the Engine during a turn.
///
/// The upper layer (a CLI, a TUI, the daemon, a desktop host) consumes these
/// via `EventReceiver` and renders/dispatches as appropriate.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AgentEvent {
/// Model text delta (high frequency).
TextDelta { text: String, turn_id: String },
/// Extended-thinking delta (high frequency). Separate from
/// [`AgentEvent::TextDelta`] so hosts can render reasoning distinctly —
/// collapsed, dimmed, or hidden — instead of splicing it into the answer.
/// A host that does not care can ignore this variant; nothing else
/// depends on it being consumed.
ThinkingDelta { text: String, turn_id: String },
/// The model has started writing a tool call. `ToolUse` with the same
/// `id` follows once its arguments are complete.
ToolUseStart {
id: String,
name: String,
turn_id: String,
},
/// A raw fragment of a started tool call's arguments (high frequency).
/// The fragments concatenate to the JSON that `ToolUse` carries parsed.
ToolArgsDelta {
id: String,
partial_json: String,
turn_id: String,
},
/// Model requested a tool call.
ToolUse {
id: String,
name: String,
input: Value,
turn_id: String,
},
/// What a running tool call reported through its `ProgressSender`. At
/// most one a second per call; `dropped` counts the reports merged away
/// since the previous one. Never written to the transcript.
ToolProgress {
tool_use_id: String,
name: String,
message: String,
#[serde(
default,
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_progress_count"
)]
progress: Option<f64>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_progress_count"
)]
total: Option<f64>,
#[serde(default)]
dropped: u64,
turn_id: String,
},
/// Tool execution completed.
ToolResult {
id: String,
name: String,
content: String,
is_error: Option<bool>,
turn_id: String,
/// The files the call wrote. Not in the transcript: the model reads
/// `content`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
file_changes: Vec<crate::interface::tool::FileChange>,
},
/// Permission check requires upper-layer decision.
PermissionPrompt {
prompt_id: String,
tool_name: String,
message: String,
paths: Vec<PathBuf>,
turn_id: String,
/// The `tool_use` block this prompt is about, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
tool_use_id: Option<String>,
/// The background task whose sub-agent asks, when one does. Its
/// question outlives the turn it happened to arrive during.
#[serde(default, skip_serializing_if = "Option::is_none")]
task_id: Option<String>,
/// The sub-agent's session, when a sub-agent asks.
#[serde(default, skip_serializing_if = "Option::is_none")]
agent_session_id: Option<String>,
/// The plugin command whose sub-call this is; `None` for the model's own.
#[serde(default, skip_serializing_if = "Option::is_none")]
origin: Option<crate::interface::elicitation::PromptOrigin>,
/// Whether `permit_always` is among the answers: an "always" that
/// would never be consulted is not offered.
#[serde(default = "logged")]
permit_always: bool,
},
/// The model asked the user something (`AskUserQuestion`) and waits for
/// the host's answer.
QuestionPrompt {
prompt_id: String,
question: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
header: Option<String>,
/// Offered answers; empty means free-form.
#[serde(default)]
options: Vec<crate::interface::elicitation::ElicitOption>,
turn_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
tool_use_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
task_id: Option<String>,
/// The sub-agent's session, when a sub-agent asks.
#[serde(default, skip_serializing_if = "Option::is_none")]
agent_session_id: Option<String>,
},
/// An MCP server asks the user something during a tool call. `message`,
/// `requested_schema` and `url` are the server's; `url_host` is the host
/// part of `url`, for a host that shows where the link goes.
McpElicitationPrompt {
prompt_id: String,
server: String,
/// `form` or `url`.
mode: String,
message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
requested_schema: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
url_host: Option<String>,
/// The engine cut `message` down to the length it puts to a person.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
limited: bool,
turn_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
tool_use_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
task_id: Option<String>,
/// The sub-agent's session, when a sub-agent asks.
#[serde(default, skip_serializing_if = "Option::is_none")]
agent_session_id: Option<String>,
},
/// The ask `prompt_id` — a `PermissionPrompt`, `QuestionPrompt` or
/// `McpElicitationPrompt` — is no longer open: answered, or given up on.
/// Emitted once per ask, by the engine that stopped waiting on it.
PromptResolved {
prompt_id: String,
resolution: PromptResolution,
/// Why it was withdrawn; `None` when it was answered.
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<WithdrawalReason>,
},
/// A tool the host declared was called: the host runs it and answers
/// with `call_id`. Comes after the call's `ToolUse` and before its
/// `ToolResult`.
HostToolCall {
call_id: String,
tool_use_id: String,
name: String,
input: Value,
timeout_ms: u64,
/// As `PermissionPrompt::task_id`.
#[serde(default, skip_serializing_if = "Option::is_none")]
task_id: Option<String>,
/// The sub-agent's session, when a sub-agent made the call.
#[serde(default, skip_serializing_if = "Option::is_none")]
agent_session_id: Option<String>,
/// As `HostCall::cwd`.
#[serde(default)]
cwd: std::path::PathBuf,
/// As `HostCall::depth`.
#[serde(default)]
depth: u32,
/// The connection that provides the tool, when one does.
#[serde(skip)]
host: Option<crate::interface::host_call::HostId>,
},
/// The host call `call_id` is no longer open. Emitted once per call.
HostToolCallResolved {
call_id: String,
resolution: PromptResolution,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<HostCallWithdrawal>,
},
/// A hook `host` registered fires: the host answers it with `call_id`.
/// `input` is the payload a command hook reads on stdin.
HostHookCall {
call_id: String,
hook_event: String,
input: Value,
timeout_ms: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
task_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
agent_session_id: Option<String>,
#[serde(default)]
cwd: std::path::PathBuf,
#[serde(default)]
depth: u32,
#[serde(skip)]
host: Option<crate::interface::host_call::HostId>,
},
/// The hook call `call_id` is no longer open. Emitted once per call.
HostHookCallResolved {
call_id: String,
resolution: PromptResolution,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<HostCallWithdrawal>,
},
/// A turn has started. Every `TurnStart` is followed by exactly one
/// `TurnComplete` or `Error` with the same `turn_id`.
TurnStart { turn_id: String },
/// The turn is about to call the model. `step` counts the turn's model
/// calls from 0.
StepStart { step: u32, turn_id: String },
/// Model call `step` failed after its stream had started, and is sent
/// again as it was once `delay_ms` has passed; a `StepStart` of the same
/// `step` follows. `attempt` counts these retries of the call from 1;
/// `reason` is the failure.
ModelRetry {
step: u32,
attempt: u32,
delay_ms: u64,
reason: String,
turn_id: String,
},
/// The model call `step` has finished and its reply — plus the results of
/// the tools it asked for — is in the transcript.
StepEnd {
step: u32,
stop_reason: String,
/// What this one call cost.
usage: Usage,
tool_calls: u32,
turn_id: String,
/// How many messages the transcript holds now — the same position
/// `session.history` pages by. Everything this step produced is on
/// disk below it.
#[serde(default)]
seq: u64,
/// Where a routed call went; `None` when nothing routed it.
#[serde(default, skip_serializing_if = "Option::is_none")]
served: Option<crate::provider::Destination>,
},
/// A turn has completed.
TurnComplete {
stop_reason: String,
api_calls: u32,
tool_calls: u32,
/// Every call of the turn as it ends: its own, its side calls' and
/// its delegates', split in `usage_breakdown`. A background
/// delegate's calls after the turn ended are not in it.
usage: Usage,
#[serde(default)]
usage_breakdown: UsageBreakdown,
turn_id: String,
/// Why the turn was stopped, when whatever stopped it said so — a
/// hook's `message`, for instance.
#[serde(default, skip_serializing_if = "Option::is_none")]
message: Option<String>,
/// What the turn's last model call reported. `usage` is the sum.
#[serde(default)]
last_call_usage: Usage,
/// How full the context is. `None` when the turn made no model call.
#[serde(default, skip_serializing_if = "Option::is_none")]
context: Option<ContextUsage>,
/// What the model last handed to `StructuredOutput` in this turn —
/// validated against the host's schema when the session has one.
#[serde(default, skip_serializing_if = "Option::is_none")]
structured_output: Option<Value>,
/// The transcript position the turn ended at; see `StepEnd::seq`.
#[serde(default)]
seq: u64,
/// A model call of this turn ended without the provider marking the
/// end of its reply ([`crate::interface::model::ModelEvent::Truncated`]),
/// so the reply may be cut short.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
truncated: bool,
/// Everything the turn did is in the session's log. `false` when a
/// write failed: the session holds the only complete copy until a
/// later write catches the log up.
#[serde(default = "logged")]
persisted: bool,
},
/// A message the user sent while this turn was running is now part of
/// the conversation; the model reads it on its next call.
UserMessageDelivered {
message_id: String,
content: String,
turn_id: String,
},
/// A message the user sent while this turn was running was refused on its
/// way in (`UserPromptSubmit` blocked it). It is not in the transcript and
/// the turn goes on; sending it again would be refused again.
UserMessageRefused {
message_id: String,
content: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
message: Option<String>,
turn_id: String,
},
/// Messages the user sent while this turn was running that the model
/// never got to read — the turn ended (interrupted, stopped by a policy
/// or an error) before the next point they could be added. They are not
/// in the transcript; whether to send them again is the host's call.
UserMessagesReturned {
messages: Vec<QueuedUserMessage>,
turn_id: String,
},
/// System initialization completed.
SystemInit {
scene: String,
tools: Vec<ToolInfo>,
mcp_servers: Vec<String>,
},
/// System notification.
System { message: String },
/// A compaction that rewrites the history is about to run, before its
/// `PreCompact` hooks. It ends in exactly one `CompactAction` (it went
/// through) or one `CompactEnded` (it did not). Trims send neither.
CompactStarted {
turn_id: String,
trigger: CompactCause,
/// The compactor's estimate of the history's size now.
tokens_before: usize,
/// Set only when the strategy is already fixed.
#[serde(default, skip_serializing_if = "Option::is_none")]
strategy: Option<String>,
},
/// The compaction a `CompactStarted` announced left the history as it was.
CompactEnded {
turn_id: String,
outcome: CompactOutcome,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
/// The history was compacted or trimmed.
CompactAction {
strategy: String,
messages_before: usize,
messages_after: usize,
turn_id: String,
/// Number of rounds dropped by the Snip strategy (if applicable).
dropped_rounds: Option<usize>,
/// Number of messages in dropped rounds (if applicable).
dropped_messages: Option<usize>,
/// Estimated tokens saved by the compaction (if applicable).
estimated_tokens_saved: Option<usize>,
/// The compactor's estimate of the history's size before and after.
#[serde(default)]
tokens_before: usize,
#[serde(default)]
tokens_after: usize,
/// The history was trimmed (old tool results blanked), not compacted:
/// no message was dropped and no `PreCompact`/`PostCompact` ran.
#[serde(default)]
trim: bool,
},
/// Session was changed (via set_session_id).
SessionChanged { session_id: String },
/// Session was persisted to disk.
SessionPersisted { session_id: String },
/// The skill catalog changed on disk — emitted at the top of the turn
/// that observed it, right after the reload.
///
/// Skill-derived slash commands resolve through the live catalog, so a
/// host that caches a command list (a completion popup, a command
/// palette) has no other way to learn its copy went stale short of
/// polling. Names are skill names, i.e. slash commands without the
/// leading `/`.
///
/// Content edits to an existing skill are not reported: the reload is
/// detected by set difference over the catalog, which sees a rename as
/// one removal plus one addition and an in-place body edit as nothing at
/// all. That is the honest scope — a consumer that cares about bodies
/// should re-read on any change rather than trust this to fire.
SkillsChanged {
added: Vec<String>,
removed: Vec<String>,
turn_id: String,
},
/// The model asked for the user's attention with `PushNotification`.
Notification {
message: String,
/// `"proactive"` when the model sent it unprompted; `None` otherwise.
status: Option<String>,
turn_id: String,
},
/// A model call went to a different provider than the session's call
/// before it: `from` could not take it, or `to` can again.
ProviderSwitched(crate::provider::ProviderSwitch),
/// A sub-agent was spawned.
AgentSpawned {
agent_id: String,
parent_turn: u32,
turn_id: String,
},
/// A sub-agent completed.
AgentCompleted {
agent_id: String,
outcome: String,
turn_id: String,
},
/// An event emitted *inside* a spawned sub-agent, re-emitted on the
/// parent session's channel so the host (IDE plugin / CLI) can render
/// sub-agent activity live instead of staring at a long pause.
///
/// This is purely additive: the sub-agent's text is still collected and
/// returned as the `Agent` tool's result for the model to read. Hosts
/// that don't understand this variant can ignore it and behave exactly
/// as before.
///
/// Attribution: `agent_label` is stable for the whole lifetime of one
/// sub-agent run, so a host can group every forwarded event under one
/// collapsible node. `parent_turn` is the parent's turn *number*
/// (`ToolContext::turn_no`); the parent's turn *id* is deliberately not
/// carried here because `runtime::turn` does not thread it into
/// `ToolContext` — transports that need it already know it from the
/// enclosing turn (see the daemon's `run_turn` stream frames).
SubagentProgress {
/// Stable per-run label, e.g. `"explore#3f2a1b7c"`.
agent_label: String,
/// The sub-agent's own session id.
agent_session_id: String,
/// Named agent type, when the spawn selected one.
agent_type: Option<String>,
/// Parent session id, when the spawn site knew it (`""` otherwise).
parent_session_id: String,
/// Parent turn number, `0` when unknown (same caveat as above).
parent_turn: u32,
/// The parent's `Agent` tool call this sub-agent is running for.
#[serde(default, skip_serializing_if = "Option::is_none")]
parent_tool_use_id: Option<String>,
/// The parent session's task this sub-agent runs as.
#[serde(default, skip_serializing_if = "Option::is_none")]
task_id: Option<String>,
/// The forwarded sub-agent event. Boxed so `AgentEvent` stays small.
event: Box<AgentEvent>,
},
/// Team orchestration progress, emitted as each stage of a `TeamCreate`
/// run starts and finishes — so a large team streams incremental
/// progress instead of going silent until the whole scratchpad is
/// returned as one tool result.
TeamProgress {
/// Team name as given to `TeamCreate`.
team: String,
/// Generated team id (also the `<project dir>/state/teams/<id>/` directory name).
team_id: String,
/// Stage name.
stage: String,
/// 0-based stage index.
stage_index: usize,
/// Total number of stages in this team run.
stage_count: usize,
/// Where this stage is in its lifecycle.
status: TeamStageStatus,
/// Labels of the members in this stage.
members: Vec<String>,
/// Labels of members whose result was an error (only meaningful for
/// `Completed`).
failed: Vec<String>,
},
/// The turn ended in failure.
Error {
failure: TurnFailure,
turn_id: String,
/// As `TurnComplete::persisted`: what the turn got to — the user's
/// message at least — is in the session's log.
#[serde(default = "logged")]
persisted: bool,
},
}
/// How an ask ended (`AgentEvent::PromptResolved`).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PromptResolution {
/// An answer reached the engine and was taken.
Answered,
/// The engine stopped waiting with no answer: the prompt timed out, the
/// turn asking it was cancelled or ended, or the session is closing.
Withdrawn,
}
/// Why the engine stopped waiting on an ask with no answer.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum WithdrawalReason {
/// Nobody answered within the prompt timeout.
TimedOut,
/// The turn asking it was cancelled or ended, or the session is closing.
Cancelled,
}
/// Why the engine stopped waiting on a host call with no answer.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HostCallWithdrawal {
TimedOut,
Cancelled,
/// Nobody watched the session when the call was made.
NoHost,
/// Everyone watching the session went away before anyone answered.
HostGone,
}
impl From<WithdrawalReason> for HostCallWithdrawal {
fn from(reason: WithdrawalReason) -> Self {
match reason {
WithdrawalReason::TimedOut => Self::TimedOut,
WithdrawalReason::Cancelled => Self::Cancelled,
}
}
}
fn logged() -> bool {
true
}
/// How a turn failed, in the terms a host decides on: whether to send it
/// again, when, and whether doing so repeats something.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum FailureKind {
RateLimited,
Overloaded,
/// The provider could not be reached or failed on its side; the request
/// itself was fine.
ModelUnavailable,
ContextTooLong,
/// The provider refused the request as malformed, or for a model or a
/// feature it does not serve.
ModelRejected,
Auth,
/// The provider has no credential configured; the request was not sent.
NoCredentials,
Billing,
EgressDenied,
/// The provider failed in a way sending again will not fix.
ModelError,
SessionClosed,
EngineStopped,
/// The engine did not take or answer a request.
EngineUnreachable,
PersistFailed,
Internal,
/// No provider in the order could take the call.
ProvidersUnavailable,
}
impl FailureKind {
pub fn as_str(self) -> &'static str {
match self {
Self::RateLimited => "rate_limited",
Self::Overloaded => "overloaded",
Self::ModelUnavailable => "model_unavailable",
Self::ContextTooLong => "context_too_long",
Self::ModelRejected => "model_rejected",
Self::Auth => "auth",
Self::NoCredentials => "no_credentials",
Self::Billing => "billing",
Self::EgressDenied => "egress_denied",
Self::ModelError => "model_error",
Self::SessionClosed => "session_closed",
Self::EngineStopped => "engine_stopped",
Self::EngineUnreachable => "engine_unreachable",
Self::PersistFailed => "persist_failed",
Self::Internal => "internal",
Self::ProvidersUnavailable => "providers_unavailable",
}
}
/// Whether the same request, sent again later, may well succeed.
pub fn retryable(self) -> bool {
matches!(
self,
Self::RateLimited
| Self::Overloaded
| Self::ModelUnavailable
| Self::EngineStopped
| Self::EngineUnreachable
| Self::PersistFailed
| Self::ProvidersUnavailable
)
}
}
impl From<crate::interface::model::ModelErrorKind> for FailureKind {
fn from(kind: crate::interface::model::ModelErrorKind) -> Self {
use crate::interface::model::ModelErrorKind as M;
match kind {
M::RateLimited => Self::RateLimited,
M::Overloaded => Self::Overloaded,
M::Unavailable | M::Transport | M::Timeout | M::StreamInterrupted => {
Self::ModelUnavailable
}
M::ContextTooLong => Self::ContextTooLong,
M::InvalidRequest | M::NotFound | M::Unsupported => Self::ModelRejected,
M::Auth => Self::Auth,
M::NoCredentials => Self::NoCredentials,
M::Billing => Self::Billing,
M::Denied => Self::EgressDenied,
M::ServerError | M::Protocol | M::Cancelled | M::NotRecorded => Self::ModelError,
M::ProvidersUnavailable => Self::ProvidersUnavailable,
}
}
}
impl std::fmt::Display for FailureKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// A turn's failure, as the engine, the pool and the wire all carry it.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct TurnFailure {
pub kind: FailureKind,
pub retryable: bool,
/// How long the provider asked to be left alone, when it said — also
/// past what the client's backoff was willing to wait.
pub retry_after_ms: Option<u64>,
/// A tool already ran in this turn, so sending it again repeats that.
pub side_effects: bool,
pub message: String,
}
impl TurnFailure {
pub fn new(kind: FailureKind, message: impl Into<String>) -> Self {
Self {
kind,
retryable: kind.retryable(),
retry_after_ms: None,
side_effects: false,
message: message.into(),
}
}
pub fn model(error: &crate::interface::model::ModelError, side_effects: bool) -> Self {
Self {
retry_after_ms: error
.retry_after
.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX)),
side_effects,
..Self::new(error.kind.into(), error.to_string())
}
}
pub fn with_side_effects(mut self, side_effects: bool) -> Self {
self.side_effects = side_effects;
self
}
}
impl std::fmt::Display for TurnFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.kind, self.message)
}
}
impl std::error::Error for TurnFailure {}
/// Lifecycle point a [`AgentEvent::TeamProgress`] event reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TeamStageStatus {
/// Every member of the stage has been dispatched.
Started,
/// Every member of the stage has finished (successfully or not).
Completed,
}
/// Summary info for a registered tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolInfo {
pub name: String,
pub description: String,
}
/// A progress figure as it goes on the wire: whole numbers as JSON integers
/// (`42`, not `42.0`) so hosts can read line and byte counts as integers;
/// only a fractional figure keeps its fraction.
pub fn progress_count_json(value: f64) -> Value {
const EXACT: f64 = 9_007_199_254_740_992.0;
if value.fract() == 0.0 && value.abs() <= EXACT {
if value >= 0.0 {
return Value::from(value as u64);
}
return Value::from(value as i64);
}
Value::from(value)
}
fn serialize_progress_count<S: serde::Serializer>(
value: &Option<f64>,
serializer: S,
) -> Result<S::Ok, S::Error> {
match value {
Some(v) => progress_count_json(*v).serialize(serializer),
None => serializer.serialize_none(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::interface::model::{ModelError, ModelErrorKind};
#[test]
fn a_model_failure_is_retryable_exactly_when_its_kind_is_transient() {
use ModelErrorKind::*;
for kind in [
RateLimited,
Overloaded,
Unavailable,
Transport,
Timeout,
StreamInterrupted,
ContextTooLong,
InvalidRequest,
NotFound,
Auth,
Billing,
Denied,
ServerError,
Protocol,
Cancelled,
Unsupported,
NotRecorded,
] {
let failure = TurnFailure::model(&ModelError::new(kind, "m"), false);
assert_eq!(failure.retryable, kind.transient(), "{kind}");
}
}
#[test]
fn a_hint_past_what_the_client_waits_for_still_reaches_the_failure() {
let error =
ModelError::rate_limited().with_retry_after(Some(std::time::Duration::from_secs(120)));
let failure = TurnFailure::model(&error, true);
assert_eq!(failure.kind, FailureKind::RateLimited);
assert_eq!(failure.retry_after_ms, Some(120_000));
assert!(failure.side_effects);
assert!(failure.to_string().starts_with("rate_limited: "));
}
}