1#![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
22pub trait Status {
28 fn is_terminal(&self) -> bool;
31
32 fn is_active(&self) -> bool;
35
36 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 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub last_gap_fingerprint: Option<String>,
138 #[serde(default)]
139 pub repeated_gap_count: u32,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub last_gap_pass: Option<u32>,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub pause_reason: Option<GoalPauseReason>,
144}
145
146#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
148#[serde(rename_all = "snake_case")]
149pub enum GoalPauseReason {
150 User,
151 Backoff,
152 NoProgress,
153 UsageLimit,
154 BudgetLimit,
155}
156
157impl GoalPauseReason {
158 #[must_use]
159 pub fn label(self) -> &'static str {
160 match self {
161 Self::User => "user",
162 Self::Backoff => "run limit",
163 Self::NoProgress => "no progress",
164 Self::UsageLimit => "usage limit",
165 Self::BudgetLimit => "budget limit",
166 }
167 }
168}
169
170pub const MAX_REPEATED_GAP_COUNT: u32 = 3;
173
174pub fn validate_goal_stall_state(
175 fingerprint: Option<&str>,
176 count: u32,
177 pass: Option<u32>,
178 continuation_count: u32,
179) -> Result<(), &'static str> {
180 match (fingerprint, count, pass) {
181 (None, 0, None) => Ok(()),
182 (Some(digest), 1..=MAX_REPEATED_GAP_COUNT, Some(pass))
183 if digest.len() == 64
184 && digest.bytes().all(|byte| byte.is_ascii_hexdigit())
185 && pass <= continuation_count
186 && count <= pass.saturating_add(1) =>
187 {
188 Ok(())
189 }
190 _ => Err("invalid persisted goal stall history"),
191 }
192}
193
194impl ThreadGoal {
195 pub fn validate_stall_state(&self) -> Result<(), &'static str> {
196 validate_goal_stall_state(
197 self.last_gap_fingerprint.as_deref(),
198 self.repeated_gap_count,
199 self.last_gap_pass,
200 u32::try_from(self.continuation_count.max(0)).unwrap_or(u32::MAX),
201 )
202 }
203
204 pub fn normalize_restored_stall_state(&mut self) -> bool {
210 if matches!(self.status, ThreadGoalStatus::Active)
211 && self.repeated_gap_count >= MAX_REPEATED_GAP_COUNT
212 {
213 self.status = ThreadGoalStatus::Paused;
214 self.pause_reason = Some(GoalPauseReason::NoProgress);
215 true
216 } else {
217 false
218 }
219 }
220}
221
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct ThreadStartParams {
224 #[serde(skip_serializing_if = "Option::is_none")]
225 pub model: Option<String>,
226 #[serde(skip_serializing_if = "Option::is_none")]
227 pub model_provider: Option<String>,
228 #[serde(skip_serializing_if = "Option::is_none")]
229 pub cwd: Option<PathBuf>,
230 #[serde(default)]
231 pub persist_extended_history: bool,
232}
233
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct ThreadResumeParams {
236 pub thread_id: String,
237 #[serde(skip_serializing_if = "Option::is_none")]
238 pub history: Option<Vec<Value>>,
239 #[serde(skip_serializing_if = "Option::is_none")]
240 pub path: Option<PathBuf>,
241 #[serde(skip_serializing_if = "Option::is_none")]
242 pub model: Option<String>,
243 #[serde(skip_serializing_if = "Option::is_none")]
244 pub model_provider: Option<String>,
245 #[serde(skip_serializing_if = "Option::is_none")]
246 pub cwd: Option<PathBuf>,
247 #[serde(skip_serializing_if = "Option::is_none")]
248 pub approval_policy: Option<String>,
249 #[serde(skip_serializing_if = "Option::is_none")]
250 pub sandbox: Option<String>,
251 #[serde(skip_serializing_if = "Option::is_none")]
252 pub config: Option<Value>,
253 #[serde(skip_serializing_if = "Option::is_none")]
254 pub base_instructions: Option<String>,
255 #[serde(skip_serializing_if = "Option::is_none")]
256 pub developer_instructions: Option<String>,
257 #[serde(skip_serializing_if = "Option::is_none")]
258 pub personality: Option<String>,
259 #[serde(default)]
260 pub persist_extended_history: bool,
261}
262
263#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct ThreadForkParams {
265 pub thread_id: String,
266 #[serde(skip_serializing_if = "Option::is_none")]
267 pub path: Option<PathBuf>,
268 #[serde(skip_serializing_if = "Option::is_none")]
269 pub model: Option<String>,
270 #[serde(skip_serializing_if = "Option::is_none")]
271 pub model_provider: Option<String>,
272 #[serde(skip_serializing_if = "Option::is_none")]
273 pub cwd: Option<PathBuf>,
274 #[serde(skip_serializing_if = "Option::is_none")]
275 pub approval_policy: Option<String>,
276 #[serde(skip_serializing_if = "Option::is_none")]
277 pub sandbox: Option<String>,
278 #[serde(skip_serializing_if = "Option::is_none")]
279 pub config: Option<Value>,
280 #[serde(skip_serializing_if = "Option::is_none")]
281 pub base_instructions: Option<String>,
282 #[serde(skip_serializing_if = "Option::is_none")]
283 pub developer_instructions: Option<String>,
284 #[serde(default)]
285 pub persist_extended_history: bool,
286}
287
288#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct ThreadListParams {
290 #[serde(default)]
291 pub include_archived: bool,
292 #[serde(skip_serializing_if = "Option::is_none")]
293 pub limit: Option<usize>,
294}
295
296#[derive(Debug, Clone, Serialize, Deserialize)]
297pub struct ThreadReadParams {
298 pub thread_id: String,
299}
300
301#[derive(Debug, Clone, Serialize, Deserialize)]
302pub struct ThreadSetNameParams {
303 pub thread_id: String,
304 pub name: String,
305}
306
307#[derive(Debug, Clone, Serialize, Deserialize)]
308pub struct ThreadGoalSetParams {
309 pub thread_id: String,
310 pub objective: String,
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub token_budget: Option<i64>,
313}
314
315#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct ThreadGoalGetParams {
317 pub thread_id: String,
318}
319
320#[derive(Debug, Clone, Serialize, Deserialize)]
321pub struct ThreadGoalClearParams {
322 pub thread_id: String,
323}
324
325#[derive(Debug, Clone, Serialize, Deserialize)]
326pub struct ThreadGoalProgressParams {
327 pub thread_id: String,
328 #[serde(default)]
329 pub token_delta: i64,
330 #[serde(default)]
331 pub time_delta_seconds: i64,
332 #[serde(default)]
333 pub record_continuation: bool,
334}
335
336#[derive(Debug, Clone, Serialize, Deserialize)]
337#[serde(tag = "kind", rename_all = "snake_case")]
338pub enum ThreadRequest {
339 Create {
340 #[serde(default)]
341 metadata: Value,
342 },
343 Start(ThreadStartParams),
344 Resume(ThreadResumeParams),
345 Fork(ThreadForkParams),
346 List(ThreadListParams),
347 Read(ThreadReadParams),
348 SetName(ThreadSetNameParams),
349 GoalSet(ThreadGoalSetParams),
350 GoalGet(ThreadGoalGetParams),
351 GoalClear(ThreadGoalClearParams),
352 GoalRecordProgress(ThreadGoalProgressParams),
353 Archive {
354 thread_id: String,
355 },
356 Unarchive {
357 thread_id: String,
358 },
359 Message {
360 thread_id: String,
361 input: String,
362 #[serde(default, skip_serializing_if = "Vec::is_empty")]
363 images: Vec<runtime::RuntimeImageInput>,
364 #[serde(
365 default,
366 rename = "maxOutputTokens",
367 alias = "max_output_tokens",
368 skip_serializing_if = "Option::is_none"
369 )]
370 max_output_tokens: Option<std::num::NonZeroU32>,
371 },
372}
373
374#[derive(Debug, Clone, Serialize, Deserialize)]
376pub struct ThreadResponse {
377 pub thread_id: String,
379 pub status: String,
381 #[serde(skip_serializing_if = "Option::is_none")]
383 pub thread: Option<Thread>,
384 #[serde(default)]
386 pub threads: Vec<Thread>,
387 #[serde(skip_serializing_if = "Option::is_none")]
389 pub goal: Option<ThreadGoal>,
390 #[serde(skip_serializing_if = "Option::is_none")]
392 pub model: Option<String>,
393 #[serde(skip_serializing_if = "Option::is_none")]
395 pub model_provider: Option<String>,
396 #[serde(skip_serializing_if = "Option::is_none")]
398 pub cwd: Option<PathBuf>,
399 #[serde(skip_serializing_if = "Option::is_none")]
401 pub approval_policy: Option<String>,
402 #[serde(skip_serializing_if = "Option::is_none")]
404 pub sandbox: Option<String>,
405 #[serde(default)]
407 pub events: Vec<EventFrame>,
408 #[serde(default)]
410 pub data: Value,
411}
412
413#[derive(Debug, Clone, Serialize, Deserialize)]
415#[serde(tag = "kind", rename_all = "snake_case")]
416pub enum AppRequest {
417 Capabilities,
419 ConfigGet { key: String },
421 ConfigSet { key: String, value: String },
423 ConfigUnset { key: String },
425 ConfigList,
427 ConfigReload,
440 Models,
442 ThreadLoadedList,
444 SubmitUserInput {
449 request_id: String,
450 answers: Vec<UserInputAnswerEvent>,
451 },
452}
453
454#[derive(Debug, Clone, Serialize, Deserialize)]
456pub struct AppResponse {
457 pub ok: bool,
459 pub data: Value,
461 #[serde(default)]
463 pub events: Vec<EventFrame>,
464}
465
466#[derive(Debug, Clone, Serialize, Deserialize)]
468pub struct PromptRequest {
469 #[serde(
470 default,
471 rename = "maxOutputTokens",
472 alias = "max_output_tokens",
473 skip_serializing_if = "Option::is_none"
474 )]
475 pub max_output_tokens: Option<std::num::NonZeroU32>,
476 #[serde(skip_serializing_if = "Option::is_none")]
478 pub thread_id: Option<String>,
479 pub prompt: String,
481 #[serde(default, skip_serializing_if = "Vec::is_empty")]
482 pub images: Vec<runtime::RuntimeImageInput>,
483 #[serde(skip_serializing_if = "Option::is_none")]
485 pub model: Option<String>,
486}
487
488#[derive(Debug, Clone, Serialize, Deserialize)]
490pub struct PromptResponse {
491 pub output: String,
493 pub model: String,
495 #[serde(default)]
497 pub events: Vec<EventFrame>,
498}
499
500#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
502#[serde(rename_all = "snake_case")]
503pub enum AskForApproval {
504 UnlessTrusted,
506 OnFailure,
508 OnRequest,
510 Reject {
512 sandbox_approval: bool,
513 rules: bool,
514 mcp_elicitations: bool,
515 },
516 Never,
518}
519
520#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
522#[serde(rename_all = "snake_case")]
523pub enum ToolKind {
524 Function,
526 Mcp,
528}
529
530#[derive(Debug, Clone, Serialize, Deserialize)]
532pub struct LocalShellParams {
533 pub command: String,
535 #[serde(skip_serializing_if = "Option::is_none")]
537 pub cwd: Option<String>,
538 #[serde(skip_serializing_if = "Option::is_none")]
540 pub timeout_ms: Option<u64>,
541}
542
543#[derive(Debug, Clone, Serialize, Deserialize)]
545#[serde(tag = "type", rename_all = "snake_case")]
546pub enum ToolPayload {
547 Function { arguments: String },
549 Custom { input: String },
551 LocalShell { params: LocalShellParams },
553 Mcp {
555 server: String,
556 tool: String,
557 raw_arguments: Value,
558 #[serde(skip_serializing_if = "Option::is_none")]
559 raw_tool_call_id: Option<String>,
560 },
561}
562
563#[derive(Debug, Clone, Serialize, Deserialize)]
565#[serde(tag = "type", rename_all = "snake_case")]
566pub enum ToolOutput {
567 Function {
569 #[serde(skip_serializing_if = "Option::is_none")]
571 body: Option<Value>,
572 success: bool,
574 },
575 Mcp {
577 result: Value,
579 },
580}
581
582impl ToolOutput {
583 pub fn success(&self) -> bool {
588 match self {
589 Self::Function { success, .. } => *success,
590 Self::Mcp { result } => {
591 matches!(result.get("isError"), None | Some(Value::Bool(false)))
592 }
593 }
594 }
595}
596
597#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
599#[serde(rename_all = "snake_case")]
600pub enum NetworkPolicyRuleAction {
601 Allow,
603 Deny,
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
609pub struct NetworkPolicyAmendment {
610 pub host: String,
612 pub action: NetworkPolicyRuleAction,
614}
615
616#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
618#[serde(tag = "type", rename_all = "snake_case")]
619pub enum ReviewDecision {
620 Approved,
622 ApprovedExecpolicyAmendment,
624 ApprovedForSession,
626 NetworkPolicyAmendment {
628 host: String,
629 action: NetworkPolicyRuleAction,
630 },
631 Denied,
633 Abort,
635}
636
637#[derive(Debug, Clone, Serialize, Deserialize)]
639#[serde(rename_all = "snake_case")]
640pub enum McpStartupStatus {
641 Starting,
643 Ready,
645 Failed { error: String },
647 Cancelled,
649}
650
651#[derive(Debug, Clone, Serialize, Deserialize)]
653pub struct McpStartupUpdateEvent {
654 pub server_name: String,
656 pub status: McpStartupStatus,
658}
659
660#[derive(Debug, Clone, Serialize, Deserialize)]
662pub struct McpStartupFailure {
663 pub server_name: String,
665 pub error: String,
667}
668
669#[derive(Debug, Clone, Serialize, Deserialize)]
671pub struct McpStartupCompleteEvent {
672 pub ready: Vec<String>,
674 pub failed: Vec<McpStartupFailure>,
676 pub cancelled: Vec<String>,
678}
679
680#[derive(Debug, Clone, Serialize, Deserialize)]
682pub struct NetworkApprovalContext {
683 pub host: String,
685 pub protocol: String,
687}
688
689#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
696pub struct UserInputOptionEvent {
697 pub label: String,
699 pub description: String,
701}
702
703#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
705pub struct UserInputQuestionEvent {
706 pub header: String,
708 pub id: String,
710 pub question: String,
712 pub options: Vec<UserInputOptionEvent>,
714 #[serde(default)]
716 pub allow_free_text: bool,
717 #[serde(default)]
719 pub multi_select: bool,
720}
721
722#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
728pub struct UserInputRequestEvent {
729 pub call_id: String,
731 pub turn_id: String,
733 pub request_id: String,
735 pub questions: Vec<UserInputQuestionEvent>,
737}
738
739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
741pub struct UserInputAnswerEvent {
742 pub id: String,
744 pub label: String,
746 pub value: String,
748}
749
750#[derive(Debug, Clone, Serialize, Deserialize)]
752pub struct ExecApprovalRequestEvent {
753 pub call_id: String,
755 pub approval_id: String,
757 pub turn_id: String,
759 pub command: String,
761 pub cwd: String,
763 pub reason: String,
765 #[serde(default, skip_serializing_if = "Option::is_none")]
767 pub matched_rule: Option<Box<str>>,
768 #[serde(skip_serializing_if = "Option::is_none")]
770 pub network_approval_context: Option<NetworkApprovalContext>,
771 #[serde(default)]
773 pub proposed_execpolicy_amendment: Vec<String>,
774 #[serde(default)]
776 pub proposed_network_policy_amendments: Vec<NetworkPolicyAmendment>,
777 #[serde(default)]
779 pub additional_permissions: Vec<String>,
780 #[serde(default)]
782 pub available_decisions: Vec<ReviewDecision>,
783}
784
785#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
787#[serde(rename_all = "snake_case")]
788pub enum ResponseChannel {
789 #[default]
791 Text,
792 Reasoning,
794}
795
796impl ResponseChannel {
797 pub const fn is_text(&self) -> bool {
799 matches!(self, ResponseChannel::Text)
800 }
801}
802
803#[derive(Debug, Clone, Serialize, Deserialize)]
805pub struct ApprovalDecisionRequest {
806 pub decision: String,
808 #[serde(default)]
810 pub remember: bool,
811}
812
813#[derive(Debug, Clone, Serialize, Deserialize)]
819#[serde(tag = "event", rename_all = "snake_case")]
820pub enum EventFrame {
821 ResponseStart { response_id: String },
823 ResponseDelta {
825 response_id: String,
826 delta: String,
827 #[serde(default, skip_serializing_if = "ResponseChannel::is_text")]
828 channel: ResponseChannel,
829 },
830 ResponseEnd { response_id: String },
832 ToolCallStart {
834 response_id: String,
835 tool_name: String,
836 arguments: Value,
837 },
838 ToolCallResult {
840 response_id: String,
841 tool_name: String,
842 output: Value,
843 },
844 McpStartupUpdate { update: McpStartupUpdateEvent },
846 McpStartupComplete { summary: McpStartupCompleteEvent },
848 McpToolCallBegin {
850 server_name: String,
851 tool_name: String,
852 },
853 McpToolCallEnd {
855 server_name: String,
856 tool_name: String,
857 ok: bool,
858 },
859 ExecApprovalRequest { request: ExecApprovalRequestEvent },
861 ApplyPatchApprovalRequest { request: ExecApprovalRequestEvent },
863 UserInputRequest { request: UserInputRequestEvent },
868 ElicitationRequest {
870 server_name: String,
871 request_id: String,
872 prompt: String,
873 },
874 ExecCommandBegin { command: String, cwd: String },
876 ExecCommandOutputDelta { command: String, delta: String },
878 ExecCommandEnd { command: String, exit_code: i32 },
880 PatchApplyBegin { path: String },
882 PatchApplyEnd { path: String, ok: bool },
884 TurnStarted { turn_id: String },
886 TurnComplete { turn_id: String },
888 TurnAborted { turn_id: String, reason: String },
890 ThreadGoalUpdated { goal: ThreadGoal },
892 ThreadGoalCleared { thread_id: String },
894 Error {
896 response_id: String,
897 message: String,
898 },
899}