Skip to main content

codewhale_protocol/
lib.rs

1// Serde-only leaf crate shared by every surface, including the TUI
2// alt-screen. Raw stdio prints must never appear here (spec ยง7,
3// `no_stdout_from_core`).
4#![deny(clippy::print_stdout)]
5#![deny(clippy::print_stderr)]
6
7use std::path::PathBuf;
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12pub mod agent_mail;
13pub mod agent_run;
14pub mod event_msg;
15pub mod fleet;
16pub mod ids;
17pub mod journal;
18pub mod op;
19pub mod runtime;
20pub mod workroom;
21
22/// Common trait for lifecycle status enums across the protocol layer.
23///
24/// Every status enum โ€” thread, goal, fleet run, worker, and job status โ€”
25/// implements this trait so generic code can ask three universal questions
26/// without matching on every variant.
27pub trait Status {
28    /// Returns `true` when this status represents a final, non-progressable state
29    /// (e.g. Completed, Failed, Cancelled, Archived, Retired).
30    fn is_terminal(&self) -> bool;
31
32    /// Returns `true` when work is currently in-flight
33    /// (e.g. Running, Active, Busy, Queued, Pending).
34    fn is_active(&self) -> bool;
35
36    /// Returns `true` when the item has been explicitly paused by the user
37    /// or system (e.g. Paused).
38    fn is_paused(&self) -> bool;
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub struct Envelope<T> {
43    pub request_id: String,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub thread_id: Option<String>,
46    pub body: T,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50#[serde(rename_all = "snake_case")]
51pub enum ThreadStatus {
52    Running,
53    Idle,
54    Completed,
55    Failed,
56    Paused,
57    Archived,
58}
59
60impl Status for ThreadStatus {
61    fn is_terminal(&self) -> bool {
62        matches!(self, Self::Completed | Self::Failed | Self::Archived)
63    }
64    fn is_active(&self) -> bool {
65        matches!(self, Self::Running)
66    }
67    fn is_paused(&self) -> bool {
68        matches!(self, Self::Paused)
69    }
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
73#[serde(rename_all = "snake_case")]
74pub enum SessionSource {
75    Interactive,
76    Resume,
77    Fork,
78    Api,
79    Unknown,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct Thread {
84    pub id: String,
85    pub preview: String,
86    pub ephemeral: bool,
87    pub model_provider: String,
88    pub created_at: i64,
89    pub updated_at: i64,
90    pub status: ThreadStatus,
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub path: Option<PathBuf>,
93    pub cwd: PathBuf,
94    pub cli_version: String,
95    pub source: SessionSource,
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub name: Option<String>,
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
101#[serde(rename_all = "snake_case")]
102pub enum ThreadGoalStatus {
103    Active,
104    Paused,
105    Blocked,
106    UsageLimited,
107    BudgetLimited,
108    Complete,
109}
110
111impl Status for ThreadGoalStatus {
112    fn is_terminal(&self) -> bool {
113        matches!(self, Self::Complete)
114    }
115    fn is_active(&self) -> bool {
116        matches!(self, Self::Active)
117    }
118    fn is_paused(&self) -> bool {
119        matches!(self, Self::Paused)
120    }
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
124pub struct ThreadGoal {
125    pub thread_id: String,
126    pub goal_id: String,
127    pub objective: String,
128    pub status: ThreadGoalStatus,
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub token_budget: Option<i64>,
131    pub tokens_used: i64,
132    pub time_used_seconds: i64,
133    pub continuation_count: i64,
134    pub created_at: i64,
135    pub updated_at: i64,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct ThreadStartParams {
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub model: Option<String>,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub model_provider: Option<String>,
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub cwd: Option<PathBuf>,
146    #[serde(default)]
147    pub persist_extended_history: bool,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct ThreadResumeParams {
152    pub thread_id: String,
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub history: Option<Vec<Value>>,
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub path: Option<PathBuf>,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub model: Option<String>,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub model_provider: Option<String>,
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub cwd: Option<PathBuf>,
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub approval_policy: Option<String>,
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub sandbox: Option<String>,
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub config: Option<Value>,
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub base_instructions: Option<String>,
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub developer_instructions: Option<String>,
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub personality: Option<String>,
175    #[serde(default)]
176    pub persist_extended_history: bool,
177}
178
179#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct ThreadForkParams {
181    pub thread_id: String,
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub path: Option<PathBuf>,
184    #[serde(skip_serializing_if = "Option::is_none")]
185    pub model: Option<String>,
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub model_provider: Option<String>,
188    #[serde(skip_serializing_if = "Option::is_none")]
189    pub cwd: Option<PathBuf>,
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub approval_policy: Option<String>,
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub sandbox: Option<String>,
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pub config: Option<Value>,
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub base_instructions: Option<String>,
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub developer_instructions: Option<String>,
200    #[serde(default)]
201    pub persist_extended_history: bool,
202}
203
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct ThreadListParams {
206    #[serde(default)]
207    pub include_archived: bool,
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub limit: Option<usize>,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct ThreadReadParams {
214    pub thread_id: String,
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize)]
218pub struct ThreadSetNameParams {
219    pub thread_id: String,
220    pub name: String,
221}
222
223#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct ThreadGoalSetParams {
225    pub thread_id: String,
226    pub objective: String,
227    #[serde(skip_serializing_if = "Option::is_none")]
228    pub token_budget: Option<i64>,
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize)]
232pub struct ThreadGoalGetParams {
233    pub thread_id: String,
234}
235
236#[derive(Debug, Clone, Serialize, Deserialize)]
237pub struct ThreadGoalClearParams {
238    pub thread_id: String,
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct ThreadGoalProgressParams {
243    pub thread_id: String,
244    #[serde(default)]
245    pub token_delta: i64,
246    #[serde(default)]
247    pub time_delta_seconds: i64,
248    #[serde(default)]
249    pub record_continuation: bool,
250}
251
252#[derive(Debug, Clone, Serialize, Deserialize)]
253#[serde(tag = "kind", rename_all = "snake_case")]
254pub enum ThreadRequest {
255    Create {
256        #[serde(default)]
257        metadata: Value,
258    },
259    Start(ThreadStartParams),
260    Resume(ThreadResumeParams),
261    Fork(ThreadForkParams),
262    List(ThreadListParams),
263    Read(ThreadReadParams),
264    SetName(ThreadSetNameParams),
265    GoalSet(ThreadGoalSetParams),
266    GoalGet(ThreadGoalGetParams),
267    GoalClear(ThreadGoalClearParams),
268    GoalRecordProgress(ThreadGoalProgressParams),
269    Archive {
270        thread_id: String,
271    },
272    Unarchive {
273        thread_id: String,
274    },
275    Message {
276        thread_id: String,
277        input: String,
278    },
279}
280
281/// Response to a [`ThreadRequest`].
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct ThreadResponse {
284    /// The thread this response pertains to.
285    pub thread_id: String,
286    /// Human-readable status string (e.g. `"ok"`, `"error"`).
287    pub status: String,
288    /// The thread details, when a single thread is returned.
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub thread: Option<Thread>,
291    /// List of threads, populated by `List` requests.
292    #[serde(default)]
293    pub threads: Vec<Thread>,
294    /// Thread goal returned by goal get/set requests.
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub goal: Option<ThreadGoal>,
297    /// The model used for the thread, if applicable.
298    #[serde(skip_serializing_if = "Option::is_none")]
299    pub model: Option<String>,
300    /// The model provider used for the thread.
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub model_provider: Option<String>,
303    /// The working directory of the thread.
304    #[serde(skip_serializing_if = "Option::is_none")]
305    pub cwd: Option<PathBuf>,
306    /// The active approval policy.
307    #[serde(skip_serializing_if = "Option::is_none")]
308    pub approval_policy: Option<String>,
309    /// The active sandbox configuration.
310    #[serde(skip_serializing_if = "Option::is_none")]
311    pub sandbox: Option<String>,
312    /// Streaming events associated with this response.
313    #[serde(default)]
314    pub events: Vec<EventFrame>,
315    /// Arbitrary additional response data.
316    #[serde(default)]
317    pub data: Value,
318}
319
320/// Application-level requests that are not tied to a specific thread.
321#[derive(Debug, Clone, Serialize, Deserialize)]
322#[serde(tag = "kind", rename_all = "snake_case")]
323pub enum AppRequest {
324    /// Query the server's capabilities.
325    Capabilities,
326    /// Read a configuration value by key.
327    ConfigGet { key: String },
328    /// Set a configuration key to a value.
329    ConfigSet { key: String, value: String },
330    /// Remove a configuration key.
331    ConfigUnset { key: String },
332    /// List all configuration entries.
333    ConfigList,
334    /// Reload configuration from disk and apply to the live runtime.
335    ///
336    /// Re-reads both `config.toml` and the sibling `permissions.toml`,
337    /// refreshing the live `Runtime.config` and `Runtime.exec_policy`
338    /// so headless clients can pick up external config-file *and*
339    /// permission-rule edits without restarting.
340    ///
341    /// Mirrors the TUI `reload_runtime_config` codepath for everything
342    /// reachable from the headless `Runtime`. MCP server connections
343    /// are not refreshed โ€” changing `mcp_config_path` or the referenced
344    /// `mcp.json` still requires a headless-runtime restart. The TUI's
345    /// explicit `/mcp reload` operation is not part of this protocol path.
346    ConfigReload,
347    /// List available models.
348    Models,
349    /// List threads that are currently loaded in memory.
350    ThreadLoadedList,
351    /// Submit answers to a prior [`EventFrame::UserInputRequest`].
352    ///
353    /// `request_id` must match a pending clarification request. Headless
354    /// clients use this to return the user's selections back to the runtime.
355    SubmitUserInput {
356        request_id: String,
357        answers: Vec<UserInputAnswerEvent>,
358    },
359}
360
361/// Response to an [`AppRequest`].
362#[derive(Debug, Clone, Serialize, Deserialize)]
363pub struct AppResponse {
364    /// Whether the request succeeded.
365    pub ok: bool,
366    /// The response payload.
367    pub data: Value,
368    /// Streaming events associated with this response.
369    #[serde(default)]
370    pub events: Vec<EventFrame>,
371}
372
373/// A simple prompt request that sends text to the model and returns output.
374#[derive(Debug, Clone, Serialize, Deserialize)]
375pub struct PromptRequest {
376    /// Optional thread context for the prompt.
377    #[serde(skip_serializing_if = "Option::is_none")]
378    pub thread_id: Option<String>,
379    /// The prompt text.
380    pub prompt: String,
381    /// Model override, or the default if omitted.
382    #[serde(skip_serializing_if = "Option::is_none")]
383    pub model: Option<String>,
384}
385
386/// Response to a [`PromptRequest`].
387#[derive(Debug, Clone, Serialize, Deserialize)]
388pub struct PromptResponse {
389    /// The model's output text.
390    pub output: String,
391    /// The model that produced the output.
392    pub model: String,
393    /// Streaming events associated with this response.
394    #[serde(default)]
395    pub events: Vec<EventFrame>,
396}
397
398/// Policy controlling when the agent must ask the user for approval before acting.
399#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
400#[serde(rename_all = "snake_case")]
401pub enum AskForApproval {
402    /// Ask for approval unless the action is on a trusted path/resource.
403    UnlessTrusted,
404    /// Only ask after a tool call fails.
405    OnFailure,
406    /// Ask every time a tool call is requested.
407    OnRequest,
408    /// Reject the action without asking, with details on which categories are blocked.
409    Reject {
410        sandbox_approval: bool,
411        rules: bool,
412        mcp_elicitations: bool,
413    },
414    /// Never ask; auto-approve all actions.
415    Never,
416}
417
418/// Classification of tool invocation origin.
419#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
420#[serde(rename_all = "snake_case")]
421pub enum ToolKind {
422    /// A built-in function tool.
423    Function,
424    /// An MCP (Model Context Protocol) tool.
425    Mcp,
426}
427
428/// Parameters for executing a local shell command.
429#[derive(Debug, Clone, Serialize, Deserialize)]
430pub struct LocalShellParams {
431    /// The shell command to execute.
432    pub command: String,
433    /// Working directory for the command.
434    #[serde(skip_serializing_if = "Option::is_none")]
435    pub cwd: Option<String>,
436    /// Timeout in milliseconds.
437    #[serde(skip_serializing_if = "Option::is_none")]
438    pub timeout_ms: Option<u64>,
439}
440
441/// The payload of a tool call, discriminated by tool type.
442#[derive(Debug, Clone, Serialize, Deserialize)]
443#[serde(tag = "type", rename_all = "snake_case")]
444pub enum ToolPayload {
445    /// A built-in function call with JSON-encoded arguments.
446    Function { arguments: String },
447    /// A custom tool invocation with a free-form input string.
448    Custom { input: String },
449    /// A local shell command execution.
450    LocalShell { params: LocalShellParams },
451    /// An MCP tool invocation targeting a specific server and tool.
452    Mcp {
453        server: String,
454        tool: String,
455        raw_arguments: Value,
456        #[serde(skip_serializing_if = "Option::is_none")]
457        raw_tool_call_id: Option<String>,
458    },
459}
460
461/// The result of a tool call, discriminated by tool type.
462#[derive(Debug, Clone, Serialize, Deserialize)]
463#[serde(tag = "type", rename_all = "snake_case")]
464pub enum ToolOutput {
465    /// Result of a built-in function call.
466    Function {
467        /// The output body, if any.
468        #[serde(skip_serializing_if = "Option::is_none")]
469        body: Option<Value>,
470        /// Whether the call succeeded.
471        success: bool,
472    },
473    /// Result of an MCP tool call.
474    Mcp {
475        /// The result value returned by the MCP server.
476        result: Value,
477    },
478}
479
480impl ToolOutput {
481    /// Returns the tool's application-level success independently of transport.
482    ///
483    /// MCP success requires the top-level `isError` field to be omitted or the
484    /// literal boolean `false`; malformed present metadata fails closed.
485    pub fn success(&self) -> bool {
486        match self {
487            Self::Function { success, .. } => *success,
488            Self::Mcp { result } => {
489                matches!(result.get("isError"), None | Some(Value::Bool(false)))
490            }
491        }
492    }
493}
494
495/// Action to take for a network policy rule.
496#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
497#[serde(rename_all = "snake_case")]
498pub enum NetworkPolicyRuleAction {
499    /// Allow network access to the host.
500    Allow,
501    /// Deny network access to the host.
502    Deny,
503}
504
505/// A proposed amendment to the network access policy for a specific host.
506#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
507pub struct NetworkPolicyAmendment {
508    /// The host to amend the policy for.
509    pub host: String,
510    /// The action to apply.
511    pub action: NetworkPolicyRuleAction,
512}
513
514/// A user's decision on an approval request.
515#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
516#[serde(tag = "type", rename_all = "snake_case")]
517pub enum ReviewDecision {
518    /// Approve the action.
519    Approved,
520    /// Approve and also amend the execution policy.
521    ApprovedExecpolicyAmendment,
522    /// Approve for the remainder of this session only.
523    ApprovedForSession,
524    /// Approve with a network policy amendment.
525    NetworkPolicyAmendment {
526        host: String,
527        action: NetworkPolicyRuleAction,
528    },
529    /// Deny the action.
530    Denied,
531    /// Abort the entire turn.
532    Abort,
533}
534
535/// Status of an MCP server during startup.
536#[derive(Debug, Clone, Serialize, Deserialize)]
537#[serde(rename_all = "snake_case")]
538pub enum McpStartupStatus {
539    /// The server is in the process of starting.
540    Starting,
541    /// The server is ready to accept requests.
542    Ready,
543    /// The server failed to start.
544    Failed { error: String },
545    /// Startup was cancelled.
546    Cancelled,
547}
548
549/// A progress update for a single MCP server's startup.
550#[derive(Debug, Clone, Serialize, Deserialize)]
551pub struct McpStartupUpdateEvent {
552    /// Name of the MCP server.
553    pub server_name: String,
554    /// Current startup status.
555    pub status: McpStartupStatus,
556}
557
558/// Details of an MCP server that failed to start.
559#[derive(Debug, Clone, Serialize, Deserialize)]
560pub struct McpStartupFailure {
561    /// Name of the MCP server that failed.
562    pub server_name: String,
563    /// Error description.
564    pub error: String,
565}
566
567/// Summary event emitted once all MCP servers have finished starting.
568#[derive(Debug, Clone, Serialize, Deserialize)]
569pub struct McpStartupCompleteEvent {
570    /// Servers that started successfully.
571    pub ready: Vec<String>,
572    /// Servers that failed to start.
573    pub failed: Vec<McpStartupFailure>,
574    /// Servers whose startup was cancelled.
575    pub cancelled: Vec<String>,
576}
577
578/// Context about a network access request that requires approval.
579#[derive(Debug, Clone, Serialize, Deserialize)]
580pub struct NetworkApprovalContext {
581    /// The host being accessed.
582    pub host: String,
583    /// The network protocol (e.g. `"https"`, `"tcp"`).
584    pub protocol: String,
585}
586
587/// A selectable option presented to the user in a clarification question.
588///
589/// Headless serialization shape for the `request_user_input` model tool,
590/// mirrored after the TUI's `UserInputOption`. Shared by the
591/// [`EventFrame::UserInputRequest`] frame and the [`AppRequest::SubmitUserInput`]
592/// reply path so both surfaces agree on the question schema.
593#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
594pub struct UserInputOptionEvent {
595    /// Short label for the option (also the value submitted when picked).
596    pub label: String,
597    /// Longer description shown alongside the label.
598    pub description: String,
599}
600
601/// A single clarification question posed to the user.
602#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
603pub struct UserInputQuestionEvent {
604    /// Compact header shown as the question title.
605    pub header: String,
606    /// Stable identifier used to correlate answers back to this question.
607    pub id: String,
608    /// The question body.
609    pub question: String,
610    /// 2-4 suggested answers.
611    pub options: Vec<UserInputOptionEvent>,
612    /// When `true`, the client should also offer a free-text response.
613    #[serde(default)]
614    pub allow_free_text: bool,
615    /// When `true`, the user may select more than one option.
616    #[serde(default)]
617    pub multi_select: bool,
618}
619
620/// An event requesting structured user input via a model-tool call.
621///
622/// Sibling of [`ExecApprovalRequestEvent`] for the clarification-question
623/// flow. Emitted fire-and-return by `Runtime::invoke_tool` when the model
624/// invokes `request_user_input` in a headless context.
625#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
626pub struct UserInputRequestEvent {
627    /// Identifier of the tool call requesting input.
628    pub call_id: String,
629    /// The turn during which the request was made.
630    pub turn_id: String,
631    /// Unique identifier for this user-input request (clients reply with it).
632    pub request_id: String,
633    /// 1-3 questions to present.
634    pub questions: Vec<UserInputQuestionEvent>,
635}
636
637/// One answer to a clarification question.
638#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
639pub struct UserInputAnswerEvent {
640    /// The `id` of the question this answer corresponds to.
641    pub id: String,
642    /// The selected option's label, or `"Other"` for a free-text response.
643    pub label: String,
644    /// The resolved value (option label, or the typed free-text).
645    pub value: String,
646}
647
648/// An event requesting user approval for a command execution or patch application.
649#[derive(Debug, Clone, Serialize, Deserialize)]
650pub struct ExecApprovalRequestEvent {
651    /// Identifier of the tool call requesting approval.
652    pub call_id: String,
653    /// Unique identifier for this approval request.
654    pub approval_id: String,
655    /// The turn during which the request was made.
656    pub turn_id: String,
657    /// The command that would be executed.
658    pub command: String,
659    /// The working directory for the command.
660    pub cwd: String,
661    /// Human-readable reason why approval is needed.
662    pub reason: String,
663    /// Policy rule that matched this approval request, when available.
664    #[serde(default, skip_serializing_if = "Option::is_none")]
665    pub matched_rule: Option<Box<str>>,
666    /// Network context if the approval involves network access.
667    #[serde(skip_serializing_if = "Option::is_none")]
668    pub network_approval_context: Option<NetworkApprovalContext>,
669    /// Proposed execution policy rule amendments.
670    #[serde(default)]
671    pub proposed_execpolicy_amendment: Vec<String>,
672    /// Proposed network policy amendments.
673    #[serde(default)]
674    pub proposed_network_policy_amendments: Vec<NetworkPolicyAmendment>,
675    /// Additional permissions being requested.
676    #[serde(default)]
677    pub additional_permissions: Vec<String>,
678    /// The set of decisions the user can choose from.
679    #[serde(default)]
680    pub available_decisions: Vec<ReviewDecision>,
681}
682
683/// The channel a response delta is being written to.
684#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
685#[serde(rename_all = "snake_case")]
686pub enum ResponseChannel {
687    /// The main visible text output.
688    #[default]
689    Text,
690    /// Internal reasoning / chain-of-thought output.
691    Reasoning,
692}
693
694impl ResponseChannel {
695    /// Returns `true` if this is the `Text` channel.
696    pub const fn is_text(&self) -> bool {
697        matches!(self, ResponseChannel::Text)
698    }
699}
700
701/// A user's approval decision sent in response to an approval request.
702#[derive(Debug, Clone, Serialize, Deserialize)]
703pub struct ApprovalDecisionRequest {
704    /// The decision identifier (e.g. `"approved"`, `"denied"`).
705    pub decision: String,
706    /// Whether to remember this decision for future similar requests.
707    #[serde(default)]
708    pub remember: bool,
709}
710
711/// A single streaming event frame emitted during agent execution.
712///
713/// Events are tagged by the `event` field and cover the full lifecycle of a
714/// turn: response streaming, tool calls, MCP lifecycle, command execution,
715/// patch application, approvals, and errors.
716#[derive(Debug, Clone, Serialize, Deserialize)]
717#[serde(tag = "event", rename_all = "snake_case")]
718pub enum EventFrame {
719    /// A new model response has started.
720    ResponseStart { response_id: String },
721    /// A incremental text delta for an in-progress response.
722    ResponseDelta {
723        response_id: String,
724        delta: String,
725        #[serde(default, skip_serializing_if = "ResponseChannel::is_text")]
726        channel: ResponseChannel,
727    },
728    /// The model response has finished.
729    ResponseEnd { response_id: String },
730    /// A tool call has begun.
731    ToolCallStart {
732        response_id: String,
733        tool_name: String,
734        arguments: Value,
735    },
736    /// A tool call has completed and produced a result.
737    ToolCallResult {
738        response_id: String,
739        tool_name: String,
740        output: Value,
741    },
742    /// Progress update for an MCP server starting up.
743    McpStartupUpdate { update: McpStartupUpdateEvent },
744    /// All MCP servers have finished starting.
745    McpStartupComplete { summary: McpStartupCompleteEvent },
746    /// An MCP tool call has begun.
747    McpToolCallBegin {
748        server_name: String,
749        tool_name: String,
750    },
751    /// An MCP tool call has finished.
752    McpToolCallEnd {
753        server_name: String,
754        tool_name: String,
755        ok: bool,
756    },
757    /// User approval is needed for a command execution.
758    ExecApprovalRequest { request: ExecApprovalRequestEvent },
759    /// User approval is needed for applying a patch.
760    ApplyPatchApprovalRequest { request: ExecApprovalRequestEvent },
761    /// A model tool is requesting structured clarification input from the user.
762    ///
763    /// Headless sibling of the TUI's `request_user_input` modal flow.
764    /// `request_id` correlates with an [`AppRequest::SubmitUserInput`] reply.
765    UserInputRequest { request: UserInputRequestEvent },
766    /// An MCP server is requesting user input (elicitation).
767    ElicitationRequest {
768        server_name: String,
769        request_id: String,
770        prompt: String,
771    },
772    /// A command has started executing.
773    ExecCommandBegin { command: String, cwd: String },
774    /// Incremental output from a running command.
775    ExecCommandOutputDelta { command: String, delta: String },
776    /// A command has finished executing.
777    ExecCommandEnd { command: String, exit_code: i32 },
778    /// A patch has started being applied to a file.
779    PatchApplyBegin { path: String },
780    /// A patch has finished being applied.
781    PatchApplyEnd { path: String, ok: bool },
782    /// A new turn has started within a thread.
783    TurnStarted { turn_id: String },
784    /// A turn has completed successfully.
785    TurnComplete { turn_id: String },
786    /// A turn was aborted before completion.
787    TurnAborted { turn_id: String, reason: String },
788    /// A thread goal was set or updated.
789    ThreadGoalUpdated { goal: ThreadGoal },
790    /// A thread goal was cleared.
791    ThreadGoalCleared { thread_id: String },
792    /// An error occurred during processing.
793    Error {
794        response_id: String,
795        message: String,
796    },
797}