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 engine_owner;
15pub mod event_msg;
16pub mod fleet;
17pub mod ids;
18pub mod journal;
19pub mod op;
20pub mod placement;
21pub mod runtime;
22
23/// Common trait for lifecycle status enums across the protocol layer.
24///
25/// Every status enum โ€” thread, goal, fleet run, worker, and job status โ€”
26/// implements this trait so generic code can ask three universal questions
27/// without matching on every variant.
28pub trait Status {
29    /// Returns `true` when this status represents a final, non-progressable state
30    /// (e.g. Completed, Failed, Cancelled, Archived, Retired).
31    fn is_terminal(&self) -> bool;
32
33    /// Returns `true` when work is currently in-flight
34    /// (e.g. Running, Active, Busy, Queued, Pending).
35    fn is_active(&self) -> bool;
36
37    /// Returns `true` when the item has been explicitly paused by the user
38    /// or system (e.g. Paused).
39    fn is_paused(&self) -> bool;
40}
41
42/// A single message entry in a conversation thread.
43///
44/// Messages form a tree structure via [`parent_entry_id`](Self::parent_entry_id),
45/// enabling conversation branching and forking.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct MessageRecord {
48    /// Auto-incremented unique identifier for this message.
49    pub id: i64,
50    /// ID of the thread this message belongs to.
51    pub thread_id: String,
52    /// Role of the message sender (e.g. `"user"`, `"assistant"`, `"system"`).
53    pub role: String,
54    /// Text content of the message.
55    pub content: String,
56    /// Optional structured item payload (tool calls, tool results, etc.).
57    pub item: Option<Value>,
58    /// Unix timestamp (seconds) when the message was created.
59    pub created_at: i64,
60    /// ID of the parent message, forming a tree structure. `None` for root messages.
61    pub parent_entry_id: Option<i64>,
62}
63
64/// A complete immutable legacy SQLite graph, not a limit or active-branch projection.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66#[serde(deny_unknown_fields)]
67pub struct LegacyThreadHistory {
68    pub version: u32,
69    pub state_store_id: String,
70    pub thread_id: String,
71    pub current_leaf_id: Option<i64>,
72    pub messages: Vec<MessageRecord>,
73    /// Captured in the same SQLite snapshot; imported Active goals stay paused.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub goal: Option<ThreadGoal>,
76}
77
78pub const MAX_CANONICAL_HISTORY_ENTRIES: usize = 16_384;
79pub const MAX_CANONICAL_HISTORY_BYTES: usize = 8 * 1024 * 1024;
80
81/// An authenticated import proposal carries conversation data only. Routing and
82/// permissions remain the current owner's create-thread policy.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84#[serde(deny_unknown_fields)]
85pub struct CanonicalHistoryImportRequest {
86    pub version: u32,
87    pub operation_key: String,
88    pub expected_data_dir: PathBuf,
89    pub expected_execution_scope: String,
90    /// Existing bare compatibility links attach their full source graph here;
91    /// the owner verifies the actual bound canonical document, never remints it.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub target_runtime_thread_id: Option<String>,
94    pub workspace: PathBuf,
95    pub model: Option<String>,
96    pub history: LegacyThreadHistory,
97}
98
99/// Durable result of the actual canonical owner operation. Its scope fields are
100/// captured from RuntimeStoreBinding; historical receipts never authenticate a
101/// current process or convey credentials.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103#[serde(deny_unknown_fields)]
104pub struct CanonicalThreadReceipt {
105    pub version: u32,
106    pub data_dir: PathBuf,
107    pub execution_scope: String,
108    pub operation_key: String,
109    pub request_digest: String,
110    pub history_digest: String,
111    pub runtime_thread_id: String,
112    pub session_id: String,
113}
114
115/// A complete read projection from the actual Engine and its existing saved
116/// journal. `session` retains the established SavedSession wire shape, including
117/// every branch; it is data, never a policy or operation-commit receipt.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119#[serde(deny_unknown_fields)]
120pub struct CanonicalThreadSnapshot {
121    pub version: u32,
122    pub data_dir: PathBuf,
123    pub execution_scope: String,
124    pub runtime_thread_id: String,
125    pub saved_session_id: Option<String>,
126    pub saved_document_digest: Option<String>,
127    pub document_digest: String,
128    pub session_goal_digest: String,
129    pub session: Value,
130}
131
132/// One client-captured intent. The key is retained after an uncertain reply;
133/// retrying it never allocates another canonical identity.
134#[derive(Debug, Clone, Serialize, Deserialize)]
135#[serde(deny_unknown_fields)]
136pub struct CanonicalThreadMutationRequest {
137    pub version: u32,
138    pub operation_key: String,
139    pub expected_data_dir: PathBuf,
140    pub expected_execution_scope: String,
141    pub workspace: PathBuf,
142    pub mutation: CanonicalThreadMutation,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
146#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
147pub enum CanonicalThreadMutation {
148    /// The existing CreateThreadRequest shape, checked by the owner. Conversation
149    /// data and an imported document never supply a routing or permission ceiling.
150    Create { config: Value },
151    Resume {
152        source: CanonicalHistorySource,
153        #[serde(default)]
154        options: CanonicalHistoryOptions,
155    },
156    Fork {
157        source: CanonicalHistorySource,
158        #[serde(default)]
159        options: CanonicalHistoryOptions,
160        #[serde(default, skip_serializing_if = "Option::is_none")]
161        selected_entry_id: Option<String>,
162    },
163}
164
165#[derive(Debug, Clone, Default, Serialize, Deserialize)]
166#[serde(deny_unknown_fields)]
167pub struct CanonicalHistoryOptions {
168    #[serde(default, skip_serializing_if = "Vec::is_empty")]
169    pub offered_history: Vec<Value>,
170    #[serde(default, skip_serializing_if = "Value::is_null")]
171    pub overrides: Value,
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub source_path: Option<PathBuf>,
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub expected_session_goal_digest: Option<String>,
176}
177
178#[derive(Debug, Clone, Serialize, Deserialize)]
179#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
180pub enum CanonicalHistorySource {
181    Thread {
182        runtime_thread_id: String,
183        expected_document_digest: String,
184    },
185    /// Local mounted handoff supplies the already protected document without
186    /// its journal-derived messages; the actual owner rebuilds them from the
187    /// journal, reopens the file and compares the same whole-document digest.
188    SavedSession {
189        session: Value,
190        expected_document_digest: String,
191    },
192}
193
194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(rename_all = "snake_case")]
196pub enum CanonicalThreadOperationKind {
197    Create,
198    Resume,
199    Fork,
200}
201
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(deny_unknown_fields)]
204pub struct CanonicalThreadOperationAssociation {
205    pub kind: CanonicalThreadOperationKind,
206    pub source_runtime_thread_id: Option<String>,
207    pub source_session_id: Option<String>,
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
211#[serde(deny_unknown_fields)]
212pub struct CanonicalThreadOperationLookup {
213    pub version: u32,
214    pub operation_key: String,
215    pub expected_data_dir: PathBuf,
216    pub expected_execution_scope: String,
217    pub workspace: PathBuf,
218}
219
220/// Explicit completion of an already-prepared retained intent, with no source proposal.
221#[derive(Debug, Clone, Serialize, Deserialize)]
222#[serde(deny_unknown_fields)]
223pub struct CanonicalThreadOperationRecovery {
224    pub operation: CanonicalThreadOperationLookup,
225    pub association: CanonicalThreadOperationAssociation,
226}
227
228#[derive(Debug, Clone, Serialize, Deserialize)]
229#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
230pub enum CanonicalThreadOperationStatus {
231    Absent,
232    Pending {
233        receipt: CanonicalThreadReceipt,
234        association: CanonicalThreadOperationAssociation,
235    },
236    Committed {
237        receipt: CanonicalThreadReceipt,
238        association: CanonicalThreadOperationAssociation,
239    },
240}
241
242/// Closed routing receipt captured from the held Runtime owner, never a bearer.
243/// Authentication also requires the actual connected kernel peer identity.
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245#[serde(deny_unknown_fields)]
246pub struct RuntimeOwnerReceipt {
247    pub version: u32,
248    pub data_dir: PathBuf,
249    pub execution_scope: String,
250    pub lease_generation: String,
251    pub pid: u32,
252    pub process_start: String,
253    pub principal: String,
254    pub socket_path: PathBuf,
255    pub config_path: Option<PathBuf>,
256}
257
258#[derive(Debug, Clone, Serialize, Deserialize)]
259pub struct Envelope<T> {
260    pub request_id: String,
261    #[serde(skip_serializing_if = "Option::is_none")]
262    pub thread_id: Option<String>,
263    pub body: T,
264}
265
266#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
267#[serde(rename_all = "snake_case")]
268pub enum ThreadStatus {
269    Running,
270    Idle,
271    Completed,
272    Failed,
273    Paused,
274    Archived,
275}
276
277impl Status for ThreadStatus {
278    fn is_terminal(&self) -> bool {
279        matches!(self, Self::Completed | Self::Failed | Self::Archived)
280    }
281    fn is_active(&self) -> bool {
282        matches!(self, Self::Running)
283    }
284    fn is_paused(&self) -> bool {
285        matches!(self, Self::Paused)
286    }
287}
288
289#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
290#[serde(rename_all = "snake_case")]
291pub enum SessionSource {
292    Interactive,
293    Resume,
294    Fork,
295    Api,
296    Unknown,
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
300pub struct Thread {
301    pub id: String,
302    pub preview: String,
303    pub ephemeral: bool,
304    pub model_provider: String,
305    pub created_at: i64,
306    pub updated_at: i64,
307    pub status: ThreadStatus,
308    #[serde(skip_serializing_if = "Option::is_none")]
309    pub path: Option<PathBuf>,
310    pub cwd: PathBuf,
311    pub cli_version: String,
312    pub source: SessionSource,
313    #[serde(skip_serializing_if = "Option::is_none")]
314    pub name: Option<String>,
315}
316
317#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
318#[serde(rename_all = "snake_case")]
319pub enum ThreadGoalStatus {
320    Active,
321    Paused,
322    Blocked,
323    UsageLimited,
324    BudgetLimited,
325    Complete,
326}
327
328impl Status for ThreadGoalStatus {
329    fn is_terminal(&self) -> bool {
330        matches!(self, Self::Complete)
331    }
332    fn is_active(&self) -> bool {
333        matches!(self, Self::Active)
334    }
335    fn is_paused(&self) -> bool {
336        matches!(self, Self::Paused)
337    }
338}
339
340#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
341pub struct ThreadGoal {
342    pub thread_id: String,
343    pub goal_id: String,
344    pub objective: String,
345    pub status: ThreadGoalStatus,
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub token_budget: Option<i64>,
348    pub tokens_used: i64,
349    pub time_used_seconds: i64,
350    pub continuation_count: i64,
351    pub created_at: i64,
352    pub updated_at: i64,
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub last_gap_fingerprint: Option<String>,
355    #[serde(default)]
356    pub repeated_gap_count: u32,
357    #[serde(default, skip_serializing_if = "Option::is_none")]
358    pub last_gap_pass: Option<u32>,
359    #[serde(default, skip_serializing_if = "Option::is_none")]
360    pub pause_reason: Option<GoalPauseReason>,
361}
362
363/// Why an unfinished goal is paused. Shared by every durable host projection.
364#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
365#[serde(rename_all = "snake_case")]
366pub enum GoalPauseReason {
367    User,
368    Backoff,
369    NoProgress,
370    UsageLimit,
371    BudgetLimit,
372    /// The model finished a stage and handed control back, rather than a
373    /// reported blocker or a completion. It is not a judgement about the work,
374    /// so the user's next message resumes the goal (the same shape as a
375    /// runtime stop, which is also resumable by writing to it).
376    Yielded,
377    /// A reason a **newer** build wrote. Kept so an older binary can still read
378    /// the durable record instead of failing the whole goal load on an unknown
379    /// variant; nothing constructs it. The resume path treats it as "not a
380    /// hand-back", which is the conservative reading.
381    #[serde(other)]
382    Unrecognized,
383}
384
385impl GoalPauseReason {
386    #[must_use]
387    pub fn label(self) -> &'static str {
388        match self {
389            Self::User => "user",
390            Self::Backoff => "run limit",
391            Self::NoProgress => "no progress",
392            Self::UsageLimit => "usage limit",
393            Self::BudgetLimit => "budget limit",
394            Self::Yielded => "handed back",
395            Self::Unrecognized => "unrecognized",
396        }
397    }
398}
399
400/// Validate the compact stall history without retaining verifier prose.
401/// Legacy records with the entire history absent start with an empty window.
402pub const MAX_REPEATED_GAP_COUNT: u32 = 3;
403
404pub fn validate_goal_stall_state(
405    fingerprint: Option<&str>,
406    count: u32,
407    pass: Option<u32>,
408    continuation_count: u32,
409) -> Result<(), &'static str> {
410    match (fingerprint, count, pass) {
411        (None, 0, None) => Ok(()),
412        (Some(digest), 1..=MAX_REPEATED_GAP_COUNT, Some(pass))
413            if digest.len() == 64
414                && digest.bytes().all(|byte| byte.is_ascii_hexdigit())
415                && pass <= continuation_count
416                && count <= pass.saturating_add(1) =>
417        {
418            Ok(())
419        }
420        _ => Err("invalid persisted goal stall history"),
421    }
422}
423
424impl ThreadGoal {
425    pub fn validate_stall_state(&self) -> Result<(), &'static str> {
426        validate_goal_stall_state(
427            self.last_gap_fingerprint.as_deref(),
428            self.repeated_gap_count,
429            self.last_gap_pass,
430            u32::try_from(self.continuation_count.max(0)).unwrap_or(u32::MAX),
431        )
432    }
433
434    /// Restore a durably impossible record as paused. The engine pauses
435    /// NoProgress in the same locked mutation that fills the stall window, so
436    /// a persisted record that is still Active at the ceiling is corrupt
437    /// (e.g. a crash between the counter write and the pause). Returns true
438    /// when the record was healed.
439    pub fn normalize_restored_stall_state(&mut self) -> bool {
440        if matches!(self.status, ThreadGoalStatus::Active)
441            && self.repeated_gap_count >= MAX_REPEATED_GAP_COUNT
442        {
443            self.status = ThreadGoalStatus::Paused;
444            self.pause_reason = Some(GoalPauseReason::NoProgress);
445            true
446        } else {
447            false
448        }
449    }
450}
451
452#[derive(Debug, Clone, Serialize, Deserialize)]
453pub struct ThreadStartParams {
454    /// Captured once for this user intent and retained for an uncertain reply.
455    #[serde(default, skip_serializing_if = "Option::is_none")]
456    pub operation_key: Option<String>,
457    #[serde(skip_serializing_if = "Option::is_none")]
458    pub model: Option<String>,
459    #[serde(skip_serializing_if = "Option::is_none")]
460    pub model_provider: Option<String>,
461    #[serde(skip_serializing_if = "Option::is_none")]
462    pub cwd: Option<PathBuf>,
463    #[serde(default)]
464    pub persist_extended_history: bool,
465}
466
467#[derive(Debug, Clone, Serialize, Deserialize)]
468pub struct ThreadResumeParams {
469    /// Captured once for this user intent and retained for an uncertain reply.
470    #[serde(default, skip_serializing_if = "Option::is_none")]
471    pub operation_key: Option<String>,
472    pub thread_id: String,
473    #[serde(skip_serializing_if = "Option::is_none")]
474    pub history: Option<Vec<Value>>,
475    #[serde(skip_serializing_if = "Option::is_none")]
476    pub path: Option<PathBuf>,
477    #[serde(skip_serializing_if = "Option::is_none")]
478    pub model: Option<String>,
479    #[serde(skip_serializing_if = "Option::is_none")]
480    pub model_provider: Option<String>,
481    #[serde(skip_serializing_if = "Option::is_none")]
482    pub cwd: Option<PathBuf>,
483    #[serde(skip_serializing_if = "Option::is_none")]
484    pub approval_policy: Option<String>,
485    #[serde(skip_serializing_if = "Option::is_none")]
486    pub sandbox: Option<String>,
487    #[serde(skip_serializing_if = "Option::is_none")]
488    pub config: Option<Value>,
489    #[serde(skip_serializing_if = "Option::is_none")]
490    pub base_instructions: Option<String>,
491    #[serde(skip_serializing_if = "Option::is_none")]
492    pub developer_instructions: Option<String>,
493    #[serde(skip_serializing_if = "Option::is_none")]
494    pub personality: Option<String>,
495    #[serde(default)]
496    pub persist_extended_history: bool,
497}
498
499#[derive(Debug, Clone, Serialize, Deserialize)]
500pub struct ThreadForkParams {
501    /// Captured once for this user intent and retained for an uncertain reply.
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    pub operation_key: Option<String>,
504    pub thread_id: String,
505    #[serde(skip_serializing_if = "Option::is_none")]
506    pub path: Option<PathBuf>,
507    #[serde(skip_serializing_if = "Option::is_none")]
508    pub model: Option<String>,
509    #[serde(skip_serializing_if = "Option::is_none")]
510    pub model_provider: Option<String>,
511    #[serde(skip_serializing_if = "Option::is_none")]
512    pub cwd: Option<PathBuf>,
513    #[serde(skip_serializing_if = "Option::is_none")]
514    pub approval_policy: Option<String>,
515    #[serde(skip_serializing_if = "Option::is_none")]
516    pub sandbox: Option<String>,
517    #[serde(skip_serializing_if = "Option::is_none")]
518    pub config: Option<Value>,
519    #[serde(skip_serializing_if = "Option::is_none")]
520    pub base_instructions: Option<String>,
521    #[serde(skip_serializing_if = "Option::is_none")]
522    pub developer_instructions: Option<String>,
523    #[serde(default)]
524    pub persist_extended_history: bool,
525}
526
527#[derive(Debug, Clone, Serialize, Deserialize)]
528pub struct ThreadListParams {
529    #[serde(default)]
530    pub include_archived: bool,
531    #[serde(skip_serializing_if = "Option::is_none")]
532    pub limit: Option<usize>,
533}
534
535#[derive(Debug, Clone, Serialize, Deserialize)]
536pub struct ThreadReadParams {
537    pub thread_id: String,
538}
539
540#[derive(Debug, Clone, Serialize, Deserialize)]
541pub struct ThreadSetNameParams {
542    pub thread_id: String,
543    pub name: String,
544}
545
546#[derive(Debug, Clone, Serialize, Deserialize)]
547pub struct ThreadGoalSetParams {
548    pub thread_id: String,
549    pub objective: String,
550    #[serde(skip_serializing_if = "Option::is_none")]
551    pub token_budget: Option<i64>,
552}
553
554#[derive(Debug, Clone, Serialize, Deserialize)]
555pub struct ThreadGoalGetParams {
556    pub thread_id: String,
557}
558
559#[derive(Debug, Clone, Serialize, Deserialize)]
560pub struct ThreadGoalClearParams {
561    pub thread_id: String,
562}
563
564#[derive(Debug, Clone, Serialize, Deserialize)]
565pub struct ThreadGoalProgressParams {
566    pub thread_id: String,
567    #[serde(default)]
568    pub token_delta: i64,
569    #[serde(default)]
570    pub time_delta_seconds: i64,
571    #[serde(default)]
572    pub record_continuation: bool,
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize)]
576#[serde(tag = "kind", rename_all = "snake_case")]
577pub enum ThreadRequest {
578    Create {
579        #[serde(default)]
580        metadata: Value,
581    },
582    Start(ThreadStartParams),
583    Resume(ThreadResumeParams),
584    Fork(ThreadForkParams),
585    List(ThreadListParams),
586    Read(ThreadReadParams),
587    SetName(ThreadSetNameParams),
588    GoalSet(ThreadGoalSetParams),
589    GoalGet(ThreadGoalGetParams),
590    GoalClear(ThreadGoalClearParams),
591    GoalRecordProgress(ThreadGoalProgressParams),
592    Archive {
593        thread_id: String,
594    },
595    Unarchive {
596        thread_id: String,
597    },
598    Message {
599        thread_id: String,
600        input: String,
601        #[serde(default, skip_serializing_if = "Option::is_none")]
602        allowed_tools: Option<Vec<String>>,
603        #[serde(default, skip_serializing_if = "Vec::is_empty")]
604        images: Vec<runtime::RuntimeImageInput>,
605        #[serde(
606            default,
607            rename = "maxOutputTokens",
608            alias = "max_output_tokens",
609            skip_serializing_if = "Option::is_none"
610        )]
611        max_output_tokens: Option<std::num::NonZeroU32>,
612    },
613}
614
615/// Response to a [`ThreadRequest`].
616#[derive(Debug, Clone, Serialize, Deserialize)]
617pub struct ThreadResponse {
618    /// The thread this response pertains to.
619    pub thread_id: String,
620    /// Human-readable status string (e.g. `"ok"`, `"error"`).
621    pub status: String,
622    /// The thread details, when a single thread is returned.
623    #[serde(skip_serializing_if = "Option::is_none")]
624    pub thread: Option<Thread>,
625    /// List of threads, populated by `List` requests.
626    #[serde(default)]
627    pub threads: Vec<Thread>,
628    /// Thread goal returned by goal get/set requests.
629    #[serde(skip_serializing_if = "Option::is_none")]
630    pub goal: Option<ThreadGoal>,
631    /// The model used for the thread, if applicable.
632    #[serde(skip_serializing_if = "Option::is_none")]
633    pub model: Option<String>,
634    /// The model provider used for the thread.
635    #[serde(skip_serializing_if = "Option::is_none")]
636    pub model_provider: Option<String>,
637    /// The working directory of the thread.
638    #[serde(skip_serializing_if = "Option::is_none")]
639    pub cwd: Option<PathBuf>,
640    /// The active approval policy.
641    #[serde(skip_serializing_if = "Option::is_none")]
642    pub approval_policy: Option<String>,
643    /// The active sandbox configuration.
644    #[serde(skip_serializing_if = "Option::is_none")]
645    pub sandbox: Option<String>,
646    /// Streaming events associated with this response.
647    #[serde(default)]
648    pub events: Vec<EventFrame>,
649    /// Arbitrary additional response data.
650    #[serde(default)]
651    pub data: Value,
652}
653
654/// Application-level requests that are not tied to a specific thread.
655#[derive(Debug, Clone, Serialize, Deserialize)]
656#[serde(tag = "kind", rename_all = "snake_case")]
657pub enum AppRequest {
658    /// Query the server's capabilities.
659    Capabilities,
660    /// Read a configuration value by key.
661    ConfigGet { key: String },
662    /// Set a configuration key to a value.
663    ConfigSet { key: String, value: String },
664    /// Remove a configuration key.
665    ConfigUnset { key: String },
666    /// List all configuration entries.
667    ConfigList,
668    /// Reload configuration from disk and apply to the live runtime.
669    ///
670    /// Re-reads both `config.toml` and the sibling `permissions.toml`,
671    /// refreshing the live `Runtime.config` and `Runtime.exec_policy`
672    /// so headless clients can pick up external config-file *and*
673    /// permission-rule edits without restarting.
674    ///
675    /// Mirrors the TUI `reload_runtime_config` codepath for everything
676    /// reachable from the headless `Runtime`. MCP server connections
677    /// are not refreshed โ€” changing `mcp_config_path` or the referenced
678    /// `mcp.json` still requires a headless-runtime restart. The TUI's
679    /// explicit `/mcp reload` operation is not part of this protocol path.
680    ConfigReload,
681    /// List available models.
682    Models,
683    /// List threads that are currently loaded in memory.
684    ThreadLoadedList,
685    /// Submit answers to a prior [`EventFrame::UserInputRequest`].
686    ///
687    /// `request_id` must match a pending clarification request. Headless
688    /// clients use this to return the user's selections back to the runtime.
689    SubmitUserInput {
690        request_id: String,
691        answers: Vec<UserInputAnswerEvent>,
692    },
693}
694
695/// Response to an [`AppRequest`].
696#[derive(Debug, Clone, Serialize, Deserialize)]
697pub struct AppResponse {
698    /// Whether the request succeeded.
699    pub ok: bool,
700    /// The response payload.
701    pub data: Value,
702    /// Streaming events associated with this response.
703    #[serde(default)]
704    pub events: Vec<EventFrame>,
705}
706
707/// A simple prompt request that sends text to the model and returns output.
708#[derive(Debug, Clone, Serialize, Deserialize)]
709pub struct PromptRequest {
710    #[serde(default, skip_serializing_if = "Option::is_none")]
711    pub allowed_tools: Option<Vec<String>>,
712    #[serde(
713        default,
714        rename = "maxOutputTokens",
715        alias = "max_output_tokens",
716        skip_serializing_if = "Option::is_none"
717    )]
718    pub max_output_tokens: Option<std::num::NonZeroU32>,
719    /// Optional thread context for the prompt.
720    #[serde(skip_serializing_if = "Option::is_none")]
721    pub thread_id: Option<String>,
722    /// The prompt text.
723    pub prompt: String,
724    #[serde(default, skip_serializing_if = "Vec::is_empty")]
725    pub images: Vec<runtime::RuntimeImageInput>,
726    /// Model override, or the default if omitted.
727    #[serde(skip_serializing_if = "Option::is_none")]
728    pub model: Option<String>,
729}
730
731/// Response to a [`PromptRequest`].
732#[derive(Debug, Clone, Serialize, Deserialize)]
733pub struct PromptResponse {
734    /// The model's output text.
735    pub output: String,
736    /// The model that produced the output.
737    pub model: String,
738    /// Streaming events associated with this response.
739    #[serde(default)]
740    pub events: Vec<EventFrame>,
741}
742
743/// Policy controlling when the agent must ask the user for approval before acting.
744#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
745#[serde(rename_all = "snake_case")]
746pub enum AskForApproval {
747    /// Ask for approval unless the action is on a trusted path/resource.
748    UnlessTrusted,
749    /// Only ask after a tool call fails.
750    OnFailure,
751    /// Ask every time a tool call is requested.
752    OnRequest,
753    /// Reject the action without asking, with details on which categories are blocked.
754    Reject {
755        sandbox_approval: bool,
756        rules: bool,
757        mcp_elicitations: bool,
758    },
759    /// Never ask; auto-approve all actions.
760    Never,
761}
762
763/// Classification of tool invocation origin.
764#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
765#[serde(rename_all = "snake_case")]
766pub enum ToolKind {
767    /// A built-in function tool.
768    Function,
769    /// An MCP (Model Context Protocol) tool.
770    Mcp,
771}
772
773/// Parameters for executing a local shell command.
774#[derive(Debug, Clone, Serialize, Deserialize)]
775pub struct LocalShellParams {
776    /// The shell command to execute.
777    pub command: String,
778    /// Working directory for the command.
779    #[serde(skip_serializing_if = "Option::is_none")]
780    pub cwd: Option<String>,
781    /// Timeout in milliseconds.
782    #[serde(skip_serializing_if = "Option::is_none")]
783    pub timeout_ms: Option<u64>,
784}
785
786/// The payload of a tool call, discriminated by tool type.
787#[derive(Debug, Clone, Serialize, Deserialize)]
788#[serde(tag = "type", rename_all = "snake_case")]
789pub enum ToolPayload {
790    /// A built-in function call with JSON-encoded arguments.
791    Function { arguments: String },
792    /// A custom tool invocation with a free-form input string.
793    Custom { input: String },
794    /// A local shell command execution.
795    LocalShell { params: LocalShellParams },
796    /// An MCP tool invocation targeting a specific server and tool.
797    Mcp {
798        server: String,
799        tool: String,
800        raw_arguments: Value,
801        #[serde(skip_serializing_if = "Option::is_none")]
802        raw_tool_call_id: Option<String>,
803    },
804}
805
806/// The result of a tool call, discriminated by tool type.
807#[derive(Debug, Clone, Serialize, Deserialize)]
808#[serde(tag = "type", rename_all = "snake_case")]
809pub enum ToolOutput {
810    /// Result of a built-in function call.
811    Function {
812        /// The output body, if any.
813        #[serde(skip_serializing_if = "Option::is_none")]
814        body: Option<Value>,
815        /// Whether the call succeeded.
816        success: bool,
817    },
818    /// Result of an MCP tool call.
819    Mcp {
820        /// The result value returned by the MCP server.
821        result: Value,
822    },
823}
824
825impl ToolOutput {
826    /// Returns the tool's application-level success independently of transport.
827    ///
828    /// MCP success requires the top-level `isError` field to be omitted or the
829    /// literal boolean `false`; malformed present metadata fails closed.
830    pub fn success(&self) -> bool {
831        match self {
832            Self::Function { success, .. } => *success,
833            Self::Mcp { result } => {
834                matches!(result.get("isError"), None | Some(Value::Bool(false)))
835            }
836        }
837    }
838}
839
840/// Action to take for a network policy rule.
841#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
842#[serde(rename_all = "snake_case")]
843pub enum NetworkPolicyRuleAction {
844    /// Allow network access to the host.
845    Allow,
846    /// Deny network access to the host.
847    Deny,
848}
849
850/// A proposed amendment to the network access policy for a specific host.
851#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
852pub struct NetworkPolicyAmendment {
853    /// The host to amend the policy for.
854    pub host: String,
855    /// The action to apply.
856    pub action: NetworkPolicyRuleAction,
857}
858
859/// A user's decision on an approval request.
860#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
861#[serde(tag = "type", rename_all = "snake_case")]
862pub enum ReviewDecision {
863    /// Approve the action.
864    Approved,
865    /// Approve and also amend the execution policy.
866    ApprovedExecpolicyAmendment,
867    /// Approve for the remainder of this session only.
868    ApprovedForSession,
869    /// Approve with a network policy amendment.
870    NetworkPolicyAmendment {
871        host: String,
872        action: NetworkPolicyRuleAction,
873    },
874    /// Deny the action.
875    Denied,
876    /// Abort the entire turn.
877    Abort,
878}
879
880/// Status of an MCP server during startup.
881#[derive(Debug, Clone, Serialize, Deserialize)]
882#[serde(rename_all = "snake_case")]
883pub enum McpStartupStatus {
884    /// The server is in the process of starting.
885    Starting,
886    /// The server is ready to accept requests.
887    Ready,
888    /// The server failed to start.
889    Failed { error: String },
890    /// Startup was cancelled.
891    Cancelled,
892}
893
894/// A progress update for a single MCP server's startup.
895#[derive(Debug, Clone, Serialize, Deserialize)]
896pub struct McpStartupUpdateEvent {
897    /// Name of the MCP server.
898    pub server_name: String,
899    /// Current startup status.
900    pub status: McpStartupStatus,
901}
902
903/// Details of an MCP server that failed to start.
904#[derive(Debug, Clone, Serialize, Deserialize)]
905pub struct McpStartupFailure {
906    /// Name of the MCP server that failed.
907    pub server_name: String,
908    /// Error description.
909    pub error: String,
910}
911
912/// Summary event emitted once all MCP servers have finished starting.
913#[derive(Debug, Clone, Serialize, Deserialize)]
914pub struct McpStartupCompleteEvent {
915    /// Servers that started successfully.
916    pub ready: Vec<String>,
917    /// Servers that failed to start.
918    pub failed: Vec<McpStartupFailure>,
919    /// Servers whose startup was cancelled.
920    pub cancelled: Vec<String>,
921}
922
923/// Context about a network access request that requires approval.
924#[derive(Debug, Clone, Serialize, Deserialize)]
925pub struct NetworkApprovalContext {
926    /// The host being accessed.
927    pub host: String,
928    /// The network protocol (e.g. `"https"`, `"tcp"`).
929    pub protocol: String,
930}
931
932/// A selectable option presented to the user in a clarification question.
933///
934/// Headless serialization shape for the `request_user_input` model tool,
935/// mirrored after the TUI's `UserInputOption`. Shared by the
936/// [`EventFrame::UserInputRequest`] frame and the [`AppRequest::SubmitUserInput`]
937/// reply path so both surfaces agree on the question schema.
938#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
939pub struct UserInputOptionEvent {
940    /// Short label for the option (also the value submitted when picked).
941    pub label: String,
942    /// Longer description shown alongside the label.
943    pub description: String,
944}
945
946/// A single clarification question posed to the user.
947#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
948pub struct UserInputQuestionEvent {
949    /// Compact header shown as the question title.
950    pub header: String,
951    /// Stable identifier used to correlate answers back to this question.
952    pub id: String,
953    /// The question body.
954    pub question: String,
955    /// 2-4 suggested answers.
956    pub options: Vec<UserInputOptionEvent>,
957    /// When `true`, the client should also offer a free-text response.
958    #[serde(default)]
959    pub allow_free_text: bool,
960    /// When `true`, the user may select more than one option.
961    #[serde(default)]
962    pub multi_select: bool,
963}
964
965/// An event requesting structured user input via a model-tool call.
966///
967/// Sibling of [`ExecApprovalRequestEvent`] for the clarification-question
968/// flow. Emitted fire-and-return by `Runtime::invoke_tool` when the model
969/// invokes `request_user_input` in a headless context.
970#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
971pub struct UserInputRequestEvent {
972    /// Identifier of the tool call requesting input.
973    pub call_id: String,
974    /// The turn during which the request was made.
975    pub turn_id: String,
976    /// Unique identifier for this user-input request (clients reply with it).
977    pub request_id: String,
978    /// 1-3 questions to present.
979    pub questions: Vec<UserInputQuestionEvent>,
980}
981
982/// One answer to a clarification question.
983#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
984pub struct UserInputAnswerEvent {
985    /// The `id` of the question this answer corresponds to.
986    pub id: String,
987    /// The selected option's label, or `"Other"` for a free-text response.
988    pub label: String,
989    /// The resolved value (option label, or the typed free-text).
990    pub value: String,
991}
992
993/// An event requesting user approval for a command execution or patch application.
994#[derive(Debug, Clone, Serialize, Deserialize)]
995pub struct ExecApprovalRequestEvent {
996    /// Identifier of the tool call requesting approval.
997    pub call_id: String,
998    /// Unique identifier for this approval request.
999    pub approval_id: String,
1000    /// The turn during which the request was made.
1001    pub turn_id: String,
1002    /// The command that would be executed.
1003    pub command: String,
1004    /// The working directory for the command.
1005    pub cwd: String,
1006    /// Human-readable reason why approval is needed.
1007    pub reason: String,
1008    /// Policy rule that matched this approval request, when available.
1009    #[serde(default, skip_serializing_if = "Option::is_none")]
1010    pub matched_rule: Option<Box<str>>,
1011    /// Network context if the approval involves network access.
1012    #[serde(skip_serializing_if = "Option::is_none")]
1013    pub network_approval_context: Option<NetworkApprovalContext>,
1014    /// Proposed execution policy rule amendments.
1015    #[serde(default)]
1016    pub proposed_execpolicy_amendment: Vec<String>,
1017    /// Proposed network policy amendments.
1018    #[serde(default)]
1019    pub proposed_network_policy_amendments: Vec<NetworkPolicyAmendment>,
1020    /// Additional permissions being requested.
1021    #[serde(default)]
1022    pub additional_permissions: Vec<String>,
1023    /// The set of decisions the user can choose from.
1024    #[serde(default)]
1025    pub available_decisions: Vec<ReviewDecision>,
1026}
1027
1028/// The channel a response delta is being written to.
1029#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1030#[serde(rename_all = "snake_case")]
1031pub enum ResponseChannel {
1032    /// The main visible text output.
1033    #[default]
1034    Text,
1035    /// Internal reasoning / chain-of-thought output.
1036    Reasoning,
1037}
1038
1039impl ResponseChannel {
1040    /// Returns `true` if this is the `Text` channel.
1041    pub const fn is_text(&self) -> bool {
1042        matches!(self, ResponseChannel::Text)
1043    }
1044}
1045
1046/// A user's approval decision sent in response to an approval request.
1047#[derive(Debug, Clone, Serialize, Deserialize)]
1048pub struct ApprovalDecisionRequest {
1049    /// The decision identifier (e.g. `"approved"`, `"denied"`).
1050    pub decision: String,
1051    /// Whether to remember this decision for future similar requests.
1052    #[serde(default)]
1053    pub remember: bool,
1054}
1055
1056/// A single streaming event frame emitted during agent execution.
1057///
1058/// Events are tagged by the `event` field and cover the full lifecycle of a
1059/// turn: response streaming, tool calls, MCP lifecycle, command execution,
1060/// patch application, approvals, and errors.
1061#[derive(Debug, Clone, Serialize, Deserialize)]
1062#[serde(tag = "event", rename_all = "snake_case")]
1063pub enum EventFrame {
1064    /// A new model response has started.
1065    ResponseStart { response_id: String },
1066    /// A incremental text delta for an in-progress response.
1067    ResponseDelta {
1068        response_id: String,
1069        delta: String,
1070        #[serde(default, skip_serializing_if = "ResponseChannel::is_text")]
1071        channel: ResponseChannel,
1072    },
1073    /// The model response has finished.
1074    ResponseEnd { response_id: String },
1075    /// A tool call has begun.
1076    ToolCallStart {
1077        response_id: String,
1078        tool_name: String,
1079        arguments: Value,
1080    },
1081    /// A tool call has completed and produced a result.
1082    ToolCallResult {
1083        response_id: String,
1084        tool_name: String,
1085        output: Value,
1086    },
1087    /// Progress update for an MCP server starting up.
1088    McpStartupUpdate { update: McpStartupUpdateEvent },
1089    /// All MCP servers have finished starting.
1090    McpStartupComplete { summary: McpStartupCompleteEvent },
1091    /// An MCP tool call has begun.
1092    McpToolCallBegin {
1093        server_name: String,
1094        tool_name: String,
1095    },
1096    /// An MCP tool call has finished.
1097    McpToolCallEnd {
1098        server_name: String,
1099        tool_name: String,
1100        ok: bool,
1101    },
1102    /// User approval is needed for a command execution.
1103    ExecApprovalRequest { request: ExecApprovalRequestEvent },
1104    /// User approval is needed for applying a patch.
1105    ApplyPatchApprovalRequest { request: ExecApprovalRequestEvent },
1106    /// A model tool is requesting structured clarification input from the user.
1107    ///
1108    /// Headless sibling of the TUI's `request_user_input` modal flow.
1109    /// `request_id` correlates with an [`AppRequest::SubmitUserInput`] reply.
1110    UserInputRequest { request: UserInputRequestEvent },
1111    /// An MCP server is requesting user input (elicitation).
1112    ElicitationRequest {
1113        server_name: String,
1114        request_id: String,
1115        prompt: String,
1116    },
1117    /// A command has started executing.
1118    ExecCommandBegin { command: String, cwd: String },
1119    /// Incremental output from a running command.
1120    ExecCommandOutputDelta { command: String, delta: String },
1121    /// A command has finished executing.
1122    ExecCommandEnd { command: String, exit_code: i32 },
1123    /// A patch has started being applied to a file.
1124    PatchApplyBegin { path: String },
1125    /// A patch has finished being applied.
1126    PatchApplyEnd { path: String, ok: bool },
1127    /// A new turn has started within a thread.
1128    TurnStarted { turn_id: String },
1129    /// A turn has completed successfully.
1130    TurnComplete { turn_id: String },
1131    /// A turn was aborted before completion.
1132    TurnAborted { turn_id: String, reason: String },
1133    /// A thread goal was set or updated.
1134    ThreadGoalUpdated { goal: ThreadGoal },
1135    /// A thread goal was cleared.
1136    ThreadGoalCleared { thread_id: String },
1137    /// An error occurred during processing.
1138    Error {
1139        response_id: String,
1140        message: String,
1141    },
1142}
1143
1144pub mod request;
1145pub mod role;
1146
1147/// Pure provenance data shared by hosts and portable status reports.
1148pub mod cloud_facts;
1149
1150pub mod display;