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