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 display name chosen by the
502    /// user (or the client), never derived from the conversation.
503    #[serde(default, skip_serializing_if = "Option::is_none")]
504    pub title: Option<String>,
505    /// Set when the session was forked from another (see
506    /// [`Op::ForkSession`]): the session it was forked from.
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    pub forked_from: Option<Id>,
509    /// Set when the session was started by a rollover (see
510    /// [`SessionRequest::rollover`]): the session it continues.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub rolled_from: Option<Id>,
513}
514
515/// Partial update to a live session's mutable state. Each field is optional so
516/// a caller patches only what changed; absent fields are left untouched.
517/// Catalog-dependent fields are resolved before the update takes effect.
518#[derive(Debug, Clone, Default, Serialize, Deserialize)]
519pub struct SessionUpdate {
520    /// Provider change, taking effect on the next turn: the conversation
521    /// continues on the named catalog provider, keeping the session id,
522    /// messages, title and permission state. `model` then names a model on that
523    /// provider; absent, the provider's default. Naming the current provider is
524    /// not a switch. Refused whole, answered with `Error` instead of
525    /// `SessionUpdated`, for an unknown provider id or for another provider
526    /// while a turn is in flight; never re-routed.
527    #[serde(default, skip_serializing_if = "Option::is_none")]
528    pub provider: Option<String>,
529    /// Pin a qualified credential reference on the resulting provider for this
530    /// session. Refused if it is outside that provider's pool, unavailable, or
531    /// a turn is running. Absent keeps the current provider's choice; another
532    /// provider starts from configured precedence.
533    #[serde(default, skip_serializing_if = "Option::is_none")]
534    pub credential: Option<String>,
535    /// Model change, taking effect on the next turn. The spec carries the
536    /// whole request, `effort` included: a set `effort` overrides the
537    /// catalog default; unset fields resolve from the catalog. Resolved on
538    /// the session's provider — the one `provider` names when both are set.
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub model: Option<ModelSpec>,
541    /// Permission mode change, taking effect on the next turn without
542    /// aborting an in-flight one.
543    #[serde(default, skip_serializing_if = "Option::is_none")]
544    pub permission_mode: Option<PermissionMode>,
545    /// Rename the session. The text is trimmed; an empty (or whitespace-only)
546    /// text clears the title.
547    #[serde(default, skip_serializing_if = "Option::is_none")]
548    pub title: Option<String>,
549}
550
551/// The session's MCP servers and their tools, sent for `session_id` as the
552/// servers come online. `skills` and `subagents` repeat the lists the
553/// session's `SessionStart` announced.
554#[derive(Debug, Clone, Serialize, Deserialize)]
555pub struct ExtensionRefreshed {
556    pub session_id: Id,
557    pub skills: Vec<SkillMetadata>,
558    pub subagents: Vec<SubagentMetadata>,
559    #[serde(default)]
560    pub mcp_servers: Vec<McpServerInfo>,
561}
562
563/// One configured MCP server. A local server is described by `command` and
564/// `args`; a remote one by `url`, with `command` empty. `tools` is empty for a
565/// server that failed to connect or exposed nothing.
566#[derive(Debug, Clone, Serialize, Deserialize)]
567pub struct McpServerInfo {
568    pub name: String,
569    pub command: String,
570    pub args: Vec<String>,
571    #[serde(default, skip_serializing_if = "Option::is_none")]
572    pub url: Option<String>,
573    pub tools: Vec<McpToolInfo>,
574}
575
576#[derive(Debug, Clone, Serialize, Deserialize)]
577pub struct McpToolInfo {
578    pub name: String,
579    pub qualified_name: String,
580    pub description: String,
581    pub parameters: Vec<McpToolParam>,
582}
583
584#[derive(Debug, Clone, Serialize, Deserialize)]
585pub struct McpToolParam {
586    pub name: String,
587    pub param_type: String,
588    pub required: bool,
589    pub description: String,
590}
591
592/// The requested session configuration — the payload of [`Op::StartSession`].
593/// A set field is pinned and wins over every default. An unset field means
594/// the host's current default (the user's settings, else built-in), never
595/// "leave unchanged".
596#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
597pub struct SessionRequest {
598    #[serde(default, skip_serializing_if = "Option::is_none")]
599    pub model: Option<String>,
600    #[serde(default, skip_serializing_if = "Option::is_none")]
601    pub provider: Option<String>,
602    /// Pin a qualified credential reference on the session's provider from
603    /// its first request, under the rules of `SessionUpdate::credential`: the
604    /// start is refused if it is outside that provider's pool or unavailable.
605    /// Absent uses configured precedence.
606    #[serde(default, skip_serializing_if = "Option::is_none")]
607    pub credential: Option<String>,
608    #[serde(default, skip_serializing_if = "Option::is_none")]
609    pub permission_mode: Option<PermissionMode>,
610    #[serde(default, skip_serializing_if = "Option::is_none")]
611    pub system_prompt: Option<String>,
612    #[serde(default, skip_serializing_if = "Option::is_none")]
613    pub append_system_prompt: Option<String>,
614    /// Exactly these tools, replacing the default tool set as the base.
615    #[serde(default, skip_serializing_if = "Option::is_none")]
616    pub tools: Option<Vec<String>>,
617    /// Tools added on top of the base set (`tools`, or the default set).
618    #[serde(default, skip_serializing_if = "Option::is_none")]
619    pub include_tools: Option<Vec<String>>,
620    /// Tools removed from the session; wins over `tools` and `include_tools`.
621    #[serde(default, skip_serializing_if = "Option::is_none")]
622    pub exclude_tools: Option<Vec<String>>,
623    #[serde(default, skip_serializing_if = "Option::is_none")]
624    pub cwd: Option<PathBuf>,
625    #[serde(default, skip_serializing_if = "Option::is_none")]
626    pub effort: Option<Effort>,
627    #[serde(default, skip_serializing_if = "Option::is_none")]
628    pub enable_auto_memory: Option<bool>,
629    #[serde(default, skip_serializing_if = "Option::is_none")]
630    pub short_prompt: Option<bool>,
631    /// When true, the session loads no skills: none are discovered,
632    /// advertised, or invocable.
633    #[serde(default, skip_serializing_if = "Option::is_none")]
634    pub no_skills: Option<bool>,
635    /// Skills added to the default set; names match exactly. Does not enable
636    /// skill loading when disabled.
637    #[serde(default, skip_serializing_if = "Option::is_none")]
638    pub include_skills: Option<Vec<String>>,
639    /// Skills removed from the session; names match exactly. Wins over
640    /// `include_skills`.
641    #[serde(default, skip_serializing_if = "Option::is_none")]
642    pub exclude_skills: Option<Vec<String>>,
643    /// Whether the session writes a transcript and a resumable snapshot.
644    #[serde(default, skip_serializing_if = "Option::is_none")]
645    pub save_session: Option<bool>,
646    /// Whether no one can answer an approval prompt for this session. When
647    /// true, a tool call that would pause the turn for approval is denied
648    /// instead of pausing. Absent means false.
649    #[serde(default, skip_serializing_if = "Option::is_none")]
650    pub unattended: Option<bool>,
651    /// A title for the session (see `SessionUpdate::title` for the rules).
652    #[serde(default, skip_serializing_if = "Option::is_none")]
653    pub title: Option<String>,
654    /// Continue the running session in this one. The running session writes
655    /// a handoff of its conversation and ends; this session starts from the
656    /// handoff alone and names that session as its
657    /// [`SessionInfo::rolled_from`]. Refused with an [`Evt::Error`] that
658    /// leaves the running session as it was when there is none, it is not
659    /// idle, it has background jobs running, or the handoff cannot be
660    /// written.
661    #[serde(default, skip_serializing_if = "Option::is_none")]
662    pub rollover: Option<Rollover>,
663}
664
665/// Asks [`Op::StartSession`] for a rollover. `instructions` optionally steer
666/// the handoff, as they steer the summary of [`Op::Compact`].
667#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
668pub struct Rollover {
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub instructions: Option<String>,
671}
672
673impl SessionRequest {
674    /// Fold `patch` onto `self`, field by field: a set field in the patch
675    /// wins, an unset one keeps `self`'s value. The exception is `rollover`,
676    /// which only the patch can ask for: a kept request never rolls over
677    /// again.
678    pub fn patched(self, patch: SessionRequest) -> SessionRequest {
679        // No `..` rest: a new field fails to compile here until its fold
680        // rule is decided.
681        let SessionRequest {
682            model,
683            provider,
684            credential,
685            permission_mode,
686            system_prompt,
687            append_system_prompt,
688            tools,
689            include_tools,
690            exclude_tools,
691            cwd,
692            effort,
693            enable_auto_memory,
694            short_prompt,
695            no_skills,
696            include_skills,
697            exclude_skills,
698            save_session,
699            unattended,
700            title,
701            rollover,
702        } = patch;
703        SessionRequest {
704            model: model.or(self.model),
705            provider: provider.or(self.provider),
706            credential: credential.or(self.credential),
707            permission_mode: permission_mode.or(self.permission_mode),
708            system_prompt: system_prompt.or(self.system_prompt),
709            append_system_prompt: append_system_prompt.or(self.append_system_prompt),
710            tools: tools.or(self.tools),
711            include_tools: include_tools.or(self.include_tools),
712            exclude_tools: exclude_tools.or(self.exclude_tools),
713            cwd: cwd.or(self.cwd),
714            effort: effort.or(self.effort),
715            enable_auto_memory: enable_auto_memory.or(self.enable_auto_memory),
716            short_prompt: short_prompt.or(self.short_prompt),
717            no_skills: no_skills.or(self.no_skills),
718            include_skills: include_skills.or(self.include_skills),
719            exclude_skills: exclude_skills.or(self.exclude_skills),
720            save_session: save_session.or(self.save_session),
721            unattended: unattended.or(self.unattended),
722            title: title.or(self.title),
723            rollover,
724        }
725    }
726}
727
728#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
729pub struct MalformedToolArgs {
730    /// Exact argument text emitted by the model for the undecodable call.
731    pub raw: String,
732    /// Decode diagnostic. This must not contain the raw argument text.
733    pub error: String,
734}
735
736/// Sentinel [`ToolUse::name`] for a call whose stream never delivered a
737/// function name; always paired with `malformed_args`.
738pub const MISSING_TOOL_NAME: &str = "missing_function_name";
739
740#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
741pub struct ToolUse {
742    pub id: String,
743    pub name: String,
744    pub args: serde_json::Value,
745    /// Present when the model's raw call could not be decoded into an
746    /// executable call: `args` that were not valid JSON, or a stream that
747    /// never delivered the function name (`name` is then
748    /// [`MISSING_TOOL_NAME`]). Such a call is non-executable and must be
749    /// returned as an error result.
750    #[serde(default, skip_serializing_if = "Option::is_none")]
751    pub malformed_args: Option<MalformedToolArgs>,
752    #[serde(skip_serializing_if = "Option::is_none")]
753    pub signature: Option<String>,
754}
755
756impl ToolUse {
757    /// A well-formed call: decoded `args`, no malformed metadata, no signature.
758    pub fn new(id: impl Into<String>, name: impl Into<String>, args: serde_json::Value) -> Self {
759        Self { id: id.into(), name: name.into(), args, malformed_args: None, signature: None }
760    }
761}
762
763#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
764pub struct ModelSpec {
765    #[serde(alias = "name")]
766    pub id: String,
767    #[serde(skip_serializing_if = "Option::is_none")]
768    pub display_name: Option<String>,
769    #[serde(skip_serializing_if = "Option::is_none")]
770    pub description: Option<String>,
771    #[serde(skip_serializing_if = "Option::is_none")]
772    pub temperature: Option<f32>,
773    #[serde(skip_serializing_if = "Option::is_none")]
774    pub top_p: Option<f32>,
775    #[serde(skip_serializing_if = "Option::is_none")]
776    pub top_k: Option<u32>,
777    #[serde(skip_serializing_if = "Option::is_none")]
778    pub max_tokens: Option<u32>,
779    #[serde(skip_serializing_if = "Option::is_none")]
780    pub stop_sequences: Option<Vec<String>>,
781    #[serde(skip_serializing_if = "Option::is_none")]
782    pub context_limit: Option<u32>,
783    #[serde(skip_serializing_if = "Option::is_none")]
784    pub effort: Option<Effort>,
785    /// The effort levels this model supports when configured in the user catalog.
786    /// When absent, the provider's built-in model profile supplies the ladder;
787    /// an empty list means that the model takes no effort setting.
788    #[serde(skip_serializing_if = "Option::is_none")]
789    pub supported_efforts: Option<Vec<Effort>>,
790    #[serde(skip_serializing_if = "Option::is_none")]
791    pub support_vision: Option<bool>,
792    #[serde(skip_serializing_if = "Option::is_none")]
793    pub weight_class: Option<WeightClass>,
794}
795
796/// Requested output/reasoning effort for model turns, on an ordinal scale.
797///
798/// `min` is the lowest effort the model supports — thinking is disabled where
799/// the model allows that; models with always-on reasoning clamp to their
800/// lowest level. Providers that expose fewer levels round a requested effort
801/// down to the nearest supported one. Ordered `Min < Low < ... < Max`.
802#[derive(Debug, Clone, Serialize, Deserialize, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
803#[serde(rename_all = "lowercase")]
804pub enum Effort {
805    Min,
806    Low,
807    Medium,
808    High,
809    XHigh,
810    Max,
811}
812
813impl Effort {
814    /// All levels in ascending order.
815    pub const ALL: [Effort; 6] =
816        [Effort::Min, Effort::Low, Effort::Medium, Effort::High, Effort::XHigh, Effort::Max];
817
818    /// The wire token for this level (`"min"`, `"low"`, ..., `"max"`).
819    pub fn as_str(self) -> &'static str {
820        match self {
821            Effort::Min => "min",
822            Effort::Low => "low",
823            Effort::Medium => "medium",
824            Effort::High => "high",
825            Effort::XHigh => "xhigh",
826            Effort::Max => "max",
827        }
828    }
829}
830
831impl std::fmt::Display for Effort {
832    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
833        f.write_str(self.as_str())
834    }
835}
836
837impl std::str::FromStr for Effort {
838    type Err = String;
839
840    fn from_str(s: &str) -> Result<Self, Self::Err> {
841        Effort::ALL.into_iter().find(|e| e.as_str() == s).ok_or_else(|| {
842            format!("unknown effort `{s}` (expected min, low, medium, high, xhigh, max)")
843        })
844    }
845}
846
847/// Size/cost class of a model, set once per model in the catalog: roughly
848/// how large and costly it is to run, independent of the per-request
849/// [`Effort`] and of `context_limit`. Ordered `Feather < Middle < Heavy`.
850#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
851#[serde(rename_all = "lowercase")]
852pub enum WeightClass {
853    /// Small, fast, cheap (Haiku- / GPT-nano-class).
854    Feather,
855    /// Mid workhorse (Sonnet- / GPT-mini- / Gemini-Flash-class).
856    Middle,
857    /// Largest, most capable, costliest (Opus- / GPT-5.x- / Gemini-Pro-class).
858    Heavy,
859}
860
861impl<'de> Deserialize<'de> for WeightClass {
862    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
863    where
864        D: Deserializer<'de>,
865    {
866        let value = String::deserialize(deserializer)?;
867        match value.to_ascii_lowercase().as_str() {
868            "feather" => Ok(Self::Feather),
869            "middle" => Ok(Self::Middle),
870            "heavy" => Ok(Self::Heavy),
871            _ => Err(serde::de::Error::unknown_variant(&value, &["feather", "middle", "heavy"])),
872        }
873    }
874}
875
876/// Token usage for one model response.
877///
878/// For every provider, `input_tokens` is the full, cache-inclusive prompt
879/// size: `cache_read_tokens` and `cache_creation_tokens` are subsets of it
880/// (the latter absent for providers that do not report cache writes). So
881/// [`Usage::total`] (`input + output`) is the context-window occupancy.
882///
883/// The cache buckets bill at their own rates, so subtract them before
884/// applying the input rate:
885/// `cost = (input - cache_read - cache_creation)·p_in
886///        + cache_read·p_cache_read + cache_creation·p_cache_write
887///        + output·p_out`.
888#[derive(Debug, Clone, Deserialize, Serialize, Default, Copy)]
889#[serde(default)]
890pub struct Usage {
891    /// Full prompt tokens, cache-inclusive (a superset of the two cache fields).
892    pub input_tokens: u32,
893    /// Generated output (completion) tokens.
894    pub output_tokens: u32,
895    /// Subset of `input_tokens` served from the prompt cache (cheaper rate).
896    #[serde(skip_serializing_if = "Option::is_none")]
897    pub cache_read_tokens: Option<u32>,
898    /// Subset of `input_tokens` written into the prompt cache (surcharge rate).
899    #[serde(skip_serializing_if = "Option::is_none")]
900    pub cache_creation_tokens: Option<u32>,
901}
902
903/// Context-window occupancy snapshot for the root session. Raw measurements
904/// only: percentages are for clients to derive.
905#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
906pub struct ContextWindow {
907    /// Tokens currently occupying the window (cache-inclusive input + output of
908    /// the most recent response).
909    pub used_tokens: u32,
910    /// Raw model context limit (e.g. 200_000).
911    pub limit_tokens: u32,
912}
913
914/// Per-category breakdown of context-window occupancy.
915///
916/// `used_tokens` is anchored on the provider-reported occupancy once the
917/// session has seen a model response; before that it is estimated. The
918/// per-category fields are estimates that normally sum to `used_tokens`, but
919/// estimation error can make them disagree slightly — clients should clamp
920/// rather than assume an exact identity.
921#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
922#[serde(default)]
923pub struct ContextBreakdown {
924    /// System prompt, excluding the skills and memory sections counted below.
925    pub system_prompt_tokens: u32,
926    /// Built-in tool schemas.
927    pub system_tools_tokens: u32,
928    /// MCP tool schemas.
929    pub mcp_tools_tokens: u32,
930    /// Memory content: project/user instruction files and the auto-memory prompt.
931    pub memory_tokens: u32,
932    /// The available-skills listing.
933    pub skills_tokens: u32,
934    /// Conversation messages: everything not attributed to a category above.
935    pub messages_tokens: u32,
936    /// Total context-window occupancy.
937    pub used_tokens: u32,
938    /// Model context limit. `None` when unverified, so clients never render a
939    /// confidently-wrong percentage.
940    pub limit_tokens: Option<u32>,
941    /// Tokens reserved at the top of the window; auto-compaction triggers once
942    /// occupancy grows into this reserve.
943    pub compact_buffer_tokens: u32,
944}
945
946impl Usage {
947    pub fn new(input_tokens: u32, output_tokens: u32) -> Self {
948        Self { input_tokens, output_tokens, cache_read_tokens: None, cache_creation_tokens: None }
949    }
950
951    /// Context-window occupancy: the full (cache-inclusive) prompt plus output.
952    pub fn total(&self) -> u32 {
953        self.input_tokens.saturating_add(self.output_tokens)
954    }
955}
956
957impl std::ops::Add<Usage> for Usage {
958    type Output = Usage;
959
960    fn add(self, other: Usage) -> Usage {
961        Usage {
962            input_tokens: self.input_tokens.saturating_add(other.input_tokens),
963            output_tokens: self.output_tokens.saturating_add(other.output_tokens),
964            cache_read_tokens: add_optional_u32(self.cache_read_tokens, other.cache_read_tokens),
965            cache_creation_tokens: add_optional_u32(
966                self.cache_creation_tokens,
967                other.cache_creation_tokens,
968            ),
969        }
970    }
971}
972
973fn add_optional_u32(a: Option<u32>, b: Option<u32>) -> Option<u32> {
974    match (a, b) {
975        (None, None) => None,
976        _ => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))),
977    }
978}
979
980impl std::ops::AddAssign<Usage> for Usage {
981    fn add_assign(&mut self, other: Usage) {
982        *self = *self + other;
983    }
984}
985
986#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, Eq, PartialEq)]
987#[serde(rename_all = "snake_case")]
988pub enum PermissionMode {
989    /// Honor user rules; an unmatched call asks unless it is provably safe.
990    #[default]
991    Strict,
992    /// Honor user rules; an unmatched call runs unless it is provably
993    /// dangerous (a deliberately narrow classification).
994    Auto,
995    /// Bypass all permission checks, including user deny rules.
996    Yolo,
997}
998
999#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1000#[serde(rename_all = "kebab-case")]
1001pub enum Scope {
1002    Project,
1003    User,
1004    System,
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009    use super::{
1010        ContextBreakdown, Effort, Evt, Id, ModelSpec, Op, PermissionMode, ProviderSpec,
1011        QuestionAnswer, QuestionOption, QuestionReply, QuestionSpec, ReviewDecision, Rollover,
1012        SessionInfo, SessionRequest, ToolDecision, ToolEnd, ToolEndStatus, ToolUse, TurnEndStatus,
1013        TurnPauseReason, Usage, WeightClass,
1014    };
1015    use std::path::PathBuf;
1016
1017    fn model_spec(name: &str) -> ModelSpec {
1018        ModelSpec { id: name.to_string(), ..Default::default() }
1019    }
1020
1021    #[test]
1022    fn tool_use_without_malformed_args_remains_backward_compatible() {
1023        let tool_use: ToolUse = serde_json::from_value(serde_json::json!({
1024            "id": "call-1",
1025            "name": "Read",
1026            "args": { "file_path": "README.md" }
1027        }))
1028        .unwrap();
1029
1030        assert!(tool_use.malformed_args.is_none());
1031        let encoded = serde_json::to_value(tool_use).unwrap();
1032        assert!(encoded.get("malformed_args").is_none());
1033    }
1034
1035    #[test]
1036    fn tool_end_without_name_remains_backward_compatible() {
1037        let legacy = serde_json::json!({
1038            "tool_use_id": "call-1",
1039            "status": "Denied",
1040            "result_json": "Tool call denied by policy and was not executed."
1041        });
1042        let mut end: ToolEnd = serde_json::from_value(legacy.clone()).unwrap();
1043        assert!(end.tool_name.is_empty());
1044        assert_eq!(end.status, ToolEndStatus::Denied);
1045
1046        end.tool_name = "Bash".to_string();
1047        let mut expected = legacy;
1048        expected["tool_name"] = serde_json::json!("Bash");
1049        assert_eq!(serde_json::to_value(end).unwrap(), expected);
1050    }
1051
1052    #[test]
1053    fn task_end_round_trips_with_observed_or_unobserved_exit() {
1054        for exit_code in [Some(2), None] {
1055            let json = serde_json::json!({
1056                "TaskEnd": { "tool_use_id": "bash-1", "exit_code": exit_code }
1057            });
1058            let event: Evt = serde_json::from_value(json.clone()).unwrap();
1059            assert!(matches!(&event, Evt::TaskEnd { tool_use_id, exit_code: code }
1060                if tool_use_id == "bash-1" && *code == exit_code));
1061            assert_eq!(serde_json::to_value(event).unwrap(), json);
1062        }
1063    }
1064
1065    #[test]
1066    fn turn_end_error_kind_is_optional_on_the_wire() {
1067        // Payloads from daemons predating the field still deserialize.
1068        let old: TurnEndStatus = serde_json::from_value(serde_json::json!({
1069            "Error": { "headline": "authentication error", "details": [] }
1070        }))
1071        .unwrap();
1072        let TurnEndStatus::Error { kind, .. } = &old else {
1073            panic!("expected Error variant");
1074        };
1075        assert!(kind.is_none());
1076
1077        // None is skipped, not emitted as null.
1078        let json = serde_json::to_value(&old).unwrap();
1079        assert!(json["Error"].get("kind").is_none());
1080
1081        // Some round-trips.
1082        let with = TurnEndStatus::Error {
1083            kind: Some("oauth".to_string()),
1084            headline: "OAuth sign-in required".to_string(),
1085            details: vec![],
1086        };
1087        let json = serde_json::to_value(&with).unwrap();
1088        assert_eq!(json["Error"]["kind"], "oauth");
1089    }
1090
1091    #[test]
1092    fn turn_end_steps_default_for_older_events() {
1093        let event =
1094            Evt::TurnEnd { turn_id: Id::new("turn"), status: TurnEndStatus::Completed, steps: 3 };
1095        let mut json = serde_json::to_value(&event).unwrap();
1096        json["TurnEnd"].as_object_mut().unwrap().remove("steps");
1097        let old: Evt = serde_json::from_value(json).unwrap();
1098
1099        assert!(matches!(old, Evt::TurnEnd { steps: 0, .. }));
1100
1101        let json = serde_json::to_value(event).unwrap();
1102        assert_eq!(json["TurnEnd"]["steps"], 3);
1103    }
1104
1105    #[test]
1106    fn effort_serializes_as_lowercase_tokens() {
1107        let mut spec = model_spec("m");
1108        spec.effort = Some(Effort::XHigh);
1109        let json = serde_json::to_value(&spec).unwrap();
1110        assert_eq!(json["effort"], "xhigh");
1111
1112        // None is skipped, not emitted as null.
1113        let json_none = serde_json::to_value(model_spec("m")).unwrap();
1114        assert!(json_none.get("effort").is_none());
1115
1116        // Every level round-trips through its wire token.
1117        for level in Effort::ALL {
1118            let parsed: ModelSpec =
1119                serde_json::from_value(serde_json::json!({"id": "m", "effort": level.as_str()}))
1120                    .unwrap();
1121            assert_eq!(parsed.effort, Some(level), "round-trip {level}");
1122        }
1123    }
1124
1125    #[test]
1126    fn skill_filters_are_optional_on_the_wire_and_preserve_empty_overrides() {
1127        let absent: SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
1128        assert_eq!(absent.include_skills, None);
1129        assert_eq!(absent.exclude_skills, None);
1130        let encoded = serde_json::to_value(absent).unwrap();
1131        assert!(encoded.get("include_skills").is_none());
1132        assert!(encoded.get("exclude_skills").is_none());
1133
1134        let json = serde_json::json!({"include_skills": ["Review"], "exclude_skills": []});
1135        let parsed: SessionRequest = serde_json::from_value(json.clone()).unwrap();
1136        assert_eq!(parsed.include_skills, Some(vec!["Review".to_string()]));
1137        assert_eq!(parsed.exclude_skills, Some(Vec::new()));
1138        assert_eq!(serde_json::to_value(parsed).unwrap(), json);
1139    }
1140
1141    fn pinned_request() -> SessionRequest {
1142        SessionRequest {
1143            model: Some("base-model".to_string()),
1144            provider: Some("anthropic".to_string()),
1145            credential: Some("oauth:anthropic/work".to_string()),
1146            permission_mode: Some(PermissionMode::Strict),
1147            system_prompt: Some("base prompt".to_string()),
1148            cwd: Some(PathBuf::from("/base")),
1149            effort: Some(Effort::Medium),
1150            enable_auto_memory: Some(true),
1151            short_prompt: Some(true),
1152            no_skills: Some(true),
1153            include_skills: Some(vec!["review".to_string()]),
1154            exclude_skills: Some(vec!["noisy".to_string()]),
1155            save_session: Some(true),
1156            unattended: Some(true),
1157            title: Some("pinned title".to_string()),
1158            ..Default::default()
1159        }
1160    }
1161
1162    #[test]
1163    fn patched_overwrites_only_the_patch_set_fields() {
1164        let patched = pinned_request().patched(SessionRequest {
1165            model: Some("new-model".to_string()),
1166            permission_mode: Some(PermissionMode::Yolo),
1167            enable_auto_memory: Some(false),
1168            short_prompt: Some(false),
1169            include_skills: Some(Vec::new()),
1170            ..Default::default()
1171        });
1172        // Overwritten by the patch:
1173        assert_eq!(patched.model.as_deref(), Some("new-model"));
1174        assert_eq!(patched.permission_mode, Some(PermissionMode::Yolo));
1175        assert_eq!(patched.enable_auto_memory, Some(false));
1176        assert_eq!(patched.short_prompt, Some(false));
1177        assert_eq!(patched.include_skills, Some(Vec::new()));
1178        // Untouched (patch unset == keep):
1179        assert_eq!(patched.provider.as_deref(), Some("anthropic"));
1180        assert_eq!(patched.credential.as_deref(), Some("oauth:anthropic/work"));
1181        assert_eq!(patched.system_prompt.as_deref(), Some("base prompt"));
1182        assert_eq!(patched.effort, Some(Effort::Medium));
1183        assert_eq!(patched.save_session, Some(true));
1184        assert_eq!(patched.unattended, Some(true));
1185        assert_eq!(patched.title.as_deref(), Some("pinned title"));
1186        assert_eq!(patched.exclude_skills, Some(vec!["noisy".to_string()]));
1187    }
1188
1189    #[test]
1190    fn rewind_names_its_input_as_to() {
1191        let to = Id::op();
1192        let json = serde_json::to_value(Op::RewindSession { to }).unwrap();
1193        assert_eq!(json, serde_json::json!({ "RewindSession": { "to": to } }));
1194        let op: Op = serde_json::from_value(json).unwrap();
1195        assert!(matches!(op, Op::RewindSession { to: decoded } if decoded == to));
1196
1197        let json = serde_json::to_value(Evt::SessionRewound { to }).unwrap();
1198        assert_eq!(json, serde_json::json!({ "SessionRewound": { "to": to } }));
1199    }
1200
1201    #[test]
1202    fn fork_at_is_optional_on_the_wire() {
1203        let whole: Op = serde_json::from_value(serde_json::json!({ "ForkSession": {} })).unwrap();
1204        assert!(matches!(whole, Op::ForkSession { at: None }));
1205
1206        let at = Id::op();
1207        let json = serde_json::to_value(Op::ForkSession { at: Some(at) }).unwrap();
1208        assert_eq!(json, serde_json::json!({ "ForkSession": { "at": at } }));
1209        let op: Op = serde_json::from_value(json).unwrap();
1210        assert!(matches!(op, Op::ForkSession { at: Some(decoded) } if decoded == at));
1211
1212        let (forked_from, session_id) = (Id::ses(), Id::ses());
1213        let forked = Evt::SessionForked { forked_from, session_id, at: None };
1214        assert_eq!(
1215            serde_json::to_value(forked).unwrap(),
1216            serde_json::json!({
1217                "SessionForked": { "forked_from": forked_from, "session_id": session_id }
1218            })
1219        );
1220    }
1221
1222    #[test]
1223    fn forked_from_is_optional_on_the_wire() {
1224        let source = Id::ses();
1225        let info = SessionInfo { forked_from: Some(source), ..Default::default() };
1226        let mut json = serde_json::to_value(&info).unwrap();
1227        assert_eq!(json["forked_from"], serde_json::json!(source));
1228        let decoded: SessionInfo = serde_json::from_value(json.clone()).unwrap();
1229        assert_eq!(decoded.forked_from, Some(source));
1230
1231        // A payload written before the field existed reads as not forked.
1232        json.as_object_mut().unwrap().remove("forked_from");
1233        let plain: SessionInfo = serde_json::from_value(json).unwrap();
1234        assert_eq!(plain.forked_from, None);
1235        assert!(serde_json::to_value(&plain).unwrap().get("forked_from").is_none());
1236    }
1237
1238    // A rollover rides optional fields: a request that asks for none and a
1239    // session that was not rolled over serialize as they did before.
1240    #[test]
1241    fn a_rollover_is_optional_on_the_wire() {
1242        let plain = serde_json::to_value(SessionRequest::default()).unwrap();
1243        assert!(plain.get("rollover").is_none());
1244        let decoded: SessionRequest = serde_json::from_value(plain).unwrap();
1245        assert_eq!(decoded.rollover, None);
1246
1247        let rollover = Rollover { instructions: Some("keep the open bugs".to_string()) };
1248        let asked = SessionRequest { rollover: Some(rollover.clone()), ..Default::default() };
1249        let json = serde_json::to_value(&asked).unwrap();
1250        assert_eq!(json["rollover"], serde_json::json!({ "instructions": "keep the open bugs" }));
1251        let decoded: SessionRequest = serde_json::from_value(json).unwrap();
1252        assert_eq!(decoded.rollover, Some(rollover));
1253        let bare: SessionRequest =
1254            serde_json::from_value(serde_json::json!({ "rollover": {} })).unwrap();
1255        assert_eq!(bare.rollover, Some(Rollover::default()));
1256
1257        let source = Id::ses();
1258        let info = SessionInfo { rolled_from: Some(source), ..Default::default() };
1259        let mut json = serde_json::to_value(&info).unwrap();
1260        assert_eq!(json["rolled_from"], serde_json::json!(source));
1261        json.as_object_mut().unwrap().remove("rolled_from");
1262        let plain: SessionInfo = serde_json::from_value(json).unwrap();
1263        assert_eq!(plain.rolled_from, None);
1264        assert!(serde_json::to_value(&plain).unwrap().get("rolled_from").is_none());
1265    }
1266
1267    // Only the patch asks for a rollover: the request a client keeps and
1268    // sends again starts an empty conversation.
1269    #[test]
1270    fn a_kept_request_never_rolls_over_again() {
1271        let kept = SessionRequest { rollover: Some(Rollover::default()), ..pinned_request() };
1272        assert_eq!(kept.clone().patched(SessionRequest::default()).rollover, None);
1273        let again = SessionRequest { rollover: Some(Rollover::default()), ..Default::default() };
1274        assert_eq!(kept.patched(again).rollover, Some(Rollover::default()));
1275    }
1276
1277    #[test]
1278    fn unattended_is_optional_on_the_wire() {
1279        // A request without the field, and a resume op written before the
1280        // field existed, both read as attended.
1281        let request: SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
1282        assert_eq!(request.unattended, None);
1283
1284        let op = Op::ResumeSession {
1285            session_id: Id::new("ses"),
1286            unattended: true,
1287            tools: None,
1288            include_tools: None,
1289            exclude_tools: None,
1290            credential: None,
1291            permission_mode: None,
1292        };
1293        let mut json = serde_json::to_value(&op).unwrap();
1294        json["ResumeSession"].as_object_mut().unwrap().remove("unattended");
1295        let decoded: Op = serde_json::from_value(json).unwrap();
1296        assert!(matches!(
1297            decoded,
1298            Op::ResumeSession {
1299                unattended: false,
1300                tools: None,
1301                include_tools: None,
1302                exclude_tools: None,
1303                credential: None,
1304                permission_mode: None,
1305                ..
1306            }
1307        ));
1308    }
1309
1310    #[test]
1311    fn resume_tool_filters_roundtrip_including_an_empty_base() {
1312        for tools in [None, Some(vec![]), Some(vec!["Read".to_string()])] {
1313            let op = Op::ResumeSession {
1314                session_id: Id::ses(),
1315                unattended: true,
1316                tools: tools.clone(),
1317                include_tools: Some(vec!["Bash".to_string()]),
1318                exclude_tools: Some(vec!["Agent".to_string()]),
1319                credential: Some("oauth:anthropic/work".to_string()),
1320                permission_mode: Some(PermissionMode::Strict),
1321            };
1322            let json = serde_json::to_value(&op).unwrap();
1323            assert_eq!(json["ResumeSession"].get("tools").is_none(), tools.is_none());
1324            assert_eq!(json["ResumeSession"]["credential"], "oauth:anthropic/work");
1325            assert_eq!(json["ResumeSession"]["permission_mode"], "strict");
1326            let decoded: Op = serde_json::from_value(json).unwrap();
1327            let Op::ResumeSession {
1328                tools: decoded_tools,
1329                include_tools,
1330                exclude_tools,
1331                permission_mode,
1332                ..
1333            } = decoded
1334            else {
1335                panic!("expected ResumeSession");
1336            };
1337            assert_eq!(permission_mode, Some(PermissionMode::Strict));
1338            assert_eq!(decoded_tools, tools);
1339            assert_eq!(include_tools, Some(vec!["Bash".to_string()]));
1340            assert_eq!(exclude_tools, Some(vec!["Agent".to_string()]));
1341        }
1342    }
1343
1344    #[test]
1345    fn session_initialized_title_is_optional_on_the_wire() {
1346        let mut payload = SessionInfo {
1347            model: model_spec("m"),
1348            provider: provider_spec("p"),
1349            session_id: Id::new("ses"),
1350            cwd: PathBuf::from("/tmp"),
1351            ..Default::default()
1352        };
1353
1354        let json = serde_json::to_value(&payload).unwrap();
1355        assert!(json.get("title").is_none(), "an unset title is omitted: {json}");
1356        let decoded: SessionInfo = serde_json::from_value(json).unwrap();
1357        assert_eq!(decoded.title, None);
1358
1359        payload.title = Some("fix".to_string());
1360        let json = serde_json::to_value(&payload).unwrap();
1361        assert_eq!(json["title"], "fix");
1362    }
1363
1364    #[test]
1365    fn weight_class_serializes_lowercase_and_is_omitted_when_none() {
1366        let mut spec = model_spec("m");
1367        spec.weight_class = Some(WeightClass::Heavy);
1368        let json = serde_json::to_value(&spec).unwrap();
1369        assert_eq!(json["weight_class"], "heavy");
1370
1371        // None is skipped, not emitted as null.
1372        let json_none = serde_json::to_value(model_spec("m")).unwrap();
1373        assert!(json_none.get("weight_class").is_none());
1374
1375        // Round-trips from the lowercase wire form.
1376        let parsed: ModelSpec =
1377            serde_json::from_value(serde_json::json!({"id": "m", "weight_class": "feather"}))
1378                .unwrap();
1379        assert_eq!(parsed.weight_class, Some(WeightClass::Feather));
1380    }
1381
1382    #[test]
1383    fn weight_class_deserializes_case_insensitively() {
1384        for (value, expected) in [
1385            ("Feather", WeightClass::Feather),
1386            ("MIDDLE", WeightClass::Middle),
1387            ("hEaVy", WeightClass::Heavy),
1388        ] {
1389            let parsed: ModelSpec =
1390                serde_json::from_value(serde_json::json!({"id": "m", "weight_class": value}))
1391                    .unwrap();
1392            assert_eq!(parsed.weight_class, Some(expected));
1393        }
1394    }
1395
1396    fn provider_spec(name: &str) -> ProviderSpec {
1397        ProviderSpec {
1398            id: name.to_string(),
1399            display_name: name.to_string(),
1400            base_url: format!("https://api.{name}.test/v1"),
1401            ..Default::default()
1402        }
1403    }
1404
1405    #[test]
1406    fn provider_credential_is_optional_on_the_wire() {
1407        let mut info = SessionInfo { provider: provider_spec("antix"), ..Default::default() };
1408        info.provider.credential = Some("oauth:antix/work".into());
1409
1410        let mut json = serde_json::to_value(&info).unwrap();
1411        assert!(json.get("credentials").is_none());
1412        assert!(json["provider"].get("credentials").is_none());
1413        assert_eq!(json["provider"]["credential"], "oauth:antix/work");
1414        let decoded: SessionInfo = serde_json::from_value(json.clone()).unwrap();
1415        assert_eq!(decoded.provider.credential, info.provider.credential);
1416
1417        json["provider"].as_object_mut().unwrap().remove("credential");
1418        let decoded: SessionInfo = serde_json::from_value(json).unwrap();
1419        assert!(decoded.provider.credential.is_none());
1420        assert!(serde_json::to_value(decoded).unwrap()["provider"].get("credential").is_none());
1421    }
1422
1423    #[test]
1424    fn compact_events_serde_roundtrip() {
1425        let compact_start =
1426            serde_json::to_string(&Evt::CompactStart).expect("serialize CompactStart");
1427        let compact_end =
1428            serde_json::to_string(&Evt::CompactEnd { summary: Some("the summary".to_string()) })
1429                .expect("serialize CompactEnd");
1430
1431        assert_eq!(compact_start, "\"CompactStart\"");
1432        assert_eq!(compact_end, r#"{"CompactEnd":{"summary":"the summary"}}"#);
1433
1434        assert!(matches!(
1435            serde_json::from_str::<Evt>(&compact_start).expect("deserialize CompactStart"),
1436            Evt::CompactStart
1437        ));
1438        assert!(matches!(
1439            serde_json::from_str::<Evt>(&compact_end).expect("deserialize CompactEnd"),
1440            Evt::CompactEnd { summary: Some(s) } if s == "the summary"
1441        ));
1442        assert!(matches!(
1443            serde_json::from_str::<Evt>(r#"{"CompactEnd":{}}"#)
1444                .expect("deserialize CompactEnd without summary"),
1445            Evt::CompactEnd { summary: None }
1446        ));
1447    }
1448
1449    #[test]
1450    fn compact_op_serde_roundtrip() {
1451        let plain = serde_json::to_string(&Op::Compact { instructions: None })
1452            .expect("serialize bare Compact");
1453        assert_eq!(plain, r#"{"Compact":{}}"#);
1454        assert!(matches!(
1455            serde_json::from_str::<Op>(&plain).expect("deserialize bare Compact"),
1456            Op::Compact { instructions: None }
1457        ));
1458
1459        let steered =
1460            serde_json::to_string(&Op::Compact { instructions: Some("keep dates".to_string()) })
1461                .expect("serialize steered Compact");
1462        assert_eq!(steered, r#"{"Compact":{"instructions":"keep dates"}}"#);
1463        assert!(matches!(
1464            serde_json::from_str::<Op>(&steered).expect("deserialize steered Compact"),
1465            Op::Compact { instructions: Some(text) } if text == "keep dates"
1466        ));
1467    }
1468
1469    #[test]
1470    fn approval_response_uses_named_tool_decisions() {
1471        let turn_id = Id::new("turn");
1472        let op = Op::ApprovalResponse {
1473            turn_id,
1474            responses: vec![ToolDecision {
1475                tool_use_id: "call-1".to_string(),
1476                decision: ReviewDecision::Deny,
1477                message: Some("use the read-only endpoint".to_string()),
1478            }],
1479        };
1480
1481        let json = serde_json::to_value(&op).expect("serialize ApprovalResponse");
1482        assert_eq!(
1483            json["ApprovalResponse"]["responses"],
1484            serde_json::json!([{
1485                "tool_use_id": "call-1",
1486                "decision": "Deny",
1487                "message": "use the read-only endpoint"
1488            }])
1489        );
1490
1491        let decoded = serde_json::from_value::<Op>(json).expect("deserialize ApprovalResponse");
1492        assert!(matches!(
1493            decoded,
1494            Op::ApprovalResponse { turn_id: id, responses }
1495                if id == turn_id
1496                    && responses == vec![ToolDecision {
1497                        tool_use_id: "call-1".to_string(),
1498                        decision: ReviewDecision::Deny,
1499                        message: Some("use the read-only endpoint".to_string()),
1500                    }]
1501        ));
1502    }
1503
1504    #[test]
1505    fn context_report_serde_roundtrip() {
1506        let breakdown = ContextBreakdown {
1507            system_prompt_tokens: 1200,
1508            system_tools_tokens: 3400,
1509            mcp_tools_tokens: 0,
1510            memory_tokens: 800,
1511            skills_tokens: 150,
1512            messages_tokens: 42_000,
1513            used_tokens: 47_550,
1514            limit_tokens: Some(200_000),
1515            compact_buffer_tokens: 20_000,
1516        };
1517        let json = serde_json::to_value(Evt::ContextReport(breakdown)).expect("serialize");
1518        assert_eq!(
1519            json,
1520            serde_json::json!({
1521                "ContextReport": {
1522                    "system_prompt_tokens": 1200,
1523                    "system_tools_tokens": 3400,
1524                    "mcp_tools_tokens": 0,
1525                    "memory_tokens": 800,
1526                    "skills_tokens": 150,
1527                    "messages_tokens": 42000,
1528                    "used_tokens": 47550,
1529                    "limit_tokens": 200000,
1530                    "compact_buffer_tokens": 20000
1531                }
1532            })
1533        );
1534        let decoded = serde_json::from_value::<Evt>(json).expect("deserialize");
1535        assert!(matches!(decoded, Evt::ContextReport(b) if b == breakdown));
1536
1537        // Fields absent on the wire (older daemons) fall back to defaults.
1538        let sparse: ContextBreakdown =
1539            serde_json::from_value(serde_json::json!({"used_tokens": 10})).unwrap();
1540        assert_eq!(sparse.used_tokens, 10);
1541        assert_eq!(sparse.limit_tokens, None);
1542
1543        let op = serde_json::to_value(Op::ContextReport).expect("serialize op");
1544        assert_eq!(op, serde_json::json!("ContextReport"));
1545        assert!(matches!(serde_json::from_value::<Op>(op).unwrap(), Op::ContextReport));
1546    }
1547
1548    #[test]
1549    fn question_pause_serde_roundtrip() {
1550        let turn_id = Id::new("op");
1551        let pause = Evt::TurnPause {
1552            turn_id,
1553            reason: TurnPauseReason::Question {
1554                tool_use_id: "toolu_1".to_string(),
1555                questions: vec![QuestionSpec {
1556                    header: "Auth method".to_string(),
1557                    question: "Which auth method should we use?".to_string(),
1558                    multi_select: false,
1559                    options: vec![
1560                        QuestionOption {
1561                            label: "JWT (Recommended)".to_string(),
1562                            description: "Stateless tokens".to_string(),
1563                            preview: None,
1564                        },
1565                        QuestionOption {
1566                            label: "Sessions".to_string(),
1567                            description: "Server-side sessions".to_string(),
1568                            preview: Some("fn login() {}".to_string()),
1569                        },
1570                    ],
1571                }],
1572            },
1573        };
1574
1575        let json = serde_json::to_value(&pause).expect("serialize question pause");
1576        // `multi_select` defaults and `preview: None` is skipped, not null.
1577        let spec = &json["TurnPause"]["reason"]["Question"]["questions"][0];
1578        assert!(spec["options"][0].get("preview").is_none());
1579        assert_eq!(spec["options"][1]["preview"], "fn login() {}");
1580
1581        let decoded: Evt = serde_json::from_value(json).expect("deserialize question pause");
1582        let Evt::TurnPause { reason: TurnPauseReason::Question { tool_use_id, questions }, .. } =
1583            decoded
1584        else {
1585            panic!("expected Question pause");
1586        };
1587        assert_eq!(tool_use_id, "toolu_1");
1588        assert_eq!(questions.len(), 1);
1589        assert!(!questions[0].multi_select);
1590
1591        // A spec without `multi_select` on the wire still decodes.
1592        let sparse: QuestionSpec = serde_json::from_value(serde_json::json!({
1593            "header": "Scope",
1594            "question": "How broad?",
1595            "options": [],
1596        }))
1597        .unwrap();
1598        assert!(!sparse.multi_select);
1599    }
1600
1601    #[test]
1602    fn question_response_serde_roundtrip() {
1603        let turn_id = Id::new("op");
1604        let op = Op::QuestionResponse {
1605            turn_id,
1606            tool_use_id: "toolu_1".to_string(),
1607            reply: QuestionReply::Answered(vec![QuestionAnswer {
1608                selected: vec!["JWT".to_string(), "Sessions".to_string()],
1609                note: None,
1610            }]),
1611        };
1612        let json = serde_json::to_string(&op).expect("serialize QuestionResponse");
1613        let decoded: Op = serde_json::from_str(&json).expect("deserialize QuestionResponse");
1614        assert!(matches!(
1615            decoded,
1616            Op::QuestionResponse { tool_use_id, reply: QuestionReply::Answered(answers), .. }
1617                if tool_use_id == "toolu_1" && answers[0].selected.len() == 2
1618        ));
1619
1620        // A skip is the bare variant; a discussion request without words is
1621        // an empty object, so `message` is never null on the wire.
1622        for (reply, expected) in [
1623            (QuestionReply::Dismissed, serde_json::json!("Dismissed")),
1624            (QuestionReply::Discuss { message: None }, serde_json::json!({ "Discuss": {} })),
1625            (
1626                QuestionReply::Discuss { message: Some("later".to_string()) },
1627                serde_json::json!({ "Discuss": { "message": "later" } }),
1628            ),
1629        ] {
1630            let json = serde_json::to_value(&reply).expect("serialize reply");
1631            assert_eq!(json, expected);
1632            let decoded: QuestionReply = serde_json::from_value(json).expect("deserialize reply");
1633            assert_eq!(decoded, reply);
1634        }
1635    }
1636
1637    #[test]
1638    fn usage_adds_cache_fields_without_overflowing() {
1639        let mut usage = Usage {
1640            input_tokens: 10,
1641            output_tokens: 20,
1642            cache_read_tokens: Some(3),
1643            cache_creation_tokens: None,
1644        };
1645        usage += Usage {
1646            input_tokens: 5,
1647            output_tokens: 6,
1648            cache_read_tokens: Some(4),
1649            cache_creation_tokens: Some(8),
1650        };
1651
1652        assert_eq!(usage.input_tokens, 15);
1653        assert_eq!(usage.output_tokens, 26);
1654        assert_eq!(usage.total(), 41);
1655        assert_eq!(usage.cache_read_tokens, Some(7));
1656        assert_eq!(usage.cache_creation_tokens, Some(8));
1657    }
1658}