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. Only events where
630    /// `HookEventKind::accepts_additional_context` holds carry it; for any
631    /// other the CLI rejects the output, so this logs a warning.
632    pub fn with_context(event: HookEventKind, context: impl Into<String>) -> Self {
633        if !event.accepts_additional_context() {
634            tracing::warn!(?event, "the CLI ignores additionalContext for this hook event");
635        }
636        Self {
637            hook_specific_output: Some(serde_json::json!({
638                "hookEventName": event,
639                "additionalContext": context.into(),
640            })),
641            ..Self::default()
642        }
643    }
644
645    /// Register `watchPaths` for `FileChanged` hooks (valid for `CwdChanged` / `FileChanged`).
646    #[must_use]
647    pub fn watch_paths(event: HookEventKind, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
648        let paths: Vec<String> = paths.into_iter().map(Into::into).collect();
649        Self {
650            hook_specific_output: Some(serde_json::json!({
651                "hookEventName": event,
652                "watchPaths": paths,
653            })),
654            ..Self::default()
655        }
656    }
657
658    /// Whether `decision` is `block`.
659    #[must_use]
660    pub fn is_block(&self) -> bool { self.decision == Some(HookDecision::Block) }
661}
662
663/// Body of a `background_tasks` control request (Ctrl+B equivalent).
664/// Send with `Session::control(&body)`.
665/// Source: chunk-20bv8pca.js:20970–20978
666#[derive(Debug, Clone, Serialize)]
667pub struct BackgroundTasksRequest {
668    /// Always `"background_tasks"`.
669    pub subtype: &'static str, // "background_tasks"
670    /// None = background all foreground tasks; Some = background specific `tool_use_id`.
671    #[serde(skip_serializing_if = "Option::is_none")]
672    pub tool_use_id: Option<String>,
673}
674
675impl BackgroundTasksRequest {
676    /// Background all foreground tasks.
677    #[must_use]
678    pub fn all() -> Self {
679        Self { subtype: "background_tasks", tool_use_id: None }
680    }
681    /// Background the task of `tool_use_id`.
682    pub fn one(tool_use_id: impl Into<String>) -> Self {
683        Self { subtype: "background_tasks", tool_use_id: Some(tool_use_id.into()) }
684    }
685}
686
687// ─── Inbound: CLI → host ─────────────────────────────────────────────────────
688
689/// Every stdout line deserializes to this.
690/// Source: chunk-20bv8pca.js (various schema locations)
691#[derive(Debug, Clone, Deserialize)]
692#[serde(tag = "type")]
693#[non_exhaustive]
694pub enum InboundMessage {
695    /// Per-turn metadata. First frame before each turn.
696    #[serde(rename = "system")]
697    System(SystemMessage),
698    /// A user message: the echo of a host prompt (`is_replay`) or a tool result.
699    #[serde(rename = "user")]
700    User(InboundUserMessage),
701    /// Complete assistant message block.
702    #[serde(rename = "assistant")]
703    Assistant(AssistantMessage),
704    /// Partial streaming chunk (requires --include-partial-messages).
705    #[serde(rename = "stream_event")]
706    StreamEvent(StreamEventMessage),
707    /// Turn complete signal.
708    #[serde(rename = "result")]
709    Result(ResultMessage),
710    /// CLI asking the host to answer: a hook callback, a tool permission
711    /// (`can_use_tool`) or an SDK MCP message. Source: chunk-20bv8pca.js:18214
712    #[serde(rename = "control_request")]
713    ControlRequest(ControlRequest),
714    /// CLI answering a host-initiated control request (initialize, interrupt, …).
715    /// Source: query.py:180–192
716    #[serde(rename = "control_response")]
717    ControlResponse(InboundControlResponse),
718    /// Process keepalive with startup marker.
719    /// Source: chunk-f89nsf5q.query.js:1403–1410
720    #[serde(rename = "keep_alive")]
721    KeepAlive(KeepAliveMessage),
722    /// The CLI withdrew a control request it sent (e.g. a `can_use_tool`
723    /// whose turn was interrupted); its answer is no longer wanted.
724    #[serde(rename = "control_cancel_request")]
725    ControlCancelRequest(ControlCancelRequest),
726    /// Any other frame type (`rate_limit_event`, `tool_progress`,
727    /// `prompt_suggestion`, `command_lifecycle`, …), kept verbatim.
728    #[serde(skip_deserializing)]
729    Other(serde_json::Value),
730    /// Decoding placeholder; `Session` turns it into `Other` and delivers
731    /// it only for a stdout line that is not JSON.
732    #[doc(hidden)]
733    #[serde(other)]
734    Unknown,
735}
736
737/// Source: binary `control_cancel_request` schema
738#[derive(Debug, Clone, Deserialize)]
739#[non_exhaustive]
740pub struct ControlCancelRequest {
741    /// Id of the withdrawn control request.
742    pub request_id: String,
743}
744
745/// Every `type:"system"` frame: `init` (first frame of each turn) plus
746/// `hook_started`, `hook_response`, `compact_boundary`, `model_fallback`,
747/// `background_tasks_changed`, `task_started`, `task_updated`, `task_notification`,
748/// `thinking_tokens`, `model_refusal_no_fallback`, `peer_message_hold`, … —
749/// only `subtype` and `session_id` are common to all; subtype-specific fields
750/// are in `extra`. Source: binary system-message schemas
751/// Source: chunk-hp1k7mph.js:194 (`WGt` function), chunk-20bv8pca.js:15125
752#[derive(Debug, Clone, Serialize, Deserialize)]
753#[non_exhaustive]
754pub struct SystemMessage {
755    /// `init`, `hook_started`, `compact_boundary`, …
756    pub subtype: String, // "init" | "hook_started" | "hook_response" | …
757    /// Session the frame belongs to.
758    pub session_id: String,
759    /// Working directory (`init`).
760    #[serde(default)]
761    pub cwd: String,
762    /// Active model (`init`).
763    #[serde(default)]
764    pub model: String,
765    /// CLI version (`init`).
766    #[serde(default)]
767    pub claude_code_version: String,
768    /// Permission mode, as its wire value (`init`).
769    #[serde(default)]
770    pub permission_mode: String,
771    /// Available tool names (`init`).
772    #[serde(default)]
773    pub tools: Vec<String>,
774    /// Enabled API betas (`init`).
775    #[serde(default)]
776    pub betas: Vec<String>,
777    /// Protocol capabilities the CLI supports, for feature detection (`init`).
778    #[serde(default)]
779    pub capabilities: Vec<String>,
780    /// Loaded skills (`init`), kept verbatim.
781    #[serde(default)]
782    pub skills: Vec<serde_json::Value>,
783    /// Loaded plugins (`init`), kept verbatim.
784    #[serde(default)]
785    pub plugins: Vec<serde_json::Value>,
786    /// Subtype-specific fields.
787    #[serde(flatten)]
788    pub extra: HashMap<String, serde_json::Value>,
789}
790
791impl SystemMessage {
792    /// `REPL` or `Eval` in `tools[]` = Code Mode active (see `SessionOptions::code_mode`).
793    #[must_use]
794    pub fn code_mode_active(&self) -> bool {
795        self.tools.iter().any(|t| t == "REPL" || t == "Eval")
796    }
797}
798
799/// A complete `assistant` frame.
800#[derive(Debug, Clone, Deserialize)]
801#[non_exhaustive]
802pub struct AssistantMessage {
803    /// The model message.
804    pub message: AssistantMessageBody,
805    /// Session the frame belongs to.
806    #[serde(default)]
807    pub session_id: Option<String>,
808    /// Tool call (e.g. a subagent) that produced the message; `None` for the main thread.
809    #[serde(default)]
810    pub parent_tool_use_id: Option<String>,
811}
812
813/// Body of an `assistant` frame.
814#[derive(Debug, Clone, Deserialize)]
815#[non_exhaustive]
816pub struct AssistantMessageBody {
817    /// Always `"assistant"`.
818    pub role: String,
819    /// Content blocks of the message.
820    pub content: Vec<AssistantBlock>,
821    /// Why the model stopped, e.g. `"end_turn"`, `"tool_use"`.
822    #[serde(default)]
823    pub stop_reason: Option<String>,
824}
825
826/// Content block of an assistant message.
827#[derive(Debug, Clone, Deserialize)]
828#[serde(tag = "type")]
829#[non_exhaustive]
830pub enum AssistantBlock {
831    /// Text.
832    #[serde(rename = "text")]
833    Text {
834        /// The text.
835        text: String,
836    },
837    /// A tool call the CLI runs.
838    #[serde(rename = "tool_use")]
839    ToolUse {
840        /// Tool-use id; the matching `tool_result` carries it.
841        id: String,
842        /// Tool name.
843        name: String,
844        /// Tool input.
845        input: serde_json::Value,
846    },
847    /// Extended thinking.
848    #[serde(rename = "thinking")]
849    Thinking {
850        /// The thinking text.
851        thinking: String,
852    },
853    /// Encrypted thinking; opaque to the host.
854    #[serde(rename = "redacted_thinking")]
855    RedactedThinking {
856        /// Encrypted thinking data.
857        data: String,
858    },
859    /// A tool the API runs itself (web search, …).
860    #[serde(rename = "server_tool_use")]
861    ServerToolUse {
862        /// Tool-use id.
863        id: String,
864        /// Server tool name.
865        name: String,
866        /// Tool input.
867        input: serde_json::Value,
868    },
869    /// Result of a server-run web search.
870    #[serde(rename = "web_search_tool_result")]
871    WebSearchToolResult {
872        /// Id of the `server_tool_use` block answered.
873        tool_use_id: String,
874        /// Search results, kept verbatim.
875        content: serde_json::Value,
876    },
877    /// Any other block type.
878    #[serde(other)]
879    Unknown,
880}
881
882/// A `user` frame: the echo of a prompt, tool results, or a message the
883/// CLI added itself (`is_synthetic`).
884#[derive(Debug, Clone, Deserialize)]
885#[non_exhaustive]
886pub struct InboundUserMessage {
887    /// Message uuid; for an echo, the host prompt's `UserMessage::uuid`.
888    #[serde(default)]
889    pub uuid: Option<String>,
890    /// `isReplay`: echo of a host prompt.
891    #[serde(default, rename = "isReplay")]
892    pub is_replay: Option<bool>,
893    /// `isSynthetic`: the CLI added the message itself.
894    #[serde(default, rename = "isSynthetic")]
895    pub is_synthetic: Option<bool>,
896    /// Tool call this message belongs to.
897    #[serde(default)]
898    pub parent_tool_use_id: Option<String>,
899    /// Subagent that produced the frame.
900    #[serde(default)]
901    pub agent_id: Option<String>,
902    /// Message body.
903    #[serde(default)]
904    pub message: Option<InboundUserBody>,
905    /// The tool's full structured output (e.g. Bash `{stdout, stderr, …}`),
906    /// beside the text sent to the model.
907    #[serde(default)]
908    pub tool_use_result: Option<serde_json::Value>,
909}
910
911/// Body of an inbound `user` frame.
912#[derive(Debug, Clone, Deserialize)]
913#[non_exhaustive]
914pub struct InboundUserBody {
915    /// A string or an array of content blocks.
916    #[serde(default)]
917    pub content: serde_json::Value,
918}
919
920/// One `tool_result` block of a `user` frame.
921#[derive(Debug, Clone, Deserialize)]
922#[non_exhaustive]
923pub struct InboundToolResult {
924    /// Id of the `tool_use` block answered.
925    pub tool_use_id: String,
926    /// A string or an array of content blocks.
927    #[serde(default)]
928    pub content: serde_json::Value,
929    /// The tool call failed.
930    #[serde(default)]
931    pub is_error: bool,
932}
933
934impl InboundUserMessage {
935    /// The `tool_result` blocks of this frame.
936    #[must_use]
937    pub fn tool_results(&self) -> Vec<InboundToolResult> {
938        let Some(blocks) = self.message.as_ref().and_then(|m| m.content.as_array()) else {
939            return vec![];
940        };
941        blocks
942            .iter()
943            .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("tool_result"))
944            .filter_map(|b| InboundToolResult::deserialize(b).ok())
945            .collect()
946    }
947}
948
949/// Partial streaming chunk.
950/// Source: chunk-20bv8pca.js:15343–15401
951#[derive(Debug, Clone, Deserialize)]
952#[non_exhaustive]
953pub struct StreamEventMessage {
954    /// Raw Anthropic streaming event (`message_start`, `content_block_delta`, …).
955    pub event: serde_json::Value,
956    /// Session the frame belongs to.
957    #[serde(default)]
958    pub session_id: Option<String>,
959    /// Time to first token, in ms.
960    #[serde(default)]
961    pub ttft_ms: Option<u64>,
962    /// Tool call (e.g. a subagent) that produced the event; `None` for the main thread.
963    #[serde(default)]
964    pub parent_tool_use_id: Option<String>,
965}
966
967/// Turn complete.
968/// Source: chunk-20bv8pca.js:14425–14913
969#[derive(Debug, Clone, Default, Deserialize)]
970#[non_exhaustive]
971pub struct ResultMessage {
972    /// "success" | "error_*". A failed API call still comes as "success"
973    /// with `is_error: true` and the message in `result`.
974    #[serde(default)]
975    pub subtype: String,
976    /// The turn failed; a failed API call sets this on a `success` result.
977    #[serde(default)]
978    pub is_error: bool,
979    /// Final text of the turn, or the error message when `is_error`.
980    #[serde(default)]
981    pub result: Option<String>,
982    /// Error details of `error_*` subtypes.
983    #[serde(default)]
984    pub errors: Option<Vec<serde_json::Value>>,
985    /// Session the turn ran in.
986    #[serde(default)]
987    pub session_id: Option<String>,
988    /// Estimated cost in USD, cumulative across the session's turns.
989    #[serde(default)]
990    pub total_cost_usd: Option<f64>,
991    /// Time to first token, in ms.
992    #[serde(default)]
993    pub ttft_ms: Option<u64>,
994    /// Wall-clock duration, in ms.
995    #[serde(default)]
996    pub duration_ms: Option<u64>,
997    /// Token usage.
998    #[serde(default)]
999    pub usage: Option<UsageSummary>,
1000    /// Why the model stopped, e.g. `"end_turn"`.
1001    #[serde(default)]
1002    pub stop_reason: Option<String>,
1003    /// Time spent in API calls, in ms.
1004    #[serde(default)]
1005    pub duration_api_ms: Option<u64>,
1006    /// Number of agent-loop turns.
1007    #[serde(default)]
1008    pub num_turns: Option<u64>,
1009    /// Why the loop ended ("completed", …).
1010    #[serde(default)]
1011    pub terminal_reason: Option<String>,
1012    /// Output matching `Initialize::json_schema`.
1013    #[serde(default)]
1014    pub structured_output: Option<serde_json::Value>,
1015    /// Tool calls the permission system denied during the turn.
1016    #[serde(default)]
1017    pub permission_denials: Vec<serde_json::Value>,
1018    /// Per-model token and cost breakdown.
1019    #[serde(default, rename = "modelUsage")]
1020    pub model_usage: Option<serde_json::Value>,
1021    /// The prompts (`UserMessage::uuid`) this turn answered.
1022    #[serde(default)]
1023    pub user_message_uuids: Vec<String>,
1024    /// Set when the CLI started the turn itself (e.g. `{"kind":"task-notification"}`
1025    /// after a background task finished); absent for turns the host prompted.
1026    #[serde(default)]
1027    pub origin: Option<serde_json::Value>,
1028    /// Fields not named above.
1029    #[serde(flatten)]
1030    pub extra: HashMap<String, serde_json::Value>,
1031}
1032
1033impl ResultMessage {
1034    /// `success` subtype without `is_error`.
1035    #[must_use]
1036    pub fn is_success(&self) -> bool {
1037        self.subtype == "success" && !self.is_error
1038    }
1039
1040    /// Whether this turn answered the prompt `uuid`. A prompt the CLI
1041    /// refuses up front (e.g. budget spent) gets a result but no echo.
1042    #[must_use]
1043    pub fn answers(&self, uuid: &str) -> bool {
1044        self.user_message_uuids.iter().any(|u| u.eq_ignore_ascii_case(uuid))
1045    }
1046
1047    /// Category of a failed turn.
1048    #[must_use]
1049    pub fn error_kind(&self) -> TurnErrorKind {
1050        match self.subtype.as_str() {
1051            "error_during_execution" => TurnErrorKind::Execution,
1052            "error_max_turns" => TurnErrorKind::MaxTurns,
1053            "error_max_budget_usd" => TurnErrorKind::MaxBudget,
1054            "error_max_structured_output_retries" => TurnErrorKind::StructuredOutputRetries,
1055            "success" => TurnErrorKind::Api,
1056            other => TurnErrorKind::Other(other.to_string()),
1057        }
1058    }
1059
1060    /// Why the turn failed: for `is_error` the CLI's message; for
1061    /// `error_*` subtypes the subtype, then its `errors` details.
1062    #[must_use]
1063    pub fn error_message(&self) -> String {
1064        if let Some(r) = self.result.as_ref().filter(|r| self.is_error && !r.is_empty()) {
1065            return r.clone();
1066        }
1067        let details: Vec<String> = self.errors.iter().flatten()
1068            .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_owned))
1069            .collect();
1070        if details.is_empty() { self.subtype.clone() } else { format!("{}: {}", self.subtype, details.join("; ")) }
1071    }
1072}
1073
1074/// Why a turn failed. Source: binary result error-subtype enum
1075#[derive(Debug, Clone, PartialEq, Eq)]
1076#[non_exhaustive]
1077pub enum TurnErrorKind {
1078    /// `error_during_execution`: includes interrupted turns.
1079    Execution,
1080    /// `error_max_turns`: `SessionOptions::max_turns` reached.
1081    MaxTurns,
1082    /// `error_max_budget_usd`: `SessionOptions::max_budget_usd` reached.
1083    MaxBudget,
1084    /// `error_max_structured_output_retries`.
1085    StructuredOutputRetries,
1086    /// The API call failed (`is_error` on a `success` result).
1087    Api,
1088    /// The CLI exited before the turn ended.
1089    SessionClosed,
1090    /// The prompt was withdrawn before it ran (`Session::cancel_prompt`,
1091    /// `Session::interrupt_all`).
1092    Cancelled,
1093    /// A subtype this SDK does not know.
1094    Other(String),
1095}
1096
1097/// Token usage breakdown.
1098/// Source: chunk-20bv8pca.js:11526–11530
1099#[derive(Debug, Clone, Deserialize, Default)]
1100#[non_exhaustive]
1101pub struct UsageSummary {
1102    /// Input tokens.
1103    #[serde(default)]
1104    pub input_tokens: u64,
1105    /// Output tokens.
1106    #[serde(default)]
1107    pub output_tokens: u64,
1108    /// Input tokens read from the prompt cache.
1109    #[serde(default)]
1110    pub cache_read_input_tokens: Option<u64>,
1111    /// Input tokens written to the prompt cache.
1112    #[serde(default)]
1113    pub cache_creation_input_tokens: Option<u64>,
1114    /// Cache writes by TTL, kept verbatim.
1115    #[serde(default)]
1116    pub cache_creation: Option<serde_json::Value>,
1117}
1118
1119/// CLI → host control request envelope:
1120/// `{"type":"control_request","request_id":"…","request":{"subtype":"…",…}}`.
1121/// Source: query.py:236–240
1122#[derive(Debug, Clone, Deserialize)]
1123#[non_exhaustive]
1124pub struct ControlRequest {
1125    /// Id to answer with in `ControlResponse`.
1126    pub request_id: String,
1127    /// Request body, tagged by `subtype`.
1128    pub request: ControlRequestBody,
1129}
1130
1131/// Body of a CLI → host control request, tagged by `subtype`.
1132#[derive(Debug, Clone, Deserialize)]
1133#[serde(tag = "subtype")]
1134#[non_exhaustive]
1135pub enum ControlRequestBody {
1136    /// Only sent when the CLI runs with `--permission-prompt-tool stdio`.
1137    #[serde(rename = "can_use_tool")]
1138    CanUseTool(CanUseToolRequest),
1139    /// A hook matched; run the callback `callback_id`.
1140    #[serde(rename = "hook_callback")]
1141    HookCallback(HookCallbackRequest),
1142    /// JSON-RPC message for an SDK MCP server. Source: query.py:305–320
1143    #[serde(rename = "mcp_message")]
1144    McpMessage(McpMessageRequest),
1145    /// An MCP server asks the user for input.
1146    #[serde(rename = "elicitation")]
1147    Elicitation(ElicitationRequest),
1148    /// A tool asks the host to render a blocking dialog; sent only for kinds
1149    /// listed in `Initialize::supported_dialog_kinds`.
1150    #[serde(rename = "request_user_dialog")]
1151    RequestUserDialog(UserDialogRequest),
1152    /// Future subtypes — answered with an error response.
1153    #[serde(other)]
1154    Unsupported,
1155}
1156
1157/// Source: binary `can_use_tool` schema; query.py:244–262
1158#[derive(Debug, Clone, Deserialize)]
1159#[non_exhaustive]
1160pub struct CanUseToolRequest {
1161    /// Tool the model wants to use.
1162    pub tool_name: String,
1163    /// Tool input.
1164    pub input: serde_json::Value,
1165    /// Tool-use id of the call.
1166    #[serde(default)]
1167    pub tool_use_id: Option<String>,
1168    /// Permission updates that would stop the CLI asking again; return them
1169    /// with `ToolDecision::allow_and_remember` for "always allow".
1170    #[serde(default)]
1171    pub permission_suggestions: Option<Vec<serde_json::Value>>,
1172    /// Human-readable reason the CLI asks; may carry ANSI escapes.
1173    #[serde(default)]
1174    pub decision_reason: Option<String>,
1175    /// Why the ask escalated: "rule", "hook", "safetyCheck", "classifier", …
1176    #[serde(default)]
1177    pub decision_reason_type: Option<String>,
1178    /// MCP server of the tool: `{"name", "source"}`.
1179    #[serde(default)]
1180    pub mcp_server: Option<serde_json::Value>,
1181    /// Path outside the allowed directories that triggered the ask.
1182    #[serde(default)]
1183    pub blocked_path: Option<String>,
1184    /// Set when a safety check is involved: `false` = one needs manual approval.
1185    #[serde(default)]
1186    pub classifier_approvable: Option<bool>,
1187    /// Do not offer "always allow" for this ask.
1188    #[serde(default)]
1189    pub suppress_always_allow_rule: Option<bool>,
1190    /// The ask must not be approvable by a single stray keystroke.
1191    #[serde(default)]
1192    pub default_to_no: Option<bool>,
1193    /// User `permissions.ask` rule that forced this prompt: `{source, tool_name, rule_content}`.
1194    #[serde(default)]
1195    pub matched_ask_rule: Option<serde_json::Value>,
1196    /// Permission-display title.
1197    #[serde(default)]
1198    pub title: Option<String>,
1199    /// Short tool or server label for display.
1200    #[serde(default)]
1201    pub display_name: Option<String>,
1202    /// Permission-display subtitle.
1203    #[serde(default)]
1204    pub description: Option<String>,
1205    /// Subagent that wants to use the tool.
1206    #[serde(default)]
1207    pub agent_id: Option<String>,
1208    /// One-tap Approve/Deny must not be offered.
1209    #[serde(default)]
1210    pub requires_user_interaction: Option<bool>,
1211    /// Fields not named above.
1212    #[serde(flatten)]
1213    pub extra: HashMap<String, serde_json::Value>,
1214}
1215
1216/// Source: binary elicitation schema
1217#[derive(Debug, Clone, Deserialize)]
1218#[non_exhaustive]
1219pub struct ElicitationRequest {
1220    /// MCP server asking for input.
1221    pub mcp_server_name: String,
1222    /// Text shown to the user.
1223    pub message: String,
1224    /// "form" or "url".
1225    #[serde(default)]
1226    pub mode: Option<String>,
1227    /// URL to open (`url` mode).
1228    #[serde(default)]
1229    pub url: Option<String>,
1230    /// Elicitation id from the MCP server.
1231    #[serde(default)]
1232    pub elicitation_id: Option<String>,
1233    /// JSON schema of the requested form fields.
1234    #[serde(default)]
1235    pub requested_schema: Option<serde_json::Value>,
1236    /// Top-level keys of `requested_schema.properties`, in the server's order.
1237    #[serde(default)]
1238    pub property_order: Option<Vec<String>>,
1239    /// Permission-display title from the MCP server.
1240    #[serde(default)]
1241    pub title: Option<String>,
1242    /// Short tool or server label from the MCP server.
1243    #[serde(default)]
1244    pub display_name: Option<String>,
1245    /// Permission-display subtitle from the MCP server.
1246    #[serde(default)]
1247    pub description: Option<String>,
1248    /// Fields not named above.
1249    #[serde(flatten)]
1250    pub extra: HashMap<String, serde_json::Value>,
1251}
1252
1253/// Answer to an `elicitation` request. Source: binary elicitation response schema
1254#[derive(Debug, Clone, Serialize)]
1255pub struct ElicitationResponse {
1256    /// `accept`, `decline` or `cancel`.
1257    pub action: ElicitationAction,
1258    /// Form values; sent with `accept`.
1259    #[serde(skip_serializing_if = "Option::is_none")]
1260    pub content: Option<serde_json::Map<String, serde_json::Value>>,
1261}
1262
1263/// What the user did with an elicitation.
1264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1265#[serde(rename_all = "lowercase")]
1266pub enum ElicitationAction {
1267    /// The user submitted the form.
1268    Accept,
1269    /// The user declined.
1270    Decline,
1271    /// The user dismissed the request.
1272    Cancel,
1273}
1274
1275impl ElicitationResponse {
1276    /// Accept with the form values.
1277    #[must_use]
1278    pub fn accept(content: serde_json::Map<String, serde_json::Value>) -> Self {
1279        Self { action: ElicitationAction::Accept, content: Some(content) }
1280    }
1281    /// Decline.
1282    #[must_use]
1283    pub fn decline() -> Self {
1284        Self { action: ElicitationAction::Decline, content: None }
1285    }
1286    /// Cancel.
1287    #[must_use]
1288    pub fn cancel() -> Self {
1289        Self { action: ElicitationAction::Cancel, content: None }
1290    }
1291}
1292
1293/// Source: binary `request_user_dialog` schema
1294#[derive(Debug, Clone, Deserialize)]
1295#[non_exhaustive]
1296pub struct UserDialogRequest {
1297    /// Which dialog to render; only kinds in `Initialize::supported_dialog_kinds`.
1298    pub dialog_kind: String,
1299    /// Dialog-specific data; shape set by `dialog_kind`.
1300    #[serde(default)]
1301    pub payload: serde_json::Value,
1302    /// Tool call that raised the dialog.
1303    #[serde(default)]
1304    pub tool_use_id: Option<String>,
1305}
1306
1307/// The user's answer to a `request_user_dialog`.
1308/// Source: binary `request_user_dialog` response schema (behavior, result)
1309#[derive(Debug, Clone, Serialize, PartialEq)]
1310pub struct UserDialogResponse {
1311    /// `completed` or `cancelled`.
1312    pub behavior: UserDialogBehavior,
1313    /// Dialog-specific choice, e.g. `"retry_fallback"` for
1314    /// `refusal_fallback_prompt`.
1315    #[serde(skip_serializing_if = "Option::is_none")]
1316    pub result: Option<serde_json::Value>,
1317}
1318
1319/// How a `request_user_dialog` ended.
1320#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
1321#[serde(rename_all = "lowercase")]
1322pub enum UserDialogBehavior {
1323    /// The user made a choice (`result`).
1324    Completed,
1325    /// The user dismissed the dialog.
1326    Cancelled,
1327}
1328
1329impl UserDialogResponse {
1330    /// The user chose `result`.
1331    pub fn completed(result: impl Into<serde_json::Value>) -> Self {
1332        Self { behavior: UserDialogBehavior::Completed, result: Some(result.into()) }
1333    }
1334    /// The user dismissed the dialog.
1335    #[must_use]
1336    pub fn cancelled() -> Self {
1337        Self { behavior: UserDialogBehavior::Cancelled, result: None }
1338    }
1339}
1340
1341/// Body of an `mcp_message` request.
1342#[derive(Debug, Clone, Deserialize)]
1343#[non_exhaustive]
1344pub struct McpMessageRequest {
1345    /// SDK MCP server the message is for.
1346    pub server_name: String,
1347    /// JSON-RPC message.
1348    pub message: serde_json::Value,
1349}
1350
1351/// Source: binary `hook_callback` schema (`callback_id`, input, `tool_use_id`, `issued_at`)
1352#[derive(Debug, Clone, Deserialize)]
1353#[non_exhaustive]
1354pub struct HookCallbackRequest {
1355    /// Callback id from `HookMatcherConfig::hook_callback_ids`.
1356    pub callback_id: String,
1357    /// Hook input.
1358    pub input: HookEventPayload,
1359    /// Tool-use id, for tool events.
1360    #[serde(default)]
1361    pub tool_use_id: Option<String>,
1362    /// Epoch ms on the CLI's clock when the request was issued.
1363    #[serde(default)]
1364    pub issued_at: Option<u64>,
1365}
1366
1367/// CLI → host answer to a host-initiated control request.
1368/// Source: query.py:180–192
1369#[derive(Debug, Clone, Deserialize)]
1370#[non_exhaustive]
1371pub struct InboundControlResponse {
1372    /// Success or error, keyed by `request_id`.
1373    pub response: InboundControlResponseBody,
1374}
1375
1376/// Body of an inbound `control_response`.
1377#[derive(Debug, Clone, Deserialize)]
1378#[non_exhaustive]
1379pub struct InboundControlResponseBody {
1380    /// `success` or `error`.
1381    pub subtype: String, // "success" | "error"
1382    /// Id of the host request answered.
1383    pub request_id: String,
1384    /// Response payload on `success`.
1385    #[serde(default)]
1386    pub response: Option<serde_json::Value>,
1387    /// Error message on `error`.
1388    #[serde(default)]
1389    pub error: Option<String>,
1390}
1391
1392/// Input to a hook handler. Contains all event-specific fields.
1393/// Source: chunk-0msz7hbn.js:7–323
1394#[derive(Debug, Clone, Deserialize)]
1395#[non_exhaustive]
1396pub struct HookEventPayload {
1397    /// Event that fired.
1398    pub hook_event_name: HookEventKind,
1399    /// Tool name, for tool events.
1400    #[serde(default)]
1401    pub tool_name: Option<String>,
1402    /// Tool input, for tool events.
1403    #[serde(default)]
1404    pub tool_input: Option<serde_json::Value>,
1405    /// Tool-use id, for tool events.
1406    #[serde(default)]
1407    pub tool_use_id: Option<String>,
1408    /// Error message, for `PostToolUseFailure`.
1409    #[serde(default)]
1410    pub error: Option<String>,
1411    /// Whether the failure came from an interrupt, for `PostToolUseFailure`.
1412    #[serde(default)]
1413    pub is_interrupt: Option<bool>,
1414    /// Session the event belongs to.
1415    #[serde(default)]
1416    pub session_id: Option<String>,
1417    /// Working directory.
1418    #[serde(default)]
1419    pub cwd: Option<String>,
1420    /// Changed file, for `FileChanged`.
1421    #[serde(default)]
1422    pub file_path: Option<String>,
1423    /// Change kind, for `FileChanged`.
1424    #[serde(default)]
1425    pub event: Option<String>,        // for FileChanged: "change"|"add"|"unlink"
1426    /// Fields not named above.
1427    #[serde(flatten)]
1428    pub extra: HashMap<String, serde_json::Value>,
1429}
1430
1431/// One entry of a `background_tasks_changed` snapshot.
1432/// Source: binary `background_tasks_changed` schema
1433#[derive(Debug, Clone, Deserialize)]
1434#[non_exhaustive]
1435pub struct BackgroundTask {
1436    /// Task id.
1437    pub task_id: String,
1438    /// Id of one run of the task; a resumed task gets a new one.
1439    #[serde(default)]
1440    pub run_id: Option<String>,
1441    /// "`local_bash`" | "`local_agent`" | "`local_workflow`" | …
1442    #[serde(default)]
1443    pub task_type: String,
1444    /// Agent type of a `local_agent` task.
1445    #[serde(default)]
1446    pub subagent_type: Option<String>,
1447    /// Task description.
1448    #[serde(default)]
1449    pub description: String,
1450    /// Task id of the subagent that launched this task.
1451    #[serde(default)]
1452    pub parent_task_id: Option<String>,
1453    /// Not activity; exclude from activity indicators.
1454    #[serde(default)]
1455    pub ambient: Option<bool>,
1456    /// A resumed subagent run that the resuming tool call waits for.
1457    #[serde(default)]
1458    pub awaited: Option<bool>,
1459    /// The task's work goes on outside this process.
1460    #[serde(default)]
1461    pub off_host: Option<bool>,
1462}
1463
1464/// Process keepalive with startup marker for readiness probing.
1465/// Source: chunk-f89nsf5q.query.js:1403–1410
1466#[derive(Debug, Clone, Deserialize)]
1467#[non_exhaustive]
1468pub struct KeepAliveMessage {
1469    /// Frame fields, kept verbatim.
1470    #[serde(flatten)]
1471    pub extra: HashMap<String, serde_json::Value>,
1472}
1473
1474// ─── Tool/Hook types ─────────────────────────────────────────────────────────
1475
1476/// A tool of an in-process SDK MCP server.
1477#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1478pub struct ToolDef {
1479    /// Tool name.
1480    pub name: String,
1481    /// Description shown to the model.
1482    pub description: String,
1483    /// JSON schema of the tool input.
1484    #[serde(skip_serializing_if = "Option::is_none")]
1485    pub input_schema: Option<serde_json::Value>,
1486    /// Display name.
1487    #[serde(default, skip_serializing_if = "Option::is_none")]
1488    pub title: Option<String>,
1489    /// JSON schema of `ToolResult::structured`.
1490    #[serde(default, skip_serializing_if = "Option::is_none")]
1491    pub output_schema: Option<serde_json::Value>,
1492    /// MCP tool hints.
1493    #[serde(default, skip_serializing_if = "Option::is_none")]
1494    pub annotations: Option<ToolAnnotations>,
1495}
1496
1497/// MCP tool hints. Source: MCP 2025-06-18 `ToolAnnotations`
1498#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1499#[serde(rename_all = "camelCase")]
1500pub struct ToolAnnotations {
1501    /// `readOnlyHint`: the tool does not modify its environment.
1502    #[serde(default, skip_serializing_if = "Option::is_none")]
1503    pub read_only_hint: Option<bool>,
1504    /// `destructiveHint`: the tool may perform destructive updates.
1505    #[serde(default, skip_serializing_if = "Option::is_none")]
1506    pub destructive_hint: Option<bool>,
1507    /// `idempotentHint`: repeated calls with the same arguments have no extra effect.
1508    #[serde(default, skip_serializing_if = "Option::is_none")]
1509    pub idempotent_hint: Option<bool>,
1510    /// `openWorldHint`: the tool interacts with external entities.
1511    #[serde(default, skip_serializing_if = "Option::is_none")]
1512    pub open_world_hint: Option<bool>,
1513}
1514
1515/// An MCP server's name and tools.
1516#[derive(Debug, Clone, Serialize, Deserialize)]
1517pub struct McpManifest {
1518    /// Server name.
1519    pub name: String,
1520    /// Server tools.
1521    pub tools: Vec<ToolDef>,
1522    /// Wire field `server_info`, kept verbatim.
1523    #[serde(default)]
1524    pub server_info: Option<serde_json::Value>,
1525}
1526
1527/// All 33 hook event kinds.
1528/// Source: chunk-20bv8pca.js:12053–12087 (N2 array)
1529#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1530#[serde(rename_all = "PascalCase")]
1531#[non_exhaustive]
1532pub enum HookEventKind {
1533    /// Before tool execution.
1534    PreToolUse,
1535    /// After tool execution.
1536    PostToolUse,
1537    /// After tool execution fails.
1538    PostToolUseFailure,
1539    /// After a batch of tool calls resolves.
1540    PostToolBatch,
1541    /// When notifications are sent.
1542    Notification,
1543    /// When the user submits a prompt.
1544    UserPromptSubmit,
1545    /// When a user-typed slash command expands into a prompt.
1546    UserPromptExpansion,
1547    /// When a new session is started.
1548    SessionStart,
1549    /// When a session is ending.
1550    SessionEnd,
1551    /// Right before Claude concludes its response.
1552    Stop,
1553    /// When the turn ends due to an API error.
1554    StopFailure,
1555    /// When a subagent (Agent tool call) is started.
1556    SubagentStart,
1557    /// Right before a subagent (Agent tool call) concludes its response.
1558    SubagentStop,
1559    /// Before conversation compaction.
1560    PreCompact,
1561    /// After conversation compaction.
1562    PostCompact,
1563    /// Before a requested model switch (`/model`, model picker, `set_model`).
1564    PreModelSwitch,
1565    /// After the session model changes (any cause).
1566    PostModelSwitch,
1567    /// When a permission dialog is displayed.
1568    PermissionRequest,
1569    /// After auto mode denies a tool call.
1570    PermissionDenied,
1571    /// Repo setup hooks for init and maintenance.
1572    Setup,
1573    /// When a teammate is about to go idle.
1574    TeammateIdle,
1575    /// When a task is being created.
1576    TaskCreated,
1577    /// When a task is being marked as completed.
1578    TaskCompleted,
1579    /// When an MCP server requests user input (elicitation).
1580    Elicitation,
1581    /// After a user responds to an MCP elicitation.
1582    ElicitationResult,
1583    /// When configuration files change during a session.
1584    ConfigChange,
1585    /// Create an isolated worktree for VCS-agnostic isolation.
1586    WorktreeCreate,
1587    /// Remove a previously created worktree.
1588    WorktreeRemove,
1589    /// When an instruction file (CLAUDE.md or rule) is loaded.
1590    InstructionsLoaded,
1591    /// After the working directory changes.
1592    CwdChanged,
1593    /// When a watched file changes.
1594    FileChanged,
1595    /// After a working directory is added mid-session.
1596    DirectoryAdded,
1597    /// While assistant message text is displayed.
1598    MessageDisplay,
1599}
1600
1601impl HookEventKind {
1602    /// Whether the CLI reads `hookSpecificOutput.additionalContext` for
1603    /// this event (`HookOutput::with_context`).
1604    /// Source: CLI hook output schema (chunk-g4jweshk.js:10682-10753)
1605    #[must_use]
1606    pub fn accepts_additional_context(self) -> bool {
1607        matches!(
1608            self,
1609            Self::PreToolUse
1610                | Self::PostToolUse
1611                | Self::PostToolUseFailure
1612                | Self::PostToolBatch
1613                | Self::UserPromptSubmit
1614                | Self::UserPromptExpansion
1615                | Self::SessionStart
1616                | Self::Setup
1617                | Self::PostModelSwitch
1618                | Self::SubagentStart
1619                | Self::Stop
1620                | Self::SubagentStop
1621                | Self::Notification
1622        )
1623    }
1624}
1625