bcode_server 0.0.1-alpha.0

Local bcode daemon runtime
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
//! Transport-neutral application operations for permissions and pending tool exchanges.

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex as StdMutex};

use tokio::sync::Mutex;

use super::{
    ClientId, PendingPermission, PendingPermissionBatch, PendingToolExchange, ServerState,
    SessionId, SkillToolDecision, SkillToolDecisionKey, ToolExchangeResolution, TurnCancelState,
    current_time_ms, publish_session_event,
};
use bcode_session_models::PendingToolExchangeSummary;

/// Application-level failure while resolving a pending tool exchange.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolveToolExchangeError {
    /// The requesting client did not advertise a compatible exchange adapter.
    IncompatibleConsumer,
    /// The serialized resolution is malformed or uses an unknown variant.
    InvalidResolution,
}

impl ResolveToolExchangeError {
    /// Stable public operation error code.
    #[must_use]
    pub const fn code(self) -> &'static str {
        match self {
            Self::IncompatibleConsumer => "incompatible_exchange_consumer",
            Self::InvalidResolution => "invalid_exchange_resolution",
        }
    }

    /// Secret-safe public operation error message.
    #[must_use]
    pub const fn message(self) -> &'static str {
        match self {
            Self::IncompatibleConsumer => "client did not advertise a compatible exchange adapter",
            Self::InvalidResolution => "tool exchange resolution is malformed or unsupported",
        }
    }
}

async fn append_permission_requested_event(
    state: &ServerState,
    session_id: SessionId,
    request: bcode_session_models::SessionEventKind,
) -> bool {
    match state
        .sessions
        .append_permission_requested(session_id, request)
        .await
    {
        Ok(event) => {
            publish_session_event(state, &event).await;
            true
        }
        Err(error) => {
            tracing::warn!("failed to append permission request: {error}");
            false
        }
    }
}

async fn append_permission_resolved_event(
    state: &ServerState,
    session_id: SessionId,
    permission_id: String,
    approved: bool,
) -> bool {
    match state
        .sessions
        .append_permission_resolved(session_id, permission_id, approved)
        .await
    {
        Ok(event) => {
            publish_session_event(state, &event).await;
            true
        }
        Err(error) => {
            tracing::warn!("failed to append permission result: {error}");
            false
        }
    }
}

impl PendingPermissionBatch {
    /// Create one unresolved batch state.
    #[must_use]
    pub const fn new(session_id: SessionId) -> Self {
        Self {
            session_id,
            decision: Mutex::const_new(None),
        }
    }
}

/// Return a remembered skill-tool permission decision when user state is available.
pub fn remembered_skill_tool_decision(key: &SkillToolDecisionKey) -> Option<SkillToolDecision> {
    bcode_settings::SettingsStore::default()
        .skill_tool_decisions()
        .ok()
        .and_then(|state| state.decision_for(key).map(|entry| entry.decision))
}

fn remember_skill_tool_decision(key: SkillToolDecisionKey, decision: SkillToolDecision) {
    let store = bcode_settings::SettingsStore::default();
    let Ok(mut state) = store.skill_tool_decisions() else {
        return;
    };
    state.upsert(bcode_skill_models::SkillToolDecisionEntry {
        key,
        decision,
        remembered_at_ms: current_time_ms(),
        reason: Some("remembered from permission dialog".to_owned()),
    });
    let _ = store.save_skill_tool_decisions(&state, current_time_ms());
}

/// Allocate the next process-local pending permission identity.
pub async fn next_permission_id(state: &ServerState) -> String {
    let mut next = state.next_permission_id.lock().await;
    let permission_id = format!("perm-{}-{}", state.daemon_status.instance_id, *next);
    *next += 1;
    permission_id
}

/// Allocate the next process-local permission batch identity.
pub async fn next_permission_batch_id(state: &ServerState) -> String {
    let mut next = state.next_permission_batch_id.lock().await;
    let batch_id = format!(
        "permission-batch-{}-{}",
        state.daemon_status.instance_id, *next
    );
    *next += 1;
    batch_id
}

/// Scoped registration for one permission batch.
pub struct PendingPermissionBatchRegistration {
    batches: Arc<StdMutex<BTreeMap<String, Arc<PendingPermissionBatch>>>>,
    batch_id: String,
}

impl PendingPermissionBatchRegistration {
    /// Allocate and register one unresolved batch until this guard is dropped.
    pub async fn allocate(state: &ServerState, session_id: SessionId) -> (String, Self) {
        let batch_id = next_permission_batch_id(state).await;
        let registration = Self::register(state, batch_id.clone(), session_id);
        (batch_id, registration)
    }

    /// Register one unresolved batch until this guard is dropped.
    #[must_use]
    pub fn register(state: &ServerState, batch_id: String, session_id: SessionId) -> Self {
        let batch = Arc::new(PendingPermissionBatch::new(session_id));
        state
            .pending_permission_batches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(batch_id.clone(), batch);
        Self {
            batches: Arc::clone(&state.pending_permission_batches),
            batch_id,
        }
    }
}

impl Drop for PendingPermissionBatchRegistration {
    fn drop(&mut self) {
        self.batches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(&self.batch_id);
    }
}

/// Normalized permission-rule update failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionRuleError {
    /// The configuration owner rejected the category.
    UnknownCategory,
    /// The configuration owner rejected the action.
    UnknownAction,
    /// Permission state could not be read or updated.
    StateUnavailable,
}

impl PermissionRuleError {
    /// Secret-safe diagnostic suitable for application clients.
    #[must_use]
    pub const fn message(self) -> &'static str {
        match self {
            Self::UnknownCategory => {
                "unknown permission category; expected command, read, write, edit, or web"
            }
            Self::UnknownAction => "unknown permission action; expected allow, ask, or deny",
            Self::StateUnavailable => "permission state could not be read or updated",
        }
    }
}

impl From<bcode_config::ConfigError> for PermissionRuleError {
    fn from(error: bcode_config::ConfigError) -> Self {
        match error {
            bcode_config::ConfigError::UnknownPermissionCategory(_) => Self::UnknownCategory,
            bcode_config::ConfigError::UnknownPermissionAction(_) => Self::UnknownAction,
            bcode_config::ConfigError::Io { .. }
            | bcode_config::ConfigError::Composition { .. }
            | bcode_config::ConfigError::RemovedShorthandToolId { .. }
            | bcode_config::ConfigError::RemovedPermissionCategory { .. } => Self::StateUnavailable,
        }
    }
}

/// Persist one normalized agent permission rule through the configuration owner.
///
/// # Errors
///
/// Returns a normalized failure when the rule fields or permission state update are invalid.
pub fn add_permission_rule(
    agent_id: &str,
    category: &str,
    pattern: String,
    action: &str,
) -> Result<PathBuf, PermissionRuleError> {
    bcode_config::upsert_agent_permission_rule(agent_id, category, pattern, action)
        .map_err(PermissionRuleError::from)
}

/// Register one pending permission while preserving its optional batch-decision latch.
///
/// Returns the already-latched decision when the batch has already resolved, or denial when the
/// referenced batch is no longer active.
pub async fn register_pending_permission(
    state: &ServerState,
    pending: &PendingPermission,
    event: bcode_session_models::SessionEventKind,
) -> Result<(), bool> {
    let batch_state = pending.summary.batch.as_ref().and_then(|batch| {
        state
            .pending_permission_batches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(&batch.batch_id)
            .cloned()
    });
    if pending.summary.batch.is_some() && batch_state.is_none() {
        return Err(false);
    }
    let batch_decision = if let Some(batch_state) = batch_state.as_ref() {
        let decision = batch_state.decision.lock().await;
        if let Some(decision) = *decision {
            return Err(decision);
        }
        Some(decision)
    } else {
        None
    };
    let mut routed = pending.clone();
    routed.summary.interaction_route = state
        .session_current_turn(pending.summary.session_id)
        .await
        .and_then(|turn| turn.interaction_route);
    if !append_permission_requested_event(state, pending.summary.session_id, event).await {
        return Err(false);
    }
    state
        .pending_permissions
        .lock()
        .await
        .insert(pending.summary.permission_id.clone(), routed.clone());
    notify_interaction_destination(state, &routed.summary).await;
    drop(batch_decision);
    Ok(())
}

/// Notify clients to refresh the destination through the normal bounded snapshot boundary.
/// This is only an invalidation; canonical permission state remains in the source session.
async fn notify_interaction_destination(
    state: &ServerState,
    permission: &bcode_session_models::PermissionSummary,
) {
    notify_route_destination(state, permission.interaction_route.as_ref()).await;
}

async fn notify_route_destination(
    state: &ServerState,
    route: Option<&bcode_session_models::ExecutionInteractionRoute>,
) {
    use futures::StreamExt as _;

    let Some(route) = route else {
        return;
    };
    let _ = state
        .interaction_invalidations
        .send(route.destination_session_id);
    let sinks = state.workflow_event_sinks().await;
    futures::stream::iter(sinks)
        .for_each_concurrent(32, |sink| async move {
            let _ = tokio::time::timeout(
                std::time::Duration::from_secs(1),
                sink.send(bcode_ipc::Event::SessionViewResyncRequired {
                    session_id: route.destination_session_id,
                }),
            )
            .await;
        })
        .await;
}

/// Read one current permission-batch decision for focused verification.
#[cfg(test)]
pub async fn permission_batch_decision(state: &ServerState, batch_id: &str) -> Option<bool> {
    let batch = state
        .pending_permission_batches
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(batch_id)
        .cloned()?;
    *batch.decision.lock().await
}

/// Restore visibility of a verified canonical wait without appending another request.
/// Recovery's caller holds execution authority; this operation grants no dispatch permission.
pub async fn restore_permission(
    state: &ServerState,
    checkpoint: bcode_session::InvocationRecoveryCheckpoint,
) -> Result<(), super::ServerError> {
    let (bcode_session_models::SessionEventKind::UserMessage { admission, .. }
    | bcode_session_models::SessionEventKind::SubmissionActivated { admission, .. }) =
        &checkpoint.turn().kind
    else {
        return Ok(());
    };
    super::validate_interaction_route(state, checkpoint.session_id(), &admission.execution).await?;
    let bcode_session_models::SessionEventKind::PermissionRequested {
        permission_id,
        tool_call_id,
        tool_name,
        arguments_json,
        policy_source,
        policy_reason,
        ..
    } = &checkpoint.permission().kind
    else {
        return Ok(());
    };
    let pending = PendingPermission {
        summary: bcode_session_models::PermissionSummary {
            permission_id: permission_id.clone(),
            session_id: checkpoint.session_id(),
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_name.clone(),
            arguments_json: arguments_json.clone(),
            batch: None,
            agent_id: admission
                .execution
                .agent_profile
                .clone()
                .unwrap_or_else(|| "build".into()),
            interaction_route: admission.execution.interaction_route.clone(),
            policy_source: policy_source.clone(),
            policy_reason: policy_reason.clone(),
            can_remember_policy: false,
        },
        decision: Arc::new(Mutex::new(None)),
        notify: Arc::new(tokio::sync::Notify::new()),
        skill_decision_key: None,
    };
    let mut recovered = state.recovered_permissions.lock().await;
    let mut permissions = state.pending_permissions.lock().await;
    if !permissions.contains_key(permission_id) {
        permissions.insert(permission_id.clone(), pending.clone());
        recovered.insert(permission_id.clone(), checkpoint);
    }
    drop(permissions);
    drop(recovered);
    notify_interaction_destination(state, &pending.summary).await;
    Ok(())
}

/// Return current pending permission summaries without transport framing.
pub async fn list_permissions(state: &ServerState) -> Vec<bcode_session_models::PermissionSummary> {
    let mut permissions = state
        .pending_permissions
        .lock()
        .await
        .values()
        .map(|permission| permission.summary.clone())
        .collect::<Vec<_>>();
    permissions.sort_by(|left, right| left.permission_id.cmp(&right.permission_id));
    permissions
}

/// Resolve one pending permission without transport framing.
pub async fn resolve_permission(
    state: &ServerState,
    permission_id: &str,
    approved: bool,
    remember: bool,
) -> bool {
    let checkpoint = state
        .recovered_permissions
        .lock()
        .await
        .get(permission_id)
        .cloned();
    if let Some(checkpoint) = checkpoint {
        return Box::pin(resolve_recovered_permission(
            state,
            permission_id,
            &checkpoint,
            approved,
            remember,
        ))
        .await;
    }
    let Some(permission) = take_pending_permission_for_individual(state, permission_id).await
    else {
        return false;
    };
    complete_pending_permission(state, permission, approved, remember).await
}

async fn resolve_recovered_permission(
    state: &ServerState,
    permission_id: &str,
    checkpoint: &bcode_session::InvocationRecoveryCheckpoint,
    approved: bool,
    remember: bool,
) -> bool {
    if remember {
        return false;
    }
    let Ok(summary) = state
        .sessions
        .session_summary(checkpoint.session_id())
        .await
    else {
        return false;
    };
    // Cross-store decision commit still requires an execution-fenced continuation owner.
    // Do not turn a session association or a prior authority observation into a grant.
    if summary.execution.is_some() {
        return false;
    }
    let bcode_session_models::SessionEventKind::PermissionRequested { tool_call_id, .. } =
        &checkpoint.permission().kind
    else {
        return false;
    };
    let Ok(Some(current)) = state
        .sessions
        .invocation_recovery_checkpoint(
            checkpoint.session_id(),
            tool_call_id,
            checkpoint.request().sequence,
            1024,
        )
        .await
    else {
        return false;
    };
    if current.turn() != checkpoint.turn()
        || current.request() != checkpoint.request()
        || current.permission() != checkpoint.permission()
    {
        return false;
    }
    // This is a fresh validation of the exact original request. A commit conflict below
    // is returned to the caller, never retried against a silently advanced generation.
    let Ok(event) = state
        .sessions
        .append_recovered_permission_decision(&current, approved)
        .await
    else {
        return false;
    };
    publish_session_event(state, &event).await;
    state
        .recovered_permissions
        .lock()
        .await
        .remove(permission_id);
    let pending = state.pending_permissions.lock().await.remove(permission_id);
    if let Some(pending) = pending {
        notify_interaction_destination(state, &pending.summary).await;
    }
    true
}

pub async fn complete_pending_permission(
    state: &ServerState,
    permission: PendingPermission,
    approved: bool,
    remember: bool,
) -> bool {
    Box::pin(complete_pending_permission_inner(
        state, permission, approved, remember,
    ))
    .await
}

async fn complete_pending_permission_inner(
    state: &ServerState,
    permission: PendingPermission,
    approved: bool,
    remember: bool,
) -> bool {
    let checkpoint = state
        .recovered_permissions
        .lock()
        .await
        .get(&permission.summary.permission_id)
        .cloned();
    if let Some(checkpoint) = checkpoint {
        let resolved = Box::pin(resolve_recovered_permission(
            state,
            &permission.summary.permission_id,
            &checkpoint,
            approved,
            remember,
        ))
        .await;
        if !resolved {
            // Live cancellation callers may already have removed the summary. Keep the
            // unresolved recovered request visible when its fenced decision is refused.
            state
                .pending_permissions
                .lock()
                .await
                .entry(permission.summary.permission_id.clone())
                .or_insert(permission);
        }
        return resolved;
    }
    // Never release a waiting invocation on a decision that has not been recorded.
    // A failed append fails closed; it must not become an in-memory approval.
    let recorded = append_permission_resolved_event(
        state,
        permission.summary.session_id,
        permission.summary.permission_id.clone(),
        approved,
    )
    .await;
    let approved = approved && recorded;
    if remember
        && recorded
        && let Some(key) = permission.skill_decision_key.clone()
    {
        remember_skill_tool_decision(
            key,
            if approved {
                SkillToolDecision::Allow
            } else {
                SkillToolDecision::Deny
            },
        );
    }
    *permission.decision.lock().await = Some(approved);
    permission.notify.notify_waiters();
    notify_interaction_destination(state, &permission.summary).await;
    recorded
}

pub async fn take_pending_permission_for_individual(
    state: &ServerState,
    permission_id: &str,
) -> Option<PendingPermission> {
    let candidate = state
        .pending_permissions
        .lock()
        .await
        .get(permission_id)
        .cloned()?;
    let Some(correlation) = candidate.summary.batch.as_ref() else {
        return state.pending_permissions.lock().await.remove(permission_id);
    };
    let batch = state
        .pending_permission_batches
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(&correlation.batch_id)
        .cloned();
    let Some(batch) = batch else {
        state.pending_permissions.lock().await.remove(permission_id);
        return None;
    };
    let batch_decision = batch.decision.lock().await;
    if batch_decision.is_some() {
        return None;
    }
    let permission = state.pending_permissions.lock().await.remove(permission_id);
    drop(batch_decision);
    permission
}

/// Deny one pending permission only when this caller wins removal from canonical pending state.
pub async fn cancel_pending_permission(state: &ServerState, permission_id: &str) -> bool {
    let permission = state.pending_permissions.lock().await.remove(permission_id);
    let Some(permission) = permission else {
        return false;
    };
    complete_pending_permission(state, permission, false, false).await
}

/// Deny and complete every pending permission for one cancelled session.
pub async fn cancel_pending_permissions_for_session(state: &ServerState, session_id: SessionId) {
    let batches = state
        .pending_permission_batches
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .values()
        .filter(|batch| batch.session_id == session_id)
        .cloned()
        .collect::<Vec<_>>();
    for batch in batches {
        let mut decision = batch.decision.lock().await;
        if decision.is_none() {
            *decision = Some(false);
        }
    }

    let permissions = {
        let mut pending = state.pending_permissions.lock().await;
        let permission_ids = pending
            .iter()
            .filter(|(_, permission)| permission.summary.session_id == session_id)
            .map(|(permission_id, _)| permission_id.clone())
            .collect::<Vec<_>>();
        let mut permissions = Vec::with_capacity(permission_ids.len());
        for permission_id in permission_ids {
            if let Some(permission) = pending.remove(&permission_id) {
                permissions.push(permission);
            }
        }
        permissions
    };
    for permission in permissions {
        complete_pending_permission(state, permission, false, false).await;
    }
}

/// Resolve one complete pending permission batch without transport framing.
pub async fn resolve_permission_batch(
    state: &ServerState,
    batch_id: &str,
    approved: bool,
) -> usize {
    let Some(batch) = state
        .pending_permission_batches
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(batch_id)
        .cloned()
    else {
        return 0;
    };
    let mut batch_decision = batch.decision.lock().await;
    if batch_decision.is_some() {
        return 0;
    }
    *batch_decision = Some(approved);
    drop(batch_decision);

    let permissions = {
        let permission_ids = {
            let pending = state.pending_permissions.lock().await;
            pending
                .iter()
                .filter(|(_, permission)| {
                    permission
                        .summary
                        .batch
                        .as_ref()
                        .is_some_and(|batch| batch.batch_id == batch_id)
                })
                .map(|(permission_id, _)| permission_id.clone())
                .collect::<Vec<_>>()
        };
        let mut pending = state.pending_permissions.lock().await;
        let mut permissions = Vec::with_capacity(permission_ids.len());
        for permission_id in permission_ids {
            if let Some(permission) = pending.remove(&permission_id) {
                permissions.push(permission);
            }
        }
        permissions
    };
    let mut resolved = 0;
    for permission in permissions {
        if complete_pending_permission(state, permission, approved, false).await {
            resolved += 1;
        }
    }
    resolved
}

/// Validate and execute one complete server-owned tool exchange lifecycle.
///
/// Invocation identity is checked before registration, and absence of any compatible consumer is
/// surfaced without creating pending state.
///
/// # Errors
///
/// Returns a normalized failure when the exchange identity is already pending.
pub async fn execute_tool_exchange(
    state: &ServerState,
    session_id: SessionId,
    tool_call_id: &str,
    request: &bcode_session_models::ToolExchangeRequest,
    cancel_state: &TurnCancelState,
) -> Result<ToolExchangeResolution, String> {
    if request.invocation_id != tool_call_id {
        return Ok(ToolExchangeResolution::Failed {
            code: "invocation_id_mismatch".to_owned(),
            message: "exchange does not belong to the active tool invocation".to_owned(),
        });
    }
    if !has_exchange_consumer(state, request).await {
        return Ok(ToolExchangeResolution::NoCompatibleConsumer);
    }
    request_tool_exchange(state, session_id, request, cancel_state).await
}

/// Register, recheck consumer availability, and await one tool exchange terminal outcome.
///
/// # Errors
///
/// Returns a normalized failure when the exchange identity is already pending.
pub async fn request_tool_exchange(
    state: &ServerState,
    session_id: SessionId,
    request: &bcode_session_models::ToolExchangeRequest,
    cancel_state: &TurnCancelState,
) -> Result<ToolExchangeResolution, String> {
    let (resolution, notify) = register_pending_tool_exchange(state, session_id, request).await?;
    if !has_exchange_consumer(state, request).await {
        return Ok(abort_tool_exchange(
            state,
            &request.exchange_id,
            ToolExchangeResolution::ConsumerDetached,
        )
        .await);
    }
    Ok(wait_for_tool_exchange_resolution(
        state,
        &request.exchange_id,
        &resolution,
        &notify,
        cancel_state,
    )
    .await)
}

/// Return whether one connected client advertised a compatible exchange adapter.
pub async fn client_supports_exchange(
    state: &ServerState,
    client_id: ClientId,
    request: &bcode_session_models::ToolExchangeRequest,
) -> bool {
    state
        .client_runtime_contexts
        .lock()
        .await
        .get(&client_id)
        .is_some_and(|context| {
            context.interaction_adapters.iter().any(|adapter| {
                adapter.supports(&request.schema, request.schema_version)
                    && request.producer_id == adapter.producer_id
            })
        })
}

/// Return whether any connected client advertised a compatible exchange adapter.
pub async fn has_exchange_consumer(
    state: &ServerState,
    request: &bcode_session_models::ToolExchangeRequest,
) -> bool {
    state
        .client_runtime_contexts
        .lock()
        .await
        .values()
        .any(|context| {
            context.interaction_adapters.iter().any(|adapter| {
                adapter.supports(&request.schema, request.schema_version)
                    && request.producer_id == adapter.producer_id
            })
        })
}

/// Register one pending exchange and return its shared resolution state.
///
/// # Errors
///
/// Returns a normalized failure when the exchange identity is already pending.
pub async fn register_pending_tool_exchange(
    state: &ServerState,
    session_id: SessionId,
    request: &bcode_session_models::ToolExchangeRequest,
) -> Result<
    (
        Arc<Mutex<Option<ToolExchangeResolution>>>,
        Arc<tokio::sync::Notify>,
    ),
    String,
> {
    let route = state
        .session_current_turn(session_id)
        .await
        .and_then(|turn| turn.interaction_route);
    let pending = PendingToolExchange {
        summary: PendingToolExchangeSummary {
            interaction_route: route.clone(),
            session_id,
            request: request.clone(),
        },
        resolution: Arc::new(Mutex::new(None)),
        notify: Arc::new(tokio::sync::Notify::new()),
    };
    let resolution = Arc::clone(&pending.resolution);
    let notify = Arc::clone(&pending.notify);
    let mut exchanges = state.pending_tool_exchanges.lock().await;
    if exchanges.contains_key(&request.exchange_id) {
        return Err(format!(
            "duplicate interactive tool request id: {}",
            request.exchange_id
        ));
    }
    exchanges.insert(request.exchange_id.clone(), pending);
    drop(exchanges);
    notify_route_destination(state, route.as_ref()).await;
    Ok((resolution, notify))
}

/// Resolve pending exchanges that no longer have any compatible connected consumer.
pub async fn resolve_exchanges_without_consumers(state: &ServerState) {
    let contexts = state.client_runtime_contexts.lock().await;
    let mut pending = state.pending_tool_exchanges.lock().await;
    let entries = std::mem::take(&mut *pending);
    let (retained, detached): (BTreeMap<_, _>, BTreeMap<_, _>) =
        entries.into_iter().partition(|(_, exchange)| {
            contexts.values().any(|context| {
                context.interaction_adapters.iter().any(|adapter| {
                    adapter.producer_id == exchange.summary.request.producer_id
                        && adapter.supports(
                            &exchange.summary.request.schema,
                            exchange.summary.request.schema_version,
                        )
                })
            })
        });
    *pending = retained;
    drop(contexts);
    drop(pending);
    for exchange in detached.into_values() {
        *exchange.resolution.lock().await = Some(ToolExchangeResolution::ConsumerDetached);
        exchange.notify.notify_waiters();
    }
}

/// Return the current bounded pending tool-exchange summaries.
pub async fn list_pending_tool_exchanges(state: &ServerState) -> Vec<PendingToolExchangeSummary> {
    let mut exchanges = state
        .pending_tool_exchanges
        .lock()
        .await
        .values()
        .map(|request| request.summary.clone())
        .collect::<Vec<_>>();
    exchanges.sort_by(|left, right| left.request.exchange_id.cmp(&right.request.exchange_id));
    exchanges
}

/// Wait for one pending exchange resolution or abort it when the owning turn is cancelled.
pub async fn wait_for_tool_exchange_resolution(
    state: &ServerState,
    interaction_id: &str,
    resolution_slot: &Arc<Mutex<Option<ToolExchangeResolution>>>,
    notify: &Arc<tokio::sync::Notify>,
    cancel_state: &TurnCancelState,
) -> ToolExchangeResolution {
    loop {
        // Register before reading so a resolution committed between the read and the wait is
        // not lost: `notify_waiters` only wakes already-registered waiters.
        let notified = notify.notified();
        let mut notified = std::pin::pin!(notified);
        notified.as_mut().enable();
        let value = resolution_slot.lock().await.clone();
        if let Some(resolution) = value {
            return resolution;
        }
        tokio::select! {
            () = &mut notified => {}
            () = cancel_state.cancelled() => {
                return abort_tool_exchange(
                    state,
                    interaction_id,
                    ToolExchangeResolution::Cancelled,
                )
                .await;
            }
        }
    }
}

/// Remove one pending exchange because its owning workflow cancelled or lost its consumer.
pub async fn abort_tool_exchange(
    state: &ServerState,
    interaction_id: &str,
    resolution: ToolExchangeResolution,
) -> ToolExchangeResolution {
    let pending = state
        .pending_tool_exchanges
        .lock()
        .await
        .remove(interaction_id);
    if let Some(pending) = pending {
        notify_route_destination(state, pending.summary.interaction_route.as_ref()).await;
    }
    resolution
}

/// Complete a known pending exchange from an authoritative internal consumer.
pub async fn complete_pending_tool_exchange(
    state: &ServerState,
    interaction_id: &str,
    resolution: ToolExchangeResolution,
) -> bool {
    let request = state
        .pending_tool_exchanges
        .lock()
        .await
        .remove(interaction_id);
    let Some(request) = request else {
        return false;
    };
    *request.resolution.lock().await = Some(resolution);
    request.notify.notify_waiters();
    notify_route_destination(state, request.summary.interaction_route.as_ref()).await;
    true
}

const MAX_TOOL_EXCHANGE_RESOLUTION_BYTES: usize = 64 * 1024;

struct ResolutionSizeBudget {
    remaining: usize,
}

impl std::io::Write for ResolutionSizeBudget {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.remaining = self.remaining.checked_sub(bytes.len()).ok_or_else(|| {
            std::io::Error::other("tool exchange resolution exceeds encoded size limit")
        })?;
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

fn validate_resolution_size(value: &impl serde::Serialize) -> Result<(), ResolveToolExchangeError> {
    serde_json::to_writer(
        ResolutionSizeBudget {
            remaining: MAX_TOOL_EXCHANGE_RESOLUTION_BYTES,
        },
        value,
    )
    .map_err(|_| ResolveToolExchangeError::InvalidResolution)
}

/// Decode one serialized client tool-exchange resolution without exposing serde failures.
pub fn decode_tool_exchange_resolution(
    resolution_json: serde_json::Value,
) -> Result<ToolExchangeResolution, ResolveToolExchangeError> {
    validate_resolution_size(&resolution_json)?;
    let resolution = serde_json::from_value(resolution_json)
        .map_err(|_| ResolveToolExchangeError::InvalidResolution)?;
    validate_client_resolution(&resolution)?;
    Ok(resolution)
}

fn validate_client_resolution(
    resolution: &ToolExchangeResolution,
) -> Result<(), ResolveToolExchangeError> {
    match resolution {
        ToolExchangeResolution::Responded { .. } | ToolExchangeResolution::Cancelled => {
            validate_resolution_size(resolution)
        }
        ToolExchangeResolution::TimedOut
        | ToolExchangeResolution::NoCompatibleConsumer
        | ToolExchangeResolution::ConsumerDetached
        | ToolExchangeResolution::Failed { .. } => Err(ResolveToolExchangeError::InvalidResolution),
    }
}

/// Resolve one pending exchange through canonical server-owned interaction state.
///
/// Returns `Ok(false)` when the exchange is already terminal or otherwise no longer pending.
///
/// # Errors
///
/// Rejects host-owned outcomes, oversized encoded resolutions, and incompatible consumers.
/// Validation precedes pending-state lookup so direct and IPC callers obey the same restrictions.
pub async fn resolve_tool_exchange(
    state: &ServerState,
    client_id: ClientId,
    interaction_id: &str,
    resolution: ToolExchangeResolution,
) -> Result<bool, ResolveToolExchangeError> {
    validate_client_resolution(&resolution)?;
    let pending = state
        .pending_tool_exchanges
        .lock()
        .await
        .get(interaction_id)
        .cloned();
    let Some(pending) = pending else {
        return Ok(false);
    };
    if !client_supports_exchange(state, client_id, &pending.summary.request).await {
        return Err(ResolveToolExchangeError::IncompatibleConsumer);
    }
    Ok(complete_pending_tool_exchange(state, interaction_id, resolution).await)
}

#[cfg(test)]
mod resolution_size_tests {
    use super::{
        MAX_TOOL_EXCHANGE_RESOLUTION_BYTES, ResolutionSizeBudget, validate_resolution_size,
    };
    use std::io::Write as _;

    #[test]
    fn responded_envelope_obeys_exact_encoded_limit_on_both_paths() {
        for character in ['a', '\n'] {
            let empty = super::ToolExchangeResolution::Responded {
                payload: serde_json::Value::String(String::new()),
            };
            let overhead = serde_json::to_vec(&empty).unwrap().len();
            let encoded_width = if character == '\n' { 2 } else { 1 };
            let remaining = MAX_TOOL_EXCHANGE_RESOLUTION_BYTES - overhead;
            let mut payload = character.to_string().repeat(remaining / encoded_width);
            payload.push_str(&"a".repeat(remaining % encoded_width));
            let exact = super::ToolExchangeResolution::Responded {
                payload: serde_json::Value::String(payload.clone()),
            };
            assert_eq!(
                serde_json::to_vec(&exact).unwrap().len(),
                MAX_TOOL_EXCHANGE_RESOLUTION_BYTES
            );
            assert!(super::validate_client_resolution(&exact).is_ok());
            assert_eq!(
                super::decode_tool_exchange_resolution(serde_json::to_value(&exact).unwrap())
                    .unwrap(),
                exact
            );
            payload.push('a');
            let oversized = super::ToolExchangeResolution::Responded {
                payload: serde_json::Value::String(payload),
            };
            assert_eq!(
                super::validate_client_resolution(&oversized),
                Err(super::ResolveToolExchangeError::InvalidResolution)
            );
            assert_eq!(
                super::decode_tool_exchange_resolution(serde_json::to_value(&oversized).unwrap()),
                Err(super::ResolveToolExchangeError::InvalidResolution)
            );
        }
    }

    #[test]
    fn encoded_resolution_size_accepts_exact_limit_and_rejects_next_byte() {
        let exact = "a".repeat(MAX_TOOL_EXCHANGE_RESOLUTION_BYTES - 2);
        assert!(validate_resolution_size(&exact).is_ok());
        assert!(validate_resolution_size(&(exact + "a")).is_err());
    }

    #[test]
    fn encoded_resolution_size_counts_json_escaping() {
        let escaped = "\n".repeat(MAX_TOOL_EXCHANGE_RESOLUTION_BYTES / 2);
        assert!(escaped.len() < MAX_TOOL_EXCHANGE_RESOLUTION_BYTES);
        assert!(validate_resolution_size(&escaped).is_err());
    }

    #[test]
    fn resolution_budget_rejects_overflow_without_consuming_budget() {
        let mut budget = ResolutionSizeBudget { remaining: 3 };
        budget.write_all(b"abc").expect("exact budget");
        assert_eq!(budget.remaining, 0);
        assert!(budget.write_all(b"d").is_err());
        assert_eq!(budget.remaining, 0);
    }
}