Skip to main content

ante_protocol_shape/
msg.rs

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