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