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