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 avatar;
15pub mod engine_owner;
16pub mod event_msg;
17pub mod fleet;
18pub mod ids;
19pub mod journal;
20pub mod op;
21pub mod placement;
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)]
528#[serde(deny_unknown_fields)]
529pub struct ThreadListParams {
530    #[serde(default)]
531    pub include_archived: bool,
532    #[serde(skip_serializing_if = "Option::is_none")]
533    pub limit: Option<usize>,
534}
535
536#[derive(Debug, Clone, Serialize, Deserialize)]
537#[serde(deny_unknown_fields)]
538pub struct ThreadReadParams {
539    pub thread_id: String,
540}
541
542#[derive(Debug, Clone, Serialize, Deserialize)]
543pub struct ThreadSetNameParams {
544    pub thread_id: String,
545    pub name: String,
546}
547
548#[derive(Debug, Clone, Serialize, Deserialize)]
549pub struct ThreadGoalSetParams {
550    pub thread_id: String,
551    pub objective: String,
552    #[serde(skip_serializing_if = "Option::is_none")]
553    pub token_budget: Option<i64>,
554}
555
556#[derive(Debug, Clone, Serialize, Deserialize)]
557pub struct ThreadGoalGetParams {
558    pub thread_id: String,
559}
560
561#[derive(Debug, Clone, Serialize, Deserialize)]
562pub struct ThreadGoalClearParams {
563    pub thread_id: String,
564}
565
566#[derive(Debug, Clone, Serialize, Deserialize)]
567pub struct ThreadGoalProgressParams {
568    pub thread_id: String,
569    #[serde(default)]
570    pub token_delta: i64,
571    #[serde(default)]
572    pub time_delta_seconds: i64,
573    #[serde(default)]
574    pub record_continuation: bool,
575}
576
577#[derive(Debug, Clone, Serialize, Deserialize)]
578#[serde(tag = "kind", rename_all = "snake_case")]
579pub enum ThreadRequest {
580    Create {
581        #[serde(default)]
582        metadata: Value,
583    },
584    Start(ThreadStartParams),
585    Resume(ThreadResumeParams),
586    Fork(ThreadForkParams),
587    List(ThreadListParams),
588    Read(ThreadReadParams),
589    SetName(ThreadSetNameParams),
590    GoalSet(ThreadGoalSetParams),
591    GoalGet(ThreadGoalGetParams),
592    GoalClear(ThreadGoalClearParams),
593    GoalRecordProgress(ThreadGoalProgressParams),
594    Archive {
595        thread_id: String,
596    },
597    Unarchive {
598        thread_id: String,
599    },
600    Message {
601        thread_id: String,
602        input: String,
603        #[serde(default, skip_serializing_if = "Option::is_none")]
604        allowed_tools: Option<Vec<String>>,
605        #[serde(default, skip_serializing_if = "Vec::is_empty")]
606        images: Vec<codewhale_app_server_protocol::runtime::RuntimeImageInput>,
607        #[serde(
608            default,
609            rename = "maxOutputTokens",
610            alias = "max_output_tokens",
611            skip_serializing_if = "Option::is_none"
612        )]
613        max_output_tokens: Option<std::num::NonZeroU32>,
614    },
615}
616
617/// Response to a [`ThreadRequest`].
618#[derive(Debug, Clone, Serialize, Deserialize)]
619pub struct ThreadResponse {
620    /// The thread this response pertains to.
621    pub thread_id: String,
622    /// Human-readable status string (e.g. `"ok"`, `"error"`).
623    pub status: String,
624    /// The thread details, when a single thread is returned.
625    #[serde(skip_serializing_if = "Option::is_none")]
626    pub thread: Option<Thread>,
627    /// List of threads, populated by `List` requests.
628    #[serde(default)]
629    pub threads: Vec<Thread>,
630    /// Thread goal returned by goal get/set requests.
631    #[serde(skip_serializing_if = "Option::is_none")]
632    pub goal: Option<ThreadGoal>,
633    /// The model used for the thread, if applicable.
634    #[serde(skip_serializing_if = "Option::is_none")]
635    pub model: Option<String>,
636    /// The model provider used for the thread.
637    #[serde(skip_serializing_if = "Option::is_none")]
638    pub model_provider: Option<String>,
639    /// The working directory of the thread.
640    #[serde(skip_serializing_if = "Option::is_none")]
641    pub cwd: Option<PathBuf>,
642    /// The active approval policy.
643    #[serde(skip_serializing_if = "Option::is_none")]
644    pub approval_policy: Option<String>,
645    /// The active sandbox configuration.
646    #[serde(skip_serializing_if = "Option::is_none")]
647    pub sandbox: Option<String>,
648    /// Streaming events associated with this response.
649    #[serde(default)]
650    pub events: Vec<EventFrame>,
651    /// Arbitrary additional response data.
652    #[serde(default)]
653    pub data: Value,
654}
655
656/// Application-level requests that are not tied to a specific thread.
657#[derive(Debug, Clone, Serialize, Deserialize)]
658#[serde(tag = "kind", rename_all = "snake_case")]
659pub enum AppRequest {
660    /// Query the server's capabilities.
661    Capabilities,
662    /// Read a configuration value by key.
663    ConfigGet { key: String },
664    /// Set a configuration key to a value.
665    ConfigSet { key: String, value: String },
666    /// Remove a configuration key.
667    ConfigUnset { key: String },
668    /// List all configuration entries.
669    ConfigList,
670    /// Reload configuration from disk and apply to the live runtime.
671    ///
672    /// Re-reads both `config.toml` and the sibling `permissions.toml`,
673    /// refreshing the live `Runtime.config` and `Runtime.exec_policy`
674    /// so headless clients can pick up external config-file *and*
675    /// permission-rule edits without restarting.
676    ///
677    /// Mirrors the TUI `reload_runtime_config` codepath for everything
678    /// reachable from the headless `Runtime`. MCP server connections
679    /// are not refreshed โ€” changing `mcp_config_path` or the referenced
680    /// `mcp.json` still requires a headless-runtime restart. The TUI's
681    /// explicit `/mcp reload` operation is not part of this protocol path.
682    ConfigReload,
683    /// List available models.
684    Models,
685    /// List threads that are currently loaded in memory.
686    ThreadLoadedList,
687    /// Submit answers to a prior [`EventFrame::UserInputRequest`].
688    ///
689    /// `request_id` must match a pending clarification request. Headless
690    /// clients use this to return the user's selections back to the runtime.
691    SubmitUserInput {
692        request_id: String,
693        answers: Vec<UserInputAnswerEvent>,
694    },
695}
696
697/// Response to an [`AppRequest`].
698#[derive(Debug, Clone, Serialize, Deserialize)]
699pub struct AppResponse {
700    /// Whether the request succeeded.
701    pub ok: bool,
702    /// The response payload.
703    pub data: Value,
704    /// Streaming events associated with this response.
705    #[serde(default)]
706    pub events: Vec<EventFrame>,
707}
708
709/// A simple prompt request that sends text to the model and returns output.
710#[derive(Debug, Clone, Serialize, Deserialize)]
711pub struct PromptRequest {
712    #[serde(default, skip_serializing_if = "Option::is_none")]
713    pub allowed_tools: Option<Vec<String>>,
714    #[serde(
715        default,
716        rename = "maxOutputTokens",
717        alias = "max_output_tokens",
718        skip_serializing_if = "Option::is_none"
719    )]
720    pub max_output_tokens: Option<std::num::NonZeroU32>,
721    /// Optional thread context for the prompt.
722    #[serde(skip_serializing_if = "Option::is_none")]
723    pub thread_id: Option<String>,
724    /// The prompt text.
725    pub prompt: String,
726    #[serde(default, skip_serializing_if = "Vec::is_empty")]
727    pub images: Vec<codewhale_app_server_protocol::runtime::RuntimeImageInput>,
728    /// Model override, or the default if omitted.
729    #[serde(skip_serializing_if = "Option::is_none")]
730    pub model: Option<String>,
731}
732
733/// Response to a [`PromptRequest`].
734#[derive(Debug, Clone, Serialize, Deserialize)]
735pub struct PromptResponse {
736    /// The model's output text.
737    pub output: String,
738    /// The model that produced the output.
739    pub model: String,
740    /// Streaming events associated with this response.
741    #[serde(default)]
742    pub events: Vec<EventFrame>,
743}
744
745/// Policy controlling when the agent must ask the user for approval before acting.
746#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
747#[serde(rename_all = "snake_case")]
748pub enum AskForApproval {
749    /// Ask for approval unless the action is on a trusted path/resource.
750    UnlessTrusted,
751    /// Only ask after a tool call fails.
752    OnFailure,
753    /// Ask every time a tool call is requested.
754    OnRequest,
755    /// Reject the action without asking, with details on which categories are blocked.
756    Reject {
757        sandbox_approval: bool,
758        rules: bool,
759        mcp_elicitations: bool,
760    },
761    /// Never ask; auto-approve all actions.
762    Never,
763}
764
765/// Classification of tool invocation origin.
766#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
767#[serde(rename_all = "snake_case")]
768pub enum ToolKind {
769    /// A built-in function tool.
770    Function,
771    /// An MCP (Model Context Protocol) tool.
772    Mcp,
773}
774
775/// Parameters for executing a local shell command.
776#[derive(Debug, Clone, Serialize, Deserialize)]
777pub struct LocalShellParams {
778    /// The shell command to execute.
779    pub command: String,
780    /// Working directory for the command.
781    #[serde(skip_serializing_if = "Option::is_none")]
782    pub cwd: Option<String>,
783    /// Timeout in milliseconds.
784    #[serde(skip_serializing_if = "Option::is_none")]
785    pub timeout_ms: Option<u64>,
786}
787
788/// The payload of a tool call, discriminated by tool type.
789#[derive(Debug, Clone, Serialize, Deserialize)]
790#[serde(tag = "type", rename_all = "snake_case")]
791pub enum ToolPayload {
792    /// A built-in function call with JSON-encoded arguments.
793    Function { arguments: String },
794    /// A custom tool invocation with a free-form input string.
795    Custom { input: String },
796    /// A local shell command execution.
797    LocalShell { params: LocalShellParams },
798    /// An MCP tool invocation targeting a specific server and tool.
799    Mcp {
800        server: String,
801        tool: String,
802        raw_arguments: Value,
803        #[serde(skip_serializing_if = "Option::is_none")]
804        raw_tool_call_id: Option<String>,
805    },
806}
807
808/// The result of a tool call, discriminated by tool type.
809#[derive(Debug, Clone, Serialize, Deserialize)]
810#[serde(tag = "type", rename_all = "snake_case")]
811pub enum ToolOutput {
812    /// Result of a built-in function call.
813    Function {
814        /// The output body, if any.
815        #[serde(skip_serializing_if = "Option::is_none")]
816        body: Option<Value>,
817        /// Whether the call succeeded.
818        success: bool,
819    },
820    /// Result of an MCP tool call.
821    Mcp {
822        /// The result value returned by the MCP server.
823        result: Value,
824    },
825}
826
827impl ToolOutput {
828    /// Returns the tool's application-level success independently of transport.
829    ///
830    /// MCP success requires the top-level `isError` field to be omitted or the
831    /// literal boolean `false`; malformed present metadata fails closed.
832    pub fn success(&self) -> bool {
833        match self {
834            Self::Function { success, .. } => *success,
835            Self::Mcp { result } => {
836                matches!(result.get("isError"), None | Some(Value::Bool(false)))
837            }
838        }
839    }
840}
841
842/// Action to take for a network policy rule.
843#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
844#[serde(rename_all = "snake_case")]
845pub enum NetworkPolicyRuleAction {
846    /// Allow network access to the host.
847    Allow,
848    /// Deny network access to the host.
849    Deny,
850}
851
852/// A proposed amendment to the network access policy for a specific host.
853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
854pub struct NetworkPolicyAmendment {
855    /// The host to amend the policy for.
856    pub host: String,
857    /// The action to apply.
858    pub action: NetworkPolicyRuleAction,
859}
860
861/// A user's decision on an approval request.
862#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
863#[serde(tag = "type", rename_all = "snake_case")]
864pub enum ReviewDecision {
865    /// Approve the action.
866    Approved,
867    /// Approve and also amend the execution policy.
868    ApprovedExecpolicyAmendment,
869    /// Approve for the remainder of this session only.
870    ApprovedForSession,
871    /// Approve with a network policy amendment.
872    NetworkPolicyAmendment {
873        host: String,
874        action: NetworkPolicyRuleAction,
875    },
876    /// Deny the action.
877    Denied,
878    /// Abort the entire turn.
879    Abort,
880}
881
882/// Status of an MCP server during startup.
883#[derive(Debug, Clone, Serialize, Deserialize)]
884#[serde(rename_all = "snake_case")]
885pub enum McpStartupStatus {
886    /// The server is in the process of starting.
887    Starting,
888    /// The server is ready to accept requests.
889    Ready,
890    /// The server failed to start.
891    Failed { error: String },
892    /// Startup was cancelled.
893    Cancelled,
894}
895
896/// A progress update for a single MCP server's startup.
897#[derive(Debug, Clone, Serialize, Deserialize)]
898pub struct McpStartupUpdateEvent {
899    /// Name of the MCP server.
900    pub server_name: String,
901    /// Current startup status.
902    pub status: McpStartupStatus,
903}
904
905/// Details of an MCP server that failed to start.
906#[derive(Debug, Clone, Serialize, Deserialize)]
907pub struct McpStartupFailure {
908    /// Name of the MCP server that failed.
909    pub server_name: String,
910    /// Error description.
911    pub error: String,
912}
913
914/// Summary event emitted once all MCP servers have finished starting.
915#[derive(Debug, Clone, Serialize, Deserialize)]
916pub struct McpStartupCompleteEvent {
917    /// Servers that started successfully.
918    pub ready: Vec<String>,
919    /// Servers that failed to start.
920    pub failed: Vec<McpStartupFailure>,
921    /// Servers whose startup was cancelled.
922    pub cancelled: Vec<String>,
923}
924
925/// Context about a network access request that requires approval.
926#[derive(Debug, Clone, Serialize, Deserialize)]
927pub struct NetworkApprovalContext {
928    /// The host being accessed.
929    pub host: String,
930    /// The network protocol (e.g. `"https"`, `"tcp"`).
931    pub protocol: String,
932}
933
934/// A selectable option presented to the user in a clarification question.
935///
936/// Headless serialization shape for the `request_user_input` model tool,
937/// mirrored after the TUI's `UserInputOption`. Shared by the
938/// [`EventFrame::UserInputRequest`] frame and the [`AppRequest::SubmitUserInput`]
939/// reply path so both surfaces agree on the question schema.
940#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
941pub struct UserInputOptionEvent {
942    /// Short label for the option (also the value submitted when picked).
943    pub label: String,
944    /// Longer description shown alongside the label.
945    #[serde(default)]
946    pub description: String,
947}
948
949#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
950#[serde(tag = "kind", rename_all = "kebab-case")]
951pub enum UserInputIntentEvent {
952    PlanReview {
953        approve: String,
954        #[serde(default, skip_serializing_if = "Option::is_none")]
955        call_id: Option<String>,
956    },
957}
958
959#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
960#[serde(rename_all = "snake_case")]
961pub enum UserInputAnswerKindEvent {
962    Choice,
963    Custom,
964    Skipped,
965}
966
967/// A single clarification question posed to the user.
968#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
969pub struct UserInputQuestionEvent {
970    /// Compact header shown as the question title.
971    #[serde(default)]
972    pub header: String,
973    /// Stable identifier used to correlate answers back to this question.
974    pub id: String,
975    /// The question body.
976    pub question: String,
977    #[serde(default, skip_serializing_if = "Option::is_none")]
978    pub detail: Option<String>,
979    #[serde(default, skip_serializing_if = "Option::is_none")]
980    pub intent: Option<UserInputIntentEvent>,
981    #[serde(default)]
982    pub options: Vec<UserInputOptionEvent>,
983    /// When `true`, the client should also offer a free-text response.
984    #[serde(default)]
985    pub allow_free_text: bool,
986    /// When `true`, the user may select more than one option.
987    #[serde(default)]
988    pub multi_select: bool,
989}
990
991/// An event requesting structured user input via a model-tool call.
992///
993/// Sibling of [`ExecApprovalRequestEvent`] for the clarification-question
994/// flow. Emitted fire-and-return by `Runtime::invoke_tool` when the model
995/// invokes `request_user_input` in a headless context.
996#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
997pub struct UserInputRequestEvent {
998    /// Identifier of the tool call requesting input.
999    pub call_id: String,
1000    /// The turn during which the request was made.
1001    pub turn_id: String,
1002    /// Unique identifier for this user-input request (clients reply with it).
1003    pub request_id: String,
1004    #[serde(default)]
1005    pub require_typed_answers: bool,
1006    pub questions: Vec<UserInputQuestionEvent>,
1007}
1008
1009/// One answer to a clarification question.
1010#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1011pub struct UserInputAnswerEvent {
1012    #[serde(default, skip_serializing_if = "Option::is_none")]
1013    pub kind: Option<UserInputAnswerKindEvent>,
1014    /// The `id` of the question this answer corresponds to.
1015    pub id: String,
1016    /// The selected option's label, or empty for typed custom/skip responses.
1017    pub label: String,
1018    /// The resolved value (option label, or the typed free-text).
1019    pub value: String,
1020}
1021
1022/// An event requesting user approval for a command execution or patch application.
1023#[derive(Debug, Clone, Serialize, Deserialize)]
1024pub struct ExecApprovalRequestEvent {
1025    /// Identifier of the tool call requesting approval.
1026    pub call_id: String,
1027    /// Unique identifier for this approval request.
1028    pub approval_id: String,
1029    /// The turn during which the request was made.
1030    pub turn_id: String,
1031    /// The command that would be executed.
1032    pub command: String,
1033    /// The working directory for the command.
1034    pub cwd: String,
1035    /// Human-readable reason why approval is needed.
1036    pub reason: String,
1037    /// Policy rule that matched this approval request, when available.
1038    #[serde(default, skip_serializing_if = "Option::is_none")]
1039    pub matched_rule: Option<Box<str>>,
1040    /// Network context if the approval involves network access.
1041    #[serde(skip_serializing_if = "Option::is_none")]
1042    pub network_approval_context: Option<NetworkApprovalContext>,
1043    /// Proposed execution policy rule amendments.
1044    #[serde(default)]
1045    pub proposed_execpolicy_amendment: Vec<String>,
1046    /// Proposed network policy amendments.
1047    #[serde(default)]
1048    pub proposed_network_policy_amendments: Vec<NetworkPolicyAmendment>,
1049    /// Additional permissions being requested.
1050    #[serde(default)]
1051    pub additional_permissions: Vec<String>,
1052    /// The set of decisions the user can choose from.
1053    #[serde(default)]
1054    pub available_decisions: Vec<ReviewDecision>,
1055}
1056
1057/// The channel a response delta is being written to.
1058#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1059#[serde(rename_all = "snake_case")]
1060pub enum ResponseChannel {
1061    /// The main visible text output.
1062    #[default]
1063    Text,
1064    /// Internal reasoning / chain-of-thought output.
1065    Reasoning,
1066}
1067
1068impl ResponseChannel {
1069    /// Returns `true` if this is the `Text` channel.
1070    pub const fn is_text(&self) -> bool {
1071        matches!(self, ResponseChannel::Text)
1072    }
1073}
1074
1075/// A user's approval decision sent in response to an approval request.
1076#[derive(Debug, Clone, Serialize, Deserialize)]
1077pub struct ApprovalDecisionRequest {
1078    /// The decision identifier (e.g. `"approved"`, `"denied"`).
1079    pub decision: String,
1080    /// Whether to remember this decision for future similar requests.
1081    #[serde(default)]
1082    pub remember: bool,
1083}
1084
1085/// A single streaming event frame emitted during agent execution.
1086///
1087/// Events are tagged by the `event` field and cover the full lifecycle of a
1088/// turn: response streaming, tool calls, MCP lifecycle, command execution,
1089/// patch application, approvals, and errors.
1090#[derive(Debug, Clone, Serialize, Deserialize)]
1091#[serde(tag = "event", rename_all = "snake_case")]
1092pub enum EventFrame {
1093    /// A new model response has started.
1094    ResponseStart { response_id: String },
1095    /// A incremental text delta for an in-progress response.
1096    ResponseDelta {
1097        response_id: String,
1098        delta: String,
1099        #[serde(default, skip_serializing_if = "ResponseChannel::is_text")]
1100        channel: ResponseChannel,
1101    },
1102    /// The model response has finished.
1103    ResponseEnd { response_id: String },
1104    /// A tool call has begun.
1105    ToolCallStart {
1106        response_id: String,
1107        tool_name: String,
1108        arguments: Value,
1109    },
1110    /// A tool call has completed and produced a result.
1111    ToolCallResult {
1112        response_id: String,
1113        tool_name: String,
1114        output: Value,
1115    },
1116    /// Progress update for an MCP server starting up.
1117    McpStartupUpdate { update: McpStartupUpdateEvent },
1118    /// All MCP servers have finished starting.
1119    McpStartupComplete { summary: McpStartupCompleteEvent },
1120    /// An MCP tool call has begun.
1121    McpToolCallBegin {
1122        server_name: String,
1123        tool_name: String,
1124    },
1125    /// An MCP tool call has finished.
1126    McpToolCallEnd {
1127        server_name: String,
1128        tool_name: String,
1129        ok: bool,
1130    },
1131    /// User approval is needed for a command execution.
1132    ExecApprovalRequest { request: ExecApprovalRequestEvent },
1133    /// User approval is needed for applying a patch.
1134    ApplyPatchApprovalRequest { request: ExecApprovalRequestEvent },
1135    /// A model tool is requesting structured clarification input from the user.
1136    ///
1137    /// Headless sibling of the TUI's `request_user_input` modal flow.
1138    /// `request_id` correlates with an [`AppRequest::SubmitUserInput`] reply.
1139    UserInputRequest { request: UserInputRequestEvent },
1140    /// An MCP server is requesting user input (elicitation).
1141    ElicitationRequest {
1142        server_name: String,
1143        request_id: String,
1144        prompt: String,
1145    },
1146    /// A command has started executing.
1147    ExecCommandBegin { command: String, cwd: String },
1148    /// Incremental output from a running command.
1149    ExecCommandOutputDelta { command: String, delta: String },
1150    /// A command has finished executing.
1151    ExecCommandEnd { command: String, exit_code: i32 },
1152    /// A patch has started being applied to a file.
1153    PatchApplyBegin { path: String },
1154    /// A patch has finished being applied.
1155    PatchApplyEnd { path: String, ok: bool },
1156    /// A new turn has started within a thread.
1157    TurnStarted { turn_id: String },
1158    /// A turn has completed successfully.
1159    TurnComplete { turn_id: String },
1160    /// A turn was aborted before completion.
1161    TurnAborted { turn_id: String, reason: String },
1162    /// A thread goal was set or updated.
1163    ThreadGoalUpdated { goal: ThreadGoal },
1164    /// A thread goal was cleared.
1165    ThreadGoalCleared { thread_id: String },
1166    /// An error occurred during processing.
1167    Error {
1168        response_id: String,
1169        message: String,
1170    },
1171}
1172
1173pub mod request;
1174pub mod role;
1175
1176/// Pure provenance data shared by hosts and portable status reports.
1177pub mod cloud_facts;
1178
1179pub mod display;