chio-kernel 0.1.2

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
use std::sync::Arc;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use dashmap::mapref::entry::Entry;
use rand::rngs::OsRng;
use rand::RngCore;

use crate::session::{SessionAnchorSnapshot, SessionRequestStart};

use super::*;

/// Number of CSPRNG bytes used to derive a fresh session id. 16 bytes (128 bits)
/// is well above the birthday-bound budget for any realistic session population
/// and matches the "URL-safe random handle" recipe used elsewhere in the
/// workspace.
const SESSION_ID_ENTROPY_BYTES: usize = 16;

/// Mint a fresh URL-safe session identifier from the operating system's
/// CSPRNG. Random handles prevent external enumeration of active tenants and
/// close the session-fixation surface that sequential ids carry.
fn generate_random_session_id() -> SessionId {
    let mut bytes = [0u8; SESSION_ID_ENTROPY_BYTES];
    OsRng.fill_bytes(&mut bytes);
    // base64url without padding produces 22 chars for 16 bytes; the
    // `sess-` prefix preserves human readability for log scanning.
    SessionId::new(format!("sess-{}", URL_SAFE_NO_PAD.encode(bytes)))
}

fn map_session_persist_error(error: SessionPersistError<KernelError>) -> KernelError {
    match error {
        SessionPersistError::Session(error) => KernelError::Session(error),
        SessionPersistError::Persist(error) => error,
    }
}

fn parse_tool_call_operation_execution_nonce(
    operation: &ToolCallOperation,
) -> Result<Option<crate::execution_nonce::SignedExecutionNonce>, KernelError> {
    match operation.execution_nonce.as_ref() {
        Some(value) => Some(serde_json::from_value(value.clone()).map_err(|error| {
            KernelError::InvalidConstraint(format!(
                "session tool call execution_nonce is malformed: {error}"
            ))
        }))
        .transpose(),
        None => Ok(None),
    }
}

impl ChioKernel {
    pub fn open_session(
        &self,
        agent_id: AgentId,
        issued_capabilities: Vec<CapabilityToken>,
    ) -> Result<SessionId, KernelError> {
        let session_id = generate_random_session_id();

        self.open_session_with_id(session_id, agent_id, issued_capabilities)
    }

    pub fn open_session_with_id(
        &self,
        session_id: SessionId,
        agent_id: AgentId,
        issued_capabilities: Vec<CapabilityToken>,
    ) -> Result<SessionId, KernelError> {
        info!(session_id = %session_id, agent_id = %agent_id, "opening session");
        let session = self.with_sessions_write(|sessions| {
            let session = Arc::new(Session::new(
                session_id.clone(),
                agent_id,
                issued_capabilities,
            ));
            match sessions.entry(session_id.clone()) {
                Entry::Occupied(_) => Err(KernelError::SessionAlreadyExists(session_id.clone())),
                Entry::Vacant(entry) => {
                    entry.insert(Arc::clone(&session));
                    Ok(session)
                }
            }
        })?;
        let session_snapshot = session.session_anchor_snapshot();
        if let Err(error) = self.persist_session_anchor_snapshot(&session_snapshot, None) {
            self.with_sessions_write(|sessions| {
                sessions.remove(&session_id);
                Ok(())
            })?;
            return Err(error);
        }

        Ok(session_id)
    }

    /// Transition a session into the `ready` state once setup is complete.
    pub fn activate_session(&self, session_id: &SessionId) -> Result<(), KernelError> {
        self.validate_web3_evidence_prerequisites()?;
        self.with_session_mut(session_id, |session| {
            session.activate()?;
            Ok(())
        })
    }

    /// Persist transport/session authentication context for a session.
    pub fn set_session_auth_context(
        &self,
        session_id: &SessionId,
        auth_context: SessionAuthContext,
    ) -> Result<(), KernelError> {
        self.with_session_mut(session_id, |session| {
            session
                .set_auth_context_persisted(auth_context, |session_snapshot, supersedes| {
                    self.persist_session_anchor_snapshot(session_snapshot, supersedes)
                })
                .map_err(map_session_persist_error)
        })
    }

    /// Persist peer capabilities negotiated at the edge for a session.
    pub fn set_session_peer_capabilities(
        &self,
        session_id: &SessionId,
        peer_capabilities: PeerCapabilities,
    ) -> Result<(), KernelError> {
        self.with_session_mut(session_id, |session| {
            session.set_peer_capabilities(peer_capabilities);
            Ok(())
        })
    }

    /// Replace the session's current root snapshot.
    pub fn replace_session_roots(
        &self,
        session_id: &SessionId,
        roots: Vec<RootDefinition>,
    ) -> Result<(), KernelError> {
        self.with_session_mut(session_id, |session| {
            session.replace_roots(roots);
            Ok(())
        })
    }

    /// Return the runtime's normalized root view for a session.
    pub fn normalized_session_roots(
        &self,
        session_id: &SessionId,
    ) -> Result<Vec<NormalizedRoot>, KernelError> {
        self.with_session(session_id, |session| Ok(session.normalized_roots()))
    }

    /// Return only the enforceable filesystem root paths for a session.
    pub fn enforceable_filesystem_root_paths(
        &self,
        session_id: &SessionId,
    ) -> Result<Vec<String>, KernelError> {
        self.with_session(session_id, |session| {
            Ok(session
                .enforceable_filesystem_roots()
                .into_iter()
                .filter_map(|root| root.normalized_filesystem_path().map(str::to_string))
                .collect())
        })
    }

    pub(crate) fn session_enforceable_filesystem_root_paths_owned(
        &self,
        session_id: &SessionId,
    ) -> Result<Vec<String>, KernelError> {
        self.with_session(session_id, |session| {
            Ok(session
                .enforceable_filesystem_roots()
                .into_iter()
                .filter_map(|root| root.normalized_filesystem_path().map(str::to_string))
                .collect())
        })
    }

    pub(crate) fn resource_path_within_root(candidate: &str, root: &str) -> bool {
        if candidate == root {
            return true;
        }

        if root == "/" {
            return candidate.starts_with('/');
        }

        candidate
            .strip_prefix(root)
            .map(|suffix| suffix.starts_with('/'))
            .unwrap_or(false)
    }

    pub(crate) fn resource_path_matches_session_roots(
        path: &str,
        session_roots: &[String],
    ) -> bool {
        if session_roots.is_empty() {
            return false;
        }

        session_roots
            .iter()
            .any(|root| Self::resource_path_within_root(path, root))
    }

    pub(crate) fn enforce_resource_roots(
        &self,
        context: &OperationContext,
        operation: &ReadResourceOperation,
    ) -> Result<(), KernelError> {
        match operation.classify_uri_for_runtime() {
            ResourceUriClassification::NonFileSystem { .. } => Ok(()),
            ResourceUriClassification::EnforceableFileSystem {
                normalized_path, ..
            } => {
                let session_roots =
                    self.session_enforceable_filesystem_root_paths_owned(&context.session_id)?;

                if Self::resource_path_matches_session_roots(&normalized_path, &session_roots) {
                    Ok(())
                } else {
                    let reason = if session_roots.is_empty() {
                        "no enforceable filesystem roots are available for this session".to_string()
                    } else {
                        format!(
                            "filesystem-backed resource path {normalized_path} is outside the negotiated roots"
                        )
                    };

                    Err(KernelError::ResourceRootDenied {
                        uri: operation.uri.clone(),
                        reason,
                    })
                }
            }
            ResourceUriClassification::UnenforceableFileSystem { reason, .. } => {
                Err(KernelError::ResourceRootDenied {
                    uri: operation.uri.clone(),
                    reason: format!(
                        "filesystem-backed resource URI could not be enforced: {reason}"
                    ),
                })
            }
        }
    }

    pub(crate) fn build_resource_read_deny_receipt(
        &self,
        operation: &ReadResourceOperation,
        reason: &str,
    ) -> Result<ChioReceipt, KernelError> {
        let receipt_content = receipt_content_for_output(None, None)?;
        let action = ToolCallAction::from_parameters(serde_json::json!({
            "uri": &operation.uri,
        }))
        .map_err(|error| {
            KernelError::ReceiptSigningFailed(format!(
                "failed to hash resource read parameters: {error}"
            ))
        })?;

        let receipt = self.build_and_sign_receipt(ReceiptParams {
            request_id: None,
            capability_id: &operation.capability.id,
            tool_name: "resources/read",
            server_id: "session",
            decision: Decision::Deny {
                reason: reason.to_string(),
                guard: "session_roots".to_string(),
            },
            action,
            content_hash: receipt_content.content_hash,
            canonical_content: receipt_content.canonical_content,
            metadata: merge_metadata_objects(
                Some(serde_json::json!({
                    "resource": {
                        "uri": &operation.uri,
                    }
                })),
                receipt_attribution_metadata(&operation.capability, None),
            ),
            timestamp: current_unix_timestamp(),
            trust_level: chio_core::receipt::kinds::TrustLevel::default(),
            tenant_id: None,
        })?;

        self.record_chio_receipt(&receipt)?;
        Ok(receipt)
    }

    /// Subscribe the session to update notifications for a concrete resource URI.
    pub fn subscribe_session_resource(
        &self,
        session_id: &SessionId,
        capability: &CapabilityToken,
        agent_id: &str,
        uri: &str,
    ) -> Result<(), KernelError> {
        self.validate_non_tool_capability(capability, agent_id)?;

        if !capability_matches_resource_subscription(capability, uri)? {
            return Err(KernelError::OutOfScopeResource {
                uri: uri.to_string(),
            });
        }

        if !self.resource_exists(uri)? {
            return Err(KernelError::ResourceNotRegistered(uri.to_string()));
        }

        self.with_session_mut(session_id, |session| {
            session.subscribe_resource(uri.to_string());
            Ok(())
        })
    }

    /// Remove a session-scoped resource subscription. Missing subscriptions are ignored.
    pub fn unsubscribe_session_resource(
        &self,
        session_id: &SessionId,
        uri: &str,
    ) -> Result<(), KernelError> {
        self.with_session_mut(session_id, |session| {
            session.unsubscribe_resource(uri);
            Ok(())
        })
    }

    /// Check whether a session currently holds a resource subscription.
    pub fn session_has_resource_subscription(
        &self,
        session_id: &SessionId,
        uri: &str,
    ) -> Result<bool, KernelError> {
        self.with_session(
            session_id,
            |session| Ok(session.is_resource_subscribed(uri)),
        )
    }

    /// Mark a session as draining. New tool calls are rejected after this point.
    pub fn begin_draining_session(&self, session_id: &SessionId) -> Result<(), KernelError> {
        self.with_session_mut(session_id, |session| {
            session.begin_draining()?;
            Ok(())
        })
    }

    /// Close a session and clear transient session-scoped state.
    pub fn close_session(&self, session_id: &SessionId) -> Result<(), KernelError> {
        self.with_session_mut(session_id, |session| {
            session
                .close_persisted(|session_snapshot, supersedes| {
                    self.persist_session_anchor_snapshot(session_snapshot, supersedes)
                })
                .map_err(map_session_persist_error)
        })
    }

    /// Inspect an existing session.
    pub fn session(&self, session_id: &SessionId) -> Option<Session> {
        self.with_sessions_read(|sessions| {
            Ok(sessions
                .get(session_id)
                .map(|session| session.value().as_ref().clone()))
        })
        .ok()
        .flatten()
    }

    pub fn session_count(&self) -> usize {
        self.with_sessions_read(|sessions| Ok(sessions.len()))
            .unwrap_or(0)
    }

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

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

    /// Validate a session-scoped operation and register it as in flight.
    pub fn begin_session_request(
        &self,
        context: &OperationContext,
        operation_kind: OperationKind,
        cancellable: bool,
    ) -> Result<(), KernelError> {
        let start = self.with_sessions_write(|sessions| {
            begin_session_request_in_sessions(sessions, context, operation_kind, cancellable)
        })?;
        if let Err(error) = self.persist_request_lineage_snapshot(&start) {
            let _ = self.with_sessions_write(|sessions| {
                if let Ok(session) = session_from_map(sessions, &start.session.session_id) {
                    session.discard_unpersisted_request_start(&start.lineage.request_id);
                }
                Ok(())
            });
            return Err(error);
        }
        Ok(())
    }

    fn begin_or_resume_execution_nonce_request(
        &self,
        context: &OperationContext,
        operation_kind: OperationKind,
        execution_nonce: Option<&crate::execution_nonce::SignedExecutionNonce>,
    ) -> Result<(), KernelError> {
        if let Some(nonce) = execution_nonce
            .filter(|nonce| nonce.nonce.bound_to.request_id == context.request_id.as_str())
        {
            let resumed = self.with_sessions_read(|sessions| {
                let session = session_from_map(sessions, &context.session_id)?;
                if session.inflight().get(&context.request_id).is_some() {
                    session.validate_execution_nonce_retry(
                        context,
                        operation_kind,
                        nonce.nonce_id(),
                    )?;
                    return Ok(true);
                }
                if session.terminal().get(&context.request_id).is_some() {
                    return Err(crate::session::SessionError::ExecutionNonceRetryMismatch {
                        request_id: context.request_id.clone(),
                    }
                    .into());
                }
                Ok(false)
            })?;
            if resumed {
                return Ok(());
            }
        }
        self.begin_session_request(context, operation_kind, true)
    }

    fn finish_execution_nonce_request(
        &self,
        context: &OperationContext,
        response: Option<&ToolCallResponse>,
        terminal_state: OperationTerminalState,
    ) -> Result<(), KernelError> {
        if let Some(nonce) = response
            .filter(|response| response.output.is_none())
            .and_then(|response| response.execution_nonce.as_deref())
        {
            return self.with_sessions_write(|sessions| {
                session_from_map(sessions, &context.session_id)?
                    .mark_execution_nonce_pending(&context.request_id, nonce.nonce_id())?;
                Ok(())
            });
        }
        self.complete_session_request_with_terminal_state(
            &context.session_id,
            &context.request_id,
            terminal_state,
        )
    }

    /// Construct and register a child request under an existing parent request.
    pub fn begin_child_request(
        &self,
        parent_context: &OperationContext,
        request_id: RequestId,
        operation_kind: OperationKind,
        progress_token: Option<ProgressToken>,
        cancellable: bool,
    ) -> Result<OperationContext, KernelError> {
        let (child_context, start) = self.with_sessions_write(|sessions| {
            begin_child_request_in_sessions(
                sessions,
                parent_context,
                request_id,
                operation_kind,
                progress_token,
                cancellable,
            )
        })?;
        if let Err(error) = self.persist_request_lineage_snapshot(&start) {
            let _ = self.with_sessions_write(|sessions| {
                if let Ok(session) = session_from_map(sessions, &start.session.session_id) {
                    session.discard_unpersisted_request_start(&start.lineage.request_id);
                }
                Ok(())
            });
            return Err(error);
        }
        Ok(child_context)
    }

    /// Complete an in-flight session request.
    pub fn complete_session_request(
        &self,
        session_id: &SessionId,
        request_id: &RequestId,
    ) -> Result<(), KernelError> {
        self.complete_session_request_with_terminal_state(
            session_id,
            request_id,
            OperationTerminalState::Completed,
        )
    }

    /// Complete an in-flight session request with an explicit terminal state.
    pub fn complete_session_request_with_terminal_state(
        &self,
        session_id: &SessionId,
        request_id: &RequestId,
        terminal_state: OperationTerminalState,
    ) -> Result<(), KernelError> {
        self.with_sessions_write(|sessions| {
            complete_session_request_with_terminal_state_in_sessions(
                sessions,
                session_id,
                request_id,
                terminal_state,
            )
        })
    }

    fn signed_session_anchor_for_snapshot(
        &self,
        snapshot: &SessionAnchorSnapshot,
    ) -> Result<chio_core::session::SessionAnchor, KernelError> {
        let body = chio_core::session::SessionAnchorBody::new(
            snapshot.session_anchor.id().to_string(),
            chio_core::session::SessionAnchorContext::new(
                snapshot.session_id.clone(),
                snapshot.agent_id.clone(),
                snapshot.auth_context.clone(),
                chio_core::session::SessionProofBinding::from_auth_context(&snapshot.auth_context),
            ),
            snapshot.session_anchor.auth_epoch(),
            snapshot.session_anchor.issued_at(),
            self.config.keypair.public_key(),
        )
        .map_err(|error| {
            KernelError::Internal(format!("failed to build session anchor body: {error}"))
        })?;

        chio_core::session::SessionAnchor::sign(body, &self.config.keypair).map_err(|error| {
            KernelError::Internal(format!("failed to sign session anchor: {error}"))
        })
    }

    fn persist_session_anchor_snapshot(
        &self,
        session: &SessionAnchorSnapshot,
        supersedes_anchor_id: Option<&str>,
    ) -> Result<(), KernelError> {
        let anchor = self.signed_session_anchor_for_snapshot(session)?;
        let anchor_json = serde_json::to_value(&anchor).map_err(|error| {
            KernelError::Internal(format!("failed to serialize session anchor: {error}"))
        })?;
        self.with_receipt_store(|store| {
            Ok(store.record_session_anchor(
                session.session_id.as_str(),
                &anchor.id,
                &anchor.auth_context_hash,
                anchor.issued_at,
                supersedes_anchor_id,
                &anchor_json,
            )?)
        })?;
        Ok(())
    }

    fn persist_request_lineage_snapshot(
        &self,
        start: &SessionRequestStart,
    ) -> Result<(), KernelError> {
        let local_lineage = &start.lineage;
        let anchor = self.signed_session_anchor_for_snapshot(&start.session)?;
        let anchor_reference = anchor.reference().map_err(|error| {
            KernelError::Internal(format!(
                "failed to derive session anchor reference: {error}"
            ))
        })?;
        let lineage_mode = if local_lineage.parent_request_id.is_some() {
            chio_core::session::RequestLineageMode::LocalChild
        } else {
            chio_core::session::RequestLineageMode::Root
        };
        let mut lineage_record = chio_core::session::RequestLineageRecord::new(
            local_lineage.request_id.clone(),
            anchor_reference,
            local_lineage.operation_kind,
            lineage_mode,
            local_lineage.started_at,
        );
        if let Some(parent_request_id) = local_lineage.parent_request_id.clone() {
            lineage_record = lineage_record.with_parent_request_id(parent_request_id);
        }
        let lineage_json = serde_json::to_value(&lineage_record).map_err(|error| {
            KernelError::Internal(format!("failed to serialize request lineage: {error}"))
        })?;
        self.with_receipt_store(|store| {
            Ok(store.record_request_lineage(
                start.session.session_id.as_str(),
                local_lineage.request_id.as_str(),
                local_lineage
                    .parent_request_id
                    .as_ref()
                    .map(|value| value.as_str()),
                Some(anchor.id.as_str()),
                local_lineage.started_at,
                None,
                &lineage_json,
            )?)
        })?;
        Ok(())
    }

    /// Mark an in-flight session request as cancelled.
    pub fn request_session_cancellation(
        &self,
        session_id: &SessionId,
        request_id: &RequestId,
    ) -> Result<(), KernelError> {
        self.with_session_mut(session_id, |session| {
            session
                .request_cancellation(request_id)
                .map_err(KernelError::from)
        })
    }

    /// Validate whether a sampling child request is allowed for this session.
    pub fn validate_sampling_request(
        &self,
        context: &OperationContext,
        operation: &CreateMessageOperation,
    ) -> Result<(), KernelError> {
        self.with_sessions_read(|sessions| {
            validate_sampling_request_in_sessions(
                sessions,
                self.config.allow_sampling,
                self.config.allow_sampling_tool_use,
                context,
                operation,
            )
        })
    }

    /// Validate whether an elicitation child request is allowed for this session.
    pub fn validate_elicitation_request(
        &self,
        context: &OperationContext,
        operation: &CreateElicitationOperation,
    ) -> Result<(), KernelError> {
        self.with_sessions_read(|sessions| {
            validate_elicitation_request_in_sessions(
                sessions,
                self.config.allow_elicitation,
                context,
                operation,
            )
        })
    }

    /// Evaluate a session-scoped tool call while allowing the target tool server to proxy
    /// negotiated nested flows back through a client transport owned by the edge.
    pub fn evaluate_tool_call_operation_with_nested_flow_client<C: NestedFlowClient>(
        &self,
        context: &OperationContext,
        operation: &ToolCallOperation,
        client: &mut C,
    ) -> Result<ToolCallResponse, KernelError> {
        self.validate_web3_evidence_prerequisites()?;
        let execution_nonce = parse_tool_call_operation_execution_nonce(operation)?;
        self.begin_or_resume_execution_nonce_request(
            context,
            OperationKind::ToolCall,
            execution_nonce.as_ref(),
        )?;

        let request = ToolCallRequest {
            request_id: context.request_id.to_string(),
            capability: operation.capability.clone(),
            tool_name: operation.tool_name.clone(),
            server_id: operation.server_id.clone(),
            agent_id: context.agent_id.clone(),
            arguments: operation.arguments.clone(),
            dpop_proof: None,
            execution_nonce,
            governed_intent: operation.governed_intent.clone(),
            approval_token: operation.approval_token.clone(),
            approval_tokens: operation.approval_tokens.clone(),
            threshold_approval_proposal: operation.threshold_approval_proposal.clone(),
            supplemental_authorization: operation.supplemental_authorization.clone(),
            model_metadata: operation.model_metadata.clone(),
            federated_origin_kernel_id: None,
        };

        let result = self.evaluate_tool_call_with_nested_flow_client(
            context,
            &request,
            client,
            operation.extra_metadata.clone(),
        );
        let terminal_state = match &result {
            Ok(response) => response.terminal_state.clone(),
            Err(KernelError::RequestCancelled { request_id, reason })
                if request_id == &context.request_id =>
            {
                self.with_session_mut(&context.session_id, |session| {
                    session.request_cancellation(&context.request_id)?;
                    Ok(())
                })?;
                OperationTerminalState::Cancelled {
                    reason: reason.clone(),
                }
            }
            _ => OperationTerminalState::Completed,
        };
        self.finish_execution_nonce_request(context, result.as_ref().ok(), terminal_state)?;
        result
    }

    /// Async-native variant for hosts that already run inside a Tokio runtime.
    ///
    /// This path avoids the synchronous dispatch bridge, so current-thread
    /// runtimes do not convert nested-flow tool calls into bridge errors. The
    /// synchronous entrypoint remains for blocking edges and still fails before
    /// side effects when a current-thread runtime is entered.
    pub async fn evaluate_tool_call_operation_with_nested_flow_client_async<C: NestedFlowClient>(
        &self,
        context: &OperationContext,
        operation: &ToolCallOperation,
        client: &mut C,
    ) -> Result<ToolCallResponse, KernelError> {
        self.validate_web3_evidence_prerequisites()?;
        let execution_nonce = parse_tool_call_operation_execution_nonce(operation)?;
        self.begin_or_resume_execution_nonce_request(
            context,
            OperationKind::ToolCall,
            execution_nonce.as_ref(),
        )?;

        let request = ToolCallRequest {
            request_id: context.request_id.to_string(),
            capability: operation.capability.clone(),
            tool_name: operation.tool_name.clone(),
            server_id: operation.server_id.clone(),
            agent_id: context.agent_id.clone(),
            arguments: operation.arguments.clone(),
            dpop_proof: None,
            execution_nonce,
            governed_intent: operation.governed_intent.clone(),
            approval_token: operation.approval_token.clone(),
            approval_tokens: operation.approval_tokens.clone(),
            threshold_approval_proposal: operation.threshold_approval_proposal.clone(),
            supplemental_authorization: operation.supplemental_authorization.clone(),
            model_metadata: operation.model_metadata.clone(),
            federated_origin_kernel_id: None,
        };

        let result = self
            .evaluate_tool_call_with_nested_flow_client_async(
                context,
                &request,
                client,
                operation.extra_metadata.clone(),
            )
            .await;
        let terminal_state = match &result {
            Ok(response) => response.terminal_state.clone(),
            Err(KernelError::RequestCancelled { request_id, reason })
                if request_id == &context.request_id =>
            {
                self.with_session_mut(&context.session_id, |session| {
                    session.request_cancellation(&context.request_id)?;
                    Ok(())
                })?;
                OperationTerminalState::Cancelled {
                    reason: reason.clone(),
                }
            }
            _ => OperationTerminalState::Completed,
        };
        self.finish_execution_nonce_request(context, result.as_ref().ok(), terminal_state)?;
        result
    }

    /// Evaluate a normalized operation against a specific session.
    ///
    /// This is the higher-level entry point that future JSON-RPC or MCP edges
    /// should target. The current stdio loop normalizes raw frames into these
    /// operations before invoking the kernel.
    pub fn evaluate_session_operation(
        &self,
        context: &OperationContext,
        operation: &SessionOperation,
    ) -> Result<SessionOperationResponse, KernelError> {
        // Install tenant_id scope for the duration of this session-scoped
        // evaluation so every receipt signed here (tool call, resource read
        // deny, etc.) is tagged with the session's tenant. The ToolCall
        // branch also installs a scope via its sync_with_session_context
        // path; the nested scope is a no-op because the value matches, but
        // it keeps non-tool-call branches (e.g. evaluate_resource_read)
        // covered.
        let tenant_id = self.resolve_tenant_id_for_session(Some(&context.session_id));
        let _tenant_request_scope = self
            .scope_receipt_tenant_id_for_request(context.request_id.as_str(), tenant_id.clone());
        let _tenant_scope = scope_receipt_tenant_id(tenant_id);

        self.validate_web3_evidence_prerequisites()?;
        let operation_kind = operation.kind();
        let should_track_inflight = matches!(
            operation,
            SessionOperation::ToolCall(_)
                | SessionOperation::ReadResource(_)
                | SessionOperation::GetPrompt(_)
                | SessionOperation::Complete(_)
        );
        let parsed_tool_call_execution_nonce = match operation {
            SessionOperation::ToolCall(tool_call) => {
                parse_tool_call_operation_execution_nonce(tool_call)?
            }
            _ => None,
        };

        if should_track_inflight {
            if matches!(operation, SessionOperation::ToolCall(_)) {
                self.begin_or_resume_execution_nonce_request(
                    context,
                    operation_kind,
                    parsed_tool_call_execution_nonce.as_ref(),
                )?;
            } else {
                self.begin_session_request(context, operation_kind, true)?;
            }
        } else {
            self.with_session_mut(&context.session_id, |session| {
                session.validate_context(context)?;
                session.ensure_operation_allowed(operation_kind)?;
                Ok(())
            })?;
        }

        let evaluation = match operation {
            SessionOperation::ToolCall(tool_call) => {
                let request = ToolCallRequest {
                    request_id: context.request_id.to_string(),
                    capability: tool_call.capability.clone(),
                    tool_name: tool_call.tool_name.clone(),
                    server_id: tool_call.server_id.clone(),
                    agent_id: context.agent_id.clone(),
                    arguments: tool_call.arguments.clone(),
                    dpop_proof: None,
                    execution_nonce: parsed_tool_call_execution_nonce,
                    governed_intent: tool_call.governed_intent.clone(),
                    approval_token: tool_call.approval_token.clone(),
                    approval_tokens: tool_call.approval_tokens.clone(),
                    threshold_approval_proposal: tool_call.threshold_approval_proposal.clone(),
                    supplemental_authorization: tool_call.supplemental_authorization.clone(),
                    model_metadata: tool_call.model_metadata.clone(),
                    federated_origin_kernel_id: None,
                };
                let session_roots =
                    self.session_enforceable_filesystem_root_paths_owned(&context.session_id)?;

                // Pass the session_id so the evaluate path can resolve
                // tenant_id from session.auth_context for every receipt
                // signed during this tool call.
                self.evaluate_tool_call_sync_with_session_context(
                    &request,
                    Some(session_roots.as_slice()),
                    tool_call.extra_metadata.clone(),
                    Some(&context.session_id),
                )
                .map(SessionOperationResponse::ToolCall)
            }
            SessionOperation::CreateMessage(_) => Err(KernelError::Internal(
                "sampling/createMessage must be evaluated by an MCP edge with a client transport"
                    .to_string(),
            )),
            SessionOperation::CreateElicitation(_) => Err(KernelError::Internal(
                "elicitation/create must be evaluated by an MCP edge with a client transport"
                    .to_string(),
            )),
            SessionOperation::ListRoots => {
                let roots = self
                    .session(&context.session_id)
                    .ok_or_else(|| KernelError::UnknownSession(context.session_id.clone()))?
                    .roots();
                Ok(SessionOperationResponse::RootList { roots })
            }
            SessionOperation::ListResources => {
                let resources = self
                    .list_resources_for_session(&context.session_id)?
                    .into_iter()
                    .collect();
                Ok(SessionOperationResponse::ResourceList { resources })
            }
            SessionOperation::ReadResource(resource_read) => {
                self.evaluate_resource_read(context, resource_read)
            }
            SessionOperation::ListResourceTemplates => {
                let templates = self.list_resource_templates_for_session(&context.session_id)?;
                Ok(SessionOperationResponse::ResourceTemplateList { templates })
            }
            SessionOperation::ListPrompts => {
                let prompts = self.list_prompts_for_session(&context.session_id)?;
                Ok(SessionOperationResponse::PromptList { prompts })
            }
            SessionOperation::GetPrompt(prompt_get) => self
                .evaluate_prompt_get(context, prompt_get)
                .map(|prompt| SessionOperationResponse::PromptGet { prompt }),
            SessionOperation::Complete(complete) => self
                .evaluate_completion(context, complete)
                .map(|completion| SessionOperationResponse::Completion { completion }),
            SessionOperation::ListCapabilities => {
                let capabilities = self
                    .session(&context.session_id)
                    .ok_or_else(|| KernelError::UnknownSession(context.session_id.clone()))?
                    .capabilities()
                    .to_vec();

                Ok(SessionOperationResponse::CapabilityList { capabilities })
            }
            SessionOperation::Heartbeat => Ok(SessionOperationResponse::Heartbeat),
        };

        if should_track_inflight {
            let terminal_state = match &evaluation {
                Ok(SessionOperationResponse::ToolCall(response)) => response.terminal_state.clone(),
                _ => OperationTerminalState::Completed,
            };
            let response = match &evaluation {
                Ok(SessionOperationResponse::ToolCall(response)) => Some(response),
                _ => None,
            };
            self.finish_execution_nonce_request(context, response, terminal_state)?;
        }

        evaluation
    }

    pub(crate) fn list_resources_for_session(
        &self,
        session_id: &SessionId,
    ) -> Result<Vec<ResourceDefinition>, KernelError> {
        let session = self
            .session(session_id)
            .ok_or_else(|| KernelError::UnknownSession(session_id.clone()))?;

        let mut resources = Vec::new();
        for provider in &self.resource_providers {
            resources.extend(provider.list_resources().into_iter().filter(|resource| {
                session.capabilities().iter().any(|capability| {
                    capability_matches_resource_request(capability, &resource.uri).unwrap_or(false)
                })
            }));
        }

        Ok(resources)
    }

    pub(crate) fn resource_exists(&self, uri: &str) -> Result<bool, KernelError> {
        for provider in &self.resource_providers {
            if provider
                .list_resources()
                .iter()
                .any(|resource| resource.uri == uri)
            {
                return Ok(true);
            }

            if provider.read_resource(uri)?.is_some() {
                return Ok(true);
            }
        }

        Ok(false)
    }

    pub(crate) fn list_resource_templates_for_session(
        &self,
        session_id: &SessionId,
    ) -> Result<Vec<ResourceTemplateDefinition>, KernelError> {
        let session = self
            .session(session_id)
            .ok_or_else(|| KernelError::UnknownSession(session_id.clone()))?;

        let mut templates = Vec::new();
        for provider in &self.resource_providers {
            templates.extend(
                provider
                    .list_resource_templates()
                    .into_iter()
                    .filter(|template| {
                        session.capabilities().iter().any(|capability| {
                            capability_matches_resource_pattern(capability, &template.uri_template)
                                .unwrap_or(false)
                        })
                    }),
            );
        }

        Ok(templates)
    }

    pub(crate) fn evaluate_resource_read(
        &self,
        context: &OperationContext,
        operation: &ReadResourceOperation,
    ) -> Result<SessionOperationResponse, KernelError> {
        self.validate_non_tool_capability(&operation.capability, &context.agent_id)?;

        if !capability_matches_resource_request(&operation.capability, &operation.uri)? {
            return Err(KernelError::OutOfScopeResource {
                uri: operation.uri.clone(),
            });
        }

        match self.enforce_resource_roots(context, operation) {
            Ok(()) => {}
            Err(KernelError::ResourceRootDenied { reason, .. }) => {
                let receipt = self.build_resource_read_deny_receipt(operation, &reason)?;
                return Ok(SessionOperationResponse::ResourceReadDenied { receipt });
            }
            Err(error) => return Err(error),
        }

        for provider in &self.resource_providers {
            if let Some(contents) = provider.read_resource(&operation.uri)? {
                return Ok(SessionOperationResponse::ResourceRead { contents });
            }
        }

        Err(KernelError::ResourceNotRegistered(operation.uri.clone()))
    }

    pub(crate) fn list_prompts_for_session(
        &self,
        session_id: &SessionId,
    ) -> Result<Vec<PromptDefinition>, KernelError> {
        let session = self
            .session(session_id)
            .ok_or_else(|| KernelError::UnknownSession(session_id.clone()))?;

        let mut prompts = Vec::new();
        for provider in &self.prompt_providers {
            prompts.extend(provider.list_prompts().into_iter().filter(|prompt| {
                session.capabilities().iter().any(|capability| {
                    capability_matches_prompt_request(capability, &prompt.name).unwrap_or(false)
                })
            }));
        }

        Ok(prompts)
    }

    pub(crate) fn evaluate_prompt_get(
        &self,
        context: &OperationContext,
        operation: &GetPromptOperation,
    ) -> Result<PromptResult, KernelError> {
        self.validate_non_tool_capability(&operation.capability, &context.agent_id)?;

        if !capability_matches_prompt_request(&operation.capability, &operation.prompt_name)? {
            return Err(KernelError::OutOfScopePrompt {
                prompt: operation.prompt_name.clone(),
            });
        }

        for provider in &self.prompt_providers {
            if let Some(prompt) =
                provider.get_prompt(&operation.prompt_name, operation.arguments.clone())?
            {
                return Ok(prompt);
            }
        }

        Err(KernelError::PromptNotRegistered(
            operation.prompt_name.clone(),
        ))
    }

    pub(crate) fn evaluate_completion(
        &self,
        context: &OperationContext,
        operation: &CompleteOperation,
    ) -> Result<CompletionResult, KernelError> {
        self.validate_non_tool_capability(&operation.capability, &context.agent_id)?;

        match &operation.reference {
            CompletionReference::Prompt { name } => {
                if !capability_matches_prompt_request(&operation.capability, name)? {
                    return Err(KernelError::OutOfScopePrompt {
                        prompt: name.clone(),
                    });
                }

                for provider in &self.prompt_providers {
                    if let Some(completion) = provider.complete_prompt_argument(
                        name,
                        &operation.argument.name,
                        &operation.argument.value,
                        &operation.context_arguments,
                    )? {
                        return Ok(completion);
                    }
                }

                Err(KernelError::PromptNotRegistered(name.clone()))
            }
            CompletionReference::Resource { uri } => {
                if !capability_matches_resource_pattern(&operation.capability, uri)? {
                    return Err(KernelError::OutOfScopeResource { uri: uri.clone() });
                }

                for provider in &self.resource_providers {
                    if let Some(completion) = provider.complete_resource_argument(
                        uri,
                        &operation.argument.name,
                        &operation.argument.value,
                        &operation.context_arguments,
                    )? {
                        return Ok(completion);
                    }
                }

                Err(KernelError::ResourceNotRegistered(uri.clone()))
            }
        }
    }
}