codewhale-protocol 0.10.3

App-server protocol frames for Codewhale runtime integrations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
// Serde-only leaf crate shared by every surface, including the TUI
// alt-screen. Raw stdio prints must never appear here (spec §7,
// `no_stdout_from_core`).
#![deny(clippy::print_stdout)]
#![deny(clippy::print_stderr)]

use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use serde_json::Value;

pub mod agent_mail;
pub mod agent_run;
pub mod avatar;
pub mod engine_owner;
pub mod event_msg;
pub mod fleet;
pub mod ids;
pub mod journal;
pub mod op;
pub mod placement;

/// Common trait for lifecycle status enums across the protocol layer.
///
/// Every status enum — thread, goal, fleet run, worker, and job status —
/// implements this trait so generic code can ask three universal questions
/// without matching on every variant.
pub trait Status {
    /// Returns `true` when this status represents a final, non-progressable state
    /// (e.g. Completed, Failed, Cancelled, Archived, Retired).
    fn is_terminal(&self) -> bool;

    /// Returns `true` when work is currently in-flight
    /// (e.g. Running, Active, Busy, Queued, Pending).
    fn is_active(&self) -> bool;

    /// Returns `true` when the item has been explicitly paused by the user
    /// or system (e.g. Paused).
    fn is_paused(&self) -> bool;
}

/// A single message entry in a conversation thread.
///
/// Messages form a tree structure via [`parent_entry_id`](Self::parent_entry_id),
/// enabling conversation branching and forking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageRecord {
    /// Auto-incremented unique identifier for this message.
    pub id: i64,
    /// ID of the thread this message belongs to.
    pub thread_id: String,
    /// Role of the message sender (e.g. `"user"`, `"assistant"`, `"system"`).
    pub role: String,
    /// Text content of the message.
    pub content: String,
    /// Optional structured item payload (tool calls, tool results, etc.).
    pub item: Option<Value>,
    /// Unix timestamp (seconds) when the message was created.
    pub created_at: i64,
    /// ID of the parent message, forming a tree structure. `None` for root messages.
    pub parent_entry_id: Option<i64>,
}

/// A complete immutable legacy SQLite graph, not a limit or active-branch projection.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LegacyThreadHistory {
    pub version: u32,
    pub state_store_id: String,
    pub thread_id: String,
    pub current_leaf_id: Option<i64>,
    pub messages: Vec<MessageRecord>,
    /// Captured in the same SQLite snapshot; imported Active goals stay paused.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub goal: Option<ThreadGoal>,
}

pub const MAX_CANONICAL_HISTORY_ENTRIES: usize = 16_384;
pub const MAX_CANONICAL_HISTORY_BYTES: usize = 8 * 1024 * 1024;

/// An authenticated import proposal carries conversation data only. Routing and
/// permissions remain the current owner's create-thread policy.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalHistoryImportRequest {
    pub version: u32,
    pub operation_key: String,
    pub expected_data_dir: PathBuf,
    pub expected_execution_scope: String,
    /// Existing bare compatibility links attach their full source graph here;
    /// the owner verifies the actual bound canonical document, never remints it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_runtime_thread_id: Option<String>,
    pub workspace: PathBuf,
    pub model: Option<String>,
    pub history: LegacyThreadHistory,
}

/// Durable result of the actual canonical owner operation. Its scope fields are
/// captured from RuntimeStoreBinding; historical receipts never authenticate a
/// current process or convey credentials.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalThreadReceipt {
    pub version: u32,
    pub data_dir: PathBuf,
    pub execution_scope: String,
    pub operation_key: String,
    pub request_digest: String,
    pub history_digest: String,
    pub runtime_thread_id: String,
    pub session_id: String,
}

/// A complete read projection from the actual Engine and its existing saved
/// journal. `session` retains the established SavedSession wire shape, including
/// every branch; it is data, never a policy or operation-commit receipt.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalThreadSnapshot {
    pub version: u32,
    pub data_dir: PathBuf,
    pub execution_scope: String,
    pub runtime_thread_id: String,
    pub saved_session_id: Option<String>,
    pub saved_document_digest: Option<String>,
    pub document_digest: String,
    pub session_goal_digest: String,
    pub session: Value,
}

/// One client-captured intent. The key is retained after an uncertain reply;
/// retrying it never allocates another canonical identity.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalThreadMutationRequest {
    pub version: u32,
    pub operation_key: String,
    pub expected_data_dir: PathBuf,
    pub expected_execution_scope: String,
    pub workspace: PathBuf,
    pub mutation: CanonicalThreadMutation,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum CanonicalThreadMutation {
    /// The existing CreateThreadRequest shape, checked by the owner. Conversation
    /// data and an imported document never supply a routing or permission ceiling.
    Create { config: Value },
    Resume {
        source: CanonicalHistorySource,
        #[serde(default)]
        options: CanonicalHistoryOptions,
    },
    Fork {
        source: CanonicalHistorySource,
        #[serde(default)]
        options: CanonicalHistoryOptions,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        selected_entry_id: Option<String>,
    },
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalHistoryOptions {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub offered_history: Vec<Value>,
    #[serde(default, skip_serializing_if = "Value::is_null")]
    pub overrides: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_path: Option<PathBuf>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_session_goal_digest: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum CanonicalHistorySource {
    Thread {
        runtime_thread_id: String,
        expected_document_digest: String,
    },
    /// Local mounted handoff supplies the already protected document without
    /// its journal-derived messages; the actual owner rebuilds them from the
    /// journal, reopens the file and compares the same whole-document digest.
    SavedSession {
        session: Value,
        expected_document_digest: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CanonicalThreadOperationKind {
    Create,
    Resume,
    Fork,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalThreadOperationAssociation {
    pub kind: CanonicalThreadOperationKind,
    pub source_runtime_thread_id: Option<String>,
    pub source_session_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalThreadOperationLookup {
    pub version: u32,
    pub operation_key: String,
    pub expected_data_dir: PathBuf,
    pub expected_execution_scope: String,
    pub workspace: PathBuf,
}

/// Explicit completion of an already-prepared retained intent, with no source proposal.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalThreadOperationRecovery {
    pub operation: CanonicalThreadOperationLookup,
    pub association: CanonicalThreadOperationAssociation,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
pub enum CanonicalThreadOperationStatus {
    Absent,
    Pending {
        receipt: CanonicalThreadReceipt,
        association: CanonicalThreadOperationAssociation,
    },
    Committed {
        receipt: CanonicalThreadReceipt,
        association: CanonicalThreadOperationAssociation,
    },
}

/// Closed routing receipt captured from the held Runtime owner, never a bearer.
/// Authentication also requires the actual connected kernel peer identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeOwnerReceipt {
    pub version: u32,
    pub data_dir: PathBuf,
    pub execution_scope: String,
    pub lease_generation: String,
    pub pid: u32,
    pub process_start: String,
    pub principal: String,
    pub socket_path: PathBuf,
    pub config_path: Option<PathBuf>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Envelope<T> {
    pub request_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_id: Option<String>,
    pub body: T,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ThreadStatus {
    Running,
    Idle,
    Completed,
    Failed,
    Paused,
    Archived,
}

impl Status for ThreadStatus {
    fn is_terminal(&self) -> bool {
        matches!(self, Self::Completed | Self::Failed | Self::Archived)
    }
    fn is_active(&self) -> bool {
        matches!(self, Self::Running)
    }
    fn is_paused(&self) -> bool {
        matches!(self, Self::Paused)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SessionSource {
    Interactive,
    Resume,
    Fork,
    Api,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Thread {
    pub id: String,
    pub preview: String,
    pub ephemeral: bool,
    pub model_provider: String,
    pub created_at: i64,
    pub updated_at: i64,
    pub status: ThreadStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
    pub cwd: PathBuf,
    pub cli_version: String,
    pub source: SessionSource,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ThreadGoalStatus {
    Active,
    Paused,
    Blocked,
    UsageLimited,
    BudgetLimited,
    Complete,
}

impl Status for ThreadGoalStatus {
    fn is_terminal(&self) -> bool {
        matches!(self, Self::Complete)
    }
    fn is_active(&self) -> bool {
        matches!(self, Self::Active)
    }
    fn is_paused(&self) -> bool {
        matches!(self, Self::Paused)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ThreadGoal {
    pub thread_id: String,
    pub goal_id: String,
    pub objective: String,
    pub status: ThreadGoalStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_budget: Option<i64>,
    pub tokens_used: i64,
    pub time_used_seconds: i64,
    pub continuation_count: i64,
    pub created_at: i64,
    pub updated_at: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_gap_fingerprint: Option<String>,
    #[serde(default)]
    pub repeated_gap_count: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_gap_pass: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pause_reason: Option<GoalPauseReason>,
}

/// Why an unfinished goal is paused. Shared by every durable host projection.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum GoalPauseReason {
    User,
    Backoff,
    NoProgress,
    UsageLimit,
    BudgetLimit,
    /// The model finished a stage and handed control back, rather than a
    /// reported blocker or a completion. It is not a judgement about the work,
    /// so the user's next message resumes the goal (the same shape as a
    /// runtime stop, which is also resumable by writing to it).
    Yielded,
    /// A reason a **newer** build wrote. Kept so an older binary can still read
    /// the durable record instead of failing the whole goal load on an unknown
    /// variant; nothing constructs it. The resume path treats it as "not a
    /// hand-back", which is the conservative reading.
    #[serde(other)]
    Unrecognized,
}

impl GoalPauseReason {
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::User => "user",
            Self::Backoff => "run limit",
            Self::NoProgress => "no progress",
            Self::UsageLimit => "usage limit",
            Self::BudgetLimit => "budget limit",
            Self::Yielded => "handed back",
            Self::Unrecognized => "unrecognized",
        }
    }
}

/// Validate the compact stall history without retaining verifier prose.
/// Legacy records with the entire history absent start with an empty window.
pub const MAX_REPEATED_GAP_COUNT: u32 = 3;

pub fn validate_goal_stall_state(
    fingerprint: Option<&str>,
    count: u32,
    pass: Option<u32>,
    continuation_count: u32,
) -> Result<(), &'static str> {
    match (fingerprint, count, pass) {
        (None, 0, None) => Ok(()),
        (Some(digest), 1..=MAX_REPEATED_GAP_COUNT, Some(pass))
            if digest.len() == 64
                && digest.bytes().all(|byte| byte.is_ascii_hexdigit())
                && pass <= continuation_count
                && count <= pass.saturating_add(1) =>
        {
            Ok(())
        }
        _ => Err("invalid persisted goal stall history"),
    }
}

impl ThreadGoal {
    pub fn validate_stall_state(&self) -> Result<(), &'static str> {
        validate_goal_stall_state(
            self.last_gap_fingerprint.as_deref(),
            self.repeated_gap_count,
            self.last_gap_pass,
            u32::try_from(self.continuation_count.max(0)).unwrap_or(u32::MAX),
        )
    }

    /// Restore a durably impossible record as paused. The engine pauses
    /// NoProgress in the same locked mutation that fills the stall window, so
    /// a persisted record that is still Active at the ceiling is corrupt
    /// (e.g. a crash between the counter write and the pause). Returns true
    /// when the record was healed.
    pub fn normalize_restored_stall_state(&mut self) -> bool {
        if matches!(self.status, ThreadGoalStatus::Active)
            && self.repeated_gap_count >= MAX_REPEATED_GAP_COUNT
        {
            self.status = ThreadGoalStatus::Paused;
            self.pause_reason = Some(GoalPauseReason::NoProgress);
            true
        } else {
            false
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadStartParams {
    /// Captured once for this user intent and retained for an uncertain reply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operation_key: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<PathBuf>,
    #[serde(default)]
    pub persist_extended_history: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadResumeParams {
    /// Captured once for this user intent and retained for an uncertain reply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operation_key: Option<String>,
    pub thread_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub history: Option<Vec<Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<PathBuf>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approval_policy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sandbox: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_instructions: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub developer_instructions: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub personality: Option<String>,
    #[serde(default)]
    pub persist_extended_history: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadForkParams {
    /// Captured once for this user intent and retained for an uncertain reply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operation_key: Option<String>,
    pub thread_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<PathBuf>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approval_policy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sandbox: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_instructions: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub developer_instructions: Option<String>,
    #[serde(default)]
    pub persist_extended_history: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ThreadListParams {
    #[serde(default)]
    pub include_archived: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ThreadReadParams {
    pub thread_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadSetNameParams {
    pub thread_id: String,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadGoalSetParams {
    pub thread_id: String,
    pub objective: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_budget: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadGoalGetParams {
    pub thread_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadGoalClearParams {
    pub thread_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadGoalProgressParams {
    pub thread_id: String,
    #[serde(default)]
    pub token_delta: i64,
    #[serde(default)]
    pub time_delta_seconds: i64,
    #[serde(default)]
    pub record_continuation: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ThreadRequest {
    Create {
        #[serde(default)]
        metadata: Value,
    },
    Start(ThreadStartParams),
    Resume(ThreadResumeParams),
    Fork(ThreadForkParams),
    List(ThreadListParams),
    Read(ThreadReadParams),
    SetName(ThreadSetNameParams),
    GoalSet(ThreadGoalSetParams),
    GoalGet(ThreadGoalGetParams),
    GoalClear(ThreadGoalClearParams),
    GoalRecordProgress(ThreadGoalProgressParams),
    Archive {
        thread_id: String,
    },
    Unarchive {
        thread_id: String,
    },
    Message {
        thread_id: String,
        input: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        allowed_tools: Option<Vec<String>>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        images: Vec<codewhale_app_server_protocol::runtime::RuntimeImageInput>,
        #[serde(
            default,
            rename = "maxOutputTokens",
            alias = "max_output_tokens",
            skip_serializing_if = "Option::is_none"
        )]
        max_output_tokens: Option<std::num::NonZeroU32>,
    },
}

/// Response to a [`ThreadRequest`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadResponse {
    /// The thread this response pertains to.
    pub thread_id: String,
    /// Human-readable status string (e.g. `"ok"`, `"error"`).
    pub status: String,
    /// The thread details, when a single thread is returned.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread: Option<Thread>,
    /// List of threads, populated by `List` requests.
    #[serde(default)]
    pub threads: Vec<Thread>,
    /// Thread goal returned by goal get/set requests.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub goal: Option<ThreadGoal>,
    /// The model used for the thread, if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// The model provider used for the thread.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_provider: Option<String>,
    /// The working directory of the thread.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<PathBuf>,
    /// The active approval policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approval_policy: Option<String>,
    /// The active sandbox configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sandbox: Option<String>,
    /// Streaming events associated with this response.
    #[serde(default)]
    pub events: Vec<EventFrame>,
    /// Arbitrary additional response data.
    #[serde(default)]
    pub data: Value,
}

/// Application-level requests that are not tied to a specific thread.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AppRequest {
    /// Query the server's capabilities.
    Capabilities,
    /// Read a configuration value by key.
    ConfigGet { key: String },
    /// Set a configuration key to a value.
    ConfigSet { key: String, value: String },
    /// Remove a configuration key.
    ConfigUnset { key: String },
    /// List all configuration entries.
    ConfigList,
    /// Reload configuration from disk and apply to the live runtime.
    ///
    /// Re-reads both `config.toml` and the sibling `permissions.toml`,
    /// refreshing the live `Runtime.config` and `Runtime.exec_policy`
    /// so headless clients can pick up external config-file *and*
    /// permission-rule edits without restarting.
    ///
    /// Mirrors the TUI `reload_runtime_config` codepath for everything
    /// reachable from the headless `Runtime`. MCP server connections
    /// are not refreshed — changing `mcp_config_path` or the referenced
    /// `mcp.json` still requires a headless-runtime restart. The TUI's
    /// explicit `/mcp reload` operation is not part of this protocol path.
    ConfigReload,
    /// List available models.
    Models,
    /// List threads that are currently loaded in memory.
    ThreadLoadedList,
    /// Submit answers to a prior [`EventFrame::UserInputRequest`].
    ///
    /// `request_id` must match a pending clarification request. Headless
    /// clients use this to return the user's selections back to the runtime.
    SubmitUserInput {
        request_id: String,
        answers: Vec<UserInputAnswerEvent>,
    },
}

/// Response to an [`AppRequest`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppResponse {
    /// Whether the request succeeded.
    pub ok: bool,
    /// The response payload.
    pub data: Value,
    /// Streaming events associated with this response.
    #[serde(default)]
    pub events: Vec<EventFrame>,
}

/// A simple prompt request that sends text to the model and returns output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allowed_tools: Option<Vec<String>>,
    #[serde(
        default,
        rename = "maxOutputTokens",
        alias = "max_output_tokens",
        skip_serializing_if = "Option::is_none"
    )]
    pub max_output_tokens: Option<std::num::NonZeroU32>,
    /// Optional thread context for the prompt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_id: Option<String>,
    /// The prompt text.
    pub prompt: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub images: Vec<codewhale_app_server_protocol::runtime::RuntimeImageInput>,
    /// Model override, or the default if omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

/// Response to a [`PromptRequest`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptResponse {
    /// The model's output text.
    pub output: String,
    /// The model that produced the output.
    pub model: String,
    /// Streaming events associated with this response.
    #[serde(default)]
    pub events: Vec<EventFrame>,
}

/// Policy controlling when the agent must ask the user for approval before acting.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AskForApproval {
    /// Ask for approval unless the action is on a trusted path/resource.
    UnlessTrusted,
    /// Only ask after a tool call fails.
    OnFailure,
    /// Ask every time a tool call is requested.
    OnRequest,
    /// Reject the action without asking, with details on which categories are blocked.
    Reject {
        sandbox_approval: bool,
        rules: bool,
        mcp_elicitations: bool,
    },
    /// Never ask; auto-approve all actions.
    Never,
}

/// Classification of tool invocation origin.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolKind {
    /// A built-in function tool.
    Function,
    /// An MCP (Model Context Protocol) tool.
    Mcp,
}

/// Parameters for executing a local shell command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalShellParams {
    /// The shell command to execute.
    pub command: String,
    /// Working directory for the command.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// Timeout in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

/// The payload of a tool call, discriminated by tool type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ToolPayload {
    /// A built-in function call with JSON-encoded arguments.
    Function { arguments: String },
    /// A custom tool invocation with a free-form input string.
    Custom { input: String },
    /// A local shell command execution.
    LocalShell { params: LocalShellParams },
    /// An MCP tool invocation targeting a specific server and tool.
    Mcp {
        server: String,
        tool: String,
        raw_arguments: Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        raw_tool_call_id: Option<String>,
    },
}

/// The result of a tool call, discriminated by tool type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ToolOutput {
    /// Result of a built-in function call.
    Function {
        /// The output body, if any.
        #[serde(skip_serializing_if = "Option::is_none")]
        body: Option<Value>,
        /// Whether the call succeeded.
        success: bool,
    },
    /// Result of an MCP tool call.
    Mcp {
        /// The result value returned by the MCP server.
        result: Value,
    },
}

impl ToolOutput {
    /// Returns the tool's application-level success independently of transport.
    ///
    /// MCP success requires the top-level `isError` field to be omitted or the
    /// literal boolean `false`; malformed present metadata fails closed.
    pub fn success(&self) -> bool {
        match self {
            Self::Function { success, .. } => *success,
            Self::Mcp { result } => {
                matches!(result.get("isError"), None | Some(Value::Bool(false)))
            }
        }
    }
}

/// Action to take for a network policy rule.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NetworkPolicyRuleAction {
    /// Allow network access to the host.
    Allow,
    /// Deny network access to the host.
    Deny,
}

/// A proposed amendment to the network access policy for a specific host.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct NetworkPolicyAmendment {
    /// The host to amend the policy for.
    pub host: String,
    /// The action to apply.
    pub action: NetworkPolicyRuleAction,
}

/// A user's decision on an approval request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ReviewDecision {
    /// Approve the action.
    Approved,
    /// Approve and also amend the execution policy.
    ApprovedExecpolicyAmendment,
    /// Approve for the remainder of this session only.
    ApprovedForSession,
    /// Approve with a network policy amendment.
    NetworkPolicyAmendment {
        host: String,
        action: NetworkPolicyRuleAction,
    },
    /// Deny the action.
    Denied,
    /// Abort the entire turn.
    Abort,
}

/// Status of an MCP server during startup.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum McpStartupStatus {
    /// The server is in the process of starting.
    Starting,
    /// The server is ready to accept requests.
    Ready,
    /// The server failed to start.
    Failed { error: String },
    /// Startup was cancelled.
    Cancelled,
}

/// A progress update for a single MCP server's startup.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpStartupUpdateEvent {
    /// Name of the MCP server.
    pub server_name: String,
    /// Current startup status.
    pub status: McpStartupStatus,
}

/// Details of an MCP server that failed to start.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpStartupFailure {
    /// Name of the MCP server that failed.
    pub server_name: String,
    /// Error description.
    pub error: String,
}

/// Summary event emitted once all MCP servers have finished starting.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpStartupCompleteEvent {
    /// Servers that started successfully.
    pub ready: Vec<String>,
    /// Servers that failed to start.
    pub failed: Vec<McpStartupFailure>,
    /// Servers whose startup was cancelled.
    pub cancelled: Vec<String>,
}

/// Context about a network access request that requires approval.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkApprovalContext {
    /// The host being accessed.
    pub host: String,
    /// The network protocol (e.g. `"https"`, `"tcp"`).
    pub protocol: String,
}

/// A selectable option presented to the user in a clarification question.
///
/// Headless serialization shape for the `request_user_input` model tool,
/// mirrored after the TUI's `UserInputOption`. Shared by the
/// [`EventFrame::UserInputRequest`] frame and the [`AppRequest::SubmitUserInput`]
/// reply path so both surfaces agree on the question schema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UserInputOptionEvent {
    /// Short label for the option (also the value submitted when picked).
    pub label: String,
    /// Longer description shown alongside the label.
    #[serde(default)]
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum UserInputIntentEvent {
    PlanReview {
        approve: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        call_id: Option<String>,
    },
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum UserInputAnswerKindEvent {
    Choice,
    Custom,
    Skipped,
}

/// A single clarification question posed to the user.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UserInputQuestionEvent {
    /// Compact header shown as the question title.
    #[serde(default)]
    pub header: String,
    /// Stable identifier used to correlate answers back to this question.
    pub id: String,
    /// The question body.
    pub question: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intent: Option<UserInputIntentEvent>,
    #[serde(default)]
    pub options: Vec<UserInputOptionEvent>,
    /// When `true`, the client should also offer a free-text response.
    #[serde(default)]
    pub allow_free_text: bool,
    /// When `true`, the user may select more than one option.
    #[serde(default)]
    pub multi_select: bool,
}

/// An event requesting structured user input via a model-tool call.
///
/// Sibling of [`ExecApprovalRequestEvent`] for the clarification-question
/// flow. Emitted fire-and-return by `Runtime::invoke_tool` when the model
/// invokes `request_user_input` in a headless context.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UserInputRequestEvent {
    /// Identifier of the tool call requesting input.
    pub call_id: String,
    /// The turn during which the request was made.
    pub turn_id: String,
    /// Unique identifier for this user-input request (clients reply with it).
    pub request_id: String,
    #[serde(default)]
    pub require_typed_answers: bool,
    pub questions: Vec<UserInputQuestionEvent>,
}

/// One answer to a clarification question.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UserInputAnswerEvent {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<UserInputAnswerKindEvent>,
    /// The `id` of the question this answer corresponds to.
    pub id: String,
    /// The selected option's label, or empty for typed custom/skip responses.
    pub label: String,
    /// The resolved value (option label, or the typed free-text).
    pub value: String,
}

/// An event requesting user approval for a command execution or patch application.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecApprovalRequestEvent {
    /// Identifier of the tool call requesting approval.
    pub call_id: String,
    /// Unique identifier for this approval request.
    pub approval_id: String,
    /// The turn during which the request was made.
    pub turn_id: String,
    /// The command that would be executed.
    pub command: String,
    /// The working directory for the command.
    pub cwd: String,
    /// Human-readable reason why approval is needed.
    pub reason: String,
    /// Policy rule that matched this approval request, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub matched_rule: Option<Box<str>>,
    /// Network context if the approval involves network access.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_approval_context: Option<NetworkApprovalContext>,
    /// Proposed execution policy rule amendments.
    #[serde(default)]
    pub proposed_execpolicy_amendment: Vec<String>,
    /// Proposed network policy amendments.
    #[serde(default)]
    pub proposed_network_policy_amendments: Vec<NetworkPolicyAmendment>,
    /// Additional permissions being requested.
    #[serde(default)]
    pub additional_permissions: Vec<String>,
    /// The set of decisions the user can choose from.
    #[serde(default)]
    pub available_decisions: Vec<ReviewDecision>,
}

/// The channel a response delta is being written to.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ResponseChannel {
    /// The main visible text output.
    #[default]
    Text,
    /// Internal reasoning / chain-of-thought output.
    Reasoning,
}

impl ResponseChannel {
    /// Returns `true` if this is the `Text` channel.
    pub const fn is_text(&self) -> bool {
        matches!(self, ResponseChannel::Text)
    }
}

/// A user's approval decision sent in response to an approval request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalDecisionRequest {
    /// The decision identifier (e.g. `"approved"`, `"denied"`).
    pub decision: String,
    /// Whether to remember this decision for future similar requests.
    #[serde(default)]
    pub remember: bool,
}

/// A single streaming event frame emitted during agent execution.
///
/// Events are tagged by the `event` field and cover the full lifecycle of a
/// turn: response streaming, tool calls, MCP lifecycle, command execution,
/// patch application, approvals, and errors.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum EventFrame {
    /// A new model response has started.
    ResponseStart { response_id: String },
    /// A incremental text delta for an in-progress response.
    ResponseDelta {
        response_id: String,
        delta: String,
        #[serde(default, skip_serializing_if = "ResponseChannel::is_text")]
        channel: ResponseChannel,
    },
    /// The model response has finished.
    ResponseEnd { response_id: String },
    /// A tool call has begun.
    ToolCallStart {
        response_id: String,
        tool_name: String,
        arguments: Value,
    },
    /// A tool call has completed and produced a result.
    ToolCallResult {
        response_id: String,
        tool_name: String,
        output: Value,
    },
    /// Progress update for an MCP server starting up.
    McpStartupUpdate { update: McpStartupUpdateEvent },
    /// All MCP servers have finished starting.
    McpStartupComplete { summary: McpStartupCompleteEvent },
    /// An MCP tool call has begun.
    McpToolCallBegin {
        server_name: String,
        tool_name: String,
    },
    /// An MCP tool call has finished.
    McpToolCallEnd {
        server_name: String,
        tool_name: String,
        ok: bool,
    },
    /// User approval is needed for a command execution.
    ExecApprovalRequest { request: ExecApprovalRequestEvent },
    /// User approval is needed for applying a patch.
    ApplyPatchApprovalRequest { request: ExecApprovalRequestEvent },
    /// A model tool is requesting structured clarification input from the user.
    ///
    /// Headless sibling of the TUI's `request_user_input` modal flow.
    /// `request_id` correlates with an [`AppRequest::SubmitUserInput`] reply.
    UserInputRequest { request: UserInputRequestEvent },
    /// An MCP server is requesting user input (elicitation).
    ElicitationRequest {
        server_name: String,
        request_id: String,
        prompt: String,
    },
    /// A command has started executing.
    ExecCommandBegin { command: String, cwd: String },
    /// Incremental output from a running command.
    ExecCommandOutputDelta { command: String, delta: String },
    /// A command has finished executing.
    ExecCommandEnd { command: String, exit_code: i32 },
    /// A patch has started being applied to a file.
    PatchApplyBegin { path: String },
    /// A patch has finished being applied.
    PatchApplyEnd { path: String, ok: bool },
    /// A new turn has started within a thread.
    TurnStarted { turn_id: String },
    /// A turn has completed successfully.
    TurnComplete { turn_id: String },
    /// A turn was aborted before completion.
    TurnAborted { turn_id: String, reason: String },
    /// A thread goal was set or updated.
    ThreadGoalUpdated { goal: ThreadGoal },
    /// A thread goal was cleared.
    ThreadGoalCleared { thread_id: String },
    /// An error occurred during processing.
    Error {
        response_id: String,
        message: String,
    },
}

pub mod request;
pub mod role;

/// Pure provenance data shared by hosts and portable status reports.
pub mod cloud_facts;

pub mod display;