Skip to main content

ante_protocol_shape/
msg.rs

1use std::path::PathBuf;
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Deserializer, Serialize};
5
6use crate::id::Id;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct EventMsg {
10    pub timestamp: DateTime<Utc>,
11    pub id: Id,
12    pub event: Evt,
13    #[serde(skip_serializing_if = "Option::is_none")]
14    pub parent: Option<Id>,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct OpMsg {
19    pub op: Op,
20    pub id: Id,
21}
22
23/// `op` stamped with a fresh op id.
24pub fn op_msg(op: Op) -> OpMsg {
25    OpMsg { op, id: Id::op() }
26}
27
28/// `event` stamped with a fresh event id and the current time, correlated
29/// to the op it answers (`parent`), if any.
30pub fn event_msg(event: Evt, parent: Option<Id>) -> EventMsg {
31    EventMsg { timestamp: Utc::now(), id: Id::evt(), event, parent }
32}
33
34#[allow(clippy::large_enum_variant)]
35#[derive(Debug, Clone, Deserialize, Serialize)]
36pub enum Op {
37    /// Start a session from the request, replacing any running one: set
38    /// fields are pinned, unset fields resolve to the host's defaults. There
39    /// is no separate restart op — a client keeps the request it sent and
40    /// re-sends it (optionally `patched`) for `/clear` semantics.
41    StartSession(SessionRequest),
42    UpdateSession(SessionUpdate),
43    Interrupt,
44    UserInput(String),
45    ShellInput(String),
46    Steer(String),
47    ApprovalResponse {
48        turn_id: Id,
49        responses: Vec<ToolDecision>,
50    },
51    /// Resolve the active turn's pending question pause
52    /// ([`TurnPauseReason::Question`]). `turn_id` must be the paused turn and
53    /// `tool_use_id` must echo the pause's; stale or mismatched responses are
54    /// dropped. `reply` is what the user did: answered, skipped, or asked to
55    /// talk instead ([`QuestionReply`]).
56    QuestionResponse {
57        turn_id: Id,
58        tool_use_id: String,
59        reply: QuestionReply,
60    },
61    SlashCommand {
62        name: String,
63        args: String,
64    },
65    /// Continue a saved conversation from its persisted snapshot: what the
66    /// host persisted is restored — the system instructions included — and
67    /// everything the snapshot does not pin resolves like a fresh session
68    /// from the host's current defaults, with the requested tool filters.
69    /// `unattended` is the resuming client's declaration, with the meaning
70    /// of `SessionRequest::unattended`; absent means false.
71    ResumeSession {
72        session_id: Id,
73        #[serde(default)]
74        unattended: bool,
75        /// Tool selection for this resume, with the same precedence as
76        /// `SessionRequest::tools`; absent uses current settings.
77        #[serde(default, skip_serializing_if = "Option::is_none")]
78        tools: Option<Vec<String>>,
79        /// Tools added to the base set for this resume.
80        #[serde(default, skip_serializing_if = "Option::is_none")]
81        include_tools: Option<Vec<String>>,
82        /// Tools removed for this resume; wins over base and included tools.
83        #[serde(default, skip_serializing_if = "Option::is_none")]
84        exclude_tools: Option<Vec<String>>,
85        /// A credential to pin for this resume, with the meaning of
86        /// `SessionRequest::credential`; absent uses configured precedence.
87        #[serde(default, skip_serializing_if = "Option::is_none")]
88        credential: Option<String>,
89    },
90    RegisterLocalProvider {
91        port: u16,
92        model: Option<ModelSpec>,
93    },
94    RestoreLocalProvider,
95    /// Manually trigger conversation compaction on the active session.
96    /// `instructions` optionally steer the replacement summary — what to
97    /// emphasize or preserve. Ignored when the reduction needs no summary.
98    Compact {
99        #[serde(default, skip_serializing_if = "Option::is_none")]
100        instructions: Option<String>,
101    },
102    /// Request a per-category breakdown of the active session's context-window
103    /// occupancy. Answered with [`Evt::ContextReport`].
104    ContextReport,
105    /// Rewind the active session's conversation — its model context and its
106    /// visible history — to input `to`: how it stood just before that input
107    /// was applied, the input and everything after it gone. `to` is a turn
108    /// id as [`Evt::TurnStart`] reports it: for a user's input, the id of
109    /// the op that submitted it. Answered with [`Evt::SessionRewound`];
110    /// refused with an [`Evt::Error`], changing nothing, while a turn runs
111    /// or is queued, a goal is set, or background jobs run, or when `to`
112    /// cannot be restored: a turn from before the session was resumed, or
113    /// one whose earlier conversation a compaction or provider switch has
114    /// since rewritten. Starts no work and undoes nothing outside the
115    /// conversation.
116    RewindSession {
117        to: Id,
118    },
119    /// Fork the active session's conversation into a new saved session: the
120    /// conversation at input `at`, as [`Op::RewindSession`] to it would leave
121    /// it, or the current conversation when `at` is absent. The active
122    /// session must be idle and is left unchanged; the new session is not
123    /// started. Answered with [`Evt::SessionForked`], or with an
124    /// [`Evt::Error`] that creates nothing.
125    ForkSession {
126        #[serde(default, skip_serializing_if = "Option::is_none")]
127        at: Option<Id>,
128    },
129    /// Set, clear, or report a goal-driven execution loop on the active
130    /// session. A set goal keeps the session working — re-running turns and
131    /// judging the condition after each one — until it is met, judged
132    /// unreachable, or cleared.
133    Goal(GoalCommand),
134    /// Request an ad-hoc "thinking phrase" prediction for the in-progress
135    /// draft. Runs off the conversation critical path on a cheap model and
136    /// answers with `Evt::Ambient`. `req_id` lets the client discard stale
137    /// results when a newer request supersedes this one.
138    AmbientPhrase {
139        draft: String,
140        req_id: u64,
141    },
142    /// Request an ad-hoc next-prompt suggestion from the last exchange, shown as
143    /// input ghost text. Like [`Op::AmbientPhrase`] it runs off the critical
144    /// path on a cheap model and answers with `Evt::Ambient`. The client carries
145    /// the context (so this stays a client-only feature — headless never fires
146    /// it) and a monotonic `req_id` to drop stale results.
147    AmbientSuggestion {
148        recent_user: String,
149        recent_agent: String,
150        req_id: u64,
151    },
152    Shutdown,
153}
154
155/// A `/goal` sub-command carried by [`Op::Goal`].
156#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
157pub enum GoalCommand {
158    /// Set (or replace) the active goal condition.
159    Set(String),
160    /// Clear the active goal, stopping the loop.
161    Clear,
162    /// Report the current goal status.
163    Status,
164}
165
166/// Which ambient feature produced an [`Evt::Ambient`]. Both run off the main
167/// conversation on a cheap model; they differ in trigger, prompt, and sink.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
169pub enum AmbientKind {
170    /// Predicted phrase for the in-progress draft, shown in the status spinner.
171    ThinkingPhrase,
172    /// Suggested next prompt from the conversation so far, shown as input ghost text.
173    PromptSuggestion,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub enum Evt {
178    SessionStart(Box<SessionInfo>),
179    SessionUpdated(Box<SessionInfo>),
180    ExtensionRefreshed(Box<ExtensionRefreshed>),
181    /// The session span closed. Mirrors `TurnEnd`: carries the span's
182    /// identity, why it ended, and its final usage accounting.
183    SessionEnd {
184        session_id: Id,
185        reason: SessionEndReason,
186        usage: Usage,
187    },
188    UserInput(String),
189    ShellOutput {
190        command: String,
191        stdout: String,
192        stderr: String,
193        exit_code: Option<i32>,
194    },
195    AgentMessage(String),
196    Thinking(String),
197    MessageDelta(String),
198    ThinkingDelta(String),
199    Info(String),
200    /// Open a grouped Info entry with `header`. Subsequent
201    /// `InfoBlockAppend` events with the same `id` are rendered as
202    /// tree-indented child lines under it. Use for multi-step background
203    /// notifications (e.g. MCP warm-up) that should visually cluster.
204    ///
205    /// When `loading` is true the renderer appends an animated `.`/`../...`
206    /// suffix to the header until the first `InfoBlockAppend` arrives,
207    /// signalling that background work is still in flight.
208    InfoBlockStart {
209        id: String,
210        header: String,
211        #[serde(default)]
212        loading: bool,
213    },
214    /// Append a child detail line to the `InfoBlockStart` with the same `id`.
215    /// Drops silently if the matching block isn't present.
216    InfoBlockAppend {
217        id: String,
218        detail: String,
219    },
220    Error(String),
221    ToolStart(ToolUse),
222    ToolUpdate(ToolUpdate),
223    ToolEnd(ToolEnd),
224    /// Work a tool call handed off ended: a Bash job that outlived its wait
225    /// window. `tool_use_id` is the call whose `ToolEnd` reported the hand-off.
226    /// `exit_code` is the process exit code, `128 + signal` for a signal
227    /// death, absent only when the exit could not be observed.
228    TaskEnd {
229        tool_use_id: String,
230        exit_code: Option<i32>,
231    },
232    CompactStart,
233    /// Compaction finished. A present `summary` is the text that replaced
234    /// the compacted history and carries forward as the session's context.
235    /// `None` means no history replacement was committed.
236    CompactEnd {
237        #[serde(default)]
238        summary: Option<String>,
239    },
240    TurnStart {
241        turn_id: Id,
242    },
243    TurnPause {
244        turn_id: Id,
245        reason: TurnPauseReason,
246    },
247    /// The turn resumed after a `TurnPause` (e.g. the approval was answered
248    /// or a steer arrived). Closes the pause bracket so clients never have to
249    /// infer resumption from the next tool event.
250    TurnResume {
251        turn_id: Id,
252    },
253    TurnEnd {
254        turn_id: Id,
255        status: TurnEndStatus,
256        /// Number of turn-loop steps attempted before the turn ended.
257        #[serde(default)]
258        steps: usize,
259    },
260    UsageUpdate {
261        usage: Usage,
262        /// Context-window occupancy for the root session. `None` carries no
263        /// context update, including for subagent usage or an unverified model
264        /// limit. Clients retain the last snapshot until the session or model changes.
265        #[serde(default, skip_serializing_if = "Option::is_none")]
266        context: Option<ContextWindow>,
267    },
268    /// Answer to [`Op::ContextReport`]: a per-category breakdown of the
269    /// session's context-window occupancy at the time of the request.
270    ContextReport(ContextBreakdown),
271    /// Answer to [`Op::RewindSession`]: the session's conversation, and the
272    /// history a resume of it replays, now stand as they did just before
273    /// input `to`. Never part of a resume replay.
274    SessionRewound {
275        to: Id,
276    },
277    /// Answer to [`Op::ForkSession`]: session `session_id` was forked from
278    /// session `forked_from`: from its conversation at input `at`, or from
279    /// its current conversation when absent. It is saved, not started;
280    /// resuming it switches to it.
281    SessionForked {
282        forked_from: Id,
283        session_id: Id,
284        #[serde(default, skip_serializing_if = "Option::is_none")]
285        at: Option<Id>,
286    },
287    /// An ephemeral ambient hint produced off the main conversation (a predicted
288    /// "thinking phrase" for the draft, or a suggested next prompt — see
289    /// [`AmbientKind`]). Never persisted to the event log. `req_id` lets clients
290    /// drop superseded results.
291    Ambient {
292        kind: AmbientKind,
293        req_id: u64,
294        text: String,
295    },
296    Goodbye,
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
300pub enum TurnPauseReason {
301    Approval {
302        tools: Vec<ToolUse>,
303        message: String,
304    },
305    /// The model asked the user structured questions via the tool call
306    /// identified by `tool_use_id`. Unlike `Approval`, this pause may coexist
307    /// with sibling tools still running: `ToolStart`/`ToolEnd` events can
308    /// arrive while it is pending. Each question's first option is the
309    /// model's recommendation; clients resolve the pause with
310    /// [`Op::QuestionResponse`], and no option is ever chosen on the user's
311    /// behalf. Clients must clear question UI on `TurnResume` *and* on
312    /// `TurnEnd` — a cancelled turn may end without a resume.
313    Question {
314        tool_use_id: String,
315        questions: Vec<QuestionSpec>,
316    },
317}
318
319/// One question in a [`TurnPauseReason::Question`] pause.
320#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
321pub struct QuestionSpec {
322    /// Short label for this question, suitable for a chip or tab.
323    pub header: String,
324    /// The full question text.
325    pub question: String,
326    /// Whether the user may select more than one option.
327    #[serde(default)]
328    pub multi_select: bool,
329    /// The offered choices. A free-text "Other" affordance is the client's
330    /// to add; it is never part of this list.
331    pub options: Vec<QuestionOption>,
332}
333
334/// One selectable option of a [`QuestionSpec`].
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336pub struct QuestionOption {
337    pub label: String,
338    /// What choosing this option means.
339    pub description: String,
340    /// Optional preview content (e.g. a code snippet or mockup) clients may
341    /// render alongside the option.
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub preview: Option<String>,
344}
345
346/// One question's answer in [`Op::QuestionResponse`].
347#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
348pub struct QuestionAnswer {
349    /// Selected option labels. Multi-select answers carry one entry per
350    /// selected option; empty when the user only typed free text.
351    pub selected: Vec<String>,
352    /// Free text the user typed: a note attached to the selection, or —
353    /// when `selected` is empty — the answer itself.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub note: Option<String>,
356}
357
358/// What the user did with a [`TurnPauseReason::Question`] pause.
359#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
360pub enum QuestionReply {
361    /// One entry per question, in question order. An entry with nothing
362    /// selected and no note leaves that question unanswered.
363    Answered(Vec<QuestionAnswer>),
364    /// The prompt was closed without answers.
365    Dismissed,
366    /// The user wants to talk before choosing. `message` carries their words
367    /// when the client collected any; absent, the model is expected to ask
368    /// what they want to clarify.
369    Discuss {
370        #[serde(default, skip_serializing_if = "Option::is_none")]
371        message: Option<String>,
372    },
373}
374
375#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
376pub enum SessionEndReason {
377    /// The session was replaced by a new or resumed session.
378    Replaced,
379    /// The connection is closing: the client sent `Shutdown` or went away.
380    Shutdown,
381}
382
383#[derive(Debug, Clone, Serialize, Deserialize)]
384pub enum TurnEndStatus {
385    Completed,
386    Interrupted {
387        #[serde(skip_serializing_if = "Option::is_none")]
388        reason: Option<String>,
389    },
390    Error {
391        /// Stable machine-readable LLM error kind. Absent for non-LLM errors
392        /// and events produced by older daemons. Notably `"oauth"` means the
393        /// provider's sign-in is missing, expired, or revoked, and only
394        /// re-authenticating can recover; clients may offer their sign-in
395        /// flow for the session's provider.
396        #[serde(default, skip_serializing_if = "Option::is_none")]
397        kind: Option<String>,
398        /// One-line summary. For a classified LLM failure this is the semantic
399        /// error kind, e.g. "rate limited"; otherwise the top of the error chain.
400        headline: String,
401        /// Expanded cause shown as indented child rows beneath the headline,
402        /// e.g. ["HTTP 400 Bad Request", "<server-provided message>"]. May be
403        /// empty when there is nothing useful to add.
404        details: Vec<String>,
405    },
406}
407
408#[derive(Debug, Clone, Serialize, Deserialize)]
409pub struct ToolUpdate {
410    pub tool_use_id: String,
411    pub seq: u64,
412    pub message: String,
413}
414
415#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
416pub enum ToolEndStatus {
417    Completed,
418    Cancelled,
419    Denied,
420    Failed,
421}
422
423impl ToolEndStatus {
424    /// Whether this terminal status represents an error result. Mirrors the
425    /// LLM-facing `ToolResult::is_error`: anything but a clean completion
426    /// (failure, denial, cancellation) is an error.
427    pub fn is_error(self) -> bool {
428        !matches!(self, ToolEndStatus::Completed)
429    }
430}
431
432#[derive(Debug, Clone, Serialize, Deserialize)]
433pub struct ToolEnd {
434    pub tool_use_id: String,
435    /// Tool name, including when execution never started. Empty in older events.
436    #[serde(default)]
437    pub tool_name: String,
438    pub status: ToolEndStatus,
439    pub result_json: serde_json::Value,
440}
441
442#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
443pub enum ReviewDecision {
444    Accept,
445    Deny,
446    AcceptForSession,
447    /// Approve and persist an allow rule to settings.json so the same call is
448    /// auto-approved across future sessions ("always allow").
449    AcceptAlways,
450}
451
452/// A decision for one requested tool call.
453#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
454pub struct ToolDecision {
455    pub tool_use_id: String,
456    pub decision: ReviewDecision,
457    /// Optional user feedback returned to the agent with a denial.
458    #[serde(default, skip_serializing_if = "Option::is_none")]
459    pub message: Option<String>,
460}
461
462#[derive(Debug, Clone, Serialize, Deserialize)]
463pub struct SkillMetadata {
464    pub name: String,
465    pub description: Option<String>,
466    pub scope: Scope,
467    pub argument_hint: Option<String>,
468}
469
470#[derive(Debug, Clone, Serialize, Deserialize)]
471pub struct SubagentMetadata {
472    pub name: String,
473    pub description: String,
474    pub scope: Scope,
475}
476
477/// The resolved provider and its explicit credential choice.
478/// The endpoint includes environment overrides. Model lists are published by
479/// `ante catalog`; unknown fields are ignored.
480#[derive(Debug, Clone, Default, Serialize, Deserialize)]
481pub struct ProviderSpec {
482    #[serde(alias = "name")]
483    pub id: String,
484    pub display_name: String,
485    pub base_url: String,
486    /// This provider's explicit credential choice, as a qualified reference
487    /// such as `oauth:antix/work`, never a token. Absent uses configured precedence.
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub credential: Option<String>,
490}
491
492/// A session's announced state: its identity and mutable settings
493/// (`SessionStart`, `SessionUpdated`) plus the capabilities it was equipped
494/// with, which are fixed for the session's lifetime.
495#[derive(Debug, Clone, Default, Serialize, Deserialize)]
496pub struct SessionInfo {
497    pub model: ModelSpec,
498    pub provider: ProviderSpec,
499    pub session_id: Id,
500    pub cwd: PathBuf,
501    pub permission_mode: PermissionMode,
502    /// The skills the user can invoke in this session. Empty when absent.
503    #[serde(default)]
504    pub skills: Vec<SkillMetadata>,
505    /// The subagents this session can delegate to. Empty when absent.
506    #[serde(default)]
507    pub subagents: Vec<SubagentMetadata>,
508    /// The session's title, when one is set: a display name chosen by the
509    /// user (or the client), never derived from the conversation.
510    #[serde(default, skip_serializing_if = "Option::is_none")]
511    pub title: Option<String>,
512    /// Set when the session was forked from another (see
513    /// [`Op::ForkSession`]): the session it was forked from.
514    #[serde(default, skip_serializing_if = "Option::is_none")]
515    pub forked_from: Option<Id>,
516}
517
518/// Partial update to a live session's mutable state. Each field is optional so
519/// a caller patches only what changed; absent fields are left untouched.
520/// Catalog-dependent fields are resolved before the update takes effect.
521#[derive(Debug, Clone, Default, Serialize, Deserialize)]
522pub struct SessionUpdate {
523    /// Provider change, taking effect on the next turn: the conversation
524    /// continues on the named catalog provider, keeping the session id,
525    /// messages, title and permission state. `model` then names a model on that
526    /// provider; absent, the provider's default. Naming the current provider is
527    /// not a switch. Refused whole, answered with `Error` instead of
528    /// `SessionUpdated`, for an unknown provider id or for another provider
529    /// while a turn is in flight; never re-routed.
530    #[serde(default, skip_serializing_if = "Option::is_none")]
531    pub provider: Option<String>,
532    /// Pin a qualified credential reference on the resulting provider for this
533    /// session. Refused if it is outside that provider's pool, unavailable, or
534    /// a turn is running. Absent keeps the current provider's choice; another
535    /// provider starts from configured precedence.
536    #[serde(default, skip_serializing_if = "Option::is_none")]
537    pub credential: Option<String>,
538    /// Model change, taking effect on the next turn. The spec carries the
539    /// whole request, `effort` included: a set `effort` overrides the
540    /// catalog default; unset fields resolve from the catalog. Resolved on
541    /// the session's provider — the one `provider` names when both are set.
542    #[serde(default, skip_serializing_if = "Option::is_none")]
543    pub model: Option<ModelSpec>,
544    /// Permission mode change, taking effect on the next turn without
545    /// aborting an in-flight one.
546    #[serde(default, skip_serializing_if = "Option::is_none")]
547    pub permission_mode: Option<PermissionMode>,
548    /// Rename the session. The text is trimmed; an empty (or whitespace-only)
549    /// text clears the title.
550    #[serde(default, skip_serializing_if = "Option::is_none")]
551    pub title: Option<String>,
552}
553
554/// The session's MCP servers and their tools, sent for `session_id` as the
555/// servers come online. `skills` and `subagents` repeat the lists the
556/// session's `SessionStart` announced.
557#[derive(Debug, Clone, Serialize, Deserialize)]
558pub struct ExtensionRefreshed {
559    pub session_id: Id,
560    pub skills: Vec<SkillMetadata>,
561    pub subagents: Vec<SubagentMetadata>,
562    #[serde(default)]
563    pub mcp_servers: Vec<McpServerInfo>,
564}
565
566/// One configured MCP server. A local server is described by `command` and
567/// `args`; a remote one by `url`, with `command` empty. `tools` is empty for a
568/// server that failed to connect or exposed nothing.
569#[derive(Debug, Clone, Serialize, Deserialize)]
570pub struct McpServerInfo {
571    pub name: String,
572    pub command: String,
573    pub args: Vec<String>,
574    #[serde(default, skip_serializing_if = "Option::is_none")]
575    pub url: Option<String>,
576    pub tools: Vec<McpToolInfo>,
577}
578
579#[derive(Debug, Clone, Serialize, Deserialize)]
580pub struct McpToolInfo {
581    pub name: String,
582    pub qualified_name: String,
583    pub description: String,
584    pub parameters: Vec<McpToolParam>,
585}
586
587#[derive(Debug, Clone, Serialize, Deserialize)]
588pub struct McpToolParam {
589    pub name: String,
590    pub param_type: String,
591    pub required: bool,
592    pub description: String,
593}
594
595/// The requested session configuration — the payload of [`Op::StartSession`].
596/// A set field is pinned: it wins over every default. An unset field means
597/// "the host's default for this, now": the daemon fills it from the user's
598/// settings (re-read at the session boundary) or its built-in default. There
599/// is exactly one meaning, regardless of who built the value — never "leave
600/// unchanged".
601#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
602pub struct SessionRequest {
603    #[serde(default, skip_serializing_if = "Option::is_none")]
604    pub model: Option<String>,
605    #[serde(default, skip_serializing_if = "Option::is_none")]
606    pub provider: Option<String>,
607    /// Pin a qualified credential reference on the session's provider from
608    /// its first request, under the rules of `SessionUpdate::credential`: the
609    /// start is refused if it is outside that provider's pool or unavailable.
610    /// Absent uses configured precedence.
611    #[serde(default, skip_serializing_if = "Option::is_none")]
612    pub credential: Option<String>,
613    #[serde(default, skip_serializing_if = "Option::is_none")]
614    pub permission_mode: Option<PermissionMode>,
615    #[serde(default, skip_serializing_if = "Option::is_none")]
616    pub system_prompt: Option<String>,
617    #[serde(default, skip_serializing_if = "Option::is_none")]
618    pub append_system_prompt: Option<String>,
619    /// Exactly these tools, replacing the default tool set as the base.
620    #[serde(default, skip_serializing_if = "Option::is_none")]
621    pub tools: Option<Vec<String>>,
622    /// Tools added on top of the base set (`tools`, or the default set).
623    #[serde(default, skip_serializing_if = "Option::is_none")]
624    pub include_tools: Option<Vec<String>>,
625    /// Tools removed from the session; wins over `tools` and `include_tools`.
626    #[serde(default, skip_serializing_if = "Option::is_none")]
627    pub exclude_tools: Option<Vec<String>>,
628    #[serde(default, skip_serializing_if = "Option::is_none")]
629    pub cwd: Option<PathBuf>,
630    #[serde(default, skip_serializing_if = "Option::is_none")]
631    pub effort: Option<Effort>,
632    #[serde(default, skip_serializing_if = "Option::is_none")]
633    pub enable_auto_memory: Option<bool>,
634    #[serde(default, skip_serializing_if = "Option::is_none")]
635    pub short_prompt: Option<bool>,
636    /// When true, the session loads no skills: none are discovered,
637    /// advertised, or invocable.
638    #[serde(default, skip_serializing_if = "Option::is_none")]
639    pub no_skills: Option<bool>,
640    /// Skills added to the default set; names match exactly. Does not enable
641    /// skill loading when disabled.
642    #[serde(default, skip_serializing_if = "Option::is_none")]
643    pub include_skills: Option<Vec<String>>,
644    /// Skills removed from the session; names match exactly. Wins over
645    /// `include_skills`.
646    #[serde(default, skip_serializing_if = "Option::is_none")]
647    pub exclude_skills: Option<Vec<String>>,
648    /// Whether the session writes a transcript and a resumable snapshot.
649    #[serde(default, skip_serializing_if = "Option::is_none")]
650    pub save_session: Option<bool>,
651    /// Whether no one can answer an approval prompt for this session. When
652    /// true, a tool call that would pause the turn for approval is denied
653    /// instead of pausing. Absent means false.
654    #[serde(default, skip_serializing_if = "Option::is_none")]
655    pub unattended: Option<bool>,
656    /// A title for the session (see `SessionUpdate::title` for the rules).
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub title: Option<String>,
659}
660
661impl SessionRequest {
662    /// Fold `patch` onto `self`, field by field: a set field in the patch
663    /// wins, an unset one keeps `self`'s value. This is the rule for every
664    /// request-over-request combination (e.g. a client retargeting the
665    /// request it keeps for `/clear`). `patch` is destructured exhaustively
666    /// (no `..` rest) so adding a field fails to compile here until its fold
667    /// rule is decided.
668    pub fn patched(self, patch: SessionRequest) -> SessionRequest {
669        let SessionRequest {
670            model,
671            provider,
672            credential,
673            permission_mode,
674            system_prompt,
675            append_system_prompt,
676            tools,
677            include_tools,
678            exclude_tools,
679            cwd,
680            effort,
681            enable_auto_memory,
682            short_prompt,
683            no_skills,
684            include_skills,
685            exclude_skills,
686            save_session,
687            unattended,
688            title,
689        } = patch;
690        SessionRequest {
691            model: model.or(self.model),
692            provider: provider.or(self.provider),
693            credential: credential.or(self.credential),
694            permission_mode: permission_mode.or(self.permission_mode),
695            system_prompt: system_prompt.or(self.system_prompt),
696            append_system_prompt: append_system_prompt.or(self.append_system_prompt),
697            tools: tools.or(self.tools),
698            include_tools: include_tools.or(self.include_tools),
699            exclude_tools: exclude_tools.or(self.exclude_tools),
700            cwd: cwd.or(self.cwd),
701            effort: effort.or(self.effort),
702            enable_auto_memory: enable_auto_memory.or(self.enable_auto_memory),
703            short_prompt: short_prompt.or(self.short_prompt),
704            no_skills: no_skills.or(self.no_skills),
705            include_skills: include_skills.or(self.include_skills),
706            exclude_skills: exclude_skills.or(self.exclude_skills),
707            save_session: save_session.or(self.save_session),
708            unattended: unattended.or(self.unattended),
709            title: title.or(self.title),
710        }
711    }
712}
713
714#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
715pub struct MalformedToolArgs {
716    /// Exact argument text emitted by the model for the undecodable call.
717    pub raw: String,
718    /// Decode diagnostic. This must not contain the raw argument text.
719    pub error: String,
720}
721
722/// Sentinel [`ToolUse::name`] for a call whose stream never delivered a
723/// function name; always paired with `malformed_args`.
724pub const MISSING_TOOL_NAME: &str = "missing_function_name";
725
726#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
727pub struct ToolUse {
728    pub id: String,
729    pub name: String,
730    pub args: serde_json::Value,
731    /// Present when the model's raw call could not be decoded into an
732    /// executable call: `args` that were not valid JSON, or a stream that
733    /// never delivered the function name (`name` is then
734    /// [`MISSING_TOOL_NAME`]). Such a call is non-executable and must be
735    /// returned as an error result.
736    #[serde(default, skip_serializing_if = "Option::is_none")]
737    pub malformed_args: Option<MalformedToolArgs>,
738    #[serde(skip_serializing_if = "Option::is_none")]
739    pub signature: Option<String>,
740}
741
742impl ToolUse {
743    /// A well-formed call: decoded `args`, no malformed metadata, no signature.
744    pub fn new(id: impl Into<String>, name: impl Into<String>, args: serde_json::Value) -> Self {
745        Self { id: id.into(), name: name.into(), args, malformed_args: None, signature: None }
746    }
747}
748
749#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
750pub struct ModelSpec {
751    #[serde(alias = "name")]
752    pub id: String,
753    #[serde(skip_serializing_if = "Option::is_none")]
754    pub display_name: Option<String>,
755    #[serde(skip_serializing_if = "Option::is_none")]
756    pub description: Option<String>,
757    #[serde(skip_serializing_if = "Option::is_none")]
758    pub temperature: Option<f32>,
759    #[serde(skip_serializing_if = "Option::is_none")]
760    pub top_p: Option<f32>,
761    #[serde(skip_serializing_if = "Option::is_none")]
762    pub top_k: Option<u32>,
763    #[serde(skip_serializing_if = "Option::is_none")]
764    pub max_tokens: Option<u32>,
765    #[serde(skip_serializing_if = "Option::is_none")]
766    pub stop_sequences: Option<Vec<String>>,
767    #[serde(skip_serializing_if = "Option::is_none")]
768    pub context_limit: Option<u32>,
769    #[serde(skip_serializing_if = "Option::is_none")]
770    pub effort: Option<Effort>,
771    /// The effort levels this model supports when configured in the user catalog.
772    /// When absent, the provider's built-in model profile supplies the ladder;
773    /// an empty list means that the model takes no effort setting.
774    #[serde(skip_serializing_if = "Option::is_none")]
775    pub supported_efforts: Option<Vec<Effort>>,
776    #[serde(skip_serializing_if = "Option::is_none")]
777    pub support_vision: Option<bool>,
778    #[serde(skip_serializing_if = "Option::is_none")]
779    pub weight_class: Option<WeightClass>,
780}
781
782/// Requested output/reasoning effort for model turns, on an ordinal scale.
783///
784/// `min` is the lowest effort the model supports — thinking is disabled where
785/// the model allows that; models with always-on reasoning clamp to their
786/// lowest level. Providers that expose fewer levels round a requested effort
787/// down to the nearest supported one. Variants are declared in ascending
788/// order so the derived `Ord` sorts `Min < Low < ... < Max`.
789#[derive(Debug, Clone, Serialize, Deserialize, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
790#[serde(rename_all = "lowercase")]
791pub enum Effort {
792    Min,
793    Low,
794    Medium,
795    High,
796    XHigh,
797    Max,
798}
799
800impl Effort {
801    /// All levels in ascending order.
802    pub const ALL: [Effort; 6] =
803        [Effort::Min, Effort::Low, Effort::Medium, Effort::High, Effort::XHigh, Effort::Max];
804
805    /// The wire token for this level (`"min"`, `"low"`, ..., `"max"`).
806    pub fn as_str(self) -> &'static str {
807        match self {
808            Effort::Min => "min",
809            Effort::Low => "low",
810            Effort::Medium => "medium",
811            Effort::High => "high",
812            Effort::XHigh => "xhigh",
813            Effort::Max => "max",
814        }
815    }
816}
817
818impl std::fmt::Display for Effort {
819    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
820        f.write_str(self.as_str())
821    }
822}
823
824impl std::str::FromStr for Effort {
825    type Err = String;
826
827    fn from_str(s: &str) -> Result<Self, Self::Err> {
828        Effort::ALL.into_iter().find(|e| e.as_str() == s).ok_or_else(|| {
829            format!("unknown effort `{s}` (expected min, low, medium, high, xhigh, max)")
830        })
831    }
832}
833
834/// Innate size/cost class of a model, set once per model in the catalog.
835///
836/// Orthogonal to the per-request [`Effort`] and to `context_limit`:
837/// a model's weight class reflects roughly how large and costly it is to run,
838/// not how hard it is asked to think on a given turn. Variants are declared in
839/// ascending order so the derived `Ord` sorts `Feather < Middle < Heavy`.
840#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
841#[serde(rename_all = "lowercase")]
842pub enum WeightClass {
843    /// Small, fast, cheap (Haiku- / GPT-nano-class).
844    Feather,
845    /// Mid workhorse (Sonnet- / GPT-mini- / Gemini-Flash-class).
846    Middle,
847    /// Largest, most capable, costliest (Opus- / GPT-5.x- / Gemini-Pro-class).
848    Heavy,
849}
850
851impl<'de> Deserialize<'de> for WeightClass {
852    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
853    where
854        D: Deserializer<'de>,
855    {
856        let value = String::deserialize(deserializer)?;
857        match value.to_ascii_lowercase().as_str() {
858            "feather" => Ok(Self::Feather),
859            "middle" => Ok(Self::Middle),
860            "heavy" => Ok(Self::Heavy),
861            _ => Err(serde::de::Error::unknown_variant(&value, &["feather", "middle", "heavy"])),
862        }
863    }
864}
865
866/// Token usage for one model response.
867///
868/// Convention, uniform across every provider mapping: `input_tokens` is the
869/// **full, cache-inclusive prompt size**. It always contains `cache_read_tokens`
870/// as a subset (verified live: OpenAI/OpenRouter/DeepSeek report it inside
871/// `prompt_tokens`; the Anthropic mapping adds it back since that API reports
872/// input net of cache). `cache_creation_tokens` is likewise inside `input_tokens`
873/// for providers that report cache writes (Anthropic); the OpenAI-style
874/// providers we use don't report writes at all. So [`Usage::total`]
875/// (`input + output`) is the context-window occupancy.
876///
877/// For **cost**, the cache buckets bill at different rates, so subtract them
878/// from the input rate instead of charging the full rate twice:
879/// `cost = (input - cache_read - cache_creation)·p_in
880///        + cache_read·p_cache_read + cache_creation·p_cache_write
881///        + output·p_out`.
882#[derive(Debug, Clone, Deserialize, Serialize, Default, Copy)]
883#[serde(default)]
884pub struct Usage {
885    /// Full prompt tokens, cache-inclusive (a superset of the two cache fields).
886    pub input_tokens: u32,
887    /// Generated output (completion) tokens.
888    pub output_tokens: u32,
889    /// Subset of `input_tokens` served from the prompt cache (cheaper rate).
890    #[serde(skip_serializing_if = "Option::is_none")]
891    pub cache_read_tokens: Option<u32>,
892    /// Subset of `input_tokens` written into the prompt cache (surcharge rate).
893    #[serde(skip_serializing_if = "Option::is_none")]
894    pub cache_creation_tokens: Option<u32>,
895}
896
897/// Context-window occupancy snapshot for the current (root) session, surfaced in
898/// the statusline. Raw measurements only — any percentage is a presentation
899/// concern derived at the edges, with no policy (e.g. auto-compaction) baked in.
900#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
901pub struct ContextWindow {
902    /// Tokens currently occupying the window (cache-inclusive input + output of
903    /// the most recent response).
904    pub used_tokens: u32,
905    /// Raw model context limit (e.g. 200_000).
906    pub limit_tokens: u32,
907}
908
909/// Per-category breakdown of context-window occupancy.
910///
911/// `used_tokens` is anchored on the provider-reported occupancy once the
912/// session has seen a model response; before that it is estimated. The
913/// per-category fields are estimates that normally sum to `used_tokens`, but
914/// estimation error can make them disagree slightly — clients should clamp
915/// rather than assume an exact identity.
916#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
917#[serde(default)]
918pub struct ContextBreakdown {
919    /// System prompt, excluding the skills and memory sections counted below.
920    pub system_prompt_tokens: u32,
921    /// Built-in tool schemas.
922    pub system_tools_tokens: u32,
923    /// MCP tool schemas.
924    pub mcp_tools_tokens: u32,
925    /// Memory content: project/user instruction files and the auto-memory prompt.
926    pub memory_tokens: u32,
927    /// The available-skills listing.
928    pub skills_tokens: u32,
929    /// Conversation messages: everything not attributed to a category above.
930    pub messages_tokens: u32,
931    /// Total context-window occupancy.
932    pub used_tokens: u32,
933    /// Model context limit. `None` when unverified, so clients never render a
934    /// confidently-wrong percentage.
935    pub limit_tokens: Option<u32>,
936    /// Tokens reserved at the top of the window; auto-compaction triggers once
937    /// occupancy grows into this reserve.
938    pub compact_buffer_tokens: u32,
939}
940
941impl Usage {
942    pub fn new(input_tokens: u32, output_tokens: u32) -> Self {
943        Self { input_tokens, output_tokens, cache_read_tokens: None, cache_creation_tokens: None }
944    }
945
946    /// Context-window occupancy: the full (cache-inclusive) prompt plus output.
947    pub fn total(&self) -> u32 {
948        self.input_tokens.saturating_add(self.output_tokens)
949    }
950}
951
952impl std::ops::Add<Usage> for Usage {
953    type Output = Usage;
954
955    fn add(self, other: Usage) -> Usage {
956        Usage {
957            input_tokens: self.input_tokens.saturating_add(other.input_tokens),
958            output_tokens: self.output_tokens.saturating_add(other.output_tokens),
959            cache_read_tokens: add_optional_u32(self.cache_read_tokens, other.cache_read_tokens),
960            cache_creation_tokens: add_optional_u32(
961                self.cache_creation_tokens,
962                other.cache_creation_tokens,
963            ),
964        }
965    }
966}
967
968fn add_optional_u32(a: Option<u32>, b: Option<u32>) -> Option<u32> {
969    match (a, b) {
970        (None, None) => None,
971        _ => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))),
972    }
973}
974
975impl std::ops::AddAssign<Usage> for Usage {
976    fn add_assign(&mut self, other: Usage) {
977        *self = *self + other;
978    }
979}
980
981#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, Eq, PartialEq)]
982#[serde(rename_all = "snake_case")]
983pub enum PermissionMode {
984    /// Honor user rules; an unmatched call asks unless it is provably safe.
985    #[default]
986    Strict,
987    /// Honor user rules; an unmatched call runs unless it is provably
988    /// dangerous (a deliberately narrow classification).
989    Auto,
990    /// Bypass all permission checks, including user deny rules.
991    Yolo,
992}
993
994#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
995#[serde(rename_all = "kebab-case")]
996pub enum Scope {
997    Project,
998    User,
999    System,
1000}
1001
1002#[cfg(test)]
1003mod tests {
1004    use super::{
1005        Effort, Evt, ExtensionRefreshed, Id, ModelSpec, Op, PermissionMode, ProviderSpec,
1006        ReviewDecision, SessionInfo, SessionRequest, SessionUpdate, ToolDecision, ToolEnd,
1007        ToolEndStatus, ToolUse, Usage, WeightClass, event_msg, op_msg,
1008    };
1009    use std::path::PathBuf;
1010
1011    #[test]
1012    fn op_msg_assigns_runtime_id() {
1013        let msg = op_msg(Op::Interrupt);
1014
1015        assert!(msg.id.to_string().starts_with("op_"));
1016        assert!(matches!(msg.op, Op::Interrupt));
1017    }
1018
1019    #[test]
1020    fn event_msg_assigns_runtime_metadata() {
1021        let event = event_msg(Evt::Info("hello".to_string()), None);
1022
1023        assert!(event.id.to_string().starts_with("evt_"));
1024        assert!(matches!(event.event, Evt::Info(message) if message == "hello"));
1025        assert!(event.parent.is_none());
1026    }
1027
1028    fn model_spec(name: &str) -> ModelSpec {
1029        ModelSpec {
1030            id: name.to_string(),
1031            display_name: None,
1032            description: None,
1033            temperature: None,
1034            top_p: None,
1035            top_k: None,
1036            max_tokens: None,
1037            stop_sequences: None,
1038            context_limit: None,
1039            effort: None,
1040            supported_efforts: None,
1041            support_vision: None,
1042            weight_class: None,
1043        }
1044    }
1045
1046    #[test]
1047    fn tool_use_without_malformed_args_remains_backward_compatible() {
1048        let tool_use: ToolUse = serde_json::from_value(serde_json::json!({
1049            "id": "call-1",
1050            "name": "Read",
1051            "args": { "file_path": "README.md" }
1052        }))
1053        .unwrap();
1054
1055        assert!(tool_use.malformed_args.is_none());
1056        let encoded = serde_json::to_value(tool_use).unwrap();
1057        assert!(encoded.get("malformed_args").is_none());
1058    }
1059
1060    #[test]
1061    fn tool_end_without_name_remains_backward_compatible() {
1062        let legacy = serde_json::json!({
1063            "tool_use_id": "call-1",
1064            "status": "Denied",
1065            "result_json": "Tool call denied by policy and was not executed."
1066        });
1067        let mut end: ToolEnd = serde_json::from_value(legacy.clone()).unwrap();
1068        assert!(end.tool_name.is_empty());
1069        assert_eq!(end.status, ToolEndStatus::Denied);
1070
1071        end.tool_name = "Bash".to_string();
1072        let mut expected = legacy;
1073        expected["tool_name"] = serde_json::json!("Bash");
1074        assert_eq!(serde_json::to_value(end).unwrap(), expected);
1075    }
1076
1077    #[test]
1078    fn task_end_round_trips_with_observed_or_unobserved_exit() {
1079        for exit_code in [Some(2), None] {
1080            let json = serde_json::json!({
1081                "TaskEnd": { "tool_use_id": "bash-1", "exit_code": exit_code }
1082            });
1083            let event: super::Evt = serde_json::from_value(json.clone()).unwrap();
1084            assert!(matches!(&event, super::Evt::TaskEnd { tool_use_id, exit_code: code }
1085                if tool_use_id == "bash-1" && *code == exit_code));
1086            assert_eq!(serde_json::to_value(event).unwrap(), json);
1087        }
1088    }
1089
1090    #[test]
1091    fn turn_end_error_kind_is_optional_on_the_wire() {
1092        // Payloads from daemons predating the field still deserialize.
1093        let old: super::TurnEndStatus = serde_json::from_value(serde_json::json!({
1094            "Error": { "headline": "authentication error", "details": [] }
1095        }))
1096        .unwrap();
1097        let super::TurnEndStatus::Error { kind, .. } = &old else {
1098            panic!("expected Error variant");
1099        };
1100        assert!(kind.is_none());
1101
1102        // None is skipped, not emitted as null.
1103        let json = serde_json::to_value(&old).unwrap();
1104        assert!(json["Error"].get("kind").is_none());
1105
1106        // Some round-trips.
1107        let with = super::TurnEndStatus::Error {
1108            kind: Some("oauth".to_string()),
1109            headline: "OAuth sign-in required".to_string(),
1110            details: vec![],
1111        };
1112        let json = serde_json::to_value(&with).unwrap();
1113        assert_eq!(json["Error"]["kind"], "oauth");
1114    }
1115
1116    #[test]
1117    fn turn_end_steps_default_for_older_events() {
1118        let event = super::Evt::TurnEnd {
1119            turn_id: super::Id::new("turn"),
1120            status: super::TurnEndStatus::Completed,
1121            steps: 3,
1122        };
1123        let mut json = serde_json::to_value(&event).unwrap();
1124        json["TurnEnd"].as_object_mut().unwrap().remove("steps");
1125        let old: super::Evt = serde_json::from_value(json).unwrap();
1126
1127        assert!(matches!(old, super::Evt::TurnEnd { steps: 0, .. }));
1128
1129        let json = serde_json::to_value(event).unwrap();
1130        assert_eq!(json["TurnEnd"]["steps"], 3);
1131    }
1132
1133    #[test]
1134    fn effort_serializes_as_lowercase_tokens() {
1135        let mut spec = model_spec("m");
1136        spec.effort = Some(super::Effort::XHigh);
1137        let json = serde_json::to_value(&spec).unwrap();
1138        assert_eq!(json["effort"], "xhigh");
1139
1140        // None is skipped, not emitted as null.
1141        let json_none = serde_json::to_value(model_spec("m")).unwrap();
1142        assert!(json_none.get("effort").is_none());
1143
1144        // Every level round-trips through its wire token.
1145        for level in super::Effort::ALL {
1146            let parsed: ModelSpec =
1147                serde_json::from_value(serde_json::json!({"id": "m", "effort": level.as_str()}))
1148                    .unwrap();
1149            assert_eq!(parsed.effort, Some(level), "round-trip {level}");
1150        }
1151    }
1152
1153    #[test]
1154    fn session_overrides_effort_round_trips() {
1155        let parsed: super::SessionRequest =
1156            serde_json::from_value(serde_json::json!({"effort": "max"})).unwrap();
1157        assert_eq!(parsed.effort, Some(super::Effort::Max));
1158
1159        let parsed: super::SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
1160        assert_eq!(parsed.effort, None);
1161    }
1162
1163    #[test]
1164    fn short_prompt_round_trips_and_defaults_to_unset() {
1165        let parsed: super::SessionRequest =
1166            serde_json::from_value(serde_json::json!({"short_prompt": true})).unwrap();
1167        assert_eq!(parsed.short_prompt, Some(true));
1168
1169        let parsed: super::SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
1170        assert_eq!(parsed.short_prompt, None);
1171    }
1172
1173    #[test]
1174    fn skill_filters_are_optional_on_the_wire_and_preserve_empty_overrides() {
1175        let absent: SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
1176        assert_eq!(absent.include_skills, None);
1177        assert_eq!(absent.exclude_skills, None);
1178        let encoded = serde_json::to_value(absent).unwrap();
1179        assert!(encoded.get("include_skills").is_none());
1180        assert!(encoded.get("exclude_skills").is_none());
1181
1182        let json = serde_json::json!({"include_skills": ["Review"], "exclude_skills": []});
1183        let parsed: SessionRequest = serde_json::from_value(json.clone()).unwrap();
1184        assert_eq!(parsed.include_skills, Some(vec!["Review".to_string()]));
1185        assert_eq!(parsed.exclude_skills, Some(Vec::new()));
1186        assert_eq!(serde_json::to_value(parsed).unwrap(), json);
1187    }
1188
1189    fn pinned_request() -> SessionRequest {
1190        SessionRequest {
1191            model: Some("base-model".to_string()),
1192            provider: Some("anthropic".to_string()),
1193            credential: Some("oauth:anthropic/work".to_string()),
1194            permission_mode: Some(PermissionMode::Strict),
1195            system_prompt: Some("base prompt".to_string()),
1196            cwd: Some(std::path::PathBuf::from("/base")),
1197            effort: Some(Effort::Medium),
1198            enable_auto_memory: Some(true),
1199            short_prompt: Some(true),
1200            no_skills: Some(true),
1201            include_skills: Some(vec!["review".to_string()]),
1202            exclude_skills: Some(vec!["noisy".to_string()]),
1203            save_session: Some(true),
1204            unattended: Some(true),
1205            title: Some("pinned title".to_string()),
1206            ..Default::default()
1207        }
1208    }
1209
1210    #[test]
1211    fn patched_with_an_empty_patch_keeps_every_field() {
1212        assert_eq!(pinned_request().patched(SessionRequest::default()), pinned_request());
1213    }
1214
1215    #[test]
1216    fn patched_overwrites_only_the_patch_set_fields() {
1217        let patched = pinned_request().patched(SessionRequest {
1218            model: Some("new-model".to_string()),
1219            permission_mode: Some(PermissionMode::Yolo),
1220            enable_auto_memory: Some(false),
1221            short_prompt: Some(false),
1222            include_skills: Some(Vec::new()),
1223            ..Default::default()
1224        });
1225        // Overwritten by the patch:
1226        assert_eq!(patched.model.as_deref(), Some("new-model"));
1227        assert_eq!(patched.permission_mode, Some(PermissionMode::Yolo));
1228        assert_eq!(patched.enable_auto_memory, Some(false));
1229        assert_eq!(patched.short_prompt, Some(false));
1230        assert_eq!(patched.include_skills, Some(Vec::new()));
1231        // Untouched (patch unset == keep):
1232        assert_eq!(patched.provider.as_deref(), Some("anthropic"));
1233        assert_eq!(patched.credential.as_deref(), Some("oauth:anthropic/work"));
1234        assert_eq!(patched.system_prompt.as_deref(), Some("base prompt"));
1235        assert_eq!(patched.effort, Some(Effort::Medium));
1236        assert_eq!(patched.save_session, Some(true));
1237        assert_eq!(patched.unattended, Some(true));
1238        assert_eq!(patched.title.as_deref(), Some("pinned title"));
1239        assert_eq!(patched.exclude_skills, Some(vec!["noisy".to_string()]));
1240    }
1241
1242    #[test]
1243    fn rewind_names_its_input_as_to() {
1244        let to = Id::op();
1245        let json = serde_json::to_value(Op::RewindSession { to }).unwrap();
1246        assert_eq!(json, serde_json::json!({ "RewindSession": { "to": to } }));
1247        let op: Op = serde_json::from_value(json).unwrap();
1248        assert!(matches!(op, Op::RewindSession { to: decoded } if decoded == to));
1249
1250        let json = serde_json::to_value(Evt::SessionRewound { to }).unwrap();
1251        assert_eq!(json, serde_json::json!({ "SessionRewound": { "to": to } }));
1252    }
1253
1254    #[test]
1255    fn fork_at_is_optional_on_the_wire() {
1256        let whole: Op = serde_json::from_value(serde_json::json!({ "ForkSession": {} })).unwrap();
1257        assert!(matches!(whole, Op::ForkSession { at: None }));
1258
1259        let at = Id::op();
1260        let json = serde_json::to_value(Op::ForkSession { at: Some(at) }).unwrap();
1261        assert_eq!(json, serde_json::json!({ "ForkSession": { "at": at } }));
1262        let op: Op = serde_json::from_value(json).unwrap();
1263        assert!(matches!(op, Op::ForkSession { at: Some(decoded) } if decoded == at));
1264
1265        let (forked_from, session_id) = (Id::ses(), Id::ses());
1266        let forked = Evt::SessionForked { forked_from, session_id, at: None };
1267        assert_eq!(
1268            serde_json::to_value(forked).unwrap(),
1269            serde_json::json!({
1270                "SessionForked": { "forked_from": forked_from, "session_id": session_id }
1271            })
1272        );
1273    }
1274
1275    #[test]
1276    fn forked_from_is_optional_on_the_wire() {
1277        let source = Id::ses();
1278        let info = SessionInfo { forked_from: Some(source), ..Default::default() };
1279        let mut json = serde_json::to_value(&info).unwrap();
1280        assert_eq!(json["forked_from"], serde_json::json!(source));
1281        let decoded: SessionInfo = serde_json::from_value(json.clone()).unwrap();
1282        assert_eq!(decoded.forked_from, Some(source));
1283
1284        // A payload written before the field existed reads as not forked.
1285        json.as_object_mut().unwrap().remove("forked_from");
1286        let plain: SessionInfo = serde_json::from_value(json).unwrap();
1287        assert_eq!(plain.forked_from, None);
1288        assert!(serde_json::to_value(&plain).unwrap().get("forked_from").is_none());
1289    }
1290
1291    #[test]
1292    fn unattended_is_optional_on_the_wire() {
1293        // A request without the field, and a resume op written before the
1294        // field existed, both read as attended.
1295        let request: SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
1296        assert_eq!(request.unattended, None);
1297
1298        let op = Op::ResumeSession {
1299            session_id: Id::new("ses"),
1300            unattended: true,
1301            tools: None,
1302            include_tools: None,
1303            exclude_tools: None,
1304            credential: None,
1305        };
1306        let mut json = serde_json::to_value(&op).unwrap();
1307        json["ResumeSession"].as_object_mut().unwrap().remove("unattended");
1308        let decoded: Op = serde_json::from_value(json).unwrap();
1309        assert!(matches!(
1310            decoded,
1311            Op::ResumeSession {
1312                unattended: false,
1313                tools: None,
1314                include_tools: None,
1315                exclude_tools: None,
1316                credential: None,
1317                ..
1318            }
1319        ));
1320    }
1321
1322    #[test]
1323    fn resume_tool_filters_roundtrip_including_an_empty_base() {
1324        for tools in [None, Some(vec![]), Some(vec!["Read".to_string()])] {
1325            let op = Op::ResumeSession {
1326                session_id: Id::ses(),
1327                unattended: true,
1328                tools: tools.clone(),
1329                include_tools: Some(vec!["Bash".to_string()]),
1330                exclude_tools: Some(vec!["Agent".to_string()]),
1331                credential: Some("oauth:anthropic/work".to_string()),
1332            };
1333            let json = serde_json::to_value(&op).unwrap();
1334            assert_eq!(json["ResumeSession"].get("tools").is_none(), tools.is_none());
1335            assert_eq!(json["ResumeSession"]["credential"], "oauth:anthropic/work");
1336            let decoded: Op = serde_json::from_value(json).unwrap();
1337            let Op::ResumeSession { tools: decoded_tools, include_tools, exclude_tools, .. } =
1338                decoded
1339            else {
1340                panic!("expected ResumeSession");
1341            };
1342            assert_eq!(decoded_tools, tools);
1343            assert_eq!(include_tools, Some(vec!["Bash".to_string()]));
1344            assert_eq!(exclude_tools, Some(vec!["Agent".to_string()]));
1345        }
1346    }
1347
1348    #[test]
1349    fn session_initialized_title_is_optional_on_the_wire() {
1350        let mut payload = SessionInfo {
1351            model: model_spec("m"),
1352            provider: provider_spec("p"),
1353            session_id: Id::new("ses"),
1354            cwd: PathBuf::from("/tmp"),
1355            permission_mode: PermissionMode::default(),
1356            skills: vec![],
1357            subagents: vec![],
1358            title: None,
1359            forked_from: None,
1360        };
1361
1362        let json = serde_json::to_value(&payload).unwrap();
1363        assert!(json.get("title").is_none(), "an unset title is omitted: {json}");
1364        let decoded: SessionInfo = serde_json::from_value(json).unwrap();
1365        assert_eq!(decoded.title, None);
1366
1367        payload.title = Some("fix".to_string());
1368        let json = serde_json::to_value(&payload).unwrap();
1369        assert_eq!(json["title"], "fix");
1370    }
1371
1372    #[test]
1373    fn weight_class_serializes_lowercase_and_is_omitted_when_none() {
1374        let mut spec = model_spec("m");
1375        spec.weight_class = Some(WeightClass::Heavy);
1376        let json = serde_json::to_value(&spec).unwrap();
1377        assert_eq!(json["weight_class"], "heavy");
1378
1379        // None is skipped, not emitted as null.
1380        let json_none = serde_json::to_value(model_spec("m")).unwrap();
1381        assert!(json_none.get("weight_class").is_none());
1382
1383        // Round-trips from the lowercase wire form.
1384        let parsed: ModelSpec =
1385            serde_json::from_value(serde_json::json!({"id": "m", "weight_class": "feather"}))
1386                .unwrap();
1387        assert_eq!(parsed.weight_class, Some(WeightClass::Feather));
1388    }
1389
1390    #[test]
1391    fn weight_class_deserializes_case_insensitively() {
1392        for (value, expected) in [
1393            ("Feather", WeightClass::Feather),
1394            ("MIDDLE", WeightClass::Middle),
1395            ("hEaVy", WeightClass::Heavy),
1396        ] {
1397            let parsed: ModelSpec =
1398                serde_json::from_value(serde_json::json!({"id": "m", "weight_class": value}))
1399                    .unwrap();
1400            assert_eq!(parsed.weight_class, Some(expected));
1401        }
1402    }
1403
1404    fn provider_spec(name: &str) -> ProviderSpec {
1405        ProviderSpec {
1406            id: name.to_string(),
1407            display_name: name.to_string(),
1408            base_url: format!("https://api.{name}.test/v1"),
1409            ..Default::default()
1410        }
1411    }
1412
1413    #[test]
1414    fn provider_credential_is_optional_on_the_wire() {
1415        let mut info = SessionInfo { provider: provider_spec("antix"), ..Default::default() };
1416        info.provider.credential = Some("oauth:antix/work".into());
1417
1418        let mut json = serde_json::to_value(&info).unwrap();
1419        assert!(json.get("credentials").is_none());
1420        assert!(json["provider"].get("credentials").is_none());
1421        assert_eq!(json["provider"]["credential"], "oauth:antix/work");
1422        let decoded: SessionInfo = serde_json::from_value(json.clone()).unwrap();
1423        assert_eq!(decoded.provider.credential, info.provider.credential);
1424
1425        json["provider"].as_object_mut().unwrap().remove("credential");
1426        let decoded: SessionInfo = serde_json::from_value(json).unwrap();
1427        assert!(decoded.provider.credential.is_none());
1428        assert!(serde_json::to_value(decoded).unwrap()["provider"].get("credential").is_none());
1429    }
1430
1431    #[test]
1432    fn compact_events_serde_roundtrip() {
1433        let compact_start =
1434            serde_json::to_string(&Evt::CompactStart).expect("serialize CompactStart");
1435        let compact_end =
1436            serde_json::to_string(&Evt::CompactEnd { summary: Some("the summary".to_string()) })
1437                .expect("serialize CompactEnd");
1438
1439        assert_eq!(compact_start, "\"CompactStart\"");
1440        assert_eq!(compact_end, r#"{"CompactEnd":{"summary":"the summary"}}"#);
1441
1442        assert!(matches!(
1443            serde_json::from_str::<Evt>(&compact_start).expect("deserialize CompactStart"),
1444            Evt::CompactStart
1445        ));
1446        assert!(matches!(
1447            serde_json::from_str::<Evt>(&compact_end).expect("deserialize CompactEnd"),
1448            Evt::CompactEnd { summary: Some(s) } if s == "the summary"
1449        ));
1450        assert!(matches!(
1451            serde_json::from_str::<Evt>(r#"{"CompactEnd":{}}"#)
1452                .expect("deserialize CompactEnd without summary"),
1453            Evt::CompactEnd { summary: None }
1454        ));
1455    }
1456
1457    #[test]
1458    fn compact_op_serde_roundtrip() {
1459        let plain = serde_json::to_string(&Op::Compact { instructions: None })
1460            .expect("serialize bare Compact");
1461        assert_eq!(plain, r#"{"Compact":{}}"#);
1462        assert!(matches!(
1463            serde_json::from_str::<Op>(&plain).expect("deserialize bare Compact"),
1464            Op::Compact { instructions: None }
1465        ));
1466
1467        let steered =
1468            serde_json::to_string(&Op::Compact { instructions: Some("keep dates".to_string()) })
1469                .expect("serialize steered Compact");
1470        assert_eq!(steered, r#"{"Compact":{"instructions":"keep dates"}}"#);
1471        assert!(matches!(
1472            serde_json::from_str::<Op>(&steered).expect("deserialize steered Compact"),
1473            Op::Compact { instructions: Some(text) } if text == "keep dates"
1474        ));
1475    }
1476
1477    #[test]
1478    fn session_end_and_turn_resume_serde_roundtrip() {
1479        let session_id = Id::new("ses");
1480        let end = Evt::SessionEnd {
1481            session_id,
1482            reason: super::SessionEndReason::Shutdown,
1483            usage: Usage::new(10, 5),
1484        };
1485        let json = serde_json::to_string(&end).expect("serialize SessionEnd");
1486        let decoded = serde_json::from_str::<Evt>(&json).expect("deserialize SessionEnd");
1487        assert!(matches!(
1488            decoded,
1489            Evt::SessionEnd { session_id: id, reason: super::SessionEndReason::Shutdown, usage }
1490                if id == session_id && usage.total() == 15
1491        ));
1492
1493        let turn_id = Id::new("op");
1494        let resume = Evt::TurnResume { turn_id };
1495        let json = serde_json::to_string(&resume).expect("serialize TurnResume");
1496        let decoded = serde_json::from_str::<Evt>(&json).expect("deserialize TurnResume");
1497        assert!(matches!(decoded, Evt::TurnResume { turn_id: id } if id == turn_id));
1498    }
1499
1500    #[test]
1501    fn extension_refreshed_serde_roundtrip() {
1502        let event = Evt::ExtensionRefreshed(Box::new(ExtensionRefreshed {
1503            session_id: Id::new("ses"),
1504            skills: Vec::new(),
1505            subagents: Vec::new(),
1506            mcp_servers: Vec::new(),
1507        }));
1508
1509        let json = serde_json::to_string(&event).expect("serialize ExtensionRefreshed");
1510        let decoded = serde_json::from_str::<Evt>(&json).expect("deserialize ExtensionRefreshed");
1511
1512        assert!(matches!(
1513            decoded,
1514            Evt::ExtensionRefreshed(payload)
1515                if payload.skills.is_empty() && payload.subagents.is_empty()
1516        ));
1517    }
1518
1519    #[test]
1520    fn session_update_op_serde_roundtrip() {
1521        let op = Op::UpdateSession(SessionUpdate {
1522            provider: Some("openai".to_string()),
1523            credential: Some("oauth:openai/work".to_string()),
1524            model: Some(ModelSpec {
1525                temperature: Some(0.2),
1526                effort: Some(super::Effort::High),
1527                ..model_spec("gpt-5.4")
1528            }),
1529            permission_mode: Some(PermissionMode::Yolo),
1530            title: Some("renamed".to_string()),
1531        });
1532
1533        let json = serde_json::to_string(&op).expect("serialize UpdateSession");
1534        let decoded = serde_json::from_str::<Op>(&json).expect("deserialize UpdateSession");
1535
1536        assert!(matches!(
1537            decoded,
1538            Op::UpdateSession(SessionUpdate {
1539                provider: Some(provider),
1540                credential: Some(credential),
1541                model: Some(model),
1542                permission_mode: Some(PermissionMode::Yolo),
1543                title: Some(title),
1544            })
1545                if provider == "openai"
1546                    && credential == "oauth:openai/work"
1547                    && model.id == "gpt-5.4"
1548                    && model.temperature == Some(0.2)
1549                    && model.effort == Some(super::Effort::High)
1550                    && title == "renamed"
1551        ));
1552    }
1553
1554    #[test]
1555    fn approval_response_uses_named_tool_decisions() {
1556        let turn_id = Id::new("turn");
1557        let op = Op::ApprovalResponse {
1558            turn_id,
1559            responses: vec![ToolDecision {
1560                tool_use_id: "call-1".to_string(),
1561                decision: ReviewDecision::Deny,
1562                message: Some("use the read-only endpoint".to_string()),
1563            }],
1564        };
1565
1566        let json = serde_json::to_value(&op).expect("serialize ApprovalResponse");
1567        assert_eq!(
1568            json["ApprovalResponse"]["responses"],
1569            serde_json::json!([{
1570                "tool_use_id": "call-1",
1571                "decision": "Deny",
1572                "message": "use the read-only endpoint"
1573            }])
1574        );
1575
1576        let decoded = serde_json::from_value::<Op>(json).expect("deserialize ApprovalResponse");
1577        assert!(matches!(
1578            decoded,
1579            Op::ApprovalResponse { turn_id: id, responses }
1580                if id == turn_id
1581                    && responses == vec![ToolDecision {
1582                        tool_use_id: "call-1".to_string(),
1583                        decision: ReviewDecision::Deny,
1584                        message: Some("use the read-only endpoint".to_string()),
1585                    }]
1586        ));
1587    }
1588
1589    #[test]
1590    fn session_updated_event_serde_roundtrip() {
1591        let session_id = Id::new("ses");
1592        let event = Evt::SessionUpdated(Box::new(SessionInfo {
1593            model: model_spec("claude-sonnet-4-6"),
1594            provider: provider_spec("anthropic"),
1595            session_id,
1596            cwd: PathBuf::from("/tmp/session-updated"),
1597            permission_mode: PermissionMode::default(),
1598            skills: vec![],
1599            subagents: vec![],
1600            title: None,
1601            forked_from: None,
1602        }));
1603
1604        let json = serde_json::to_string(&event).expect("serialize SessionUpdated");
1605        let decoded = serde_json::from_str::<Evt>(&json).expect("deserialize SessionUpdated");
1606
1607        assert!(matches!(
1608            decoded,
1609            Evt::SessionUpdated(payload)
1610                if payload.model.id == "claude-sonnet-4-6"
1611                    && payload.provider.id == "anthropic"
1612                    && payload.provider.base_url == "https://api.anthropic.test/v1"
1613                    && payload.session_id == session_id
1614                    && payload.cwd == std::path::Path::new("/tmp/session-updated")
1615        ));
1616    }
1617
1618    #[test]
1619    fn provider_spec_ignores_the_dropped_model_list() {
1620        // Payloads from daemons that still send the provider's model list
1621        // decode against the narrowed shape.
1622        let spec: ProviderSpec = serde_json::from_value(serde_json::json!({
1623            "id": "anthropic",
1624            "display_name": "Anthropic",
1625            "base_url": "https://api.anthropic.test/v1",
1626            "preferred_models": [{ "id": "claude-sonnet-4-6" }],
1627        }))
1628        .unwrap();
1629
1630        assert_eq!(spec.id, "anthropic");
1631        assert_eq!(spec.display_name, "Anthropic");
1632        assert_eq!(spec.base_url, "https://api.anthropic.test/v1");
1633
1634        // And the catalog data does not go back out.
1635        let encoded = serde_json::to_value(&spec).unwrap();
1636        assert!(encoded.get("preferred_models").is_none());
1637    }
1638
1639    #[test]
1640    fn context_report_serde_roundtrip() {
1641        let breakdown = super::ContextBreakdown {
1642            system_prompt_tokens: 1200,
1643            system_tools_tokens: 3400,
1644            mcp_tools_tokens: 0,
1645            memory_tokens: 800,
1646            skills_tokens: 150,
1647            messages_tokens: 42_000,
1648            used_tokens: 47_550,
1649            limit_tokens: Some(200_000),
1650            compact_buffer_tokens: 20_000,
1651        };
1652        let json = serde_json::to_value(Evt::ContextReport(breakdown)).expect("serialize");
1653        assert_eq!(
1654            json,
1655            serde_json::json!({
1656                "ContextReport": {
1657                    "system_prompt_tokens": 1200,
1658                    "system_tools_tokens": 3400,
1659                    "mcp_tools_tokens": 0,
1660                    "memory_tokens": 800,
1661                    "skills_tokens": 150,
1662                    "messages_tokens": 42000,
1663                    "used_tokens": 47550,
1664                    "limit_tokens": 200000,
1665                    "compact_buffer_tokens": 20000
1666                }
1667            })
1668        );
1669        let decoded = serde_json::from_value::<Evt>(json).expect("deserialize");
1670        assert!(matches!(decoded, Evt::ContextReport(b) if b == breakdown));
1671
1672        // Fields absent on the wire (older daemons) fall back to defaults.
1673        let sparse: super::ContextBreakdown =
1674            serde_json::from_value(serde_json::json!({"used_tokens": 10})).unwrap();
1675        assert_eq!(sparse.used_tokens, 10);
1676        assert_eq!(sparse.limit_tokens, None);
1677
1678        let op = serde_json::to_value(Op::ContextReport).expect("serialize op");
1679        assert_eq!(op, serde_json::json!("ContextReport"));
1680        assert!(matches!(serde_json::from_value::<Op>(op).unwrap(), Op::ContextReport));
1681    }
1682
1683    #[test]
1684    fn question_pause_serde_roundtrip() {
1685        let turn_id = Id::new("op");
1686        let pause = Evt::TurnPause {
1687            turn_id,
1688            reason: super::TurnPauseReason::Question {
1689                tool_use_id: "toolu_1".to_string(),
1690                questions: vec![super::QuestionSpec {
1691                    header: "Auth method".to_string(),
1692                    question: "Which auth method should we use?".to_string(),
1693                    multi_select: false,
1694                    options: vec![
1695                        super::QuestionOption {
1696                            label: "JWT (Recommended)".to_string(),
1697                            description: "Stateless tokens".to_string(),
1698                            preview: None,
1699                        },
1700                        super::QuestionOption {
1701                            label: "Sessions".to_string(),
1702                            description: "Server-side sessions".to_string(),
1703                            preview: Some("fn login() {}".to_string()),
1704                        },
1705                    ],
1706                }],
1707            },
1708        };
1709
1710        let json = serde_json::to_value(&pause).expect("serialize question pause");
1711        // `multi_select` defaults and `preview: None` is skipped, not null.
1712        let spec = &json["TurnPause"]["reason"]["Question"]["questions"][0];
1713        assert!(spec["options"][0].get("preview").is_none());
1714        assert_eq!(spec["options"][1]["preview"], "fn login() {}");
1715
1716        let decoded: Evt = serde_json::from_value(json).expect("deserialize question pause");
1717        let Evt::TurnPause {
1718            reason: super::TurnPauseReason::Question { tool_use_id, questions },
1719            ..
1720        } = decoded
1721        else {
1722            panic!("expected Question pause");
1723        };
1724        assert_eq!(tool_use_id, "toolu_1");
1725        assert_eq!(questions.len(), 1);
1726        assert!(!questions[0].multi_select);
1727
1728        // A spec without `multi_select` on the wire still decodes.
1729        let sparse: super::QuestionSpec = serde_json::from_value(serde_json::json!({
1730            "header": "Scope",
1731            "question": "How broad?",
1732            "options": [],
1733        }))
1734        .unwrap();
1735        assert!(!sparse.multi_select);
1736    }
1737
1738    #[test]
1739    fn question_response_serde_roundtrip() {
1740        let turn_id = Id::new("op");
1741        let op = Op::QuestionResponse {
1742            turn_id,
1743            tool_use_id: "toolu_1".to_string(),
1744            reply: super::QuestionReply::Answered(vec![super::QuestionAnswer {
1745                selected: vec!["JWT".to_string(), "Sessions".to_string()],
1746                note: None,
1747            }]),
1748        };
1749        let json = serde_json::to_string(&op).expect("serialize QuestionResponse");
1750        let decoded: Op = serde_json::from_str(&json).expect("deserialize QuestionResponse");
1751        assert!(matches!(
1752            decoded,
1753            Op::QuestionResponse { tool_use_id, reply: super::QuestionReply::Answered(answers), .. }
1754                if tool_use_id == "toolu_1" && answers[0].selected.len() == 2
1755        ));
1756
1757        // A skip is the bare variant; a discussion request without words is
1758        // an empty object, so `message` is never null on the wire.
1759        for (reply, expected) in [
1760            (super::QuestionReply::Dismissed, serde_json::json!("Dismissed")),
1761            (super::QuestionReply::Discuss { message: None }, serde_json::json!({ "Discuss": {} })),
1762            (
1763                super::QuestionReply::Discuss { message: Some("later".to_string()) },
1764                serde_json::json!({ "Discuss": { "message": "later" } }),
1765            ),
1766        ] {
1767            let json = serde_json::to_value(&reply).expect("serialize reply");
1768            assert_eq!(json, expected);
1769            let decoded: super::QuestionReply =
1770                serde_json::from_value(json).expect("deserialize reply");
1771            assert_eq!(decoded, reply);
1772        }
1773    }
1774
1775    #[test]
1776    fn usage_adds_cache_fields_without_overflowing() {
1777        let mut usage = Usage {
1778            input_tokens: 10,
1779            output_tokens: 20,
1780            cache_read_tokens: Some(3),
1781            cache_creation_tokens: None,
1782        };
1783        usage += Usage {
1784            input_tokens: 5,
1785            output_tokens: 6,
1786            cache_read_tokens: Some(4),
1787            cache_creation_tokens: Some(8),
1788        };
1789
1790        assert_eq!(usage.input_tokens, 15);
1791        assert_eq!(usage.output_tokens, 26);
1792        assert_eq!(usage.total(), 41);
1793        assert_eq!(usage.cache_read_tokens, Some(7));
1794        assert_eq!(usage.cache_creation_tokens, Some(8));
1795    }
1796}