chio-kernel 0.1.0

Chio runtime kernel: capability validation, guard evaluation, receipt signing
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
1180
1181
1182
1183
1184
1185
1186
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use chio_core::crypto::{canonical_json_bytes, sha256_hex};
use chio_core::session::{
    CompletionResult, CreateElicitationOperation, NormalizedRoot, OperationContext, OperationKind,
    OperationTerminalState, ProgressToken, PromptDefinition, PromptResult, RequestId,
    RequestOwnershipSnapshot, ResourceContent, ResourceDefinition, ResourceTemplateDefinition,
    RootDefinition, SessionAnchorReference, SessionAuthContext, SessionId,
};
use chio_core::{AgentId, CapabilityToken};

use crate::{ToolCallResponse, ToolServerEvent};
use chio_core::receipt::ChioReceipt;

/// Lifecycle state of a logical kernel session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionState {
    Initializing,
    Ready,
    Draining,
    Closed,
}

impl SessionState {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Initializing => "initializing",
            Self::Ready => "ready",
            Self::Draining => "draining",
            Self::Closed => "closed",
        }
    }
}

/// Feature flags negotiated with the peer at session establishment.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PeerCapabilities {
    pub supports_progress: bool,
    pub supports_cancellation: bool,
    pub supports_subscriptions: bool,
    pub supports_chio_tool_streaming: bool,
    pub supports_roots: bool,
    pub roots_list_changed: bool,
    pub supports_sampling: bool,
    pub sampling_context: bool,
    pub sampling_tools: bool,
    pub supports_elicitation: bool,
    pub elicitation_form: bool,
    pub elicitation_url: bool,
}

/// Bookkeeping record for an in-flight request.
#[derive(Debug, Clone)]
pub struct InflightRequest {
    pub request_id: RequestId,
    pub parent_request_id: Option<RequestId>,
    pub operation_kind: OperationKind,
    pub session_anchor_id: String,
    pub started_at: Instant,
    pub progress_token: Option<ProgressToken>,
    pub cancellation_requested: bool,
    pub cancellable: bool,
}

impl InflightRequest {
    pub fn ownership(&self) -> RequestOwnershipSnapshot {
        RequestOwnershipSnapshot::request_owned()
    }
}

/// Registry of requests that are currently active within a session.
#[derive(Debug, Clone, Default)]
pub struct InflightRegistry {
    requests: HashMap<RequestId, InflightRequest>,
}

impl InflightRegistry {
    pub fn track(
        &mut self,
        context: &OperationContext,
        operation_kind: OperationKind,
        session_anchor_id: &str,
        cancellable: bool,
    ) -> Result<(), SessionError> {
        if self.requests.contains_key(&context.request_id) {
            return Err(SessionError::DuplicateInflightRequest {
                request_id: context.request_id.clone(),
            });
        }

        self.requests.insert(
            context.request_id.clone(),
            InflightRequest {
                request_id: context.request_id.clone(),
                parent_request_id: context.parent_request_id.clone(),
                operation_kind,
                session_anchor_id: session_anchor_id.to_string(),
                started_at: Instant::now(),
                progress_token: context.progress_token.clone(),
                cancellation_requested: false,
                cancellable,
            },
        );
        Ok(())
    }

    pub fn complete(&mut self, request_id: &RequestId) -> Result<InflightRequest, SessionError> {
        self.requests
            .remove(request_id)
            .ok_or_else(|| SessionError::RequestNotInflight {
                request_id: request_id.clone(),
            })
    }

    pub fn mark_cancellation_requested(
        &mut self,
        request_id: &RequestId,
    ) -> Result<(), SessionError> {
        let request =
            self.requests
                .get_mut(request_id)
                .ok_or_else(|| SessionError::RequestNotInflight {
                    request_id: request_id.clone(),
                })?;

        if !request.cancellable {
            return Err(SessionError::RequestNotCancellable {
                request_id: request_id.clone(),
            });
        }

        request.cancellation_requested = true;
        Ok(())
    }

    pub fn get(&self, request_id: &RequestId) -> Option<&InflightRequest> {
        self.requests.get(request_id)
    }

    pub fn len(&self) -> usize {
        self.requests.len()
    }

    pub fn is_empty(&self) -> bool {
        self.requests.is_empty()
    }

    pub fn clear(&mut self) {
        self.requests.clear();
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum SubscriptionSubject {
    Resource(String),
}

/// Registry for session-scoped subscriptions.
#[derive(Debug, Clone, Default)]
pub struct SubscriptionRegistry {
    subscriptions: HashSet<SubscriptionSubject>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LateSessionEvent {
    ElicitationCompleted {
        elicitation_id: String,
        related_task_id: Option<String>,
    },
    ResourceUpdated {
        uri: String,
    },
    ResourcesListChanged,
    ToolsListChanged,
    PromptsListChanged,
}

#[derive(Debug, Clone)]
struct PendingUrlElicitation {
    related_task_id: Option<String>,
}

impl SubscriptionRegistry {
    pub fn subscribe_resource(&mut self, uri: impl Into<String>) {
        self.subscriptions
            .insert(SubscriptionSubject::Resource(uri.into()));
    }

    pub fn unsubscribe_resource(&mut self, uri: &str) {
        self.subscriptions
            .remove(&SubscriptionSubject::Resource(uri.to_string()));
    }

    pub fn contains_resource(&self, uri: &str) -> bool {
        self.subscriptions
            .contains(&SubscriptionSubject::Resource(uri.to_string()))
    }

    pub fn len(&self) -> usize {
        self.subscriptions.len()
    }

    pub fn is_empty(&self) -> bool {
        self.subscriptions.is_empty()
    }

    pub fn clear(&mut self) {
        self.subscriptions.clear();
    }
}

const TERMINAL_HISTORY_LIMIT: usize = 256;

/// Bounded history of terminal request outcomes for a session.
#[derive(Debug, Clone)]
pub struct TerminalRegistry {
    states: HashMap<RequestId, OperationTerminalState>,
    order: VecDeque<RequestId>,
    limit: usize,
}

impl Default for TerminalRegistry {
    fn default() -> Self {
        Self {
            states: HashMap::new(),
            order: VecDeque::new(),
            limit: TERMINAL_HISTORY_LIMIT,
        }
    }
}

impl TerminalRegistry {
    pub fn record(&mut self, request_id: RequestId, state: OperationTerminalState) {
        if !self.states.contains_key(&request_id) {
            self.order.push_back(request_id.clone());
        }
        self.states.insert(request_id, state);

        while self.order.len() > self.limit {
            if let Some(oldest) = self.order.pop_front() {
                self.states.remove(&oldest);
            }
        }
    }

    pub fn get(&self, request_id: &RequestId) -> Option<&OperationTerminalState> {
        self.states.get(request_id)
    }

    pub fn len(&self) -> usize {
        self.states.len()
    }

    pub fn is_empty(&self) -> bool {
        self.states.is_empty()
    }
}

/// Errors for session lifecycle and in-flight management.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum SessionError {
    #[error("invalid session transition from {from} to {to}")]
    InvalidTransition {
        from: &'static str,
        to: &'static str,
    },

    #[error("session {session_id} cannot handle {operation} while {state}")]
    OperationNotAllowed {
        session_id: SessionId,
        operation: &'static str,
        state: &'static str,
    },

    #[error("operation context session {actual} does not match runtime session {expected}")]
    ContextSessionMismatch {
        expected: SessionId,
        actual: SessionId,
    },

    #[error("operation context agent {actual} does not match session agent {expected}")]
    ContextAgentMismatch { expected: AgentId, actual: AgentId },

    #[error("request {request_id} is already in flight")]
    DuplicateInflightRequest { request_id: RequestId },

    #[error("request {request_id} already has authoritative lineage in this session")]
    DuplicateRequestLineage { request_id: RequestId },

    #[error("request {request_id} is not in flight")]
    RequestNotInflight { request_id: RequestId },

    #[error("request {request_id} is not cancellable")]
    RequestNotCancellable { request_id: RequestId },

    #[error("parent request {parent_request_id} is not in flight for child request {request_id}")]
    ParentRequestNotInflight {
        request_id: RequestId,
        parent_request_id: RequestId,
    },

    #[error(
        "parent request {parent_request_id} for child request {request_id} belongs to stale session anchor {parent_session_anchor_id}, current anchor is {current_session_anchor_id}"
    )]
    ParentRequestAnchorMismatch {
        request_id: RequestId,
        parent_request_id: RequestId,
        parent_session_anchor_id: String,
        current_session_anchor_id: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionAnchorState {
    id: String,
    auth_epoch: u64,
    auth_context_hash: String,
    issued_at: u64,
}

impl SessionAnchorState {
    fn new(session_id: &SessionId, auth_context: &SessionAuthContext, auth_epoch: u64) -> Self {
        let auth_context_hash = auth_context_hash(auth_context);
        let hash_prefix = &auth_context_hash[..12.min(auth_context_hash.len())];
        Self {
            id: format!("{session_id}:anchor:{auth_epoch}:{hash_prefix}"),
            auth_epoch,
            auth_context_hash,
            issued_at: current_unix_timestamp(),
        }
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn auth_epoch(&self) -> u64 {
        self.auth_epoch
    }

    pub fn auth_context_hash(&self) -> &str {
        &self.auth_context_hash
    }

    pub fn issued_at(&self) -> u64 {
        self.issued_at
    }

    pub fn reference(&self) -> SessionAnchorReference {
        SessionAnchorReference::new(self.id.clone(), self.auth_context_hash.clone())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestLineageRecord {
    pub request_id: RequestId,
    pub session_anchor_id: String,
    pub auth_epoch: u64,
    pub parent_request_id: Option<RequestId>,
    pub operation_kind: OperationKind,
    pub started_at: u64,
    pub terminal_state: Option<OperationTerminalState>,
}

/// Session host object owned by the kernel.
#[derive(Debug, Clone)]
pub struct Session {
    id: SessionId,
    agent_id: AgentId,
    state: SessionState,
    session_anchor: SessionAnchorState,
    auth_context: SessionAuthContext,
    peer_capabilities: PeerCapabilities,
    roots: Vec<RootDefinition>,
    normalized_roots: Vec<NormalizedRoot>,
    issued_capabilities: Vec<CapabilityToken>,
    inflight: InflightRegistry,
    subscriptions: SubscriptionRegistry,
    terminal: TerminalRegistry,
    request_lineage: HashMap<RequestId, RequestLineageRecord>,
    pending_url_elicitations: HashMap<String, PendingUrlElicitation>,
    late_events: VecDeque<LateSessionEvent>,
}

impl Session {
    pub fn new(
        id: SessionId,
        agent_id: AgentId,
        issued_capabilities: Vec<CapabilityToken>,
    ) -> Self {
        let auth_context = SessionAuthContext::in_process_anonymous();
        let session_anchor = SessionAnchorState::new(&id, &auth_context, 0);
        Self {
            id,
            agent_id,
            state: SessionState::Initializing,
            session_anchor,
            auth_context,
            peer_capabilities: PeerCapabilities::default(),
            roots: Vec::new(),
            normalized_roots: Vec::new(),
            issued_capabilities,
            inflight: InflightRegistry::default(),
            subscriptions: SubscriptionRegistry::default(),
            terminal: TerminalRegistry::default(),
            request_lineage: HashMap::new(),
            pending_url_elicitations: HashMap::new(),
            late_events: VecDeque::new(),
        }
    }

    pub fn id(&self) -> &SessionId {
        &self.id
    }

    pub fn agent_id(&self) -> &str {
        &self.agent_id
    }

    pub fn state(&self) -> SessionState {
        self.state
    }

    pub fn auth_context(&self) -> &SessionAuthContext {
        &self.auth_context
    }

    pub fn session_anchor(&self) -> &SessionAnchorState {
        &self.session_anchor
    }

    pub fn request_lineage(&self, request_id: &RequestId) -> Option<&RequestLineageRecord> {
        self.request_lineage.get(request_id)
    }

    pub fn peer_capabilities(&self) -> &PeerCapabilities {
        &self.peer_capabilities
    }

    pub fn capabilities(&self) -> &[CapabilityToken] {
        &self.issued_capabilities
    }

    pub fn roots(&self) -> &[RootDefinition] {
        &self.roots
    }

    pub fn normalized_roots(&self) -> &[NormalizedRoot] {
        &self.normalized_roots
    }

    pub fn enforceable_filesystem_roots(&self) -> impl Iterator<Item = &NormalizedRoot> {
        self.normalized_roots
            .iter()
            .filter(|root| root.is_enforceable_filesystem())
    }

    pub fn inflight(&self) -> &InflightRegistry {
        &self.inflight
    }

    pub fn subscriptions(&self) -> &SubscriptionRegistry {
        &self.subscriptions
    }

    pub fn terminal(&self) -> &TerminalRegistry {
        &self.terminal
    }

    pub fn register_pending_url_elicitation(
        &mut self,
        elicitation_id: impl Into<String>,
        related_task_id: Option<String>,
    ) {
        self.pending_url_elicitations.insert(
            elicitation_id.into(),
            PendingUrlElicitation { related_task_id },
        );
    }

    pub fn register_required_url_elicitations(
        &mut self,
        elicitations: &[CreateElicitationOperation],
        related_task_id: Option<&str>,
    ) {
        for elicitation in elicitations {
            let CreateElicitationOperation::Url { elicitation_id, .. } = elicitation else {
                continue;
            };
            self.register_pending_url_elicitation(
                elicitation_id.clone(),
                related_task_id.map(ToString::to_string),
            );
        }
    }

    pub fn queue_late_event(&mut self, event: LateSessionEvent) {
        self.late_events.push_back(event);
    }

    pub fn take_late_events(&mut self) -> Vec<LateSessionEvent> {
        self.late_events.drain(..).collect()
    }

    pub fn queue_tool_server_event(&mut self, event: ToolServerEvent) {
        match event {
            ToolServerEvent::ElicitationCompleted { elicitation_id } => {
                let Some(pending) = self.pending_url_elicitations.remove(&elicitation_id) else {
                    return;
                };
                self.queue_late_event(LateSessionEvent::ElicitationCompleted {
                    elicitation_id,
                    related_task_id: pending.related_task_id,
                });
            }
            ToolServerEvent::ResourceUpdated { uri } => {
                if self.is_resource_subscribed(&uri) {
                    self.queue_late_event(LateSessionEvent::ResourceUpdated { uri });
                }
            }
            ToolServerEvent::ResourcesListChanged => {
                self.queue_late_event(LateSessionEvent::ResourcesListChanged);
            }
            ToolServerEvent::ToolsListChanged => {
                self.queue_late_event(LateSessionEvent::ToolsListChanged);
            }
            ToolServerEvent::PromptsListChanged => {
                self.queue_late_event(LateSessionEvent::PromptsListChanged);
            }
        }
    }

    pub fn queue_elicitation_completion(&mut self, elicitation_id: &str) {
        let Some(pending) = self.pending_url_elicitations.remove(elicitation_id) else {
            return;
        };
        self.queue_late_event(LateSessionEvent::ElicitationCompleted {
            elicitation_id: elicitation_id.to_string(),
            related_task_id: pending.related_task_id,
        });
    }

    pub fn subscribe_resource(&mut self, uri: impl Into<String>) {
        self.subscriptions.subscribe_resource(uri);
    }

    pub fn unsubscribe_resource(&mut self, uri: &str) {
        self.subscriptions.unsubscribe_resource(uri);
    }

    pub fn is_resource_subscribed(&self, uri: &str) -> bool {
        self.subscriptions.contains_resource(uri)
    }

    pub fn set_auth_context(&mut self, auth_context: SessionAuthContext) -> bool {
        let rotated = self.auth_context != auth_context;
        if rotated {
            let next_epoch = self.session_anchor.auth_epoch.saturating_add(1);
            self.session_anchor = SessionAnchorState::new(&self.id, &auth_context, next_epoch);
        }
        self.auth_context = auth_context;
        rotated
    }

    pub fn set_peer_capabilities(&mut self, peer_capabilities: PeerCapabilities) {
        self.peer_capabilities = peer_capabilities;
    }

    pub fn replace_roots(&mut self, roots: Vec<RootDefinition>) {
        self.normalized_roots = roots
            .iter()
            .map(RootDefinition::normalize_for_runtime)
            .collect();
        self.roots = roots;
    }

    pub fn activate(&mut self) -> Result<(), SessionError> {
        self.transition(SessionState::Ready)
    }

    pub fn begin_draining(&mut self) -> Result<(), SessionError> {
        self.transition(SessionState::Draining)
    }

    pub fn close(&mut self) -> Result<(), SessionError> {
        self.transition(SessionState::Closed)?;
        self.inflight.clear();
        self.subscriptions.clear();
        self.roots.clear();
        self.normalized_roots.clear();
        self.pending_url_elicitations.clear();
        self.late_events.clear();
        Ok(())
    }

    pub fn ensure_operation_allowed(&self, operation: OperationKind) -> Result<(), SessionError> {
        let allowed = match self.state {
            SessionState::Initializing => matches!(
                operation,
                OperationKind::ListCapabilities | OperationKind::Heartbeat
            ),
            SessionState::Ready => true,
            SessionState::Draining => matches!(
                operation,
                OperationKind::ListCapabilities | OperationKind::Heartbeat
            ),
            SessionState::Closed => false,
        };

        if allowed {
            Ok(())
        } else {
            Err(SessionError::OperationNotAllowed {
                session_id: self.id.clone(),
                operation: operation.as_str(),
                state: self.state.as_str(),
            })
        }
    }

    pub fn track_request(
        &mut self,
        context: &OperationContext,
        operation_kind: OperationKind,
        cancellable: bool,
    ) -> Result<(), SessionError> {
        self.validate_context(context)?;
        if let Some(parent_request_id) = &context.parent_request_id {
            self.validate_parent_request_lineage(&context.request_id, parent_request_id)?;
        }
        if self.inflight.get(&context.request_id).is_some() {
            return Err(SessionError::DuplicateInflightRequest {
                request_id: context.request_id.clone(),
            });
        }
        if self.request_lineage.contains_key(&context.request_id) {
            return Err(SessionError::DuplicateRequestLineage {
                request_id: context.request_id.clone(),
            });
        }
        self.inflight.track(
            context,
            operation_kind,
            self.session_anchor.id(),
            cancellable,
        )?;
        self.request_lineage.insert(
            context.request_id.clone(),
            RequestLineageRecord {
                request_id: context.request_id.clone(),
                session_anchor_id: self.session_anchor.id().to_string(),
                auth_epoch: self.session_anchor.auth_epoch(),
                parent_request_id: context.parent_request_id.clone(),
                operation_kind,
                started_at: current_unix_timestamp(),
                terminal_state: None,
            },
        );
        Ok(())
    }

    pub fn complete_request(
        &mut self,
        request_id: &RequestId,
    ) -> Result<InflightRequest, SessionError> {
        self.complete_request_with_terminal_state(request_id, OperationTerminalState::Completed)
    }

    pub fn complete_request_with_terminal_state(
        &mut self,
        request_id: &RequestId,
        terminal_state: OperationTerminalState,
    ) -> Result<InflightRequest, SessionError> {
        let inflight = self.inflight.complete(request_id)?;
        self.terminal
            .record(request_id.clone(), terminal_state.clone());
        if let Some(lineage) = self.request_lineage.get_mut(request_id) {
            lineage.terminal_state = Some(terminal_state);
        }
        Ok(inflight)
    }

    pub fn request_cancellation(&mut self, request_id: &RequestId) -> Result<(), SessionError> {
        self.inflight.mark_cancellation_requested(request_id)
    }

    pub fn validate_parent_request_lineage(
        &self,
        request_id: &RequestId,
        parent_request_id: &RequestId,
    ) -> Result<&RequestLineageRecord, SessionError> {
        let Some(parent_inflight) = self.inflight.get(parent_request_id) else {
            return Err(SessionError::ParentRequestNotInflight {
                request_id: request_id.clone(),
                parent_request_id: parent_request_id.clone(),
            });
        };
        let Some(parent_lineage) = self.request_lineage.get(parent_request_id) else {
            return Err(SessionError::ParentRequestNotInflight {
                request_id: request_id.clone(),
                parent_request_id: parent_request_id.clone(),
            });
        };
        if parent_lineage.session_anchor_id != self.session_anchor.id() {
            return Err(SessionError::ParentRequestAnchorMismatch {
                request_id: request_id.clone(),
                parent_request_id: parent_request_id.clone(),
                parent_session_anchor_id: parent_inflight.session_anchor_id.clone(),
                current_session_anchor_id: self.session_anchor.id().to_string(),
            });
        }
        Ok(parent_lineage)
    }

    fn transition(&mut self, next: SessionState) -> Result<(), SessionError> {
        let valid = match (self.state, next) {
            (SessionState::Initializing, SessionState::Ready)
            | (SessionState::Initializing, SessionState::Closed)
            | (SessionState::Ready, SessionState::Draining)
            | (SessionState::Ready, SessionState::Closed)
            | (SessionState::Draining, SessionState::Closed) => true,
            _ if self.state == next => true,
            _ => false,
        };

        if !valid {
            return Err(SessionError::InvalidTransition {
                from: self.state.as_str(),
                to: next.as_str(),
            });
        }

        self.state = next;
        Ok(())
    }

    pub fn validate_context(&self, context: &OperationContext) -> Result<(), SessionError> {
        if context.session_id != self.id {
            return Err(SessionError::ContextSessionMismatch {
                expected: self.id.clone(),
                actual: context.session_id.clone(),
            });
        }

        if context.agent_id != self.agent_id {
            return Err(SessionError::ContextAgentMismatch {
                expected: self.agent_id.clone(),
                actual: context.agent_id.clone(),
            });
        }

        Ok(())
    }
}

fn current_unix_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or(0)
}

fn auth_context_hash(auth_context: &SessionAuthContext) -> String {
    canonical_json_bytes(auth_context)
        .map(|bytes| sha256_hex(&bytes))
        .unwrap_or_else(|_| "session-auth-context-hash-unavailable".to_string())
}

/// Session-aware kernel response, decoupled from the current wire protocol.
#[derive(Debug)]
pub enum SessionOperationResponse {
    ToolCall(ToolCallResponse),
    RootList {
        roots: Vec<RootDefinition>,
    },
    ResourceList {
        resources: Vec<ResourceDefinition>,
    },
    ResourceRead {
        contents: Vec<ResourceContent>,
    },
    ResourceReadDenied {
        receipt: ChioReceipt,
    },
    ResourceTemplateList {
        templates: Vec<ResourceTemplateDefinition>,
    },
    PromptList {
        prompts: Vec<PromptDefinition>,
    },
    PromptGet {
        prompt: PromptResult,
    },
    Completion {
        completion: CompletionResult,
    },
    CapabilityList {
        capabilities: Vec<CapabilityToken>,
    },
    Heartbeat,
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    fn make_context(request_id: &str) -> OperationContext {
        OperationContext {
            session_id: SessionId::new("sess-1"),
            request_id: RequestId::new(request_id),
            agent_id: "agent-1".to_string(),
            parent_request_id: None,
            progress_token: Some(ProgressToken::String("progress-1".to_string())),
        }
    }

    #[test]
    fn lifecycle_transitions_cover_ready_draining_closed() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());

        assert_eq!(session.state(), SessionState::Initializing);
        session.activate().unwrap();
        assert_eq!(session.state(), SessionState::Ready);
        session.begin_draining().unwrap();
        assert_eq!(session.state(), SessionState::Draining);
        session.close().unwrap();
        assert_eq!(session.state(), SessionState::Closed);
    }

    #[test]
    fn tool_calls_not_allowed_during_initializing_or_draining() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());

        let err = session
            .ensure_operation_allowed(OperationKind::ToolCall)
            .unwrap_err();
        assert!(matches!(err, SessionError::OperationNotAllowed { .. }));

        session.activate().unwrap();
        session.begin_draining().unwrap();

        let err = session
            .ensure_operation_allowed(OperationKind::ToolCall)
            .unwrap_err();
        assert!(matches!(err, SessionError::OperationNotAllowed { .. }));
    }

    #[test]
    fn peer_capabilities_and_roots_are_session_scoped() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());

        session.set_peer_capabilities(PeerCapabilities {
            supports_progress: false,
            supports_cancellation: false,
            supports_subscriptions: false,
            supports_chio_tool_streaming: false,
            supports_roots: true,
            roots_list_changed: true,
            supports_sampling: true,
            sampling_context: true,
            sampling_tools: false,
            supports_elicitation: false,
            elicitation_form: false,
            elicitation_url: false,
        });
        session.replace_roots(vec![RootDefinition {
            uri: "file:///workspace/project".to_string(),
            name: Some("Project".to_string()),
        }]);

        assert!(session.peer_capabilities().supports_roots);
        assert!(session.peer_capabilities().roots_list_changed);
        assert_eq!(session.roots().len(), 1);
        assert_eq!(session.roots()[0].uri, "file:///workspace/project");
        assert_eq!(session.normalized_roots().len(), 1);
        assert!(matches!(
            session.normalized_roots()[0],
            NormalizedRoot::EnforceableFileSystem {
                ref normalized_path,
                ..
            } if normalized_path == "/workspace/project"
        ));
        assert_eq!(session.enforceable_filesystem_roots().count(), 1);

        session.close().unwrap();
        assert!(session.roots().is_empty());
        assert!(session.normalized_roots().is_empty());
    }

    #[test]
    fn mixed_roots_preserve_metadata_without_widening_enforceable_set() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        session.replace_roots(vec![
            RootDefinition {
                uri: "file:///workspace/project/src".to_string(),
                name: Some("Code".to_string()),
            },
            RootDefinition {
                uri: "repo://docs/roadmap".to_string(),
                name: Some("Roadmap".to_string()),
            },
            RootDefinition {
                uri: "file://remote-host/workspace/project".to_string(),
                name: Some("Remote".to_string()),
            },
        ]);

        assert_eq!(session.normalized_roots().len(), 3);
        assert!(matches!(
            session.normalized_roots()[0],
            NormalizedRoot::EnforceableFileSystem {
                ref normalized_path,
                ..
            } if normalized_path == "/workspace/project/src"
        ));
        assert!(matches!(
            session.normalized_roots()[1],
            NormalizedRoot::NonFileSystem { ref scheme, .. } if scheme == "repo"
        ));
        assert!(matches!(
            session.normalized_roots()[2],
            NormalizedRoot::UnenforceableFileSystem { ref reason, .. }
                if reason == "non_local_file_authority"
        ));
        assert_eq!(session.enforceable_filesystem_roots().count(), 1);
    }

    #[test]
    fn inflight_registry_tracks_and_completes_requests() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let context = make_context("req-1");

        session.activate().unwrap();
        session
            .track_request(&context, OperationKind::ToolCall, true)
            .unwrap();
        assert_eq!(session.inflight().len(), 1);

        let completed = session.complete_request(&context.request_id).unwrap();
        assert_eq!(completed.request_id, RequestId::new("req-1"));
        assert_eq!(completed.parent_request_id, None);
        assert!(completed.cancellable);
        assert!(session.inflight().is_empty());
        assert_eq!(
            session.terminal().get(&context.request_id),
            Some(&OperationTerminalState::Completed)
        );
    }

    #[test]
    fn child_request_requires_parent_inflight() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let mut child_context = make_context("req-child");
        child_context.parent_request_id = Some(RequestId::new("req-parent"));

        session.activate().unwrap();
        let err = session
            .track_request(&child_context, OperationKind::CreateMessage, true)
            .unwrap_err();
        assert!(matches!(err, SessionError::ParentRequestNotInflight { .. }));
    }

    #[test]
    fn duplicate_inflight_request_is_rejected() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let context = make_context("req-1");

        session.activate().unwrap();
        session
            .track_request(&context, OperationKind::ToolCall, true)
            .unwrap();

        let err = session
            .track_request(&context, OperationKind::ToolCall, true)
            .unwrap_err();
        assert!(matches!(err, SessionError::DuplicateInflightRequest { .. }));
    }

    #[test]
    fn cancellation_marks_cancellable_request() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let context = make_context("req-1");

        session.activate().unwrap();
        session
            .track_request(&context, OperationKind::ToolCall, true)
            .unwrap();
        session.request_cancellation(&context.request_id).unwrap();

        let inflight = session.inflight().get(&context.request_id).unwrap();
        assert!(inflight.cancellation_requested);
    }

    #[test]
    fn inflight_request_reports_request_owned_semantics() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let context = make_context("req-1");

        session.activate().unwrap();
        session
            .track_request(&context, OperationKind::ToolCall, true)
            .unwrap();

        let inflight = session.inflight().get(&context.request_id).unwrap();
        let ownership = inflight.ownership();
        assert_eq!(ownership.work_owner, chio_core::session::WorkOwner::Request);
        assert_eq!(
            ownership.result_stream_owner,
            chio_core::session::StreamOwner::RequestStream
        );
        assert_eq!(
            ownership.terminal_state_owner,
            chio_core::session::WorkOwner::Request
        );
    }

    #[test]
    fn complete_request_can_record_cancelled_terminal_state() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let context = make_context("req-1");

        session.activate().unwrap();
        session
            .track_request(&context, OperationKind::ToolCall, true)
            .unwrap();
        session.request_cancellation(&context.request_id).unwrap();
        session
            .complete_request_with_terminal_state(
                &context.request_id,
                OperationTerminalState::Cancelled {
                    reason: "cancelled by client".to_string(),
                },
            )
            .unwrap();

        assert!(session.inflight().is_empty());
        assert_eq!(
            session.terminal().get(&context.request_id),
            Some(&OperationTerminalState::Cancelled {
                reason: "cancelled by client".to_string(),
            })
        );
    }

    #[test]
    fn resource_subscriptions_are_cleared_on_close() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());

        session.activate().unwrap();
        session.subscribe_resource("repo://docs/roadmap");

        assert!(session.is_resource_subscribed("repo://docs/roadmap"));
        assert_eq!(session.subscriptions().len(), 1);

        session.close().unwrap();

        assert!(!session.is_resource_subscribed("repo://docs/roadmap"));
        assert_eq!(session.subscriptions().len(), 0);
    }

    #[test]
    fn session_anchor_rotates_on_auth_context_change() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let initial_anchor = session.session_anchor().clone();
        assert_eq!(
            session.auth_context(),
            &SessionAuthContext::in_process_anonymous()
        );

        let rotated = session.set_auth_context(SessionAuthContext::streamable_http_static_bearer(
            "static-bearer:abcd1234",
            "cafebabe",
            Some("http://localhost:3000".to_string()),
        ));

        assert!(rotated);
        assert!(session.auth_context().is_authenticated());
        assert_eq!(
            session.auth_context().principal(),
            Some("static-bearer:abcd1234")
        );
        assert_ne!(session.session_anchor().id(), initial_anchor.id());
        assert_eq!(session.session_anchor().auth_epoch(), 1);
        assert_ne!(
            session.session_anchor().auth_context_hash(),
            initial_anchor.auth_context_hash()
        );
    }

    #[test]
    fn session_anchor_does_not_rotate_when_auth_context_is_unchanged() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let auth_context = SessionAuthContext::streamable_http_static_bearer(
            "static-bearer:abcd1234",
            "cafebabe",
            Some("http://localhost:3000".to_string()),
        );

        assert!(session.set_auth_context(auth_context.clone()));
        let rotated_anchor = session.session_anchor().clone();
        assert!(!session.set_auth_context(auth_context));

        assert_eq!(session.session_anchor(), &rotated_anchor);
    }

    #[test]
    fn child_request_is_rejected_after_parent_anchor_rotation() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        let parent_context = make_context("req-parent");
        let mut child_context = make_context("req-child");
        child_context.parent_request_id = Some(parent_context.request_id.clone());

        session.activate().unwrap();
        session
            .track_request(&parent_context, OperationKind::ToolCall, true)
            .unwrap();
        assert!(
            session.set_auth_context(SessionAuthContext::streamable_http_static_bearer(
                "static-bearer:abcd1234",
                "cafebabe",
                Some("http://localhost:3000".to_string()),
            ))
        );

        let err = session
            .track_request(&child_context, OperationKind::CreateMessage, true)
            .unwrap_err();
        assert!(matches!(
            err,
            SessionError::ParentRequestAnchorMismatch { .. }
        ));
    }

    #[test]
    fn url_elicitation_completions_become_session_late_events() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        session.register_pending_url_elicitation("elicit-1", Some("task-7".to_string()));

        session.queue_elicitation_completion("elicit-1");
        session.queue_elicitation_completion("unknown");

        assert_eq!(
            session.take_late_events(),
            vec![LateSessionEvent::ElicitationCompleted {
                elicitation_id: "elicit-1".to_string(),
                related_task_id: Some("task-7".to_string()),
            }]
        );
        assert!(session.take_late_events().is_empty());
    }

    #[test]
    fn tool_server_events_are_filtered_and_stored_per_session() {
        let mut session = Session::new(SessionId::new("sess-1"), "agent-1".to_string(), Vec::new());
        session.activate().unwrap();
        session.subscribe_resource("repo://docs/roadmap");
        session.register_pending_url_elicitation("elicit-2", None);

        session.queue_tool_server_event(ToolServerEvent::ResourceUpdated {
            uri: "repo://secret/ops".to_string(),
        });
        session.queue_tool_server_event(ToolServerEvent::ResourceUpdated {
            uri: "repo://docs/roadmap".to_string(),
        });
        session.queue_tool_server_event(ToolServerEvent::ResourcesListChanged);
        session.queue_tool_server_event(ToolServerEvent::ElicitationCompleted {
            elicitation_id: "elicit-2".to_string(),
        });

        assert_eq!(
            session.take_late_events(),
            vec![
                LateSessionEvent::ResourceUpdated {
                    uri: "repo://docs/roadmap".to_string(),
                },
                LateSessionEvent::ResourcesListChanged,
                LateSessionEvent::ElicitationCompleted {
                    elicitation_id: "elicit-2".to_string(),
                    related_task_id: None,
                },
            ]
        );
    }
}