Skip to main content

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