mobius 0.15.29

A small, modular Rust framework for building coding agents
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
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use serde_json::Value;

use super::MiddlewareStack;
use super::tools::Catalog;
use super::tools::ToolResult;
use super::{approximate_item_tokens, approximate_tokens, serialized_len};
use crate::agent::{AgentRole, WeakAgentSender};
use crate::backend::checkpoint::{
    Checkpoint, CheckpointStore, ContextRewriteReason, ExecutionOutcome, MAX_QUEUED_MESSAGES,
    QueuedMessage as DurableQueuedMessage, QueuedMessageBoundary,
};
use crate::backend::model::{ModelRouter, message_input};
use crate::backend::sandbox::ApprovalPolicy;
use crate::protocol::{
    EventMsg, FrontendEvent, MAX_CAPABILITY_INPUT_BYTES, MessageAuthor, MessageEvent,
    MessageSubmission, MessageTarget, ReviewDecision, SessionContext, SessionFileReference,
    TokenUsage, ToolCall, message_metadata,
};
use crate::{Error, Result};

/// Sends middleware-owned UI updates without depending on a concrete frontend.
pub type FrontendEventSink = Arc<dyn Fn(FrontendEvent) -> Result<()> + Send + Sync>;

/// Read-only queued message owned by the middleware receiving it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct QueuedMessageView<'a> {
    item: &'a DurableQueuedMessage,
}

impl<'a> QueuedMessageView<'a> {
    /// Returns the identity token required by a conditional queue mutation.
    #[must_use]
    pub fn id(&self) -> &'a str {
        self.item.id()
    }

    /// Returns the prepared presentation event.
    #[must_use]
    pub fn event(&self) -> MessageEvent {
        self.item.event()
    }
}

/// Read-only startup snapshot containing only one middleware's queued messages.
#[derive(Clone, Default)]
pub struct QueuedMessageSnapshot {
    items: Vec<DurableQueuedMessage>,
}

impl QueuedMessageSnapshot {
    /// Returns every queued item owned by this middleware, oldest first.
    pub fn views(&self) -> impl Iterator<Item = QueuedMessageView<'_>> {
        self.items.iter().map(|item| QueuedMessageView { item })
    }

    pub(super) fn for_owner(owner: &str, items: &[DurableQueuedMessage]) -> Self {
        Self {
            items: items
                .iter()
                .filter(|item| item.owner() == owner)
                .cloned()
                .collect(),
        }
    }
}

/// Mutable scoped view of messages retained until their delivery boundary.
pub struct MessageQueue<'a> {
    items: &'a mut Vec<DurableQueuedMessage>,
    owner: Option<&'static str>,
}

impl<'a> MessageQueue<'a> {
    pub(crate) fn new(items: &'a mut Vec<DurableQueuedMessage>) -> Self {
        Self { items, owner: None }
    }

    pub(super) fn scope(&mut self, owner: &'static str) {
        self.owner = Some(owner);
    }

    fn owner(&self) -> Result<&'static str> {
        self.owner
            .ok_or_else(|| Error::Config("message queue is not scoped to a middleware".into()))
    }

    /// Returns the number of queued items owned by this middleware.
    #[must_use]
    pub fn count(&self) -> usize {
        let Some(owner) = self.owner else {
            return 0;
        };
        self.items
            .iter()
            .filter(|item| item.owner() == owner)
            .count()
    }

    /// Returns the newest message available to this context.
    #[must_use]
    pub fn latest(&self) -> Option<QueuedMessageView<'_>> {
        let owner = self.owner?;
        self.items
            .iter()
            .rev()
            .find(|item| item.owner() == owner)
            .map(|item| QueuedMessageView { item })
    }

    /// Returns one owned item by its revision identity.
    #[must_use]
    pub fn find(&self, id: &str) -> Option<QueuedMessageView<'_>> {
        let owner = self.owner?;
        self.items
            .iter()
            .find(|item| item.owner() == owner && item.id() == id)
            .map(|item| QueuedMessageView { item })
    }

    /// Appends one prepared message, or returns `false` when it is full or duplicated.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn enqueue(
        &mut self,
        id: &str,
        boundary: QueuedMessageBoundary,
        event: MessageEvent,
    ) -> Result<bool> {
        let owner = self.owner()?;
        let item = DurableQueuedMessage::new(owner, id, boundary, event)?;
        if self.items.len() >= MAX_QUEUED_MESSAGES {
            return Ok(false);
        }
        if self
            .items
            .iter()
            .any(|item| item.owner() == owner && item.id() == id)
        {
            return Ok(false);
        }
        self.items.push(item);
        Ok(true)
    }

    /// Atomically replaces one owned item while preserving its queue position.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn replace(&mut self, id: &str, replacement_id: &str, event: MessageEvent) -> Result<bool> {
        let owner = self.owner()?;
        let Some(index) = self
            .items
            .iter()
            .position(|item| item.owner() == owner && item.id() == id)
        else {
            return Ok(false);
        };
        if self.items.iter().enumerate().any(|(candidate, item)| {
            candidate != index && item.owner() == owner && item.id() == replacement_id
        }) {
            return Ok(false);
        }
        self.items[index].replace(replacement_id, event)?;
        Ok(true)
    }

    pub(crate) fn stage_model_messages(&mut self, turn_id: &str) -> Result<Vec<PreparedMessage>> {
        let Some(owner) = self.owner else {
            return Ok(Vec::new());
        };
        self.items
            .extract_if(.., |item| {
                item.owner() == owner
                    && matches!(
                        item.boundary(),
                        QueuedMessageBoundary::Steer { turn_id: target }
                            if target == turn_id
                    )
            })
            .map(PreparedMessage::try_from)
            .collect()
    }

    pub(crate) fn next_turn(&self) -> Result<Option<PreparedMessage>> {
        let owner = self.owner()?;
        self.items
            .iter()
            .find(|item| item.owner() == owner && item.boundary().starts_turn())
            .cloned()
            .map(PreparedMessage::try_from)
            .transpose()
    }

    pub(crate) fn consume_next_turn(&mut self, id: &str) -> Result<()> {
        let owner = self.owner()?;
        let index = self
            .items
            .iter()
            .position(|item| {
                item.owner() == owner && item.id() == id && item.boundary().starts_turn()
            })
            .ok_or_else(|| Error::Checkpoint("prepared message is no longer queued".into()))?;
        self.items.remove(index);
        Ok(())
    }

    pub(crate) fn promote_failed_turn(&mut self, turn_id: &str) -> Result<()> {
        let owner = self.owner()?;
        for item in self.items.iter_mut().filter(|item| {
            item.owner() == owner
                && matches!(
                    item.boundary(),
                    QueuedMessageBoundary::Steer { turn_id: target }
                        if target == turn_id
                )
        }) {
            item.promote_to_next_turn()?;
        }
        Ok(())
    }
}

/// One queued message prepared for its model boundary.
pub(crate) struct PreparedMessage {
    pub(crate) submission_id: String,
    pub(crate) input: Value,
    pub(crate) event: EventMsg,
    pub(crate) title_seed: Option<String>,
    pub(crate) boundary_events: Vec<EventMsg>,
}

impl TryFrom<DurableQueuedMessage> for PreparedMessage {
    type Error = Error;

    fn try_from(message: DurableQueuedMessage) -> Result<Self> {
        let (submission_id, event) = message.into_parts();
        let input = message_input(&event)?;
        let title_seed = matches!(
            event.author,
            MessageAuthor::User | MessageAuthor::Peer { .. }
        )
        .then(|| event.text.trim().to_string())
        .filter(|title| !title.is_empty());
        Ok(Self {
            submission_id,
            input,
            event: EventMsg::Message(event),
            title_seed,
            boundary_events: Vec::new(),
        })
    }
}

/// Durable runtime identity exposed while middleware starts a session.
#[derive(Clone)]
pub struct RuntimeContext {
    /// The sender.
    pub sender: WeakAgentSender,
    /// The checkpoints.
    pub checkpoints: Arc<dyn CheckpointStore>,
    /// The session identifier.
    pub session_id: String,
    /// The model route.
    pub model_route: String,
    /// The model.
    pub model: String,
    /// The approval policy.
    pub approval_policy: ApprovalPolicy,
    /// The session context.
    pub session_context: SessionContext,
    /// The metadata.
    pub metadata: BTreeMap<String, Value>,
    /// The role.
    pub role: AgentRole,
    /// The frontend.
    pub frontend: FrontendEventSink,
}

impl RuntimeContext {
    pub(crate) fn turn_identity<'a>(&'a self, turn_id: &'a str) -> TurnIdentity<'a> {
        TurnIdentity {
            session_id: &self.session_id,
            turn_id,
            model: &self.model,
            approval_policy: self.approval_policy,
        }
    }
}

/// Stable facts shared by hooks that run within one active turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TurnIdentity<'a> {
    /// The session identifier.
    pub session_id: &'a str,
    /// The turn identifier.
    pub turn_id: &'a str,
    /// The model.
    pub model: &'a str,
    /// The approval policy.
    pub approval_policy: ApprovalPolicy,
}

/// Why [`Middleware::session_start`](super::Middleware::session_start) is running.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionStartSource {
    /// Selects the startup case.
    Startup,
    /// Selects the resume case.
    Resume,
    /// Selects the compact case.
    Compact,
}

/// Mutable state shared by the declaration-ordered `SessionStart` hooks.
pub struct SessionStartContext<'a> {
    /// The runtime.
    pub runtime: &'a RuntimeContext,
    pub(crate) source: SessionStartSource,
    pub(crate) queued_messages: QueuedMessageSnapshot,
    pub(crate) input: &'a mut Vec<Value>,
    pub(crate) input_changed: bool,
    pub(crate) stop_reason: Option<String>,
}

impl SessionStartContext<'_> {
    #[must_use]
    /// Returns the session-start source.
    pub fn source(&self) -> SessionStartSource {
        self.source
    }

    #[must_use]
    /// Returns the queued messages.
    pub fn queued_messages(&self) -> &QueuedMessageSnapshot {
        &self.queued_messages
    }

    /// Appends hidden provider context produced while the session starts.
    pub fn push_input(&mut self, item: Value) {
        self.input.push(item);
        self.input_changed = true;
    }

    pub(crate) fn retain_input(&mut self, mut keep: impl FnMut(&Value) -> bool) {
        let input_len = self.input.len();
        self.input.retain(&mut keep);
        self.input_changed |= self.input.len() != input_len;
    }

    /// Stops the active turn after session-start processing completes.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn stop(&mut self, reason: impl Into<String>) -> Result<()> {
        set_stop_reason(&mut self.stop_reason, "session-start stop", reason)
    }

    /// Returns the first stop requested by the ordered middleware chain.
    #[must_use]
    pub fn stop_reason(&self) -> Option<&str> {
        self.stop_reason.as_deref()
    }
}

/// Mutable state exposed before a prepared next-turn message enters durable context.
pub struct MessageSubmitContext<'a> {
    /// The turn.
    pub turn: TurnIdentity<'a>,
    /// The author.
    pub author: &'a MessageAuthor,
    /// The message.
    pub message: &'a str,
    /// The attachments.
    pub attachments: &'a [SessionFileReference],
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
    pub(crate) input: Vec<Value>,
    pub(crate) rejection: Option<String>,
}

impl MessageSubmitContext<'_> {
    /// Adds provider-neutral context immediately before the submitted message.
    pub fn push_input(&mut self, item: Value) {
        self.input.push(item);
    }

    /// Rejects the submission without treating the policy decision as a hook failure.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn reject(&mut self, reason: impl Into<String>) -> Result<()> {
        let reason = hook_message("prompt rejection", reason)?;
        if self.rejection.is_none() {
            self.rejection = Some(reason);
        }
        Ok(())
    }
}

pub(crate) struct MessageSubmitResult {
    pub(crate) input: Vec<Value>,
    pub(crate) rejection: Option<String>,
}

/// Mutable state exposed immediately before a model request.
pub struct ModelContext<'a> {
    /// The model.
    pub model: &'a ModelRouter,
    /// The provider.
    pub provider: &'a str,
    /// The session identifier.
    pub session_id: &'a str,
    /// The session context.
    pub session_context: &'a SessionContext,
    /// The metadata.
    pub metadata: &'a BTreeMap<String, Value>,
    /// The turn identifier.
    pub turn_id: &'a str,
    /// The model step.
    pub model_step: usize,
    /// The context window.
    pub context_window: i64,
    /// The instructions.
    pub instructions: &'a str,
    pub(crate) checkpoint_sequence: u64,
    pub(crate) available_tools: &'a mut BTreeSet<String>,
    pub(crate) allow_hosted_tools: &'a mut bool,
    pub(crate) durable_input: &'a mut Vec<Value>,
    pub(crate) transcript_delta: &'a mut Vec<Value>,
    pub(crate) context_epoch: &'a mut u64,
    pub(crate) compaction_count: &'a mut u64,
    pub(crate) rewrite_reasons: &'a mut Vec<ContextRewriteReason>,
    pub(crate) turn_stop: &'a mut Option<String>,
    pub(crate) queued_messages: Vec<DurableQueuedMessage>,
    /// The last usage.
    pub last_usage: Option<&'a TokenUsage>,
    /// The tools.
    pub tools: &'a Catalog,
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
    /// The usage.
    pub usage: &'a mut Vec<TokenUsage>,
    /// Set when this hook changes durable checkpoint state.
    pub(crate) checkpoint_changed: &'a mut bool,
    pub(crate) runtime: &'a RuntimeContext,
    pub(crate) hooks: &'a MiddlewareStack,
}

/// Live capability state used to hide registered tools at a model boundary.
pub struct ToolExposureContext<'a> {
    /// The session identifier.
    pub session_id: &'a str,
    pub(crate) supports_tool_image_input: bool,
    pub(crate) input: &'a [Value],
    pub(crate) available: &'a mut BTreeSet<String>,
}

impl ToolExposureContext<'_> {
    /// Reports whether the active model accepts image input.
    #[must_use]
    pub fn supports_tool_image_input(&self) -> bool {
        self.supports_tool_image_input
    }

    /// Returns the most recent typed conversation message in model context.
    #[must_use]
    pub fn latest_message(&self) -> Option<MessageEvent> {
        self.input.iter().rev().find_map(message_metadata)
    }

    /// Hides registered tools for this boundary.
    pub fn hide(&mut self, names: &[&str]) {
        for name in names {
            self.available.remove(*name);
        }
    }
}

impl ModelContext<'_> {
    /// Prevents provider-hosted tools for this model step.
    pub fn disable_hosted_tools(&mut self) {
        *self.allow_hosted_tools = false;
    }

    /// Returns durable provider-neutral model context.
    #[must_use]
    pub fn input(&self) -> &[Value] {
        self.durable_input
    }

    /// Replaces active model context and advances its rewrite epoch once per boundary.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn rewrite_input(
        &mut self,
        reason: ContextRewriteReason,
        mut input: Vec<Value>,
    ) -> Result<()> {
        if *self.durable_input == input {
            return Ok(());
        }
        if self.rewrite_reasons.is_empty() {
            *self.context_epoch = self
                .context_epoch
                .checked_add(1)
                .ok_or_else(|| Error::Checkpoint("context rewrite epoch overflow".into()))?;
        }
        if !self.rewrite_reasons.contains(&reason) {
            self.rewrite_reasons.push(reason);
        }
        crate::backend::model::reset_prompt_cache_breakpoint(&mut input);
        *self.durable_input = input;
        self.last_usage = None;
        *self.checkpoint_changed = true;
        Ok(())
    }

    /// Appends a durable replay item without adding it to provider context.
    pub(crate) fn record_transcript_item(&mut self, item: Value) {
        self.transcript_delta.push(item);
        *self.checkpoint_changed = true;
    }

    /// Appends durable provider context without adding synthetic replay history.
    pub fn append_model_input(&mut self, item: Value) {
        self.durable_input.push(item);
        *self.checkpoint_changed = true;
    }

    /// Appends durable input to model context and its transcript journal.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn push_input(&mut self, item: Value) -> Result<MessageTarget> {
        self.durable_input.push(item.clone());
        self.transcript_delta.push(item);
        *self.checkpoint_changed = true;
        provisional_message_target(self.checkpoint_sequence, self.transcript_delta.len())
    }

    /// Estimates visible history, instructions, and tool schemas at four bytes per token.
    #[must_use]
    pub fn estimated_input_tokens(&self) -> i64 {
        let Ok(tools) = self
            .tools
            .prepare(self.input(), self.available_tools.clone())
        else {
            return i64::MAX;
        };
        let visible = tools
            .direct()
            .iter()
            .chain(
                tools
                    .deferred()
                    .iter()
                    .filter(|tool| tools.materialized().contains(&tool.name)),
            )
            .collect::<Vec<_>>();
        let Some(tool_bytes) = serialized_len(&visible) else {
            return i64::MAX;
        };
        let history = self
            .durable_input
            .iter()
            .map(approximate_item_tokens)
            .fold(0usize, usize::saturating_add);
        i64::try_from(history.saturating_add(approximate_tokens(
            tool_bytes.saturating_add(self.instructions.len()),
        )))
        .unwrap_or(i64::MAX)
    }

    pub(crate) async fn pre_compact(&mut self) -> Result<()> {
        let hooks = self.hooks;
        let stop_reason = hooks
            .pre_compact(CompactContext {
                session_id: self.session_id,
                turn_id: self.turn_id,
                model: &self.runtime.model,
                input: self.durable_input,
                events: self.events,
                stop_reason: None,
            })
            .await?;
        set_first(self.turn_stop, stop_reason);
        Ok(())
    }

    pub(crate) async fn post_compact(&mut self) -> Result<()> {
        let hooks = self.hooks;
        let stop_reason = hooks
            .post_compact(CompactContext {
                session_id: self.session_id,
                turn_id: self.turn_id,
                model: &self.runtime.model,
                input: self.durable_input,
                events: self.events,
                stop_reason: None,
            })
            .await?;
        set_first(self.turn_stop, stop_reason);
        if self.turn_stop.is_some() {
            return Ok(());
        }
        let start = hooks
            .session_start(
                self.runtime,
                &self.queued_messages,
                SessionStartSource::Compact,
                self.durable_input,
            )
            .await?;
        set_first(self.turn_stop, start.stop_reason);
        Ok(())
    }

    #[must_use]
    pub(crate) fn turn_stopped(&self) -> bool {
        self.turn_stop.is_some()
    }
}

/// Request-only model input exposed after every durable `PreModel` hook.
pub struct ModelRequestContext<'a> {
    /// The role.
    pub role: &'a AgentRole,
    /// The model.
    pub model: &'a ModelRouter,
    /// The provider.
    pub provider: &'a str,
    /// The session identifier.
    pub session_id: &'a str,
    /// The turn identifier.
    pub turn_id: &'a str,
    /// The model step.
    pub model_step: usize,
    pub(crate) input: Cow<'a, [Value]>,
}

impl ModelRequestContext<'_> {
    /// Returns the input currently prepared for this one model request.
    #[must_use]
    pub fn input(&self) -> &[Value] {
        self.input.as_ref()
    }

    /// Replaces only the input sent by this model request.
    pub fn replace_input(&mut self, input: Vec<Value>) {
        self.input = Cow::Owned(input);
    }
}

/// Mutable policy boundary for one normalized model-requested tool call.
pub struct PreToolUseContext<'a> {
    /// The turn.
    pub turn: TurnIdentity<'a>,
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
    pub(crate) tools: &'a Catalog,
    pub(crate) call: &'a mut ToolCall,
    pub(crate) input: Vec<Value>,
    pub(crate) denial: Option<String>,
}

impl PreToolUseContext<'_> {
    /// Returns the call after any earlier middleware rewrites.
    #[must_use]
    pub fn call(&self) -> &ToolCall {
        self.call
    }

    /// Replaces the tool name and arguments while preserving the provider call ID.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn replace(&mut self, name: impl Into<String>, arguments: Value) -> Result<()> {
        self.call.replace(name.into(), arguments)
    }

    /// Adds durable provider-neutral context before this call at a tool-complete boundary.
    pub fn push_input(&mut self, item: Value) {
        self.input.push(item);
    }

    /// Denies the call. Later middleware may observe but cannot undo the denial.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn deny(&mut self, reason: impl Into<String>) -> Result<()> {
        let reason = hook_message("tool denial", reason)?;
        if self.denial.is_none() {
            self.denial = Some(reason);
        }
        Ok(())
    }

    /// Returns the first denial made by the ordered middleware chain.
    #[must_use]
    pub fn denial(&self) -> Option<&str> {
        self.denial.as_deref()
    }
}

/// Mutable policy boundary for a sandbox approval request.
pub struct PermissionRequestContext<'a> {
    /// The turn.
    pub turn: TurnIdentity<'a>,
    /// The calls.
    pub calls: &'a [ToolCall],
    /// The requested call identifiers.
    pub requested_call_ids: &'a [String],
    /// The reason.
    pub reason: &'a str,
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
    pub(crate) tools: &'a Catalog,
    pub(crate) decision: Option<ReviewDecision>,
}

impl PermissionRequestContext<'_> {
    /// Returns the decision accumulated from earlier middleware.
    #[must_use]
    pub fn decision(&self) -> Option<&ReviewDecision> {
        self.decision.as_ref()
    }

    /// Allows this request unless an earlier middleware denied it.
    pub fn allow(&mut self) {
        if !matches!(self.decision, Some(ReviewDecision::Denied { .. })) {
            self.decision = Some(ReviewDecision::Approved);
        }
    }

    /// Denies this request. The decision cannot be weakened by later middleware.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn deny(&mut self, reason: impl Into<String>) -> Result<()> {
        let reason = hook_message("permission denial", reason)?;
        if !matches!(self.decision, Some(ReviewDecision::Denied { .. })) {
            self.decision = Some(ReviewDecision::Denied { rejection: reason });
        }
        Ok(())
    }
}

/// Mutable model-visible result exposed after an executed tool call.
pub struct PostToolUseContext<'a> {
    /// The turn.
    pub turn: TurnIdentity<'a>,
    /// The call.
    pub call: &'a ToolCall,
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
    pub(crate) tools: &'a Catalog,
    pub(crate) result: &'a mut ToolResult,
}

impl PostToolUseContext<'_> {
    /// Returns the result after any earlier middleware changes.
    #[must_use]
    pub fn result(&self) -> &ToolResult {
        self.result
    }

    /// Replaces the feedback returned to the model without changing past side effects.
    pub fn replace(&mut self, output: impl Into<String>) {
        self.result.replace(output.into());
    }

    /// Adds provider-neutral context immediately after this tool output.
    pub fn push_input(&mut self, item: Value) {
        self.result.additional_input.push(item);
    }
}

/// State exposed immediately before or after context compaction.
pub struct CompactContext<'a> {
    /// The session identifier.
    pub session_id: &'a str,
    /// The turn identifier.
    pub turn_id: &'a str,
    /// The model.
    pub model: &'a str,
    /// The input.
    pub input: &'a [Value],
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
    pub(crate) stop_reason: Option<String>,
}

impl CompactContext<'_> {
    /// Stops the active turn at this compaction boundary.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn stop(&mut self, reason: impl Into<String>) -> Result<()> {
        set_stop_reason(&mut self.stop_reason, "compaction stop", reason)
    }

    /// Returns the first stop requested by the ordered middleware chain.
    #[must_use]
    pub fn stop_reason(&self) -> Option<&str> {
        self.stop_reason.as_deref()
    }
}

/// Mutable policy boundary immediately before normal turn completion.
pub struct StopContext<'a> {
    /// The turn.
    pub turn: TurnIdentity<'a>,
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
    pub(crate) role: &'a AgentRole,
    pub(crate) stop_hook_active: bool,
    pub(crate) last_assistant_message: Option<&'a str>,
    pub(crate) continuation: Option<String>,
}

impl StopContext<'_> {
    #[must_use]
    /// Returns the agent role.
    pub fn role(&self) -> &AgentRole {
        self.role
    }

    #[must_use]
    /// Stops hook active.
    pub fn stop_hook_active(&self) -> bool {
        self.stop_hook_active
    }

    #[must_use]
    /// Returns the last assistant message.
    pub fn last_assistant_message(&self) -> Option<&str> {
        self.last_assistant_message
    }

    /// Returns the first continuation requested by the middleware chain.
    #[must_use]
    pub fn continuation(&self) -> Option<&str> {
        self.continuation.as_deref()
    }

    /// Requests one more model step with hidden context.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn continue_with(&mut self, prompt: impl Into<String>) -> Result<()> {
        if self.stop_hook_active {
            return Err(Error::Config(
                "a stop hook may continue a turn only once".into(),
            ));
        }
        let prompt = hook_message("stop continuation prompt", prompt)?;
        if self.continuation.is_none() {
            self.continuation = Some(prompt);
        }
        Ok(())
    }
}

fn hook_message(name: &str, value: impl Into<String>) -> Result<String> {
    let value = value.into();
    if value.trim().is_empty() || value.len() > MAX_CAPABILITY_INPUT_BYTES {
        return Err(Error::Config(format!("{name} is empty or too long")));
    }
    Ok(value)
}

fn set_stop_reason(
    target: &mut Option<String>,
    name: &str,
    reason: impl Into<String>,
) -> Result<()> {
    let reason = hook_message(name, reason)?;
    if target.is_none() {
        *target = Some(reason);
    }
    Ok(())
}

fn set_first(target: &mut Option<String>, value: Option<String>) {
    if target.is_none() {
        *target = value;
    }
}

pub(super) fn provisional_message_target(
    checkpoint_sequence: u64,
    batch_item_count: usize,
) -> Result<MessageTarget> {
    Ok(MessageTarget {
        checkpoint_sequence: checkpoint_sequence
            .checked_add(1)
            .ok_or_else(|| Error::Checkpoint("checkpoint sequence overflow".into()))?,
        batch_item_count,
    })
}

/// Mutable state exposed to the middleware preparing conversation messages.
pub struct MessageRouteContext<'a> {
    /// The submission identifier.
    pub submission_id: &'a str,
    /// The message.
    pub message: &'a MessageSubmission,
    /// The active turn identifier.
    pub active_turn_id: Option<&'a str>,
    /// The queued messages.
    pub queued_messages: MessageQueue<'a>,
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
}

/// Mutable turn state exposed to a capability command that can run immediately.
pub struct ActiveCommandContext<'a> {
    /// The checkpoints.
    pub checkpoints: &'a dyn CheckpointStore,
    /// The submission identifier.
    pub submission_id: &'a str,
    /// The session identifier.
    pub session_id: &'a str,
    /// The metadata.
    pub metadata: &'a BTreeMap<String, Value>,
    /// The active turn identifier.
    pub active_turn_id: &'a str,
    /// The command.
    pub command: &'a str,
    /// The arguments.
    pub arguments: &'a str,
    /// The input.
    pub input: Option<&'a str>,
    /// The target.
    pub target: Option<MessageTarget>,
    /// The queued messages.
    pub queued_messages: MessageQueue<'a>,
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
}

/// Result of one middleware-owned submission.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubmissionResult {
    /// Selects the accepted case.
    Accepted {
        /// The input changed.
        input_changed: bool,
    },
    /// The operation completed without changing durable turn state; publish its events now.
    Handled,
    /// Selects the rejected case.
    Rejected(String),
}

/// State exposed when the loop finishes or aborts a turn.
pub struct TurnEndContext<'a> {
    /// The session identifier.
    pub session_id: &'a str,
    /// The turn identifier.
    pub turn_id: &'a str,
    pub(crate) outcome: ExecutionOutcome,
    pub(crate) queued_messages: &'a [DurableQueuedMessage],
    pub(crate) owner: Option<&'static str>,
    /// The events.
    pub events: &'a mut Vec<EventMsg>,
}

impl TurnEndContext<'_> {
    #[must_use]
    /// Returns the turn outcome.
    pub fn outcome(&self) -> ExecutionOutcome {
        self.outcome
    }

    /// Returns queued messages still pending for this middleware, oldest first.
    pub fn queued_messages(&self) -> impl Iterator<Item = QueuedMessageView<'_>> {
        let owner = self.owner;
        self.queued_messages
            .iter()
            .filter(move |item| owner.is_some_and(|owner| item.owner() == owner))
            .map(|item| QueuedMessageView { item })
    }
}

/// State available to a middleware-owned frontend command.
pub struct MiddlewareCommandContext<'a> {
    /// The command.
    pub command: &'a str,
    /// The arguments.
    pub arguments: &'a str,
    /// The input.
    pub input: Option<&'a str>,
    /// The target.
    pub target: Option<MessageTarget>,
    /// The session identifier.
    pub session_id: &'a str,
    /// The session context.
    pub session_context: &'a SessionContext,
    /// The checkpoint.
    pub checkpoint: &'a Checkpoint,
    /// The checkpoints.
    pub checkpoints: Arc<dyn CheckpointStore>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::model::{Model, ModelEventSink, ModelOutput, ModelRequest};

    struct NoModel;

    impl Model for NoModel {
        fn respond<'a>(
            &'a self,
            _request: ModelRequest<'a>,
            _events: ModelEventSink,
        ) -> crate::BoxFuture<'a, crate::Result<ModelOutput>> {
            Box::pin(async { Err(crate::Error::Provider("unused".into())) })
        }
    }

    #[test]
    fn request_input_is_borrowed_until_replaced() {
        let original = vec![Value::String("original".into())];
        let role = AgentRole::Main;
        let router = ModelRouter::new("test", Arc::new(NoModel));
        let mut context = ModelRequestContext {
            role: &role,
            model: &router,
            provider: "test",
            session_id: "session",
            turn_id: "turn",
            model_step: 0,
            input: Cow::Borrowed(&original),
        };

        assert!(matches!(&context.input, Cow::Borrowed(_)));
        context.replace_input(vec![Value::String("replacement".into())]);
        assert!(matches!(&context.input, Cow::Owned(_)));
        assert_eq!(original, [Value::String("original".into())]);
    }
}