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