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.329 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.329 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    /// Always `"control_request"`.
19    #[serde(rename = "type")]
20    pub kind: &'static str, // "control_request"
21    /// Id the CLI echoes in its `control_response`.
22    pub request_id: &'a str,
23    /// Request body; its `subtype` names the request.
24    pub request: &'a B,
25}
26
27/// Body of the `initialize` control request — the first stdin line.
28///
29/// Process-level settings (cwd, model, permission mode, session id) are CLI
30/// flags, not initialize fields; they live on `SessionOptions`.
31/// `hooks` is filled in by `Session::spawn` from `SessionOptions::hooks`.
32/// Source: binary initialize schema (subtype "initialize", hooks, agents,
33/// systemPrompt, appendSystemPrompt, jsonSchema, …); query.py:150–155
34#[derive(Debug, Clone, Serialize, Default)]
35#[serde(rename_all = "camelCase")]
36pub struct Initialize {
37    /// Hook matchers per event; matches arrive as `hook_callback` requests.
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub hooks: Option<HashMap<HookEventKind, Vec<HookMatcherConfig>>>,
40    /// `systemPrompt`: the custom system prompt slot, same as `--system-prompt`.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub system_prompt: Option<String>,
43    /// `appendSystemPrompt`: appended to the system prompt.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub append_system_prompt: Option<String>,
46    /// Subagent definitions, keyed by agent name.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub agents: Option<serde_json::Value>,
49    /// JSON schema for structured output; the result arrives in
50    /// `TurnResult::structured_output`.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub json_schema: Option<serde_json::Value>,
53    /// Session title; skips automatic title generation.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub title: Option<String>,
56    /// Load only the skills with these names.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub skills: Option<Vec<String>>,
59    /// Plugins to load, e.g. `{"type": "local", "path": "./my-plugin"}`.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub plugins: Option<Vec<serde_json::Value>>,
62    /// MCP servers the CLI runs or connects to, keyed by name: stdio
63    /// (`{"command": …, "args": […]}`), `http` or `sse` configs.
64    /// In-process servers go in `SessionOptions::mcp_servers`.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub mcp_servers: Option<serde_json::Map<String, serde_json::Value>>,
67    /// Replaces the default plan-mode workflow text.
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub plan_mode_instructions: Option<String>,
70    /// Omit per-user dynamic sections (working directory, memory path) from
71    /// the system prompt, so it caches across users.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub exclude_dynamic_sections: Option<bool>,
74    /// Record the system prompt once per conversation and reuse it verbatim.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub system_prompt_snapshot: Option<bool>,
77    /// Emit `prompt_suggestion` frames after turns.
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub prompt_suggestions: Option<bool>,
80    /// Emit progress summaries of running subagents.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub agent_progress_summaries: Option<bool>,
83    /// Forward subagent text and thinking.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub forward_subagent_text: Option<bool>,
86    /// Tool-name aliases applied before tool-name resolution.
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub tool_aliases: Option<HashMap<String, String>>,
89    /// `request_user_dialog` kinds `SessionOptions::on_user_dialog` renders;
90    /// the CLI sends only these kinds.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub supported_dialog_kinds: Option<Vec<String>>,
93    /// Declares that the host renders a per-task stop control (`stop_task`).
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub per_task_stop_affordance: Option<bool>,
96    /// Workspace trust the host obtained from the user for `directory`.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub workspace_trust: Option<WorkspaceTrust>,
99}
100
101/// Send `accepted: true` only after the user accepted a trust dialog for
102/// `directory`. Source: binary initialize.workspaceTrust schema
103#[derive(Debug, Clone, Serialize)]
104pub struct WorkspaceTrust {
105    /// `true` only after the user accepted the trust dialog.
106    pub accepted: bool,
107    /// Directory the user trusted.
108    pub directory: String,
109}
110
111/// One hook matcher in the initialize request.
112/// Source: query.py:142–147 (`matcher`, `hookCallbackIds`, `timeout`)
113#[derive(Debug, Clone, Serialize)]
114#[serde(rename_all = "camelCase")]
115pub struct HookMatcherConfig {
116    /// Tool-name pattern the hook applies to; `None` matches every tool.
117    pub matcher: Option<String>,
118    /// Callback ids the CLI sends back in `hook_callback` requests.
119    pub hook_callback_ids: Vec<String>,
120    /// Hook timeout in seconds.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub timeout: Option<u32>,
123}
124
125/// Permission modes accepted by `--permission-mode` and `set_permission_mode`.
126/// Source: binary permission-mode enum
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(rename_all = "camelCase")]
129pub enum PermissionMode {
130    /// `default`: standard behavior; prompts for dangerous operations.
131    Default,
132    /// `acceptEdits`: auto-accepts file edits.
133    AcceptEdits,
134    /// `bypassPermissions`: bypasses all permission checks.
135    BypassPermissions,
136    /// `plan`: planning mode, no actual tool execution.
137    Plan,
138    /// `dontAsk`: never prompts; denies anything not pre-approved.
139    DontAsk,
140    /// `auto`: a model classifier approves or denies permission prompts.
141    Auto,
142}
143
144impl PermissionMode {
145    /// Wire value, e.g. `"acceptEdits"`.
146    #[must_use]
147    pub fn as_str(self) -> &'static str {
148        match self {
149            Self::Default => "default",
150            Self::AcceptEdits => "acceptEdits",
151            Self::BypassPermissions => "bypassPermissions",
152            Self::Plan => "plan",
153            Self::DontAsk => "dontAsk",
154            Self::Auto => "auto",
155        }
156    }
157}
158
159/// Effort levels accepted by `--effort` and `set_effort`.
160/// Source: `claude --help` (2.1.329)
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
162#[serde(rename_all = "lowercase")]
163pub enum Effort {
164    /// `low`.
165    Low,
166    /// `medium`.
167    Medium,
168    /// `high`.
169    High,
170    /// `xhigh`.
171    Xhigh,
172    /// `max`.
173    Max,
174}
175
176impl Effort {
177    /// Wire value, e.g. `"xhigh"`.
178    #[must_use]
179    pub fn as_str(self) -> &'static str {
180        match self {
181            Self::Low => "low",
182            Self::Medium => "medium",
183            Self::High => "high",
184            Self::Xhigh => "xhigh",
185            Self::Max => "max",
186        }
187    }
188}
189
190/// `--thinking`. Source: binary `--thinking <mode>` option (hidden)
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub enum Thinking {
193    /// `enabled`.
194    Enabled,
195    /// `adaptive`.
196    Adaptive,
197    /// `disabled`.
198    Disabled,
199}
200
201impl Thinking {
202    /// Wire value, e.g. `"adaptive"`.
203    #[must_use]
204    pub fn as_str(self) -> &'static str {
205        match self {
206            Self::Enabled => "enabled",
207            Self::Adaptive => "adaptive",
208            Self::Disabled => "disabled",
209        }
210    }
211}
212
213/// How thinking content appears (`--thinking-display`, `set_max_thinking_tokens`).
214/// Source: binary thinking-display enum
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
216#[serde(rename_all = "lowercase")]
217pub enum ThinkingDisplay {
218    /// `summarized`.
219    Summarized,
220    /// `omitted`.
221    Omitted,
222    /// `highlights`.
223    Highlights,
224}
225
226impl ThinkingDisplay {
227    /// Wire value, e.g. `"summarized"`.
228    #[must_use]
229    pub fn as_str(self) -> &'static str {
230        match self {
231            Self::Summarized => "summarized",
232            Self::Omitted => "omitted",
233            Self::Highlights => "highlights",
234        }
235    }
236}
237
238/// `--autocompact`: when the CLI compacts the context on its own.
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub enum Autocompact {
241    /// The CLI's default window.
242    Auto,
243    /// Compact at this many tokens (at least 100 000).
244    Tokens(u64),
245}
246
247impl Autocompact {
248    /// CLI argument: `"auto"` or the token count.
249    #[must_use]
250    pub fn to_arg(self) -> String {
251        match self {
252            Self::Auto => "auto".into(),
253            Self::Tokens(n) => n.to_string(),
254        }
255    }
256}
257
258/// `--permission-prompts`: who answers a permission prompt.
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub enum PermissionPrompts {
261    /// The SDK host (`SessionOptions::can_use_tool`).
262    Host,
263    /// Nobody: anything that would prompt is denied.
264    None,
265}
266
267impl PermissionPrompts {
268    /// CLI argument: `"host"` or `"none"`.
269    #[must_use]
270    pub fn as_str(self) -> &'static str {
271        match self {
272            Self::Host => "host",
273            Self::None => "none",
274        }
275    }
276}
277
278/// When a prompt sent during a running turn is taken in.
279/// Source: binary user-message `priority` enum
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(rename_all = "lowercase")]
282pub enum Priority {
283    /// Aborts the running turn, then runs. The aborted turn still ends with
284    /// a `success` result (`terminal_reason: "aborted_streaming"`).
285    Now,
286    /// Taken in at the next opportunity inside the running turn.
287    Next,
288    /// Queued until the running turn ends.
289    Later,
290}
291
292/// A user turn.
293/// Source: _internal/client.py:126–131
294#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct UserMessage {
296    /// Always `"user"`.
297    #[serde(rename = "type")]
298    pub kind: String, // "user"
299    /// Role and content blocks.
300    pub message: UserMessageBody,
301    /// Tool call this message belongs to; `None` for a top-level prompt.
302    pub parent_tool_use_id: Option<String>,
303    /// Echoed back (`isReplay: true`) when the CLI starts this message's turn,
304    /// because the session runs with `--replay-user-messages`.
305    pub uuid: String,
306    /// When the CLI takes the message in during a running turn; `None` = CLI default.
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub priority: Option<Priority>,
309    /// `Some(false)`: append to the conversation without starting a turn.
310    #[serde(default, rename = "shouldQuery", skip_serializing_if = "Option::is_none")]
311    pub should_query: Option<bool>,
312    /// ISO 8601 time the message was created. Part of the wire schema, but
313    /// CLI 2.1.329 records its own receive time in the echo and transcript.
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub timestamp: Option<String>,
316    /// `Some(true)`: the host composed this text (the user did not type it).
317    /// The CLI delivers it as written: no `@path` expansion, no slash-command
318    /// dispatch, and no turn-start context attachments.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub client_composed: Option<bool>,
321}
322
323impl UserMessage {
324    /// A plain-text prompt.
325    pub fn text(content: impl Into<String>) -> Self {
326        Self::blocks(vec![ContentBlock::Text { text: content.into() }])
327    }
328
329    /// A message with several blocks, e.g. text plus images.
330    #[must_use]
331    pub fn blocks(content: Vec<ContentBlock>) -> Self {
332        Self {
333            kind: "user".into(),
334            message: UserMessageBody { role: "user".into(), content },
335            parent_tool_use_id: None,
336            uuid: uuid::Uuid::new_v4().to_string(),
337            priority: None,
338            should_query: None,
339            timestamp: None,
340            client_composed: None,
341        }
342    }
343
344    /// Creation time as an ISO 8601 string, e.g. "2026-11-20T07:03:32.670Z".
345    #[must_use]
346    pub fn with_timestamp(mut self, timestamp: impl Into<String>) -> Self {
347        self.timestamp = Some(timestamp.into());
348        self
349    }
350
351    /// Mark the text as host-composed: delivered verbatim, with no `@path`
352    /// expansion, slash-command dispatch or turn-start attachments.
353    #[must_use]
354    pub fn client_composed(mut self) -> Self {
355        self.client_composed = Some(true);
356        self
357    }
358
359    /// Set when the prompt is taken in during a running turn.
360    #[must_use]
361    pub fn with_priority(mut self, priority: Priority) -> Self {
362        self.priority = Some(priority);
363        self
364    }
365
366    /// Add the message to the conversation without starting a turn. Its
367    /// content is seen by the model on the next prompt.
368    #[must_use]
369    pub fn context_only(mut self) -> Self {
370        self.should_query = Some(false);
371        self
372    }
373}
374
375/// Message body: `role` plus content blocks.
376#[derive(Debug, Clone, Serialize, Deserialize)]
377pub struct UserMessageBody {
378    /// Always `"user"`.
379    pub role: String,
380    /// Content blocks of the message.
381    pub content: Vec<ContentBlock>,
382}
383
384/// Content block of a user message (Anthropic Messages API shape).
385#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
386#[serde(tag = "type")]
387pub enum ContentBlock {
388    /// Plain text.
389    #[serde(rename = "text")]
390    Text {
391        /// The text.
392        text: String,
393    },
394    /// An image.
395    #[serde(rename = "image")]
396    Image {
397        /// Where the image data comes from.
398        source: ImageSource,
399    },
400    /// A PDF or plain-text document.
401    #[serde(rename = "document")]
402    Document {
403        /// Where the document data comes from.
404        source: DocumentSource,
405        /// Document title.
406        #[serde(default, skip_serializing_if = "Option::is_none")]
407        title: Option<String>,
408    },
409    /// The result of a tool call, answering a `tool_use` block.
410    #[serde(rename = "tool_result")]
411    ToolResult {
412        /// Id of the `tool_use` block answered.
413        tool_use_id: String,
414        /// Result content.
415        content: Vec<ContentBlock>,
416        /// `Some(true)`: the tool call failed.
417        #[serde(default, skip_serializing_if = "Option::is_none")]
418        is_error: Option<bool>,
419    },
420}
421
422impl ContentBlock {
423    /// An image from base64 data; `media_type` e.g. "image/png".
424    pub fn image_base64(media_type: impl Into<String>, data: impl Into<String>) -> Self {
425        Self::Image {
426            source: ImageSource::Base64 { media_type: media_type.into(), data: data.into() },
427        }
428    }
429
430    /// A PDF from base64 data.
431    pub fn pdf_base64(data: impl Into<String>) -> Self {
432        Self::Document {
433            source: DocumentSource::Base64 { media_type: "application/pdf".into(), data: data.into() },
434            title: None,
435        }
436    }
437}
438
439/// Anthropic Messages API document source.
440#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
441#[serde(tag = "type", rename_all = "lowercase")]
442pub enum DocumentSource {
443    /// Base64-encoded data.
444    Base64 {
445        /// MIME type, e.g. `"application/pdf"`.
446        media_type: String,
447        /// Base64 data.
448        data: String,
449    },
450    /// Plain text.
451    Text {
452        /// MIME type, e.g. `"text/plain"`.
453        media_type: String,
454        /// The text.
455        data: String,
456    },
457    /// A URL the API fetches.
458    Url {
459        /// Document URL.
460        url: String,
461    },
462}
463
464/// Anthropic Messages API image source.
465#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
466#[serde(tag = "type", rename_all = "lowercase")]
467pub enum ImageSource {
468    /// Base64-encoded data.
469    Base64 {
470        /// MIME type, e.g. `"image/png"`.
471        media_type: String,
472        /// Base64 data.
473        data: String,
474    },
475    /// A URL the API fetches.
476    Url {
477        /// Image URL.
478        url: String,
479    },
480}
481
482/// Envelope for every host → CLI answer to a CLI-initiated control request.
483/// Source: query.py:325–345
484#[derive(Debug, Clone, Serialize)]
485pub struct ControlResponse {
486    /// Always `"control_response"`.
487    #[serde(rename = "type")]
488    pub kind: &'static str, // "control_response"
489    /// Success or error, keyed by `request_id`.
490    pub response: ControlResponseBody,
491}
492
493/// Body of a `control_response`, tagged by `subtype`.
494#[derive(Debug, Clone, Serialize)]
495#[serde(tag = "subtype", rename_all = "lowercase")]
496pub enum ControlResponseBody {
497    /// The request succeeded.
498    Success {
499        /// Id of the request answered.
500        request_id: String,
501        /// Response payload.
502        response: serde_json::Value,
503    },
504    /// The request failed.
505    Error {
506        /// Id of the request answered.
507        request_id: String,
508        /// Error message.
509        error: String,
510    },
511}
512
513impl ControlResponse {
514    /// Successful answer to the request `request_id`.
515    pub fn success(request_id: impl Into<String>, response: serde_json::Value) -> Self {
516        Self {
517            kind: "control_response",
518            response: ControlResponseBody::Success { request_id: request_id.into(), response },
519        }
520    }
521    /// Error answer to the request `request_id`.
522    pub fn error(request_id: impl Into<String>, error: impl Into<String>) -> Self {
523        Self {
524            kind: "control_response",
525            response: ControlResponseBody::Error { request_id: request_id.into(), error: error.into() },
526        }
527    }
528}
529
530/// Answer to a `can_use_tool` request.
531/// Source: binary `can_use_tool` response schema (`behavior`, `updatedInput`,
532/// `updatedPermissions`, `message`, `interrupt`)
533#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
534#[serde(tag = "behavior", rename_all = "camelCase")]
535pub enum ToolDecision {
536    /// `updated_input: None` → the original input is sent back unchanged.
537    /// `updated_permissions`: permission updates to apply, e.g. the
538    /// request's `permission_suggestions` for "always allow".
539    #[serde(rename = "allow")]
540    Allow {
541        /// `updatedInput`: replacement tool input.
542        #[serde(rename = "updatedInput", skip_serializing_if = "Option::is_none")]
543        updated_input: Option<serde_json::Value>,
544        /// `updatedPermissions`: permission updates to apply.
545        #[serde(rename = "updatedPermissions", default, skip_serializing_if = "Option::is_none")]
546        updated_permissions: Option<Vec<serde_json::Value>>,
547    },
548    /// Refuse the tool call.
549    #[serde(rename = "deny")]
550    Deny {
551        /// Reason sent back for the denial.
552        message: String,
553        /// `Some(true)`: also interrupt the turn.
554        #[serde(skip_serializing_if = "Option::is_none")]
555        interrupt: Option<bool>,
556    },
557}
558
559impl ToolDecision {
560    /// Allow with the original input.
561    #[must_use]
562    pub fn allow() -> Self { Self::Allow { updated_input: None, updated_permissions: None } }
563    /// Allow with a rewritten input.
564    #[must_use]
565    pub fn allow_with_input(input: serde_json::Value) -> Self {
566        Self::Allow { updated_input: Some(input), updated_permissions: None }
567    }
568    /// Allow and apply permission updates, so the CLI stops asking (pass the
569    /// request's `permission_suggestions` for "always allow").
570    #[must_use]
571    pub fn allow_and_remember(updates: Vec<serde_json::Value>) -> Self {
572        Self::Allow { updated_input: None, updated_permissions: Some(updates) }
573    }
574    /// Deny with `message`.
575    pub fn deny(message: impl Into<String>) -> Self {
576        Self::Deny { message: message.into(), interrupt: None }
577    }
578}
579
580/// Hook result — the same JSON a shell hook prints on stdout.
581/// Source: binary hook-output schema (continue, suppressOutput, stopReason,
582/// decision, systemMessage, reason, hookSpecificOutput).
583#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
584#[serde(rename_all = "camelCase")]
585pub struct HookOutput {
586    /// `false` stops the whole agent loop.
587    #[serde(rename = "continue", skip_serializing_if = "Option::is_none")]
588    pub continue_: Option<bool>,
589    /// Hide stdout from the transcript (default: false).
590    #[serde(skip_serializing_if = "Option::is_none")]
591    pub suppress_output: Option<bool>,
592    /// Message shown when `continue` is false.
593    #[serde(skip_serializing_if = "Option::is_none")]
594    pub stop_reason: Option<String>,
595    /// `approve` or `block`.
596    #[serde(skip_serializing_if = "Option::is_none")]
597    pub decision: Option<HookDecision>,
598    /// Warning shown to the user.
599    #[serde(skip_serializing_if = "Option::is_none")]
600    pub system_message: Option<String>,
601    /// Reason fed back to the model when `decision` is `block`.
602    #[serde(skip_serializing_if = "Option::is_none")]
603    pub reason: Option<String>,
604    /// Event-specific output; must carry `hookEventName`.
605    #[serde(skip_serializing_if = "Option::is_none")]
606    pub hook_specific_output: Option<serde_json::Value>,
607}
608
609/// `decision` of a hook result.
610#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
611#[serde(rename_all = "lowercase")]
612pub enum HookDecision {
613    /// `approve`.
614    Approve,
615    /// `block`: `reason` is fed back to the model.
616    Block,
617}
618
619impl HookOutput {
620    /// No opinion — the CLI proceeds as if the hook printed nothing.
621    #[must_use]
622    pub fn allow() -> Self { Self::default() }
623
624    /// Block the action; `reason` is shown to the model.
625    pub fn block(reason: impl Into<String>) -> Self {
626        Self { decision: Some(HookDecision::Block), reason: Some(reason.into()), ..Self::default() }
627    }
628
629    /// Inject `additionalContext` for the given event.
630    pub fn with_context(event: HookEventKind, context: impl Into<String>) -> Self {
631        Self {
632            hook_specific_output: Some(serde_json::json!({
633                "hookEventName": event,
634                "additionalContext": context.into(),
635            })),
636            ..Self::default()
637        }
638    }
639
640    /// Register `watchPaths` for `FileChanged` hooks (valid for `CwdChanged` / `FileChanged`).
641    #[must_use]
642    pub fn watch_paths(event: HookEventKind, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
643        let paths: Vec<String> = paths.into_iter().map(Into::into).collect();
644        Self {
645            hook_specific_output: Some(serde_json::json!({
646                "hookEventName": event,
647                "watchPaths": paths,
648            })),
649            ..Self::default()
650        }
651    }
652
653    /// Whether `decision` is `block`.
654    #[must_use]
655    pub fn is_block(&self) -> bool { self.decision == Some(HookDecision::Block) }
656}
657
658/// Body of a `background_tasks` control request (Ctrl+B equivalent).
659/// Send with `Session::control(&body)`.
660/// Source: chunk-20bv8pca.js:20970–20978
661#[derive(Debug, Clone, Serialize)]
662pub struct BackgroundTasksRequest {
663    /// Always `"background_tasks"`.
664    pub subtype: &'static str, // "background_tasks"
665    /// None = background all foreground tasks; Some = background specific `tool_use_id`.
666    #[serde(skip_serializing_if = "Option::is_none")]
667    pub tool_use_id: Option<String>,
668}
669
670impl BackgroundTasksRequest {
671    /// Background all foreground tasks.
672    #[must_use]
673    pub fn all() -> Self {
674        Self { subtype: "background_tasks", tool_use_id: None }
675    }
676    /// Background the task of `tool_use_id`.
677    pub fn one(tool_use_id: impl Into<String>) -> Self {
678        Self { subtype: "background_tasks", tool_use_id: Some(tool_use_id.into()) }
679    }
680}
681
682// ─── Inbound: CLI → host ─────────────────────────────────────────────────────
683
684/// Every stdout line deserializes to this.
685/// Source: chunk-20bv8pca.js (various schema locations)
686#[derive(Debug, Clone, Deserialize)]
687#[serde(tag = "type")]
688#[non_exhaustive]
689pub enum InboundMessage {
690    /// Per-turn metadata. First frame before each turn.
691    #[serde(rename = "system")]
692    System(SystemMessage),
693    /// A user message: the echo of a host prompt (`is_replay`) or a tool result.
694    #[serde(rename = "user")]
695    User(InboundUserMessage),
696    /// Complete assistant message block.
697    #[serde(rename = "assistant")]
698    Assistant(AssistantMessage),
699    /// Partial streaming chunk (requires --include-partial-messages).
700    #[serde(rename = "stream_event")]
701    StreamEvent(StreamEventMessage),
702    /// Turn complete signal.
703    #[serde(rename = "result")]
704    Result(ResultMessage),
705    /// CLI asking the host to answer: a hook callback, a tool permission
706    /// (`can_use_tool`) or an SDK MCP message. Source: chunk-20bv8pca.js:18214
707    #[serde(rename = "control_request")]
708    ControlRequest(ControlRequest),
709    /// CLI answering a host-initiated control request (initialize, interrupt, …).
710    /// Source: query.py:180–192
711    #[serde(rename = "control_response")]
712    ControlResponse(InboundControlResponse),
713    /// Process keepalive with startup marker.
714    /// Source: chunk-f89nsf5q.query.js:1403–1410
715    #[serde(rename = "keep_alive")]
716    KeepAlive(KeepAliveMessage),
717    /// The CLI withdrew a control request it sent (e.g. a `can_use_tool`
718    /// whose turn was interrupted); its answer is no longer wanted.
719    #[serde(rename = "control_cancel_request")]
720    ControlCancelRequest(ControlCancelRequest),
721    /// Any other frame type (`rate_limit_event`, `tool_progress`,
722    /// `prompt_suggestion`, `command_lifecycle`, …), kept verbatim.
723    #[serde(skip_deserializing)]
724    Other(serde_json::Value),
725    /// Decoding placeholder; `Session` turns it into `Other` and delivers
726    /// it only for a stdout line that is not JSON.
727    #[doc(hidden)]
728    #[serde(other)]
729    Unknown,
730}
731
732/// Source: binary `control_cancel_request` schema
733#[derive(Debug, Clone, Deserialize)]
734#[non_exhaustive]
735pub struct ControlCancelRequest {
736    /// Id of the withdrawn control request.
737    pub request_id: String,
738}
739
740/// Every `type:"system"` frame: `init` (first frame of each turn) plus
741/// `hook_started`, `hook_response`, `compact_boundary`, `model_fallback`,
742/// `background_tasks_changed`, `task_started`, `task_updated`, `task_notification`,
743/// `thinking_tokens`, `model_refusal_no_fallback`, `peer_message_hold`, … —
744/// only `subtype` and `session_id` are common to all; subtype-specific fields
745/// are in `extra`. Source: binary system-message schemas
746/// Source: chunk-hp1k7mph.js:194 (`WGt` function), chunk-20bv8pca.js:15125
747#[derive(Debug, Clone, Serialize, Deserialize)]
748#[non_exhaustive]
749pub struct SystemMessage {
750    /// `init`, `hook_started`, `compact_boundary`, …
751    pub subtype: String, // "init" | "hook_started" | "hook_response" | …
752    /// Session the frame belongs to.
753    pub session_id: String,
754    /// Working directory (`init`).
755    #[serde(default)]
756    pub cwd: String,
757    /// Active model (`init`).
758    #[serde(default)]
759    pub model: String,
760    /// CLI version (`init`).
761    #[serde(default)]
762    pub claude_code_version: String,
763    /// Permission mode, as its wire value (`init`).
764    #[serde(default)]
765    pub permission_mode: String,
766    /// Available tool names (`init`).
767    #[serde(default)]
768    pub tools: Vec<String>,
769    /// Enabled API betas (`init`).
770    #[serde(default)]
771    pub betas: Vec<String>,
772    /// Protocol capabilities the CLI supports, for feature detection (`init`).
773    #[serde(default)]
774    pub capabilities: Vec<String>,
775    /// Loaded skills (`init`), kept verbatim.
776    #[serde(default)]
777    pub skills: Vec<serde_json::Value>,
778    /// Loaded plugins (`init`), kept verbatim.
779    #[serde(default)]
780    pub plugins: Vec<serde_json::Value>,
781    /// Subtype-specific fields.
782    #[serde(flatten)]
783    pub extra: HashMap<String, serde_json::Value>,
784}
785
786impl SystemMessage {
787    /// `REPL` or `Eval` in `tools[]` = Code Mode active (see `SessionOptions::code_mode`).
788    #[must_use]
789    pub fn code_mode_active(&self) -> bool {
790        self.tools.iter().any(|t| t == "REPL" || t == "Eval")
791    }
792}
793
794/// A complete `assistant` frame.
795#[derive(Debug, Clone, Deserialize)]
796#[non_exhaustive]
797pub struct AssistantMessage {
798    /// The model message.
799    pub message: AssistantMessageBody,
800    /// Session the frame belongs to.
801    #[serde(default)]
802    pub session_id: Option<String>,
803    /// Tool call (e.g. a subagent) that produced the message; `None` for the main thread.
804    #[serde(default)]
805    pub parent_tool_use_id: Option<String>,
806}
807
808/// Body of an `assistant` frame.
809#[derive(Debug, Clone, Deserialize)]
810#[non_exhaustive]
811pub struct AssistantMessageBody {
812    /// Always `"assistant"`.
813    pub role: String,
814    /// Content blocks of the message.
815    pub content: Vec<AssistantBlock>,
816    /// Why the model stopped, e.g. `"end_turn"`, `"tool_use"`.
817    #[serde(default)]
818    pub stop_reason: Option<String>,
819}
820
821/// Content block of an assistant message.
822#[derive(Debug, Clone, Deserialize)]
823#[serde(tag = "type")]
824#[non_exhaustive]
825pub enum AssistantBlock {
826    /// Text.
827    #[serde(rename = "text")]
828    Text {
829        /// The text.
830        text: String,
831    },
832    /// A tool call the CLI runs.
833    #[serde(rename = "tool_use")]
834    ToolUse {
835        /// Tool-use id; the matching `tool_result` carries it.
836        id: String,
837        /// Tool name.
838        name: String,
839        /// Tool input.
840        input: serde_json::Value,
841    },
842    /// Extended thinking.
843    #[serde(rename = "thinking")]
844    Thinking {
845        /// The thinking text.
846        thinking: String,
847    },
848    /// Encrypted thinking; opaque to the host.
849    #[serde(rename = "redacted_thinking")]
850    RedactedThinking {
851        /// Encrypted thinking data.
852        data: String,
853    },
854    /// A tool the API runs itself (web search, …).
855    #[serde(rename = "server_tool_use")]
856    ServerToolUse {
857        /// Tool-use id.
858        id: String,
859        /// Server tool name.
860        name: String,
861        /// Tool input.
862        input: serde_json::Value,
863    },
864    /// Result of a server-run web search.
865    #[serde(rename = "web_search_tool_result")]
866    WebSearchToolResult {
867        /// Id of the `server_tool_use` block answered.
868        tool_use_id: String,
869        /// Search results, kept verbatim.
870        content: serde_json::Value,
871    },
872    /// Any other block type.
873    #[serde(other)]
874    Unknown,
875}
876
877/// A `user` frame: the echo of a prompt, tool results, or a message the
878/// CLI added itself (`is_synthetic`).
879#[derive(Debug, Clone, Deserialize)]
880#[non_exhaustive]
881pub struct InboundUserMessage {
882    /// Message uuid; for an echo, the host prompt's `UserMessage::uuid`.
883    #[serde(default)]
884    pub uuid: Option<String>,
885    /// `isReplay`: echo of a host prompt.
886    #[serde(default, rename = "isReplay")]
887    pub is_replay: Option<bool>,
888    /// `isSynthetic`: the CLI added the message itself.
889    #[serde(default, rename = "isSynthetic")]
890    pub is_synthetic: Option<bool>,
891    /// Tool call this message belongs to.
892    #[serde(default)]
893    pub parent_tool_use_id: Option<String>,
894    /// Subagent that produced the frame.
895    #[serde(default)]
896    pub agent_id: Option<String>,
897    /// Message body.
898    #[serde(default)]
899    pub message: Option<InboundUserBody>,
900    /// The tool's full structured output (e.g. Bash `{stdout, stderr, …}`),
901    /// beside the text sent to the model.
902    #[serde(default)]
903    pub tool_use_result: Option<serde_json::Value>,
904}
905
906/// Body of an inbound `user` frame.
907#[derive(Debug, Clone, Deserialize)]
908#[non_exhaustive]
909pub struct InboundUserBody {
910    /// A string or an array of content blocks.
911    #[serde(default)]
912    pub content: serde_json::Value,
913}
914
915/// One `tool_result` block of a `user` frame.
916#[derive(Debug, Clone, Deserialize)]
917#[non_exhaustive]
918pub struct InboundToolResult {
919    /// Id of the `tool_use` block answered.
920    pub tool_use_id: String,
921    /// A string or an array of content blocks.
922    #[serde(default)]
923    pub content: serde_json::Value,
924    /// The tool call failed.
925    #[serde(default)]
926    pub is_error: bool,
927}
928
929impl InboundUserMessage {
930    /// The `tool_result` blocks of this frame.
931    #[must_use]
932    pub fn tool_results(&self) -> Vec<InboundToolResult> {
933        let Some(blocks) = self.message.as_ref().and_then(|m| m.content.as_array()) else {
934            return vec![];
935        };
936        blocks
937            .iter()
938            .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("tool_result"))
939            .filter_map(|b| InboundToolResult::deserialize(b).ok())
940            .collect()
941    }
942}
943
944/// Partial streaming chunk.
945/// Source: chunk-20bv8pca.js:15343–15401
946#[derive(Debug, Clone, Deserialize)]
947#[non_exhaustive]
948pub struct StreamEventMessage {
949    /// Raw Anthropic streaming event (`message_start`, `content_block_delta`, …).
950    pub event: serde_json::Value,
951    /// Session the frame belongs to.
952    #[serde(default)]
953    pub session_id: Option<String>,
954    /// Time to first token, in ms.
955    #[serde(default)]
956    pub ttft_ms: Option<u64>,
957    /// Tool call (e.g. a subagent) that produced the event; `None` for the main thread.
958    #[serde(default)]
959    pub parent_tool_use_id: Option<String>,
960}
961
962/// Turn complete.
963/// Source: chunk-20bv8pca.js:14425–14913
964#[derive(Debug, Clone, Default, Deserialize)]
965#[non_exhaustive]
966pub struct ResultMessage {
967    /// "success" | "error_*". A failed API call still comes as "success"
968    /// with `is_error: true` and the message in `result`.
969    #[serde(default)]
970    pub subtype: String,
971    /// The turn failed; a failed API call sets this on a `success` result.
972    #[serde(default)]
973    pub is_error: bool,
974    /// Final text of the turn, or the error message when `is_error`.
975    #[serde(default)]
976    pub result: Option<String>,
977    /// Error details of `error_*` subtypes.
978    #[serde(default)]
979    pub errors: Option<Vec<serde_json::Value>>,
980    /// Session the turn ran in.
981    #[serde(default)]
982    pub session_id: Option<String>,
983    /// Estimated cost in USD, cumulative across the session's turns.
984    #[serde(default)]
985    pub total_cost_usd: Option<f64>,
986    /// Time to first token, in ms.
987    #[serde(default)]
988    pub ttft_ms: Option<u64>,
989    /// Wall-clock duration, in ms.
990    #[serde(default)]
991    pub duration_ms: Option<u64>,
992    /// Token usage.
993    #[serde(default)]
994    pub usage: Option<UsageSummary>,
995    /// Why the model stopped, e.g. `"end_turn"`.
996    #[serde(default)]
997    pub stop_reason: Option<String>,
998    /// Time spent in API calls, in ms.
999    #[serde(default)]
1000    pub duration_api_ms: Option<u64>,
1001    /// Number of agent-loop turns.
1002    #[serde(default)]
1003    pub num_turns: Option<u64>,
1004    /// Why the loop ended ("completed", …).
1005    #[serde(default)]
1006    pub terminal_reason: Option<String>,
1007    /// Output matching `Initialize::json_schema`.
1008    #[serde(default)]
1009    pub structured_output: Option<serde_json::Value>,
1010    /// Tool calls the permission system denied during the turn.
1011    #[serde(default)]
1012    pub permission_denials: Vec<serde_json::Value>,
1013    /// Per-model token and cost breakdown.
1014    #[serde(default, rename = "modelUsage")]
1015    pub model_usage: Option<serde_json::Value>,
1016    /// The prompts (`UserMessage::uuid`) this turn answered.
1017    #[serde(default)]
1018    pub user_message_uuids: Vec<String>,
1019    /// Set when the CLI started the turn itself (e.g. `{"kind":"task-notification"}`
1020    /// after a background task finished); absent for turns the host prompted.
1021    #[serde(default)]
1022    pub origin: Option<serde_json::Value>,
1023    /// Fields not named above.
1024    #[serde(flatten)]
1025    pub extra: HashMap<String, serde_json::Value>,
1026}
1027
1028impl ResultMessage {
1029    /// `success` subtype without `is_error`.
1030    #[must_use]
1031    pub fn is_success(&self) -> bool {
1032        self.subtype == "success" && !self.is_error
1033    }
1034
1035    /// Whether this turn answered the prompt `uuid`. A prompt the CLI
1036    /// refuses up front (e.g. budget spent) gets a result but no echo.
1037    #[must_use]
1038    pub fn answers(&self, uuid: &str) -> bool {
1039        self.user_message_uuids.iter().any(|u| u.eq_ignore_ascii_case(uuid))
1040    }
1041
1042    /// Category of a failed turn.
1043    #[must_use]
1044    pub fn error_kind(&self) -> TurnErrorKind {
1045        match self.subtype.as_str() {
1046            "error_during_execution" => TurnErrorKind::Execution,
1047            "error_max_turns" => TurnErrorKind::MaxTurns,
1048            "error_max_budget_usd" => TurnErrorKind::MaxBudget,
1049            "error_max_structured_output_retries" => TurnErrorKind::StructuredOutputRetries,
1050            "success" => TurnErrorKind::Api,
1051            other => TurnErrorKind::Other(other.to_string()),
1052        }
1053    }
1054
1055    /// Why the turn failed: for `is_error` the CLI's message; for
1056    /// `error_*` subtypes the subtype, then its `errors` details.
1057    #[must_use]
1058    pub fn error_message(&self) -> String {
1059        if let Some(r) = self.result.as_ref().filter(|r| self.is_error && !r.is_empty()) {
1060            return r.clone();
1061        }
1062        let details: Vec<String> = self.errors.iter().flatten()
1063            .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_owned))
1064            .collect();
1065        if details.is_empty() { self.subtype.clone() } else { format!("{}: {}", self.subtype, details.join("; ")) }
1066    }
1067}
1068
1069/// Why a turn failed. Source: binary result error-subtype enum
1070#[derive(Debug, Clone, PartialEq, Eq)]
1071#[non_exhaustive]
1072pub enum TurnErrorKind {
1073    /// `error_during_execution`: includes interrupted turns.
1074    Execution,
1075    /// `error_max_turns`: `SessionOptions::max_turns` reached.
1076    MaxTurns,
1077    /// `error_max_budget_usd`: `SessionOptions::max_budget_usd` reached.
1078    MaxBudget,
1079    /// `error_max_structured_output_retries`.
1080    StructuredOutputRetries,
1081    /// The API call failed (`is_error` on a `success` result).
1082    Api,
1083    /// The CLI exited before the turn ended.
1084    SessionClosed,
1085    /// The prompt was withdrawn before it ran (`Session::cancel_prompt`,
1086    /// `Session::interrupt_all`).
1087    Cancelled,
1088    /// A subtype this SDK does not know.
1089    Other(String),
1090}
1091
1092/// Token usage breakdown.
1093/// Source: chunk-20bv8pca.js:11526–11530
1094#[derive(Debug, Clone, Deserialize, Default)]
1095#[non_exhaustive]
1096pub struct UsageSummary {
1097    /// Input tokens.
1098    #[serde(default)]
1099    pub input_tokens: u64,
1100    /// Output tokens.
1101    #[serde(default)]
1102    pub output_tokens: u64,
1103    /// Input tokens read from the prompt cache.
1104    #[serde(default)]
1105    pub cache_read_input_tokens: Option<u64>,
1106    /// Input tokens written to the prompt cache.
1107    #[serde(default)]
1108    pub cache_creation_input_tokens: Option<u64>,
1109    /// Cache writes by TTL, kept verbatim.
1110    #[serde(default)]
1111    pub cache_creation: Option<serde_json::Value>,
1112}
1113
1114/// CLI → host control request envelope:
1115/// `{"type":"control_request","request_id":"…","request":{"subtype":"…",…}}`.
1116/// Source: query.py:236–240
1117#[derive(Debug, Clone, Deserialize)]
1118#[non_exhaustive]
1119pub struct ControlRequest {
1120    /// Id to answer with in `ControlResponse`.
1121    pub request_id: String,
1122    /// Request body, tagged by `subtype`.
1123    pub request: ControlRequestBody,
1124}
1125
1126/// Body of a CLI → host control request, tagged by `subtype`.
1127#[derive(Debug, Clone, Deserialize)]
1128#[serde(tag = "subtype")]
1129#[non_exhaustive]
1130pub enum ControlRequestBody {
1131    /// Only sent when the CLI runs with `--permission-prompt-tool stdio`.
1132    #[serde(rename = "can_use_tool")]
1133    CanUseTool(CanUseToolRequest),
1134    /// A hook matched; run the callback `callback_id`.
1135    #[serde(rename = "hook_callback")]
1136    HookCallback(HookCallbackRequest),
1137    /// JSON-RPC message for an SDK MCP server. Source: query.py:305–320
1138    #[serde(rename = "mcp_message")]
1139    McpMessage(McpMessageRequest),
1140    /// An MCP server asks the user for input.
1141    #[serde(rename = "elicitation")]
1142    Elicitation(ElicitationRequest),
1143    /// A tool asks the host to render a blocking dialog; sent only for kinds
1144    /// listed in `Initialize::supported_dialog_kinds`.
1145    #[serde(rename = "request_user_dialog")]
1146    RequestUserDialog(UserDialogRequest),
1147    /// Future subtypes — answered with an error response.
1148    #[serde(other)]
1149    Unsupported,
1150}
1151
1152/// Source: binary `can_use_tool` schema; query.py:244–262
1153#[derive(Debug, Clone, Deserialize)]
1154#[non_exhaustive]
1155pub struct CanUseToolRequest {
1156    /// Tool the model wants to use.
1157    pub tool_name: String,
1158    /// Tool input.
1159    pub input: serde_json::Value,
1160    /// Tool-use id of the call.
1161    #[serde(default)]
1162    pub tool_use_id: Option<String>,
1163    /// Permission updates that would stop the CLI asking again; return them
1164    /// with `ToolDecision::allow_and_remember` for "always allow".
1165    #[serde(default)]
1166    pub permission_suggestions: Option<Vec<serde_json::Value>>,
1167    /// Human-readable reason the CLI asks; may carry ANSI escapes.
1168    #[serde(default)]
1169    pub decision_reason: Option<String>,
1170    /// Why the ask escalated: "rule", "hook", "safetyCheck", "classifier", …
1171    #[serde(default)]
1172    pub decision_reason_type: Option<String>,
1173    /// MCP server of the tool: `{"name", "source"}`.
1174    #[serde(default)]
1175    pub mcp_server: Option<serde_json::Value>,
1176    /// Path outside the allowed directories that triggered the ask.
1177    #[serde(default)]
1178    pub blocked_path: Option<String>,
1179    /// Set when a safety check is involved: `false` = one needs manual approval.
1180    #[serde(default)]
1181    pub classifier_approvable: Option<bool>,
1182    /// Do not offer "always allow" for this ask.
1183    #[serde(default)]
1184    pub suppress_always_allow_rule: Option<bool>,
1185    /// The ask must not be approvable by a single stray keystroke.
1186    #[serde(default)]
1187    pub default_to_no: Option<bool>,
1188    /// User `permissions.ask` rule that forced this prompt: `{source, tool_name, rule_content}`.
1189    #[serde(default)]
1190    pub matched_ask_rule: Option<serde_json::Value>,
1191    /// Permission-display title.
1192    #[serde(default)]
1193    pub title: Option<String>,
1194    /// Short tool or server label for display.
1195    #[serde(default)]
1196    pub display_name: Option<String>,
1197    /// Permission-display subtitle.
1198    #[serde(default)]
1199    pub description: Option<String>,
1200    /// Subagent that wants to use the tool.
1201    #[serde(default)]
1202    pub agent_id: Option<String>,
1203    /// One-tap Approve/Deny must not be offered.
1204    #[serde(default)]
1205    pub requires_user_interaction: Option<bool>,
1206    /// Fields not named above.
1207    #[serde(flatten)]
1208    pub extra: HashMap<String, serde_json::Value>,
1209}
1210
1211/// Source: binary elicitation schema
1212#[derive(Debug, Clone, Deserialize)]
1213#[non_exhaustive]
1214pub struct ElicitationRequest {
1215    /// MCP server asking for input.
1216    pub mcp_server_name: String,
1217    /// Text shown to the user.
1218    pub message: String,
1219    /// "form" or "url".
1220    #[serde(default)]
1221    pub mode: Option<String>,
1222    /// URL to open (`url` mode).
1223    #[serde(default)]
1224    pub url: Option<String>,
1225    /// Elicitation id from the MCP server.
1226    #[serde(default)]
1227    pub elicitation_id: Option<String>,
1228    /// JSON schema of the requested form fields.
1229    #[serde(default)]
1230    pub requested_schema: Option<serde_json::Value>,
1231    /// Top-level keys of `requested_schema.properties`, in the server's order.
1232    #[serde(default)]
1233    pub property_order: Option<Vec<String>>,
1234    /// Permission-display title from the MCP server.
1235    #[serde(default)]
1236    pub title: Option<String>,
1237    /// Short tool or server label from the MCP server.
1238    #[serde(default)]
1239    pub display_name: Option<String>,
1240    /// Permission-display subtitle from the MCP server.
1241    #[serde(default)]
1242    pub description: Option<String>,
1243    /// Fields not named above.
1244    #[serde(flatten)]
1245    pub extra: HashMap<String, serde_json::Value>,
1246}
1247
1248/// Answer to an `elicitation` request. Source: binary elicitation response schema
1249#[derive(Debug, Clone, Serialize)]
1250pub struct ElicitationResponse {
1251    /// `accept`, `decline` or `cancel`.
1252    pub action: ElicitationAction,
1253    /// Form values; sent with `accept`.
1254    #[serde(skip_serializing_if = "Option::is_none")]
1255    pub content: Option<serde_json::Map<String, serde_json::Value>>,
1256}
1257
1258/// What the user did with an elicitation.
1259#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1260#[serde(rename_all = "lowercase")]
1261pub enum ElicitationAction {
1262    /// The user submitted the form.
1263    Accept,
1264    /// The user declined.
1265    Decline,
1266    /// The user dismissed the request.
1267    Cancel,
1268}
1269
1270impl ElicitationResponse {
1271    /// Accept with the form values.
1272    #[must_use]
1273    pub fn accept(content: serde_json::Map<String, serde_json::Value>) -> Self {
1274        Self { action: ElicitationAction::Accept, content: Some(content) }
1275    }
1276    /// Decline.
1277    #[must_use]
1278    pub fn decline() -> Self {
1279        Self { action: ElicitationAction::Decline, content: None }
1280    }
1281    /// Cancel.
1282    #[must_use]
1283    pub fn cancel() -> Self {
1284        Self { action: ElicitationAction::Cancel, content: None }
1285    }
1286}
1287
1288/// Source: binary `request_user_dialog` schema
1289#[derive(Debug, Clone, Deserialize)]
1290#[non_exhaustive]
1291pub struct UserDialogRequest {
1292    /// Which dialog to render; only kinds in `Initialize::supported_dialog_kinds`.
1293    pub dialog_kind: String,
1294    /// Dialog-specific data; shape set by `dialog_kind`.
1295    #[serde(default)]
1296    pub payload: serde_json::Value,
1297    /// Tool call that raised the dialog.
1298    #[serde(default)]
1299    pub tool_use_id: Option<String>,
1300}
1301
1302/// The user's answer to a `request_user_dialog`.
1303/// Source: binary `request_user_dialog` response schema (behavior, result)
1304#[derive(Debug, Clone, Serialize, PartialEq)]
1305pub struct UserDialogResponse {
1306    /// `completed` or `cancelled`.
1307    pub behavior: UserDialogBehavior,
1308    /// Dialog-specific choice, e.g. `"retry_fallback"` for
1309    /// `refusal_fallback_prompt`.
1310    #[serde(skip_serializing_if = "Option::is_none")]
1311    pub result: Option<serde_json::Value>,
1312}
1313
1314/// How a `request_user_dialog` ended.
1315#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
1316#[serde(rename_all = "lowercase")]
1317pub enum UserDialogBehavior {
1318    /// The user made a choice (`result`).
1319    Completed,
1320    /// The user dismissed the dialog.
1321    Cancelled,
1322}
1323
1324impl UserDialogResponse {
1325    /// The user chose `result`.
1326    pub fn completed(result: impl Into<serde_json::Value>) -> Self {
1327        Self { behavior: UserDialogBehavior::Completed, result: Some(result.into()) }
1328    }
1329    /// The user dismissed the dialog.
1330    #[must_use]
1331    pub fn cancelled() -> Self {
1332        Self { behavior: UserDialogBehavior::Cancelled, result: None }
1333    }
1334}
1335
1336/// Body of an `mcp_message` request.
1337#[derive(Debug, Clone, Deserialize)]
1338#[non_exhaustive]
1339pub struct McpMessageRequest {
1340    /// SDK MCP server the message is for.
1341    pub server_name: String,
1342    /// JSON-RPC message.
1343    pub message: serde_json::Value,
1344}
1345
1346/// Source: binary `hook_callback` schema (`callback_id`, input, `tool_use_id`, `issued_at`)
1347#[derive(Debug, Clone, Deserialize)]
1348#[non_exhaustive]
1349pub struct HookCallbackRequest {
1350    /// Callback id from `HookMatcherConfig::hook_callback_ids`.
1351    pub callback_id: String,
1352    /// Hook input.
1353    pub input: HookEventPayload,
1354    /// Tool-use id, for tool events.
1355    #[serde(default)]
1356    pub tool_use_id: Option<String>,
1357    /// Epoch ms on the CLI's clock when the request was issued.
1358    #[serde(default)]
1359    pub issued_at: Option<u64>,
1360}
1361
1362/// CLI → host answer to a host-initiated control request.
1363/// Source: query.py:180–192
1364#[derive(Debug, Clone, Deserialize)]
1365#[non_exhaustive]
1366pub struct InboundControlResponse {
1367    /// Success or error, keyed by `request_id`.
1368    pub response: InboundControlResponseBody,
1369}
1370
1371/// Body of an inbound `control_response`.
1372#[derive(Debug, Clone, Deserialize)]
1373#[non_exhaustive]
1374pub struct InboundControlResponseBody {
1375    /// `success` or `error`.
1376    pub subtype: String, // "success" | "error"
1377    /// Id of the host request answered.
1378    pub request_id: String,
1379    /// Response payload on `success`.
1380    #[serde(default)]
1381    pub response: Option<serde_json::Value>,
1382    /// Error message on `error`.
1383    #[serde(default)]
1384    pub error: Option<String>,
1385}
1386
1387/// Input to a hook handler. Contains all event-specific fields.
1388/// Source: chunk-0msz7hbn.js:7–323
1389#[derive(Debug, Clone, Deserialize)]
1390#[non_exhaustive]
1391pub struct HookEventPayload {
1392    /// Event that fired.
1393    pub hook_event_name: HookEventKind,
1394    /// Tool name, for tool events.
1395    #[serde(default)]
1396    pub tool_name: Option<String>,
1397    /// Tool input, for tool events.
1398    #[serde(default)]
1399    pub tool_input: Option<serde_json::Value>,
1400    /// Tool-use id, for tool events.
1401    #[serde(default)]
1402    pub tool_use_id: Option<String>,
1403    /// Error message, for `PostToolUseFailure`.
1404    #[serde(default)]
1405    pub error: Option<String>,
1406    /// Whether the failure came from an interrupt, for `PostToolUseFailure`.
1407    #[serde(default)]
1408    pub is_interrupt: Option<bool>,
1409    /// Session the event belongs to.
1410    #[serde(default)]
1411    pub session_id: Option<String>,
1412    /// Working directory.
1413    #[serde(default)]
1414    pub cwd: Option<String>,
1415    /// Changed file, for `FileChanged`.
1416    #[serde(default)]
1417    pub file_path: Option<String>,
1418    /// Change kind, for `FileChanged`.
1419    #[serde(default)]
1420    pub event: Option<String>,        // for FileChanged: "change"|"add"|"unlink"
1421    /// Fields not named above.
1422    #[serde(flatten)]
1423    pub extra: HashMap<String, serde_json::Value>,
1424}
1425
1426/// One entry of a `background_tasks_changed` snapshot.
1427/// Source: binary `background_tasks_changed` schema
1428#[derive(Debug, Clone, Deserialize)]
1429#[non_exhaustive]
1430pub struct BackgroundTask {
1431    /// Task id.
1432    pub task_id: String,
1433    /// Id of one run of the task; a resumed task gets a new one.
1434    #[serde(default)]
1435    pub run_id: Option<String>,
1436    /// "`local_bash`" | "`local_agent`" | "`local_workflow`" | …
1437    #[serde(default)]
1438    pub task_type: String,
1439    /// Agent type of a `local_agent` task.
1440    #[serde(default)]
1441    pub subagent_type: Option<String>,
1442    /// Task description.
1443    #[serde(default)]
1444    pub description: String,
1445    /// Task id of the subagent that launched this task.
1446    #[serde(default)]
1447    pub parent_task_id: Option<String>,
1448    /// Not activity; exclude from activity indicators.
1449    #[serde(default)]
1450    pub ambient: Option<bool>,
1451    /// A resumed subagent run that the resuming tool call waits for.
1452    #[serde(default)]
1453    pub awaited: Option<bool>,
1454    /// The task's work goes on outside this process.
1455    #[serde(default)]
1456    pub off_host: Option<bool>,
1457}
1458
1459/// Process keepalive with startup marker for readiness probing.
1460/// Source: chunk-f89nsf5q.query.js:1403–1410
1461#[derive(Debug, Clone, Deserialize)]
1462#[non_exhaustive]
1463pub struct KeepAliveMessage {
1464    /// Frame fields, kept verbatim.
1465    #[serde(flatten)]
1466    pub extra: HashMap<String, serde_json::Value>,
1467}
1468
1469// ─── Tool/Hook types ─────────────────────────────────────────────────────────
1470
1471/// A tool of an in-process SDK MCP server.
1472#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1473pub struct ToolDef {
1474    /// Tool name.
1475    pub name: String,
1476    /// Description shown to the model.
1477    pub description: String,
1478    /// JSON schema of the tool input.
1479    #[serde(skip_serializing_if = "Option::is_none")]
1480    pub input_schema: Option<serde_json::Value>,
1481    /// Display name.
1482    #[serde(default, skip_serializing_if = "Option::is_none")]
1483    pub title: Option<String>,
1484    /// JSON schema of `ToolResult::structured`.
1485    #[serde(default, skip_serializing_if = "Option::is_none")]
1486    pub output_schema: Option<serde_json::Value>,
1487    /// MCP tool hints.
1488    #[serde(default, skip_serializing_if = "Option::is_none")]
1489    pub annotations: Option<ToolAnnotations>,
1490}
1491
1492/// MCP tool hints. Source: MCP 2025-06-18 `ToolAnnotations`
1493#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1494#[serde(rename_all = "camelCase")]
1495pub struct ToolAnnotations {
1496    /// `readOnlyHint`: the tool does not modify its environment.
1497    #[serde(default, skip_serializing_if = "Option::is_none")]
1498    pub read_only_hint: Option<bool>,
1499    /// `destructiveHint`: the tool may perform destructive updates.
1500    #[serde(default, skip_serializing_if = "Option::is_none")]
1501    pub destructive_hint: Option<bool>,
1502    /// `idempotentHint`: repeated calls with the same arguments have no extra effect.
1503    #[serde(default, skip_serializing_if = "Option::is_none")]
1504    pub idempotent_hint: Option<bool>,
1505    /// `openWorldHint`: the tool interacts with external entities.
1506    #[serde(default, skip_serializing_if = "Option::is_none")]
1507    pub open_world_hint: Option<bool>,
1508}
1509
1510/// An MCP server's name and tools.
1511#[derive(Debug, Clone, Serialize, Deserialize)]
1512pub struct McpManifest {
1513    /// Server name.
1514    pub name: String,
1515    /// Server tools.
1516    pub tools: Vec<ToolDef>,
1517    /// Wire field `server_info`, kept verbatim.
1518    #[serde(default)]
1519    pub server_info: Option<serde_json::Value>,
1520}
1521
1522/// All 33 hook event kinds.
1523/// Source: chunk-20bv8pca.js:12053–12087 (N2 array)
1524#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1525#[serde(rename_all = "PascalCase")]
1526#[non_exhaustive]
1527pub enum HookEventKind {
1528    /// Before tool execution.
1529    PreToolUse,
1530    /// After tool execution.
1531    PostToolUse,
1532    /// After tool execution fails.
1533    PostToolUseFailure,
1534    /// After a batch of tool calls resolves.
1535    PostToolBatch,
1536    /// When notifications are sent.
1537    Notification,
1538    /// When the user submits a prompt.
1539    UserPromptSubmit,
1540    /// When a user-typed slash command expands into a prompt.
1541    UserPromptExpansion,
1542    /// When a new session is started.
1543    SessionStart,
1544    /// When a session is ending.
1545    SessionEnd,
1546    /// Right before Claude concludes its response.
1547    Stop,
1548    /// When the turn ends due to an API error.
1549    StopFailure,
1550    /// When a subagent (Agent tool call) is started.
1551    SubagentStart,
1552    /// Right before a subagent (Agent tool call) concludes its response.
1553    SubagentStop,
1554    /// Before conversation compaction.
1555    PreCompact,
1556    /// After conversation compaction.
1557    PostCompact,
1558    /// Before a requested model switch (`/model`, model picker, `set_model`).
1559    PreModelSwitch,
1560    /// After the session model changes (any cause).
1561    PostModelSwitch,
1562    /// When a permission dialog is displayed.
1563    PermissionRequest,
1564    /// After auto mode denies a tool call.
1565    PermissionDenied,
1566    /// Repo setup hooks for init and maintenance.
1567    Setup,
1568    /// When a teammate is about to go idle.
1569    TeammateIdle,
1570    /// When a task is being created.
1571    TaskCreated,
1572    /// When a task is being marked as completed.
1573    TaskCompleted,
1574    /// When an MCP server requests user input (elicitation).
1575    Elicitation,
1576    /// After a user responds to an MCP elicitation.
1577    ElicitationResult,
1578    /// When configuration files change during a session.
1579    ConfigChange,
1580    /// Create an isolated worktree for VCS-agnostic isolation.
1581    WorktreeCreate,
1582    /// Remove a previously created worktree.
1583    WorktreeRemove,
1584    /// When an instruction file (CLAUDE.md or rule) is loaded.
1585    InstructionsLoaded,
1586    /// After the working directory changes.
1587    CwdChanged,
1588    /// When a watched file changes.
1589    FileChanged,
1590    /// After a working directory is added mid-session.
1591    DirectoryAdded,
1592    /// While assistant message text is displayed.
1593    MessageDisplay,
1594}
1595