Skip to main content

ante_protocol_shape/
msg.rs

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