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