Skip to main content

ante_protocol_shape/
msg.rs

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