Skip to main content

claude_code_agent/
protocol.rs

1//! Wire types for the Claude Code stream-json protocol.
2//! Source: the Claude Code 2.1.328 binary's zod schemas and the official
3//! Python SDK (claude_agent_sdk 0.1.48); citations are on the types they cover.
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6
7// ─── Outbound: host → CLI ────────────────────────────────────────────────────
8//
9// Wire format verified against the official Python SDK
10// (claude_agent_sdk 0.1.48, _internal/query.py:150–160, :238–375) and the
11// zod schemas inside the Claude Code 2.1.328 binary.
12
13/// Envelope for every host → CLI control request:
14/// `{"type":"control_request","request_id":"…","request":{"subtype":"…",…}}`.
15/// Source: query.py:368–372
16#[derive(Debug, Clone, Serialize)]
17pub struct OutboundControlRequest<'a, B: Serialize> {
18    #[serde(rename = "type")]
19    pub kind: &'static str, // "control_request"
20    pub request_id: &'a str,
21    pub request: &'a B,
22}
23
24/// Body of the `initialize` control request — the first stdin line.
25///
26/// Process-level settings (cwd, model, permission mode, session id) are CLI
27/// flags, not initialize fields; they live on `SessionOptions`.
28/// `hooks` is filled in by `Session::spawn` from `SessionOptions::hooks`.
29/// Source: binary initialize schema (subtype "initialize", hooks, agents,
30/// systemPrompt, appendSystemPrompt, jsonSchema, …); query.py:150–155
31#[derive(Debug, Clone, Serialize, Default)]
32#[serde(rename_all = "camelCase")]
33pub struct Initialize {
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub hooks: Option<HashMap<HookEventKind, Vec<HookMatcherConfig>>>,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub system_prompt: Option<String>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub append_system_prompt: Option<String>,
40    /// Subagent definitions, keyed by agent name.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub agents: Option<serde_json::Value>,
43    /// JSON schema for structured output; the result arrives in
44    /// `TurnResult::structured_output`.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub json_schema: Option<serde_json::Value>,
47    /// Session title; skips automatic title generation.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub title: Option<String>,
50    /// Load only the skills with these names.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub skills: Option<Vec<String>>,
53    /// Plugins to load, e.g. `{"type": "local", "path": "./my-plugin"}`.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub plugins: Option<Vec<serde_json::Value>>,
56    /// MCP servers the CLI runs or connects to, keyed by name: stdio
57    /// (`{"command": …, "args": […]}`), `http` or `sse` configs.
58    /// In-process servers go in `SessionOptions::mcp_servers`.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub mcp_servers: Option<serde_json::Map<String, serde_json::Value>>,
61    /// Replaces the default plan-mode workflow text.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub plan_mode_instructions: Option<String>,
64    /// Omit per-user dynamic sections (working directory, memory path) from
65    /// the system prompt, so it caches across users.
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub exclude_dynamic_sections: Option<bool>,
68    /// Record the system prompt once per conversation and reuse it verbatim.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub system_prompt_snapshot: Option<bool>,
71    /// Emit `prompt_suggestion` frames after turns.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub prompt_suggestions: Option<bool>,
74    /// Emit progress summaries of running subagents.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub agent_progress_summaries: Option<bool>,
77    /// Forward subagent text and thinking.
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub forward_subagent_text: Option<bool>,
80    /// Tool-name aliases applied before tool-name resolution.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub tool_aliases: Option<HashMap<String, String>>,
83    /// `request_user_dialog` kinds `SessionOptions::on_user_dialog` renders;
84    /// the CLI sends only these kinds.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub supported_dialog_kinds: Option<Vec<String>>,
87    /// Declares that the host renders a per-task stop control (`stop_task`).
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub per_task_stop_affordance: Option<bool>,
90    /// Workspace trust the host obtained from the user for `directory`.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub workspace_trust: Option<WorkspaceTrust>,
93}
94
95/// Send `accepted: true` only after the user accepted a trust dialog for
96/// `directory`. Source: binary initialize.workspaceTrust schema
97#[derive(Debug, Clone, Serialize)]
98pub struct WorkspaceTrust {
99    pub accepted: bool,
100    pub directory: String,
101}
102
103/// One hook matcher in the initialize request.
104/// Source: query.py:142–147 (`matcher`, `hookCallbackIds`, `timeout`)
105#[derive(Debug, Clone, Serialize)]
106#[serde(rename_all = "camelCase")]
107pub struct HookMatcherConfig {
108    pub matcher: Option<String>,
109    pub hook_callback_ids: Vec<String>,
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub timeout: Option<u32>,
112}
113
114/// Permission modes accepted by `--permission-mode` and `set_permission_mode`.
115/// Source: binary permission-mode enum
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub enum PermissionMode {
119    Default,
120    AcceptEdits,
121    BypassPermissions,
122    Plan,
123    DontAsk,
124    Auto,
125}
126
127impl PermissionMode {
128    pub fn as_str(self) -> &'static str {
129        match self {
130            Self::Default => "default",
131            Self::AcceptEdits => "acceptEdits",
132            Self::BypassPermissions => "bypassPermissions",
133            Self::Plan => "plan",
134            Self::DontAsk => "dontAsk",
135            Self::Auto => "auto",
136        }
137    }
138}
139
140/// Effort levels accepted by `--effort` and `set_effort`.
141/// Source: `claude --help` (2.1.329)
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
143#[serde(rename_all = "lowercase")]
144pub enum Effort {
145    Low,
146    Medium,
147    High,
148    Xhigh,
149    Max,
150}
151
152impl Effort {
153    pub fn as_str(self) -> &'static str {
154        match self {
155            Self::Low => "low",
156            Self::Medium => "medium",
157            Self::High => "high",
158            Self::Xhigh => "xhigh",
159            Self::Max => "max",
160        }
161    }
162}
163
164/// `--thinking`. Source: binary `--thinking <mode>` option (hidden)
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub enum Thinking {
167    Enabled,
168    Adaptive,
169    Disabled,
170}
171
172impl Thinking {
173    pub fn as_str(self) -> &'static str {
174        match self {
175            Self::Enabled => "enabled",
176            Self::Adaptive => "adaptive",
177            Self::Disabled => "disabled",
178        }
179    }
180}
181
182/// How thinking content appears (`--thinking-display`, `set_max_thinking_tokens`).
183/// Source: binary thinking-display enum
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
185#[serde(rename_all = "lowercase")]
186pub enum ThinkingDisplay {
187    Summarized,
188    Omitted,
189    Highlights,
190}
191
192impl ThinkingDisplay {
193    pub fn as_str(self) -> &'static str {
194        match self {
195            Self::Summarized => "summarized",
196            Self::Omitted => "omitted",
197            Self::Highlights => "highlights",
198        }
199    }
200}
201
202/// `--autocompact`: when the CLI compacts the context on its own.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub enum Autocompact {
205    /// The CLI's default window.
206    Auto,
207    /// Compact at this many tokens (at least 100 000).
208    Tokens(u64),
209}
210
211impl Autocompact {
212    pub fn to_arg(self) -> String {
213        match self {
214            Self::Auto => "auto".into(),
215            Self::Tokens(n) => n.to_string(),
216        }
217    }
218}
219
220/// `--permission-prompts`: who answers a permission prompt.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum PermissionPrompts {
223    /// The SDK host (`SessionOptions::can_use_tool`).
224    Host,
225    /// Nobody: anything that would prompt is denied.
226    None,
227}
228
229impl PermissionPrompts {
230    pub fn as_str(self) -> &'static str {
231        match self {
232            Self::Host => "host",
233            Self::None => "none",
234        }
235    }
236}
237
238/// When a prompt sent during a running turn is taken in.
239/// Source: binary user-message `priority` enum
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
241#[serde(rename_all = "lowercase")]
242pub enum Priority {
243    /// Aborts the running turn, then runs. The aborted turn still ends with
244    /// a `success` result (`terminal_reason: "aborted_streaming"`).
245    Now,
246    /// Taken in at the next opportunity inside the running turn.
247    Next,
248    /// Queued until the running turn ends.
249    Later,
250}
251
252/// A user turn.
253/// Source: _internal/client.py:126–131
254#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct UserMessage {
256    #[serde(rename = "type")]
257    pub kind: String, // "user"
258    pub message: UserMessageBody,
259    pub parent_tool_use_id: Option<String>,
260    /// Echoed back (`isReplay: true`) when the CLI starts this message's turn,
261    /// because the session runs with `--replay-user-messages`.
262    pub uuid: String,
263    #[serde(default, skip_serializing_if = "Option::is_none")]
264    pub priority: Option<Priority>,
265    /// `Some(false)`: append to the conversation without starting a turn.
266    #[serde(default, rename = "shouldQuery", skip_serializing_if = "Option::is_none")]
267    pub should_query: Option<bool>,
268    /// ISO 8601 time the message was created. Part of the wire schema, but
269    /// CLI 2.1.329 records its own receive time in the echo and transcript.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub timestamp: Option<String>,
272    /// `Some(true)`: the host composed this text (the user did not type it).
273    /// The CLI delivers it as written: no `@path` expansion, no slash-command
274    /// dispatch, and no turn-start context attachments.
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub client_composed: Option<bool>,
277}
278
279impl UserMessage {
280    pub fn text(content: impl Into<String>) -> Self {
281        Self::blocks(vec![ContentBlock::Text { text: content.into() }])
282    }
283
284    /// A message with several blocks, e.g. text plus images.
285    pub fn blocks(content: Vec<ContentBlock>) -> Self {
286        Self {
287            kind: "user".into(),
288            message: UserMessageBody { role: "user".into(), content },
289            parent_tool_use_id: None,
290            uuid: uuid::Uuid::new_v4().to_string(),
291            priority: None,
292            should_query: None,
293            timestamp: None,
294            client_composed: None,
295        }
296    }
297
298    /// Creation time as an ISO 8601 string, e.g. "2026-11-20T07:03:32.670Z".
299    pub fn with_timestamp(mut self, timestamp: impl Into<String>) -> Self {
300        self.timestamp = Some(timestamp.into());
301        self
302    }
303
304    /// Mark the text as host-composed: delivered verbatim, with no `@path`
305    /// expansion, slash-command dispatch or turn-start attachments.
306    pub fn client_composed(mut self) -> Self {
307        self.client_composed = Some(true);
308        self
309    }
310
311    pub fn with_priority(mut self, priority: Priority) -> Self {
312        self.priority = Some(priority);
313        self
314    }
315
316    /// Add the message to the conversation without starting a turn. Its
317    /// content is seen by the model on the next prompt.
318    pub fn context_only(mut self) -> Self {
319        self.should_query = Some(false);
320        self
321    }
322}
323
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct UserMessageBody {
326    pub role: String,
327    pub content: Vec<ContentBlock>,
328}
329
330#[derive(Debug, Clone, Serialize, Deserialize)]
331#[serde(tag = "type")]
332pub enum ContentBlock {
333    #[serde(rename = "text")]
334    Text { text: String },
335    #[serde(rename = "image")]
336    Image { source: ImageSource },
337    /// A PDF or plain-text document.
338    #[serde(rename = "document")]
339    Document {
340        source: DocumentSource,
341        #[serde(default, skip_serializing_if = "Option::is_none")]
342        title: Option<String>,
343    },
344    #[serde(rename = "tool_result")]
345    ToolResult {
346        tool_use_id: String,
347        content: Vec<ContentBlock>,
348        #[serde(default, skip_serializing_if = "Option::is_none")]
349        is_error: Option<bool>,
350    },
351}
352
353impl ContentBlock {
354    /// An image from base64 data; `media_type` e.g. "image/png".
355    pub fn image_base64(media_type: impl Into<String>, data: impl Into<String>) -> Self {
356        Self::Image {
357            source: ImageSource::Base64 { media_type: media_type.into(), data: data.into() },
358        }
359    }
360
361    /// A PDF from base64 data.
362    pub fn pdf_base64(data: impl Into<String>) -> Self {
363        Self::Document {
364            source: DocumentSource::Base64 { media_type: "application/pdf".into(), data: data.into() },
365            title: None,
366        }
367    }
368}
369
370/// Anthropic Messages API document source.
371#[derive(Debug, Clone, Serialize, Deserialize)]
372#[serde(tag = "type", rename_all = "lowercase")]
373pub enum DocumentSource {
374    Base64 { media_type: String, data: String },
375    Text { media_type: String, data: String },
376    Url { url: String },
377}
378
379/// Anthropic Messages API image source.
380#[derive(Debug, Clone, Serialize, Deserialize)]
381#[serde(tag = "type", rename_all = "lowercase")]
382pub enum ImageSource {
383    Base64 { media_type: String, data: String },
384    Url { url: String },
385}
386
387/// Envelope for every host → CLI answer to a CLI-initiated control request.
388/// Source: query.py:325–345
389#[derive(Debug, Clone, Serialize)]
390pub struct ControlResponse {
391    #[serde(rename = "type")]
392    pub kind: &'static str, // "control_response"
393    pub response: ControlResponseBody,
394}
395
396#[derive(Debug, Clone, Serialize)]
397#[serde(tag = "subtype", rename_all = "lowercase")]
398pub enum ControlResponseBody {
399    Success { request_id: String, response: serde_json::Value },
400    Error { request_id: String, error: String },
401}
402
403impl ControlResponse {
404    pub fn success(request_id: impl Into<String>, response: serde_json::Value) -> Self {
405        Self {
406            kind: "control_response",
407            response: ControlResponseBody::Success { request_id: request_id.into(), response },
408        }
409    }
410    pub fn error(request_id: impl Into<String>, error: impl Into<String>) -> Self {
411        Self {
412            kind: "control_response",
413            response: ControlResponseBody::Error { request_id: request_id.into(), error: error.into() },
414        }
415    }
416}
417
418/// Answer to a `can_use_tool` request.
419/// Source: binary can_use_tool response schema (`behavior`, `updatedInput`,
420/// `updatedPermissions`, `message`, `interrupt`)
421#[derive(Debug, Clone, Serialize, Deserialize)]
422#[serde(tag = "behavior", rename_all = "camelCase")]
423pub enum ToolDecision {
424    /// `updated_input: None` → the original input is sent back unchanged.
425    /// `updated_permissions`: permission updates to apply, e.g. the
426    /// request's `permission_suggestions` for "always allow".
427    #[serde(rename = "allow")]
428    Allow {
429        #[serde(rename = "updatedInput", skip_serializing_if = "Option::is_none")]
430        updated_input: Option<serde_json::Value>,
431        #[serde(rename = "updatedPermissions", default, skip_serializing_if = "Option::is_none")]
432        updated_permissions: Option<Vec<serde_json::Value>>,
433    },
434    #[serde(rename = "deny")]
435    Deny {
436        message: String,
437        #[serde(skip_serializing_if = "Option::is_none")]
438        interrupt: Option<bool>,
439    },
440}
441
442impl ToolDecision {
443    pub fn allow() -> Self { Self::Allow { updated_input: None, updated_permissions: None } }
444    /// Allow with a rewritten input.
445    pub fn allow_with_input(input: serde_json::Value) -> Self {
446        Self::Allow { updated_input: Some(input), updated_permissions: None }
447    }
448    /// Allow and apply permission updates, so the CLI stops asking (pass the
449    /// request's `permission_suggestions` for "always allow").
450    pub fn allow_and_remember(updates: Vec<serde_json::Value>) -> Self {
451        Self::Allow { updated_input: None, updated_permissions: Some(updates) }
452    }
453    pub fn deny(message: impl Into<String>) -> Self {
454        Self::Deny { message: message.into(), interrupt: None }
455    }
456}
457
458/// Hook result — the same JSON a shell hook prints on stdout.
459/// Source: binary hook-output schema (continue, suppressOutput, stopReason,
460/// decision, systemMessage, reason, hookSpecificOutput).
461#[derive(Debug, Clone, Serialize, Deserialize, Default)]
462#[serde(rename_all = "camelCase")]
463pub struct HookOutput {
464    /// `false` stops the whole agent loop.
465    #[serde(rename = "continue", skip_serializing_if = "Option::is_none")]
466    pub continue_: Option<bool>,
467    #[serde(skip_serializing_if = "Option::is_none")]
468    pub suppress_output: Option<bool>,
469    #[serde(skip_serializing_if = "Option::is_none")]
470    pub stop_reason: Option<String>,
471    #[serde(skip_serializing_if = "Option::is_none")]
472    pub decision: Option<HookDecision>,
473    /// Warning shown to the user.
474    #[serde(skip_serializing_if = "Option::is_none")]
475    pub system_message: Option<String>,
476    /// Reason fed back to the model when `decision` is `block`.
477    #[serde(skip_serializing_if = "Option::is_none")]
478    pub reason: Option<String>,
479    /// Event-specific output; must carry `hookEventName`.
480    #[serde(skip_serializing_if = "Option::is_none")]
481    pub hook_specific_output: Option<serde_json::Value>,
482}
483
484#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
485#[serde(rename_all = "lowercase")]
486pub enum HookDecision {
487    Approve,
488    Block,
489}
490
491impl HookOutput {
492    /// No opinion — the CLI proceeds as if the hook printed nothing.
493    pub fn allow() -> Self { Self::default() }
494
495    /// Block the action; `reason` is shown to the model.
496    pub fn block(reason: impl Into<String>) -> Self {
497        Self { decision: Some(HookDecision::Block), reason: Some(reason.into()), ..Self::default() }
498    }
499
500    /// Inject `additionalContext` for the given event.
501    pub fn with_context(event: HookEventKind, context: impl Into<String>) -> Self {
502        Self {
503            hook_specific_output: Some(serde_json::json!({
504                "hookEventName": event,
505                "additionalContext": context.into(),
506            })),
507            ..Self::default()
508        }
509    }
510
511    /// Register `watchPaths` for FileChanged hooks (valid for CwdChanged / FileChanged).
512    pub fn watch_paths(event: HookEventKind, paths: Vec<String>) -> Self {
513        Self {
514            hook_specific_output: Some(serde_json::json!({
515                "hookEventName": event,
516                "watchPaths": paths,
517            })),
518            ..Self::default()
519        }
520    }
521
522    pub fn is_block(&self) -> bool { self.decision == Some(HookDecision::Block) }
523}
524
525/// Body of a `background_tasks` control request (Ctrl+B equivalent).
526/// Send with `Session::control(&body)`.
527/// Source: chunk-20bv8pca.js:20970–20978
528#[derive(Debug, Clone, Serialize)]
529pub struct BackgroundTasksRequest {
530    pub subtype: &'static str, // "background_tasks"
531    /// None = background all foreground tasks; Some = background specific tool_use_id.
532    #[serde(skip_serializing_if = "Option::is_none")]
533    pub tool_use_id: Option<String>,
534}
535
536impl BackgroundTasksRequest {
537    pub fn all() -> Self {
538        Self { subtype: "background_tasks", tool_use_id: None }
539    }
540    pub fn one(tool_use_id: impl Into<String>) -> Self {
541        Self { subtype: "background_tasks", tool_use_id: Some(tool_use_id.into()) }
542    }
543}
544
545// ─── Inbound: CLI → host ─────────────────────────────────────────────────────
546
547/// Every stdout line deserializes to this.
548/// Source: chunk-20bv8pca.js (various schema locations)
549#[derive(Debug, Clone, Deserialize)]
550#[serde(tag = "type")]
551pub enum InboundMessage {
552    /// Per-turn metadata. First frame before each turn.
553    #[serde(rename = "system")]
554    System(SystemMessage),
555    /// A user message: the echo of a host prompt (`is_replay`) or a tool result.
556    #[serde(rename = "user")]
557    User(InboundUserMessage),
558    /// Complete assistant message block.
559    #[serde(rename = "assistant")]
560    Assistant(AssistantMessage),
561    /// Partial streaming chunk (requires --include-partial-messages).
562    #[serde(rename = "stream_event")]
563    StreamEvent(StreamEventMessage),
564    /// Turn complete signal.
565    #[serde(rename = "result")]
566    Result(ResultMessage),
567    /// CLI asking the host to answer: a hook callback, a tool permission
568    /// (`can_use_tool`) or an SDK MCP message. Source: chunk-20bv8pca.js:18214
569    #[serde(rename = "control_request")]
570    ControlRequest(ControlRequest),
571    /// CLI answering a host-initiated control request (initialize, interrupt, …).
572    /// Source: query.py:180–192
573    #[serde(rename = "control_response")]
574    ControlResponse(InboundControlResponse),
575    /// Process keepalive with startup marker.
576    /// Source: chunk-f89nsf5q.query.js:1403–1410
577    #[serde(rename = "keep_alive")]
578    KeepAlive(KeepAliveMessage),
579    /// The CLI withdrew a control request it sent (e.g. a `can_use_tool`
580    /// whose turn was interrupted); its answer is no longer wanted.
581    #[serde(rename = "control_cancel_request")]
582    ControlCancelRequest(ControlCancelRequest),
583    /// Any other frame type (`rate_limit_event`, `tool_progress`,
584    /// `prompt_suggestion`, `command_lifecycle`, …), kept verbatim.
585    #[serde(skip_deserializing)]
586    Other(serde_json::Value),
587    /// Decoding placeholder; `Session` turns it into `Other`.
588    #[serde(other)]
589    Unknown,
590}
591
592/// Source: binary control_cancel_request schema
593#[derive(Debug, Clone, Deserialize)]
594pub struct ControlCancelRequest {
595    pub request_id: String,
596}
597
598/// Every `type:"system"` frame: `init` (first frame of each turn) plus
599/// `hook_started`, `hook_response`, `compact_boundary`, `model_fallback`,
600/// `background_tasks_changed`, `task_started`, `task_updated`, `task_notification`,
601/// `thinking_tokens`, `model_refusal_no_fallback`, `peer_message_hold`, … —
602/// only `subtype` and `session_id` are common to all; subtype-specific fields
603/// are in `extra`. Source: binary system-message schemas
604/// Source: chunk-hp1k7mph.js:194 (WGt function), chunk-20bv8pca.js:15125
605#[derive(Debug, Clone, Serialize, Deserialize)]
606pub struct SystemMessage {
607    pub subtype: String, // "init" | "hook_started" | "hook_response" | …
608    pub session_id: String,
609    #[serde(default)]
610    pub cwd: String,
611    #[serde(default)]
612    pub model: String,
613    #[serde(default)]
614    pub claude_code_version: String,
615    #[serde(default)]
616    pub permission_mode: String,
617    #[serde(default)]
618    pub tools: Vec<String>,
619    #[serde(default)]
620    pub betas: Vec<String>,
621    #[serde(default)]
622    pub capabilities: Vec<String>,
623    #[serde(default)]
624    pub skills: Vec<serde_json::Value>,
625    #[serde(default)]
626    pub plugins: Vec<serde_json::Value>,
627    #[serde(flatten)]
628    pub extra: HashMap<String, serde_json::Value>,
629}
630
631impl SystemMessage {
632    /// `REPL` or `Eval` in `tools[]` = Code Mode active (see `SessionOptions::code_mode`).
633    pub fn code_mode_active(&self) -> bool {
634        self.tools.iter().any(|t| t == "REPL" || t == "Eval")
635    }
636}
637
638#[derive(Debug, Clone, Deserialize)]
639pub struct AssistantMessage {
640    pub message: AssistantMessageBody,
641    #[serde(default)]
642    pub session_id: Option<String>,
643    #[serde(default)]
644    pub parent_tool_use_id: Option<String>,
645}
646
647#[derive(Debug, Clone, Deserialize)]
648pub struct AssistantMessageBody {
649    pub role: String,
650    pub content: Vec<AssistantBlock>,
651    #[serde(default)]
652    pub stop_reason: Option<String>,
653}
654
655#[derive(Debug, Clone, Deserialize)]
656#[serde(tag = "type")]
657pub enum AssistantBlock {
658    #[serde(rename = "text")]
659    Text { text: String },
660    #[serde(rename = "tool_use")]
661    ToolUse {
662        id: String,
663        name: String,
664        input: serde_json::Value,
665    },
666    #[serde(rename = "thinking")]
667    Thinking { thinking: String },
668    /// Encrypted thinking; opaque to the host.
669    #[serde(rename = "redacted_thinking")]
670    RedactedThinking { data: String },
671    /// A tool the API runs itself (web search, …).
672    #[serde(rename = "server_tool_use")]
673    ServerToolUse {
674        id: String,
675        name: String,
676        input: serde_json::Value,
677    },
678    #[serde(rename = "web_search_tool_result")]
679    WebSearchToolResult {
680        tool_use_id: String,
681        content: serde_json::Value,
682    },
683    #[serde(other)]
684    Unknown,
685}
686
687/// A `user` frame: the echo of a prompt, tool results, or a message the
688/// CLI added itself (`is_synthetic`).
689#[derive(Debug, Clone, Deserialize)]
690pub struct InboundUserMessage {
691    #[serde(default)]
692    pub uuid: Option<String>,
693    #[serde(default, rename = "isReplay")]
694    pub is_replay: Option<bool>,
695    #[serde(default, rename = "isSynthetic")]
696    pub is_synthetic: Option<bool>,
697    #[serde(default)]
698    pub parent_tool_use_id: Option<String>,
699    /// Subagent that produced the frame.
700    #[serde(default)]
701    pub agent_id: Option<String>,
702    #[serde(default)]
703    pub message: Option<InboundUserBody>,
704    /// The tool's full structured output (e.g. Bash `{stdout, stderr, …}`),
705    /// beside the text sent to the model.
706    #[serde(default)]
707    pub tool_use_result: Option<serde_json::Value>,
708}
709
710#[derive(Debug, Clone, Deserialize)]
711pub struct InboundUserBody {
712    /// A string or an array of content blocks.
713    #[serde(default)]
714    pub content: serde_json::Value,
715}
716
717/// One `tool_result` block of a `user` frame.
718#[derive(Debug, Clone, Deserialize)]
719pub struct InboundToolResult {
720    pub tool_use_id: String,
721    /// A string or an array of content blocks.
722    #[serde(default)]
723    pub content: serde_json::Value,
724    #[serde(default)]
725    pub is_error: bool,
726}
727
728impl InboundUserMessage {
729    /// The `tool_result` blocks of this frame.
730    pub fn tool_results(&self) -> Vec<InboundToolResult> {
731        let Some(blocks) = self.message.as_ref().and_then(|m| m.content.as_array()) else {
732            return vec![];
733        };
734        blocks
735            .iter()
736            .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("tool_result"))
737            .filter_map(|b| serde_json::from_value(b.clone()).ok())
738            .collect()
739    }
740}
741
742/// Partial streaming chunk.
743/// Source: chunk-20bv8pca.js:15343–15401
744#[derive(Debug, Clone, Deserialize)]
745pub struct StreamEventMessage {
746    pub event: serde_json::Value,
747    #[serde(default)]
748    pub session_id: Option<String>,
749    #[serde(default)]
750    pub ttft_ms: Option<u64>,
751    #[serde(default)]
752    pub parent_tool_use_id: Option<String>,
753}
754
755/// Turn complete.
756/// Source: chunk-20bv8pca.js:14425–14913
757#[derive(Debug, Clone, Default, Deserialize)]
758pub struct ResultMessage {
759    /// "success" | "error_*". A failed API call still comes as "success"
760    /// with `is_error: true` and the message in `result`.
761    #[serde(default)]
762    pub subtype: String,
763    #[serde(default)]
764    pub is_error: bool,
765    /// Final text of the turn, or the error message when `is_error`.
766    #[serde(default)]
767    pub result: Option<String>,
768    /// Error details of `error_*` subtypes.
769    #[serde(default)]
770    pub errors: Option<Vec<serde_json::Value>>,
771    #[serde(default)]
772    pub session_id: Option<String>,
773    #[serde(default)]
774    pub total_cost_usd: Option<f64>,
775    #[serde(default)]
776    pub ttft_ms: Option<u64>,
777    #[serde(default)]
778    pub duration_ms: Option<u64>,
779    #[serde(default)]
780    pub usage: Option<UsageSummary>,
781    #[serde(default)]
782    pub stop_reason: Option<String>,
783    #[serde(default)]
784    pub duration_api_ms: Option<u64>,
785    #[serde(default)]
786    pub num_turns: Option<u64>,
787    /// Why the loop ended ("completed", …).
788    #[serde(default)]
789    pub terminal_reason: Option<String>,
790    /// Output matching `Initialize::json_schema`.
791    #[serde(default)]
792    pub structured_output: Option<serde_json::Value>,
793    /// Tool calls the permission system denied during the turn.
794    #[serde(default)]
795    pub permission_denials: Vec<serde_json::Value>,
796    /// Per-model token and cost breakdown.
797    #[serde(default, rename = "modelUsage")]
798    pub model_usage: Option<serde_json::Value>,
799    /// The prompts (`UserMessage::uuid`) this turn answered.
800    #[serde(default)]
801    pub user_message_uuids: Vec<String>,
802    /// Set when the CLI started the turn itself (e.g. `{"kind":"task-notification"}`
803    /// after a background task finished); absent for turns the host prompted.
804    #[serde(default)]
805    pub origin: Option<serde_json::Value>,
806    #[serde(flatten)]
807    pub extra: HashMap<String, serde_json::Value>,
808}
809
810impl ResultMessage {
811    pub fn is_success(&self) -> bool {
812        self.subtype == "success" && !self.is_error
813    }
814
815    /// Whether this turn answered the prompt `uuid`. A prompt the CLI
816    /// refuses up front (e.g. budget spent) gets a result but no echo.
817    pub fn answers(&self, uuid: &str) -> bool {
818        self.user_message_uuids.iter().any(|u| u.eq_ignore_ascii_case(uuid))
819    }
820
821    /// Category of a failed turn.
822    pub fn error_kind(&self) -> TurnErrorKind {
823        match self.subtype.as_str() {
824            "error_during_execution" => TurnErrorKind::Execution,
825            "error_max_turns" => TurnErrorKind::MaxTurns,
826            "error_max_budget_usd" => TurnErrorKind::MaxBudget,
827            "error_max_structured_output_retries" => TurnErrorKind::StructuredOutputRetries,
828            "success" => TurnErrorKind::Api,
829            other => TurnErrorKind::Other(other.to_string()),
830        }
831    }
832
833    /// Why the turn failed: for `is_error` the CLI's message; for
834    /// `error_*` subtypes the subtype, then its `errors` details.
835    pub fn error_message(&self) -> String {
836        if let Some(r) = self.result.as_ref().filter(|r| self.is_error && !r.is_empty()) {
837            return r.clone();
838        }
839        let details: Vec<String> = self.errors.iter().flatten()
840            .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_owned))
841            .collect();
842        if details.is_empty() { self.subtype.clone() } else { format!("{}: {}", self.subtype, details.join("; ")) }
843    }
844}
845
846/// Why a turn failed. Source: binary result error-subtype enum
847#[derive(Debug, Clone, PartialEq, Eq)]
848pub enum TurnErrorKind {
849    /// `error_during_execution`: includes interrupted turns.
850    Execution,
851    /// `error_max_turns`: `SessionOptions::max_turns` reached.
852    MaxTurns,
853    /// `error_max_budget_usd`: `SessionOptions::max_budget_usd` reached.
854    MaxBudget,
855    /// `error_max_structured_output_retries`.
856    StructuredOutputRetries,
857    /// The API call failed (`is_error` on a `success` result).
858    Api,
859    /// The CLI exited before the turn ended.
860    SessionClosed,
861    /// The prompt was withdrawn before it ran (`Session::cancel_prompt`,
862    /// `Session::interrupt_all`).
863    Cancelled,
864    /// A subtype this SDK does not know.
865    Other(String),
866}
867
868/// Token usage breakdown.
869/// Source: chunk-20bv8pca.js:11526–11530
870#[derive(Debug, Clone, Deserialize, Default)]
871pub struct UsageSummary {
872    #[serde(default)]
873    pub input_tokens: u64,
874    #[serde(default)]
875    pub output_tokens: u64,
876    #[serde(default)]
877    pub cache_read_input_tokens: Option<u64>,
878    #[serde(default)]
879    pub cache_creation_input_tokens: Option<u64>,
880    #[serde(default)]
881    pub cache_creation: Option<serde_json::Value>,
882}
883
884/// CLI → host control request envelope:
885/// `{"type":"control_request","request_id":"…","request":{"subtype":"…",…}}`.
886/// Source: query.py:236–240
887#[derive(Debug, Clone, Deserialize)]
888pub struct ControlRequest {
889    pub request_id: String,
890    pub request: ControlRequestBody,
891}
892
893#[derive(Debug, Clone, Deserialize)]
894#[serde(tag = "subtype")]
895pub enum ControlRequestBody {
896    /// Only sent when the CLI runs with `--permission-prompt-tool stdio`.
897    #[serde(rename = "can_use_tool")]
898    CanUseTool(CanUseToolRequest),
899    #[serde(rename = "hook_callback")]
900    HookCallback(HookCallbackRequest),
901    /// JSON-RPC message for an SDK MCP server. Source: query.py:305–320
902    #[serde(rename = "mcp_message")]
903    McpMessage(McpMessageRequest),
904    /// An MCP server asks the user for input.
905    #[serde(rename = "elicitation")]
906    Elicitation(ElicitationRequest),
907    /// A tool asks the host to render a blocking dialog; sent only for kinds
908    /// listed in `Initialize::supported_dialog_kinds`.
909    #[serde(rename = "request_user_dialog")]
910    RequestUserDialog(UserDialogRequest),
911    /// Future subtypes — answered with an error response.
912    #[serde(other)]
913    Unsupported,
914}
915
916/// Source: binary can_use_tool schema; query.py:244–262
917#[derive(Debug, Clone, Deserialize)]
918pub struct CanUseToolRequest {
919    pub tool_name: String,
920    pub input: serde_json::Value,
921    #[serde(default)]
922    pub tool_use_id: Option<String>,
923    /// Permission updates that would stop the CLI asking again; return them
924    /// with `ToolDecision::allow_and_remember` for "always allow".
925    #[serde(default)]
926    pub permission_suggestions: Option<Vec<serde_json::Value>>,
927    /// Human-readable reason the CLI asks; may carry ANSI escapes.
928    #[serde(default)]
929    pub decision_reason: Option<String>,
930    /// Why the ask escalated: "rule", "hook", "safetyCheck", "classifier", …
931    #[serde(default)]
932    pub decision_reason_type: Option<String>,
933    /// MCP server of the tool: `{"name", "source"}`.
934    #[serde(default)]
935    pub mcp_server: Option<serde_json::Value>,
936    /// Path outside the allowed directories that triggered the ask.
937    #[serde(default)]
938    pub blocked_path: Option<String>,
939    #[serde(default)]
940    pub classifier_approvable: Option<bool>,
941    /// Do not offer "always allow" for this ask.
942    #[serde(default)]
943    pub suppress_always_allow_rule: Option<bool>,
944    /// The ask must not be approvable by a single stray keystroke.
945    #[serde(default)]
946    pub default_to_no: Option<bool>,
947    #[serde(default)]
948    pub matched_ask_rule: Option<serde_json::Value>,
949    #[serde(default)]
950    pub title: Option<String>,
951    #[serde(default)]
952    pub display_name: Option<String>,
953    #[serde(default)]
954    pub description: Option<String>,
955    /// Subagent that wants to use the tool.
956    #[serde(default)]
957    pub agent_id: Option<String>,
958    #[serde(default)]
959    pub requires_user_interaction: Option<bool>,
960    /// Fields not named above.
961    #[serde(flatten)]
962    pub extra: HashMap<String, serde_json::Value>,
963}
964
965/// Source: binary elicitation schema
966#[derive(Debug, Clone, Deserialize)]
967pub struct ElicitationRequest {
968    pub mcp_server_name: String,
969    pub message: String,
970    /// "form" or "url".
971    #[serde(default)]
972    pub mode: Option<String>,
973    #[serde(default)]
974    pub url: Option<String>,
975    #[serde(default)]
976    pub elicitation_id: Option<String>,
977    /// JSON schema of the requested form fields.
978    #[serde(default)]
979    pub requested_schema: Option<serde_json::Value>,
980    /// Top-level keys of `requested_schema.properties`, in the server's order.
981    #[serde(default)]
982    pub property_order: Option<Vec<String>>,
983    #[serde(default)]
984    pub title: Option<String>,
985    #[serde(default)]
986    pub display_name: Option<String>,
987    #[serde(default)]
988    pub description: Option<String>,
989    #[serde(flatten)]
990    pub extra: HashMap<String, serde_json::Value>,
991}
992
993/// Answer to an `elicitation` request. Source: binary elicitation response schema
994#[derive(Debug, Clone, Serialize)]
995pub struct ElicitationResponse {
996    pub action: ElicitationAction,
997    #[serde(skip_serializing_if = "Option::is_none")]
998    pub content: Option<serde_json::Map<String, serde_json::Value>>,
999}
1000
1001#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1002#[serde(rename_all = "lowercase")]
1003pub enum ElicitationAction {
1004    Accept,
1005    Decline,
1006    Cancel,
1007}
1008
1009impl ElicitationResponse {
1010    pub fn accept(content: serde_json::Map<String, serde_json::Value>) -> Self {
1011        Self { action: ElicitationAction::Accept, content: Some(content) }
1012    }
1013    pub fn decline() -> Self {
1014        Self { action: ElicitationAction::Decline, content: None }
1015    }
1016    pub fn cancel() -> Self {
1017        Self { action: ElicitationAction::Cancel, content: None }
1018    }
1019}
1020
1021/// Source: binary request_user_dialog schema
1022#[derive(Debug, Clone, Deserialize)]
1023pub struct UserDialogRequest {
1024    pub dialog_kind: String,
1025    #[serde(default)]
1026    pub payload: serde_json::Value,
1027    #[serde(default)]
1028    pub tool_use_id: Option<String>,
1029}
1030
1031/// The user's answer to a `request_user_dialog`.
1032/// Source: binary request_user_dialog response schema (behavior, result)
1033#[derive(Debug, Clone, Serialize, PartialEq)]
1034pub struct UserDialogResponse {
1035    pub behavior: UserDialogBehavior,
1036    /// Dialog-specific choice, e.g. `"retry_fallback"` for
1037    /// `refusal_fallback_prompt`.
1038    #[serde(skip_serializing_if = "Option::is_none")]
1039    pub result: Option<serde_json::Value>,
1040}
1041
1042#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
1043#[serde(rename_all = "lowercase")]
1044pub enum UserDialogBehavior {
1045    Completed,
1046    /// The user dismissed the dialog.
1047    Cancelled,
1048}
1049
1050impl UserDialogResponse {
1051    pub fn completed(result: impl Into<serde_json::Value>) -> Self {
1052        Self { behavior: UserDialogBehavior::Completed, result: Some(result.into()) }
1053    }
1054    pub fn cancelled() -> Self {
1055        Self { behavior: UserDialogBehavior::Cancelled, result: None }
1056    }
1057}
1058
1059#[derive(Debug, Clone, Deserialize)]
1060pub struct McpMessageRequest {
1061    pub server_name: String,
1062    pub message: serde_json::Value,
1063}
1064
1065/// Source: binary hook_callback schema (callback_id, input, tool_use_id, issued_at)
1066#[derive(Debug, Clone, Deserialize)]
1067pub struct HookCallbackRequest {
1068    pub callback_id: String,
1069    pub input: HookEventPayload,
1070    #[serde(default)]
1071    pub tool_use_id: Option<String>,
1072    /// Epoch ms on the CLI's clock when the request was issued.
1073    #[serde(default)]
1074    pub issued_at: Option<u64>,
1075}
1076
1077/// CLI → host answer to a host-initiated control request.
1078/// Source: query.py:180–192
1079#[derive(Debug, Clone, Deserialize)]
1080pub struct InboundControlResponse {
1081    pub response: InboundControlResponseBody,
1082}
1083
1084#[derive(Debug, Clone, Deserialize)]
1085pub struct InboundControlResponseBody {
1086    pub subtype: String, // "success" | "error"
1087    pub request_id: String,
1088    #[serde(default)]
1089    pub response: Option<serde_json::Value>,
1090    #[serde(default)]
1091    pub error: Option<String>,
1092}
1093
1094/// Input to a hook handler. Contains all event-specific fields.
1095/// Source: chunk-0msz7hbn.js:7–323
1096#[derive(Debug, Clone, Deserialize)]
1097pub struct HookEventPayload {
1098    pub hook_event_name: HookEventKind,
1099    #[serde(default)]
1100    pub tool_name: Option<String>,
1101    #[serde(default)]
1102    pub tool_input: Option<serde_json::Value>,
1103    #[serde(default)]
1104    pub tool_use_id: Option<String>,
1105    #[serde(default)]
1106    pub error: Option<String>,
1107    #[serde(default)]
1108    pub is_interrupt: Option<bool>,
1109    #[serde(default)]
1110    pub session_id: Option<String>,
1111    #[serde(default)]
1112    pub cwd: Option<String>,
1113    #[serde(default)]
1114    pub file_path: Option<String>,
1115    #[serde(default)]
1116    pub event: Option<String>,        // for FileChanged: "change"|"add"|"unlink"
1117    #[serde(flatten)]
1118    pub extra: HashMap<String, serde_json::Value>,
1119}
1120
1121/// One entry of a `background_tasks_changed` snapshot.
1122/// Source: binary background_tasks_changed schema
1123#[derive(Debug, Clone, Deserialize)]
1124pub struct BackgroundTask {
1125    pub task_id: String,
1126    #[serde(default)]
1127    pub run_id: Option<String>,
1128    /// "local_bash" | "local_agent" | "local_workflow" | …
1129    #[serde(default)]
1130    pub task_type: String,
1131    #[serde(default)]
1132    pub subagent_type: Option<String>,
1133    #[serde(default)]
1134    pub description: String,
1135    #[serde(default)]
1136    pub parent_task_id: Option<String>,
1137    #[serde(default)]
1138    pub ambient: Option<bool>,
1139    #[serde(default)]
1140    pub awaited: Option<bool>,
1141    #[serde(default)]
1142    pub off_host: Option<bool>,
1143}
1144
1145/// Process keepalive with startup marker for readiness probing.
1146/// Source: chunk-f89nsf5q.query.js:1403–1410
1147#[derive(Debug, Clone, Deserialize)]
1148pub struct KeepAliveMessage {
1149    #[serde(flatten)]
1150    pub extra: HashMap<String, serde_json::Value>,
1151}
1152
1153// ─── Tool/Hook types ─────────────────────────────────────────────────────────
1154
1155#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1156pub struct ToolDef {
1157    pub name: String,
1158    pub description: String,
1159    #[serde(skip_serializing_if = "Option::is_none")]
1160    pub input_schema: Option<serde_json::Value>,
1161    /// Display name.
1162    #[serde(default, skip_serializing_if = "Option::is_none")]
1163    pub title: Option<String>,
1164    /// JSON schema of `ToolResult::structured`.
1165    #[serde(default, skip_serializing_if = "Option::is_none")]
1166    pub output_schema: Option<serde_json::Value>,
1167    #[serde(default, skip_serializing_if = "Option::is_none")]
1168    pub annotations: Option<ToolAnnotations>,
1169}
1170
1171/// MCP tool hints. Source: MCP 2025-06-18 `ToolAnnotations`
1172#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1173#[serde(rename_all = "camelCase")]
1174pub struct ToolAnnotations {
1175    #[serde(default, skip_serializing_if = "Option::is_none")]
1176    pub read_only_hint: Option<bool>,
1177    #[serde(default, skip_serializing_if = "Option::is_none")]
1178    pub destructive_hint: Option<bool>,
1179    #[serde(default, skip_serializing_if = "Option::is_none")]
1180    pub idempotent_hint: Option<bool>,
1181    #[serde(default, skip_serializing_if = "Option::is_none")]
1182    pub open_world_hint: Option<bool>,
1183}
1184
1185#[derive(Debug, Clone, Serialize, Deserialize)]
1186pub struct McpManifest {
1187    pub name: String,
1188    pub tools: Vec<ToolDef>,
1189    #[serde(default)]
1190    pub server_info: Option<serde_json::Value>,
1191}
1192
1193/// All 33 hook event kinds.
1194/// Source: chunk-20bv8pca.js:12053–12087 (N2 array)
1195#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1196#[serde(rename_all = "PascalCase")]
1197pub enum HookEventKind {
1198    PreToolUse,
1199    PostToolUse,
1200    PostToolUseFailure,
1201    PostToolBatch,
1202    Notification,
1203    UserPromptSubmit,
1204    UserPromptExpansion,
1205    SessionStart,
1206    SessionEnd,
1207    Stop,
1208    StopFailure,
1209    SubagentStart,
1210    SubagentStop,
1211    PreCompact,
1212    PostCompact,
1213    PreModelSwitch,
1214    PostModelSwitch,
1215    PermissionRequest,
1216    PermissionDenied,
1217    Setup,
1218    TeammateIdle,
1219    TaskCreated,
1220    TaskCompleted,
1221    Elicitation,
1222    ElicitationResult,
1223    ConfigChange,
1224    WorktreeCreate,
1225    WorktreeRemove,
1226    InstructionsLoaded,
1227    CwdChanged,
1228    FileChanged,
1229    DirectoryAdded,
1230    MessageDisplay,
1231}
1232