wcode-harness 0.3.2

Minimal, extensible agent harness kernel: event loop, tools, hooks, JSONL sessions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
//! In-process session actor — one mailbox, one stream.
//!
//! [`SessionActor`] turns an [`Agent`] into a task with an inbox and a
//! subscribable outbox, so a caller drives the session entirely through
//! [`Request`]s and observes it through [`AgentEvent`]s — never by holding the
//! `Agent` itself:
//!
//! ```text
//!   caller  (REPL / TUI / future peer session — all identical here)
//!     │  send(Request)                          ▲  subscribe() → recv()
//!     ▼                                         │  (own cursor per subscriber)
//!   inbox: mpsc::Unbounded<Request>       outbox: broadcast<AgentEvent>
//!     │                                         ▲  events.send(ev)
//!     └───────────► SessionActor task ◄─────────┘
//!                   owns the Agent; serves one Request at a time;
//!                   `deferred: VecDeque<Request>` parks mid-run commands
//! ```
//!
//! This is the seam the whole protocol design hangs on. A REPL, a TUI, and
//! (later) a peer session are all just callers that hold a [`SessionHandle`];
//! they differ only in how they render the stream and which address they hold,
//! not in the mechanism they speak. Today the inbox and outbox are in-process
//! channels; the shapes are chosen so that a socket ([`Frame`]s over NDJSON,
//! stage S2) can replace the transport without changing this API.
//!
//! ## Flow
//!
//! `serve()` — no run in flight: pull ONE Request, service it, repeat.
//!
//! ```text
//!   deferred non-empty? ──yes──► take from deferred (FIFO, order kept)
//!        │ no
//!        ▼
//!   inbox.recv().await ──► match Request:
//!        Submit    {..} ─► run(...)              → enters the in-run map below
//!        Notify    {..} ─► agent.notify(tagged)  → append, no turn
//!        Interrupt {..} ─► agent.steer(tagged)   → queued for the next turn
//!        Wake      {..} ─► run(tagged)           → a turn even when idle
//!        Cancel         ─► (no-op — nothing is running)
//!        SetModel  {..} ─► agent.set_model(..)
//!        SetEffort {..} ─► agent.set_effort(..)
//!        Compact   {..} ─► agent.compact(..).await
//!        GetHistory     ─► reply with the context
//!        Unknown        ─► (ignored)
//! ```
//!
//! `run()` — the Agent is borrowed for the whole run, so it is reached only
//! through clones taken *before* the borrow.
//!
//! ```text
//!   steer     = agent.steer_sender()
//!   follow_up = agent.follow_up_sender()
//!   cancel    = agent.cancel_token()
//!
//!   loop { tokio::select! { biased; ... } }   ← biased: inbox polled FIRST
//!        ├─ Some(req) = inbox.recv() ─► Cancel   ─► cancel.cancel()         ┐ to the
//!        │                              Steer    ─► steer.send(msg)         │ live run
//!        │                              FollowUp ─► follow_up.send(msg)     │
//!        │                              other    ─► deferred.push_back(req) ┘ waits
//!        ├─ result  = &mut run  ──────► run finished → break
//!        └─ Some(ev) = sink_rx.recv() ► events.send(ev)  (fan-out to subscribers)
//!   }
//!   then: drain leftover sink_rx → events.send ; on Err(run) → Error event
//! ```
//!
//! [`Frame`]: crate::protocol::Frame
//!
//! ## Delivery rules
//!
//! A run holds the agent's `&mut` for its whole life, so the actor splits the
//! inbox by what each request needs:
//!
//! | request | while a run is in flight |
//! |---------|--------------------------|
//! | `Cancel` | delivered at once — the token is cancelled; the loop aborts |
//! | `Interrupt` / `Wake` | forwarded to the run's channels at once |
//! | `SetModel` / `SetEffort` / `Compact` | deferred, applied when the run ends |
//! | another `Submit` | deferred, becomes the next run |
//!
//! The interactive path therefore never waits on a run. The deferred set is
//! exactly the requests that need `&mut Agent` — you cannot swap the model or
//! compact the context out from under a run — and deferring them is also the
//! documented meaning: `set_model`/`set_effort` "take effect on the next run".
//!
//! One caveat lives in the kernel, not here — the actor hands a `Cancel` over at
//! once, but the *loop* is what acts on it, and its latency depends on where the
//! run is:
//!
//! ```text
//! where the run is when Cancel arrives          when it stops
//! ---------------------------------------------  -----------------------
//! model streaming     (loop races the token)     immediately
//! between turns       (checked at turn start)    immediately
//! inside a tool call  (no race on the future)    when the tool returns *
//! ```
//!
//! `*` unless the tool watches `ToolContext::cancel` itself (e.g. `bash` kills
//! its child) — then it can stop early.
//!
//! ## Requests and replies
//!
//! `send` is fire-and-forget; `ask` awaits a reply. The reply is an
//! [`AgentEvent`] reply variant — [`AgentEvent::History`] for `GetHistory`,
//! [`AgentEvent::Ack`]/[`AgentEvent::Error`] for `SetModel`/`SetEffort`/
//! [`AgentEvent::Compaction`] for `Compact` — correlated in-process by a
//! one-shot channel. Replies are never fanned out on the event stream; the wire
//! (S2) will carry the same variants correlated by the envelope's `reply_to`.
//!
//! Scope so far: every request variant that maps onto an existing [`Agent`]
//! method is serviced. Still to come (S1b): pointing the CLI at a handle.

use std::collections::VecDeque;
use std::fmt;

use tokio::sync::{broadcast, mpsc, oneshot, watch};

use crate::agent::Agent;
use crate::compaction::CompactOutcome;
use crate::event::AgentEvent;
use crate::hooks::HooksSet;
use crate::loop_::LoopError;
use crate::message::{AgentMessage, StopReason};
use crate::protocol::{MemberState, Request, SessionId};

/// Default outbox buffer: how far a subscriber may lag before it starts losing
/// events (`broadcast` semantics — the slowest reader drops, it never blocks the
/// run).
pub const EVENT_BUFFER: usize = 1024;

/// Handle to a running [`SessionActor`].
///
/// Cloning gives another caller the same mailbox and stream. When the last
/// handle drops, the session shuts down and its [`Agent`] is dropped.
#[derive(Clone)]
pub struct SessionHandle {
    inbox: mpsc::UnboundedSender<Message>,
    events: broadcast::Sender<AgentEvent>,
    /// The run-state cell — the ONE server-side liveness fact (bug 2). A `watch`
    /// (not a bare `AtomicU8`) so a registry/server task can WAKE on a transition
    /// and re-push the roster; `send_replace` keeps the latest value even with no
    /// receiver yet. `Clone` rides freely (the sender is shared).
    state: watch::Sender<MemberState>,
}

impl SessionHandle {
    /// Submit a request to the session's inbox.
    ///
    /// Fails only if the session has shut down (every handle was dropped and the
    /// actor task has ended). A `Submit` runs to completion before the next
    /// non-interrupt request is serviced, but `Interrupt`/`Wake`/`Cancel` sent
    /// during a run are handled immediately (see the actor's delivery rules).
    pub fn send(&self, request: Request) -> Result<(), SessionClosed> {
        self.tell(None, request)
    }

    /// Like [`SessionHandle::send`], but attributed to a sender address so the
    /// recipient can attribute and policy-check the message (a peer session
    /// passes its own `"agent:<id>"` address).
    pub fn send_from(&self, from: SessionId, request: Request) -> Result<(), SessionClosed> {
        self.tell(Some(from), request)
    }

    fn tell(&self, from: Option<SessionId>, request: Request) -> Result<(), SessionClosed> {
        self.inbox
            .send(Message::Tell { from, request })
            .map_err(|_| SessionClosed)
    }

    /// Send a request and await its reply.
    ///
    /// `ask` is for requests that expect a reply: `GetHistory` (→
    /// [`AgentEvent::History`]), `SetModel`/`SetEffort` (→ [`AgentEvent::Ack`]
    /// or [`AgentEvent::Error`]), `Compact` (→ [`AgentEvent::Compaction`],
    /// [`AgentEvent::Ack`], or [`AgentEvent::Error`]). It also works for
    /// `Submit`, replying when the run completes. Interrupts
    /// (`Interrupt`/`Wake`/`Cancel`) want no reply — use `send`; an `ask` on one
    /// is deferred like any command while a run is in flight.
    ///
    /// Fails only if the session has shut down.
    pub async fn ask(&self, request: Request) -> Result<AgentEvent, SessionClosed> {
        self.question(None, request).await
    }

    /// Like [`SessionHandle::ask`], attributed to a sender address.
    pub async fn ask_from(
        &self,
        from: SessionId,
        request: Request,
    ) -> Result<AgentEvent, SessionClosed> {
        self.question(Some(from), request).await
    }

    async fn question(
        &self,
        from: Option<SessionId>,
        request: Request,
    ) -> Result<AgentEvent, SessionClosed> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.inbox
            .send(Message::Ask {
                from,
                request,
                reply: reply_tx,
            })
            .map_err(|_| SessionClosed)?;
        reply_rx.await.map_err(|_| SessionClosed)
    }

    /// The session's current run-state. Read-only, lock-free (a `watch` borrow),
    /// so a `peers` listing / roster read over N members is cheap.
    pub fn state(&self) -> MemberState {
        *self.state.borrow()
    }

    /// A live view of the run-state, so a registry/server task can wake on a
    /// transition instead of polling. Seeded with the current value (like
    /// `Registry::subscribe`).
    pub fn state_rx(&self) -> watch::Receiver<MemberState> {
        self.state.subscribe()
    }
    /// Subscribe to the session's event stream. Each subscriber gets its own
    /// receiver; a lagging subscriber drops events rather than stalling the run.
    pub fn subscribe(&self) -> broadcast::Receiver<AgentEvent> {
        self.events.subscribe()
    }
}

/// Returned when a [`SessionHandle::send`] targets a session that has ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionClosed;

impl fmt::Display for SessionClosed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("session actor has shut down")
    }
}

impl std::error::Error for SessionClosed {}

/// A mailbox item: fire-and-forget, or a request that expects a reply.
enum Message {
    /// No reply wanted. `from` is the sender's address — `None` for a local
    /// caller (the human), `Some(peer)` when another session sends.
    Tell {
        from: Option<SessionId>,
        request: Request,
    },
    /// The reply to the request is sent here when it is serviced.
    Ask {
        from: Option<SessionId>,
        request: Request,
        reply: oneshot::Sender<AgentEvent>,
    },
}

/// Spawns the actor task that owns an [`Agent`].
///
/// The `Agent` moves into a background task; all interaction returns through the
/// [`SessionHandle`]. The task exits when the last handle drops.
pub struct SessionActor;

impl SessionActor {
    pub fn spawn(agent: Agent) -> SessionHandle {
        let (inbox_tx, inbox_rx) = mpsc::unbounded_channel();
        let (events_tx, _) = broadcast::channel(EVENT_BUFFER);
        let events = events_tx.clone();
        let (state_tx, _state_rx) = watch::channel(MemberState::Idle);
        tokio::spawn(serve(agent, inbox_rx, events_tx, state_tx.clone()));
        SessionHandle {
            inbox: inbox_tx,
            events,
            state: state_tx,
        }
    }
}

/// The actor loop: pull one request at a time, service it, repeat.
async fn serve(
    mut agent: Agent,
    mut inbox: mpsc::UnboundedReceiver<Message>,
    events: broadcast::Sender<AgentEvent>,
    state: watch::Sender<MemberState>,
) {
    // Requests that arrive *during* a run but cannot be applied to it (a
    // second `Submit`, a model swap) wait here and are serviced once the run
    // ends, preserving their order.
    let mut deferred: VecDeque<Message> = VecDeque::new();

    loop {
        let message = match deferred.pop_front() {
            Some(message) => message,
            None => match inbox.recv().await {
                Some(message) => message,
                None => break, // every handle dropped: shut down
            },
        };

        dispatch(&mut agent, message, &mut inbox, &events, &mut deferred, &state).await;
    }
}

/// Prefix an inbound peer message with its sender, so the model sees who sent
/// it and knows the address to reply to (§13.13).
fn tag(sender: &SessionId, content: &str) -> String {
    format!("[message from {sender}]\n{content}")
}

/// Run the inbound policy on an A2A message (the mirror of
/// `before_tool_call`). Returns `Some(reason)` if the message was dropped; the
/// request may have been rewritten in place by the hook either way.
async fn gate_inbound(hooks: &HooksSet, message: &mut Message) -> Option<String> {
    let (from, request) = match message {
        Message::Tell { from, request } | Message::Ask { from, request, .. } => (from, request),
    };
    if !crate::protocol::is_inbound(request) {
        return None;
    }
    hooks.before_inbound(from.as_ref(), request).await
}

/// Service one mailbox item: run the request, then answer an `Ask` with the
/// reply it produced (a `Tell` drops the reply on the floor).
async fn dispatch(
    agent: &mut Agent,
    mut message: Message,
    inbox: &mut mpsc::UnboundedReceiver<Message>,
    events: &broadcast::Sender<AgentEvent>,
    deferred: &mut VecDeque<Message>,
    state: &watch::Sender<MemberState>,
) {
    // Inbound peer-message policy (S4-1): a drop skips delivery entirely; a
    // rewrite (in place) is what gets serviced.
    if let Some(reason) = gate_inbound(agent.hooks(), &mut message).await {
        if let Message::Ask { reply, .. } = message {
            let _ = reply.send(AgentEvent::Error {
                message: format!("inbound blocked: {reason}"),
            });
        }
        return;
    }

    let (from, request, reply) = match message {
        Message::Tell { from, request } => (from, request, None),
        Message::Ask { from, request, reply } => (from, request, Some(reply)),
    };
    let sender = from.unwrap_or_else(SessionId::user);

    let event = match request {
        Request::Submit { text } => match run(agent, &text, inbox, events, deferred, state).await {
            Ok(stop_reason) => AgentEvent::Stopped { stop_reason },
            Err(e) => AgentEvent::Error {
                message: e.to_string(),
            },
        },
        // A2A delivery verbs (S4-1). `Notify` appends with no turn;
        // `Interrupt`/`Wake` are the canonical interrupt/continue forms.
        Request::Notify { content } => match agent.notify(tag(&sender, &content)) {
            Ok(_) => {
                let _ = events.send(AgentEvent::MessageReceived {
                    from: sender.clone(),
                    content,
                });
                AgentEvent::Ack
            }
            Err(e) => AgentEvent::Error {
                message: e.to_string(),
            },
        },
        Request::Interrupt { content } => {
            agent.steer(AgentMessage::user_text(tag(&sender, &content)));
            let _ = events.send(AgentEvent::MessageReceived {
                from: sender.clone(),
                content,
            });
            AgentEvent::Ack
        }
        // A `Wake` runs even when idle: start a turn with the (tagged) content,
        // like `Submit` — otherwise a worker handed a task would only queue a
        // follow-up and never act on it.
        Request::Wake { content } => {
            let _ = events.send(AgentEvent::MessageReceived {
                from: sender.clone(),
                content: content.clone(),
            });
            match run(agent, &tag(&sender, &content), inbox, events, deferred, state).await {
                Ok(stop_reason) => AgentEvent::Stopped { stop_reason },
                Err(e) => AgentEvent::Error {
                    message: e.to_string(),
                },
            }
        }
        // An idle cancel is a no-op (see the delivery rules): the token is
        // minted fresh at the end of each run, so cancelling an idle session
        // would otherwise abort the next run on its first poll.
        Request::Cancel => AgentEvent::Ack,
        Request::SetModel { model } => match agent.set_model(model) {
            Ok(()) => AgentEvent::Ack,
            Err(e) => AgentEvent::Error {
                message: e.to_string(),
            },
        },
        Request::SetEffort { effort } => match agent.set_effort(effort) {
            Ok(()) => AgentEvent::Ack,
            Err(e) => AgentEvent::Error {
                message: e.to_string(),
            },
        },
        Request::Compact { instructions } => match agent.compact(instructions.as_deref()).await {
            Ok(CompactOutcome::NothingToDo) => AgentEvent::Ack,
            Ok(CompactOutcome::Done {
                summarized, kept, ..
            }) => AgentEvent::Compaction { summarized, kept },
            Err(e) => AgentEvent::Error { message: e },
        },
        // `/btw`: a tool-free side call. `side_ask` takes `&self`, so no borrow
        // conflict with the run. A `SideAsk` arriving mid-run is deferred to a
        // turn boundary like any other inbox request (see the run loop's
        // `deferred.push_back`) — queued, not refused.
        Request::SideAsk { text } => match agent.side_ask(&text).await {
            Ok(answer) => AgentEvent::SideAnswer {
                text: answer.text,
                usage: answer.usage,
            },
            Err(e) => AgentEvent::Error {
                message: e.to_string(),
            },
        },
        // Toggle plan mode: flips the shared handle (the `PlanModeHooks` reads
        // the same one) and recomposes the system prompt. Infallible.
        Request::SetPlanMode { on } => {
            agent.set_plan_mode(on);
            AgentEvent::Ack
        }
        Request::GetHistory => AgentEvent::History {
            messages: agent.messages().to_vec(),
        },
        Request::Status => AgentEvent::Status {
            last_assistant_text: crate::message::last_assistant_text(agent.messages()),
        },
        // A served peer is defined by a socket server's injected handler; an
        // in-process session has no factory, so it can only refuse.
        Request::Define { .. } => AgentEvent::Error {
            message: "agent definition is served, not in-process".into(),
        },
        Request::ListSessions | Request::Unknown => AgentEvent::Ack,
    };

    if let Some(reply) = reply {
        let _ = reply.send(event);
    }
}

/// Drive one `Agent::run`, forwarding its events to the outbox while still
/// servicing the inbox so `Interrupt`/`Wake`/`Cancel` reach the in-flight run.
async fn run(
    agent: &mut Agent,
    text: &str,
    inbox: &mut mpsc::UnboundedReceiver<Message>,
    events: &broadcast::Sender<AgentEvent>,
    deferred: &mut VecDeque<Message>,
    state: &watch::Sender<MemberState>,
) -> Result<StopReason, LoopError> {
    // State transitions live at the run boundary — this `run()` is the in-flight
    // window. The event stream's `AgentStart`/`AgentEnd` are the OTHER place this
    // could be derived; the actor-owned cell is authoritative because it is set
    // synchronously before the first await, so a reader never misses `Running`.
    // A `Cancel` ends on `Ok(StopReason::Aborted)` -> `Done`: an abort is not a
    // failure, matching the TUI.
    state.send_replace(MemberState::Running);
    let (sink_tx, mut sink_rx) = mpsc::unbounded_channel::<AgentEvent>();
    // Sender/token clones taken *before* `run` borrows the agent: steering and
    // cancelling the in-flight run must not need the `&mut`.
    let steer = agent.steer_sender();
    let follow_up = agent.follow_up_sender();
    let cancel = agent.cancel_token();
    let hooks = agent.hooks().clone();
    // Read-only handle for mid-run `GetHistory`/`SideAsk` (see the arms below).
    let side = agent.side_handle();

    let mut run = Box::pin(agent.run(text, sink_tx));
    let result = loop {
        // Biased: service the inbox *before* advancing the run. An `Interrupt` must
        // be in the agent's steering channel before the run reaches its next
        // turn-boundary drain, or it is silently a turn late. Polling the run
        // first would let it cross that boundary while the request still sits
        // here.
        tokio::select! {
            biased;
            Some(mut message) = inbox.recv() => {
                if let Some(reason) = gate_inbound(&hooks, &mut message).await {
                    if let Message::Ask { reply, .. } = message {
                        let _ = reply.send(AgentEvent::Error {
                            message: format!("inbound blocked: {reason}"),
                        });
                    }
                    continue;
                }
                match message {
                    Message::Tell {
                        request: Request::Cancel,
                        ..
                    } => cancel.cancel(),
                    Message::Tell {
                        request: Request::Notify { content } | Request::Interrupt { content },
                        from,
                    } => {
                        let from = from.unwrap_or_else(SessionId::user);
                        let _ = steer.send(AgentMessage::user_text(tag(&from, &content)));
                        let _ = events.send(AgentEvent::MessageReceived {
                            from,
                            content,
                        });
                    }
                    Message::Tell {
                        request: Request::Wake { content },
                        from,
                    } => {
                        let from = from.unwrap_or_else(SessionId::user);
                        let _ = follow_up.send(AgentMessage::user_text(tag(&from, &content)));
                        let _ = events.send(AgentEvent::MessageReceived {
                            from,
                            content,
                        });
                    }
                    // Read-only queries are answered mid-run from the context
                    // snapshot `run_loop` republishes each turn — a `/btw` or
                    // `/usage` never waits for the whole run. `side` was cloned
                    // before the run borrowed the agent.
                    Message::Ask {
                        request: Request::GetHistory,
                        reply,
                        ..
                    } => {
                        let _ = reply.send(AgentEvent::History { messages: side.history() });
                    }
                    Message::Ask {
                        request: Request::Status,
                        reply,
                        ..
                    } => {
                        let _ = reply.send(AgentEvent::Status {
                            last_assistant_text: side.last_assistant_text(),
                        });
                    }
                    Message::Ask {
                        request: Request::SideAsk { text },
                        reply,
                        ..
                    } => {
                        // A side ask is itself a model call: spawn it so it runs
                        // alongside the run instead of stalling the inbox.
                        let side = side.clone();
                        tokio::spawn(async move {
                            let event = match side.side_ask(&text).await {
                                Ok(answer) => AgentEvent::SideAnswer {
                                    text: answer.text,
                                    usage: answer.usage,
                                },
                                Err(e) => AgentEvent::Error {
                                    message: e.to_string(),
                                },
                            };
                            let _ = reply.send(event);
                        });
                    }
                    // A mutation cannot apply mid-run (it needs `&mut Agent`), but
                    // its contract is "next run": acknowledge now and re-queue it
                    // as a `Tell` so it is applied silently at the run boundary —
                    // instead of leaving the ask to time out (item-41 ASK_TIMEOUT).
                    Message::Ask {
                        from,
                        request:
                            req @ (Request::SetModel { .. }
                            | Request::SetEffort { .. }
                            | Request::SetPlanMode { .. }),
                        reply,
                    } => {
                        let _ = reply.send(AgentEvent::Ack);
                        deferred.push_back(Message::Tell { from, request: req });
                    }
                    other => deferred.push_back(other),
                }
            },
            result = &mut run => break result,
            Some(event) = sink_rx.recv() => {
                let _ = events.send(event);
            }
        }
    };

    // The run dropped its sink on completion; forward whatever is still buffered
    // so the last events (e.g. `AgentEnd`) are never stranded.
    while let Ok(event) = sink_rx.try_recv() {
        let _ = events.send(event);
    }

    // A session-write error inside the run is a `LoopError`; the run's own
    // `AgentEvent::Error` covers stream failures, so surface this one the same
    // way rather than dropping it silently.
    if let Err(e) = &result {
        let _ = events.send(AgentEvent::Error {
            message: e.to_string(),
        });
    }
    // Final transition: a normal stop is `Done`; a run-failure — the loop's
    // `StopReason::Error` or a `LoopError` — is `Failed` (sticky until the next
    // run sets `Running`).
    match &result {
        Ok(StopReason::Error) | Err(_) => {
            state.send_replace(MemberState::Failed);
        }
        Ok(_) => {
            state.send_replace(MemberState::Done);
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::{Agent, AgentConfig};
    use crate::compaction::CompactionPolicy;
    use crate::event::LlmStreamEvent;
    use crate::hooks::HooksSet;
    use crate::message::StopReason;
    use crate::streamfn::{LlmOpts, LlmStream, StreamFn};
    use crate::tool::{ToolContext, ToolOutput, TypedTool, erased};
    use futures::StreamExt as _;
    use serde::Deserialize;
    use serde_json::json;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    #[derive(Clone, Default)]
    struct Recorder {
        script: Arc<Mutex<VecDeque<Vec<LlmStreamEvent>>>>,
        calls: Arc<Mutex<Vec<Vec<AgentMessage>>>>,
        models: Arc<Mutex<Vec<String>>>,
    }

    impl Recorder {
        fn push(&self, events: Vec<LlmStreamEvent>) {
            self.script.lock().unwrap().push_back(events);
        }
        fn calls(&self) -> Vec<Vec<AgentMessage>> {
            self.calls.lock().unwrap().clone()
        }
        fn models(&self) -> Vec<String> {
            self.models.lock().unwrap().clone()
        }
    }

    fn fake_stream_fn(rec: &Recorder) -> StreamFn {
        let rec = rec.clone();
        Arc::new(
            move |ctx: &[AgentMessage], _system, _tools, opts: &LlmOpts| {
                rec.calls.lock().unwrap().push(ctx.to_vec());
                rec.models.lock().unwrap().push(opts.model.clone());
                let events = rec.script.lock().unwrap().pop_front().unwrap_or_default();
                Box::pin(futures::stream::iter(events)) as LlmStream
            },
        )
    }

    fn agent_config(stream_fn: StreamFn, tools: Vec<crate::tool::Tool>) -> AgentConfig {
        AgentConfig {
            system: "sys".into(),
            tools,
            llm: LlmOpts {
                model: "m1".into(),
                ..LlmOpts::default()
            },
            stream_fn,
            hooks: HooksSet::default(),
            session: None,
            context: Vec::new(),
            working_dir: std::path::PathBuf::new(),
            max_turns: crate::loop_::DEFAULT_MAX_TURNS,
            parallel_tools: true,
            compaction: CompactionPolicy::default(),
            plan_mode: crate::hooks::PlanModeHandle::new(),
        }
    }

    /// Block until the run ends, panicking if it stalls.
    async fn wait_for_end(rx: &mut broadcast::Receiver<AgentEvent>) {
        loop {
            let event = tokio::time::timeout(Duration::from_secs(5), rx.recv())
                .await
                .expect("an event within the timeout")
                .expect("the outbox stays open");
            if matches!(event, AgentEvent::AgentEnd) {
                return;
            }
        }
    }

    #[tokio::test]
    async fn submit_streams_events_to_a_subscriber() {
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::TextDelta("hello".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "hi".into() }).unwrap();

        let mut saw_text = false;
        loop {
            let event = tokio::time::timeout(Duration::from_secs(5), rx.recv())
                .await
                .expect("an event")
                .expect("open");
            match event {
                AgentEvent::MessageUpdate { message } if message.as_text() == "hello" => {
                    saw_text = true;
                }
                AgentEvent::AgentEnd => break,
                _ => {}
            }
        }
        assert!(saw_text, "the streamed text reached the subscriber");
    }

    #[tokio::test]
    async fn idle_cancel_does_not_poison_the_next_run() {
        let rec = Recorder::default();
        for text in ["one", "two"] {
            rec.push(vec![
                LlmStreamEvent::TextDelta(text.into()),
                LlmStreamEvent::Done {
                    stop_reason: StopReason::Stop,
                    usage: None,
                },
            ]);
        }
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let mut rx = handle.subscribe();

        handle.send(Request::Submit { text: "a".into() }).unwrap();
        wait_for_end(&mut rx).await;

        // No run in flight: this must be swallowed, not arm a kill for run two.
        handle.send(Request::Cancel).unwrap();
        handle.send(Request::Submit { text: "b".into() }).unwrap();

        let mut saw_two = false;
        loop {
            let event = tokio::time::timeout(Duration::from_secs(5), rx.recv())
                .await
                .expect("an event")
                .expect("open");
            match event {
                AgentEvent::MessageUpdate { message } if message.as_text() == "two" => {
                    saw_two = true;
                }
                AgentEvent::AgentEnd => break,
                _ => {}
            }
        }
        assert!(saw_two, "the second run completed despite the idle cancel");
    }

    #[tokio::test]
    async fn cancel_aborts_an_in_flight_run() {
        // One delta, then the stream hangs: only a working cancel ends the run.
        let stream_fn: StreamFn = Arc::new(|_ctx, _sys, _tools, _opts| {
            let head = futures::stream::iter(vec![LlmStreamEvent::TextDelta("part".into())]);
            Box::pin(head.chain(futures::stream::pending())) as LlmStream
        });
        let handle = SessionActor::spawn(Agent::new(agent_config(stream_fn, vec![])));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "hi".into() }).unwrap();

        loop {
            let event = tokio::time::timeout(Duration::from_secs(5), rx.recv())
                .await
                .expect("an event")
                .expect("open");
            if matches!(event, AgentEvent::MessageUpdate { .. }) {
                handle.send(Request::Cancel).unwrap();
                break;
            }
        }
        // Without a live cancel this would time out on the pending stream.
        wait_for_end(&mut rx).await;
    }

    #[tokio::test]
    async fn state_is_running_during_a_turn_then_done_after() {
        // A stream that emits one delta then hangs: the run is observably in
        // flight until a cancel ends it.
        let stream_fn: StreamFn = Arc::new(|_ctx, _sys, _tools, _opts| {
            let head = futures::stream::iter(vec![LlmStreamEvent::TextDelta("part".into())]);
            Box::pin(head.chain(futures::stream::pending())) as LlmStream
        });
        let handle = SessionActor::spawn(Agent::new(agent_config(stream_fn, vec![])));
        assert_eq!(handle.state(), MemberState::Idle, "a virgin session is idle");

        // A watcher wakes on the transition rather than polling.
        let mut state_rx = handle.state_rx();
        handle.send(Request::Submit { text: "hi".into() }).unwrap();
        tokio::time::timeout(Duration::from_secs(5), state_rx.changed())
            .await
            .expect("a state change")
            .expect("open");
        assert_eq!(*state_rx.borrow_and_update(), MemberState::Running);
        assert_eq!(handle.state(), MemberState::Running, "the run is in flight");

        handle.send(Request::Cancel).unwrap();
        tokio::time::timeout(Duration::from_secs(5), state_rx.changed())
            .await
            .expect("a state change")
            .expect("open");
        assert_eq!(
            *state_rx.borrow_and_update(),
            MemberState::Done,
            "an abort ends Done, not Failed"
        );
        assert_eq!(handle.state(), MemberState::Done);
    }

    #[tokio::test]
    async fn a_fatal_stream_error_ends_failed() {
        let rec = Recorder::default();
        rec.push(vec![LlmStreamEvent::Error {
            message: "boom".into(),
            fatal: true,
        }]);
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "hi".into() }).unwrap();
        wait_for_end(&mut rx).await;
        assert_eq!(handle.state(), MemberState::Failed);
    }

    #[derive(Deserialize, schemars::JsonSchema)]
    struct GateArgs {
        text: String,
    }

    /// Blocks until released, so the actor can be steered while a run is inside
    /// a tool call.
    struct GateTool {
        entered: mpsc::UnboundedSender<()>,
        release: Arc<tokio::sync::Notify>,
    }

    #[async_trait::async_trait]
    impl TypedTool for GateTool {
        type Args = GateArgs;
        fn name(&self) -> &str {
            "gate"
        }
        fn description(&self) -> &str {
            "blocks until released"
        }
        async fn execute(&self, args: GateArgs, _ctx: &ToolContext) -> ToolOutput {
            self.entered.send(()).ok();
            self.release.notified().await;
            ToolOutput {
                output: format!("released:{}", args.text),
                is_error: false,
                diff: None,
                path: None,
            }
        }
    }

    #[tokio::test]
    async fn config_request_during_a_run_is_deferred_to_after_it() {
        // Run one: turn 1 blocks in the gate, turn 2 finishes — both on the
        // run's own model. Run two is a fresh request and must see the swap.
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::ToolCall {
                id: "c1".into(),
                name: "gate".into(),
                arguments: json!({ "text": "hi" }),
            },
            LlmStreamEvent::Done {
                stop_reason: StopReason::ToolUse,
                usage: None,
            },
        ]);
        for text in ["turn two", "run two"] {
            rec.push(vec![
                LlmStreamEvent::TextDelta(text.into()),
                LlmStreamEvent::Done {
                    stop_reason: StopReason::Stop,
                    usage: None,
                },
            ]);
        }

        let (entered_tx, mut entered_rx) = mpsc::unbounded_channel::<()>();
        let release = Arc::new(tokio::sync::Notify::new());
        let gate = erased(GateTool {
            entered: entered_tx,
            release: release.clone(),
        });

        let handle =
            SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![gate])));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "a".into() }).unwrap();

        entered_rx.recv().await.unwrap(); // run one is inside the tool
        handle
            .send(Request::SetModel { model: "m2".into() })
            .unwrap(); // must not take effect until run one is done
        release.notify_one();
        wait_for_end(&mut rx).await; // run one ends on m1

        handle.send(Request::Submit { text: "b".into() }).unwrap();
        wait_for_end(&mut rx).await; // run two

        assert_eq!(
            rec.models(),
            ["m1", "m1", "m2"],
            "the swap waited for the run, then applied to the next one"
        );
    }

    #[tokio::test]
    async fn ask_history_returns_the_conversation() {
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::TextDelta("hi back".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let mut rx = handle.subscribe();
        handle
            .send(Request::Submit {
                text: "hello".into(),
            })
            .unwrap();
        wait_for_end(&mut rx).await;

        let reply = handle.ask(Request::GetHistory).await.unwrap();
        let AgentEvent::History { messages } = reply else {
            panic!("expected a History reply, got {reply:?}");
        };
        assert!(
            messages.iter().any(|m| m.as_text() == "hello"),
            "the read-back carries the user turn: {messages:?}"
        );
    }

    #[tokio::test]
    async fn ask_set_model_replies_ack_and_takes_effect() {
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::TextDelta("x".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let mut rx = handle.subscribe();

        let reply = handle
            .ask(Request::SetModel { model: "m2".into() })
            .await
            .unwrap();
        assert!(matches!(reply, AgentEvent::Ack), "{reply:?}");

        handle.send(Request::Submit { text: "go".into() }).unwrap();
        wait_for_end(&mut rx).await;
        assert_eq!(rec.models(), ["m2"], "the swap applied to the next run");
    }

    #[tokio::test]
    async fn define_on_a_local_session_is_an_error() {
        let rec = Recorder::default();
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let reply = handle
            .ask(Request::Define {
                name: Some("w1".into()),
                model: None,
                role: None,
                tools: None,
                base_url: None,
                api_key: None,
                read_only: false,
                effort: None,
            })
            .await
            .unwrap();
        assert!(
            matches!(&reply, AgentEvent::Error { message } if message.contains("served")),
            "{reply:?}"
        );
    }

    #[tokio::test]
    async fn ask_compact_with_nothing_to_do_replies_ack() {
        let handle = SessionActor::spawn(Agent::new(agent_config(
            fake_stream_fn(&Recorder::default()),
            vec![],
        )));
        let reply = handle
            .ask(Request::Compact { instructions: None })
            .await
            .unwrap();
        assert!(matches!(reply, AgentEvent::Ack), "{reply:?}");
    }

    #[tokio::test]
    async fn ask_submit_replies_stopped_with_the_reason() {
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::TextDelta("done".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let reply = handle
            .ask(Request::Submit { text: "hi".into() })
            .await
            .unwrap();
        assert!(
            matches!(
                reply,
                AgentEvent::Stopped {
                    stop_reason: StopReason::Stop
                }
            ),
            "{reply:?}"
        );
    }

    #[tokio::test]
    async fn notify_appends_without_starting_a_turn() {
        let rec = Recorder::default();
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let mut rx = handle.subscribe();

        let reply = handle
            .ask(Request::Notify {
                content: "ping".into(),
            })
            .await
            .unwrap();
        assert!(matches!(reply, AgentEvent::Ack), "{reply:?}");

        // The message was surfaced to subscribers...
        let surfaced = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("an event")
            .expect("open");
        assert!(
            matches!(&surfaced, AgentEvent::MessageReceived { content, .. } if content == "ping"),
            "{surfaced:?}"
        );

        // ...the conversation carries it...
        let AgentEvent::History { messages } = handle.ask(Request::GetHistory).await.unwrap() else {
            panic!("expected History");
        };
        assert!(
            messages
                .iter()
                .any(|m| m.as_text() == "[message from user]\nping"),
            "{messages:?}"
        );

        // ...and no turn ran (the loop was never entered).
        assert!(rec.calls().is_empty(), "notify must not run the loop");
    }

    #[tokio::test]
    async fn wake_starts_a_run_when_idle() {
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::TextDelta("acted".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let mut rx = handle.subscribe();

        let reply = handle
            .ask(Request::Wake {
                content: "do the task".into(),
            })
            .await
            .unwrap();
        assert!(
            matches!(
                reply,
                AgentEvent::Stopped {
                    stop_reason: StopReason::Stop
                }
            ),
            "{reply:?}"
        );
        wait_for_end(&mut rx).await;

        let calls = rec.calls();
        assert_eq!(calls.len(), 1, "Wake ran the loop once");
        assert!(
            calls[0]
                .iter()
                .any(|m| m.as_text() == "[message from user]\ndo the task"),
            "the tagged task is the prompt: {:?}",
            calls[0]
        );
    }

    struct InboundPolicy;

    #[async_trait::async_trait]
    impl crate::hooks::Hooks for InboundPolicy {
        async fn before_inbound(
            &self,
            _from: Option<&SessionId>,
            request: &mut Request,
        ) -> Option<String> {
            let Request::Notify { content } = request else {
                return None;
            };
            if content.starts_with("drop:") {
                return Some("policy".into());
            }
            *content = format!("{content}!");
            None
        }
    }

    #[tokio::test]
    async fn before_inbound_drops_and_rewrites_a_notify() {
        let rec = Recorder::default();
        let mut cfg = agent_config(fake_stream_fn(&rec), vec![]);
        cfg.hooks = HooksSet::one(Arc::new(InboundPolicy));
        let handle = SessionActor::spawn(Agent::new(cfg));

        // Dropped: an `ask` is answered with an Error, and nothing lands.
        let reply = handle
            .ask(Request::Notify {
                content: "drop: me".into(),
            })
            .await
            .unwrap();
        assert!(
            matches!(&reply, AgentEvent::Error { message } if message.contains("policy")),
            "{reply:?}"
        );

        // Rewritten: the hook's edit is what is recorded.
        let reply = handle
            .ask(Request::Notify {
                content: "keep me".into(),
            })
            .await
            .unwrap();
        assert!(matches!(reply, AgentEvent::Ack), "{reply:?}");

        let AgentEvent::History { messages } = handle.ask(Request::GetHistory).await.unwrap() else {
            panic!("expected History");
        };
        let texts: Vec<String> = messages.iter().map(|m| m.as_text()).collect();
        assert!(
            !texts.iter().any(|t| t == "drop: me"),
            "the dropped message never landed: {texts:?}"
        );
        assert!(
            texts.iter().any(|t| t == "[message from user]\nkeep me!"),
            "the rewrite landed: {texts:?}"
        );
    }

    #[tokio::test]
    async fn interrupt_reaches_the_next_turn_while_a_tool_is_blocked() {
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::ToolCall {
                id: "c1".into(),
                name: "gate".into(),
                arguments: json!({ "text": "hi" }),
            },
            LlmStreamEvent::Done {
                stop_reason: StopReason::ToolUse,
                usage: None,
            },
        ]);
        rec.push(vec![
            LlmStreamEvent::TextDelta("after interrupt".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);

        let (entered_tx, mut entered_rx) = mpsc::unbounded_channel::<()>();
        let release = Arc::new(tokio::sync::Notify::new());
        let gate = erased(GateTool {
            entered: entered_tx,
            release: release.clone(),
        });

        let handle =
            SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![gate])));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "hi".into() }).unwrap();

        entered_rx.recv().await.unwrap(); // the tool is now blocked
        handle
            .send(Request::Interrupt {
                content: "mid-run interrupt".into(),
            })
            .unwrap();
        release.notify_one();

        wait_for_end(&mut rx).await;

        let calls = rec.calls();
        assert_eq!(calls.len(), 2, "two stream calls: the tool turn and the next");
        assert!(
            calls[1]
                .iter()
                .any(|m| matches!(m, AgentMessage::User { .. })
                    && m.as_text() == "[message from user]\nmid-run interrupt"),
            "the interrupt drained into the next turn: {:?}",
            calls[1]
        );
    }

    #[tokio::test]
    async fn send_from_attributes_the_sender() {
        let rec = Recorder::default();
        let handle = SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![])));
        let mut rx = handle.subscribe();

        handle
            .send_from(
                SessionId::agent("b"),
                Request::Notify {
                    content: "ping".into(),
                },
            )
            .unwrap();

        let event = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("an event")
            .expect("open");
        assert!(
            matches!(&event, AgentEvent::MessageReceived { from, content }
                if from.as_str() == "agent:b" && content == "ping"),
            "{event:?}"
        );
    }

    struct SenderPolicy;

    #[async_trait::async_trait]
    impl crate::hooks::Hooks for SenderPolicy {
        async fn before_inbound(
            &self,
            from: Option<&SessionId>,
            _request: &mut Request,
        ) -> Option<String> {
            (from.map(SessionId::as_str) == Some("agent:evil")).then(|| "blocked sender".into())
        }
    }

    #[tokio::test]
    async fn before_inbound_sees_the_sender() {
        let rec = Recorder::default();
        let mut cfg = agent_config(fake_stream_fn(&rec), vec![]);
        cfg.hooks = HooksSet::one(Arc::new(SenderPolicy));
        let handle = SessionActor::spawn(Agent::new(cfg));

        // A hostile peer is dropped...
        let reply = handle
            .ask_from(
                SessionId::agent("evil"),
                Request::Notify {
                    content: "let me in".into(),
                },
            )
            .await
            .unwrap();
        assert!(
            matches!(&reply, AgentEvent::Error { message } if message.contains("blocked sender")),
            "{reply:?}"
        );

        // ...a friendly one is not.
        let reply = handle
            .ask_from(
                SessionId::agent("friend"),
                Request::Notify {
                    content: "hello".into(),
                },
            )
            .await
            .unwrap();
        assert!(matches!(reply, AgentEvent::Ack), "{reply:?}");

        let AgentEvent::History { messages } = handle.ask(Request::GetHistory).await.unwrap() else {
            panic!("expected History");
        };
        let texts: Vec<String> = messages.iter().map(|m| m.as_text()).collect();
        assert!(
            texts
                .iter()
                .any(|t| t == "[message from agent:friend]\nhello"),
            "{texts:?}"
        );
        assert!(!texts.iter().any(|t| t.contains("let me in")), "{texts:?}");
    }

    #[tokio::test]
    async fn side_ask_is_answered_mid_run() {
        // Run one blocks in the gate (turn 1), so the actor is mid-run when the
        // side ask arrives; it must be answered without waiting for the run.
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::ToolCall {
                id: "c1".into(),
                name: "gate".into(),
                arguments: json!({ "text": "hi" }),
            },
            LlmStreamEvent::Done {
                stop_reason: StopReason::ToolUse,
                usage: None,
            },
        ]);
        // The side ask's own model call (empty tool list) pops this.
        rec.push(vec![
            LlmStreamEvent::TextDelta("aside".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);
        // Run one, turn 2, after the gate releases.
        rec.push(vec![
            LlmStreamEvent::TextDelta("done".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);

        let (entered_tx, mut entered_rx) = mpsc::unbounded_channel::<()>();
        let release = Arc::new(tokio::sync::Notify::new());
        let gate = erased(GateTool {
            entered: entered_tx,
            release: release.clone(),
        });
        let handle =
            SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![gate])));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "a".into() }).unwrap();

        entered_rx.recv().await.unwrap(); // run one is inside the tool, still in flight

        // Answered now, not after the run: `ask` returns before we release.
        let reply = tokio::time::timeout(
            Duration::from_secs(5),
            handle.ask(Request::SideAsk { text: "why?".into() }),
        )
        .await
        .expect("the side ask must not wait for the run")
        .unwrap();
        assert!(
            matches!(&reply, AgentEvent::SideAnswer { text, .. } if text == "aside"),
            "{reply:?}"
        );

        release.notify_one();
        wait_for_end(&mut rx).await;
    }

    #[tokio::test]
    async fn get_history_is_answered_mid_run_from_the_snapshot() {
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::ToolCall {
                id: "c1".into(),
                name: "gate".into(),
                arguments: json!({ "text": "hi" }),
            },
            LlmStreamEvent::Done {
                stop_reason: StopReason::ToolUse,
                usage: None,
            },
        ]);
        rec.push(vec![
            LlmStreamEvent::TextDelta("done".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);

        let (entered_tx, mut entered_rx) = mpsc::unbounded_channel::<()>();
        let release = Arc::new(tokio::sync::Notify::new());
        let gate = erased(GateTool {
            entered: entered_tx,
            release: release.clone(),
        });
        let handle =
            SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![gate])));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "a".into() }).unwrap();

        entered_rx.recv().await.unwrap();

        let reply = tokio::time::timeout(Duration::from_secs(5), handle.ask(Request::GetHistory))
            .await
            .expect("history must not wait for the run")
            .unwrap();
        let AgentEvent::History { messages } = reply else {
            panic!("expected History, got {reply:?}");
        };
        assert!(
            messages.iter().any(|m| m.as_text() == "a"),
            "the mid-run snapshot carries the submit: {messages:?}"
        );

        release.notify_one();
        wait_for_end(&mut rx).await;
    }

    #[tokio::test]
    async fn a_deferred_command_is_acked_before_the_run_ends() {
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::ToolCall {
                id: "c1".into(),
                name: "gate".into(),
                arguments: json!({ "text": "hi" }),
            },
            LlmStreamEvent::Done {
                stop_reason: StopReason::ToolUse,
                usage: None,
            },
        ]);
        for text in ["turn two", "run two"] {
            rec.push(vec![
                LlmStreamEvent::TextDelta(text.into()),
                LlmStreamEvent::Done {
                    stop_reason: StopReason::Stop,
                    usage: None,
                },
            ]);
        }

        let (entered_tx, mut entered_rx) = mpsc::unbounded_channel::<()>();
        let release = Arc::new(tokio::sync::Notify::new());
        let gate = erased(GateTool {
            entered: entered_tx,
            release: release.clone(),
        });
        let handle =
            SessionActor::spawn(Agent::new(agent_config(fake_stream_fn(&rec), vec![gate])));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "a".into() }).unwrap();

        entered_rx.recv().await.unwrap();

        // Acked now (mid-run), not left to time out; applied at the run boundary.
        let reply = tokio::time::timeout(
            Duration::from_secs(5),
            handle.ask(Request::SetModel { model: "m2".into() }),
        )
        .await
        .expect("a deferred command must be acked, not hang")
        .unwrap();
        assert!(matches!(reply, AgentEvent::Ack), "{reply:?}");

        release.notify_one();
        wait_for_end(&mut rx).await; // run one ends on m1

        handle.send(Request::Submit { text: "b".into() }).unwrap();
        wait_for_end(&mut rx).await; // run two
        assert_eq!(
            rec.models(),
            ["m1", "m1", "m2"],
            "the swap applied after the run, not before"
        );
    }

    #[tokio::test]
    async fn ask_status_is_answered_mid_run_from_the_snapshot() {
        // A lean `Status` (no transcript): the member's last assistant text,
        // answered while a run is in flight from the turn-boundary snapshot.
        let rec = Recorder::default();
        rec.push(vec![
            LlmStreamEvent::ToolCall {
                id: "c1".into(),
                name: "gate".into(),
                arguments: json!({ "text": "hi" }),
            },
            LlmStreamEvent::Done {
                stop_reason: StopReason::ToolUse,
                usage: None,
            },
        ]);
        rec.push(vec![
            LlmStreamEvent::TextDelta("done".into()),
            LlmStreamEvent::Done {
                stop_reason: StopReason::Stop,
                usage: None,
            },
        ]);

        let (entered_tx, mut entered_rx) = mpsc::unbounded_channel::<()>();
        let release = Arc::new(tokio::sync::Notify::new());
        let gate = erased(GateTool {
            entered: entered_tx,
            release: release.clone(),
        });
        // Seed an assistant so the mid-run snapshot has a "last work".
        let mut cfg = agent_config(fake_stream_fn(&rec), vec![gate]);
        cfg.context = vec![AgentMessage::Assistant {
            content: vec![crate::message::ContentBlock::Text {
                text: "seeded work".into(),
            }],
            stop_reason: StopReason::Stop,
            usage: None,
            model: None,
        }];
        let handle = SessionActor::spawn(Agent::new(cfg));
        let mut rx = handle.subscribe();
        handle.send(Request::Submit { text: "a".into() }).unwrap();

        entered_rx.recv().await.unwrap(); // run is inside the tool

        let reply = tokio::time::timeout(Duration::from_secs(5), handle.ask(Request::Status))
            .await
            .expect("status must not wait for the run")
            .unwrap();
        let AgentEvent::Status { last_assistant_text } = reply else {
            panic!("expected Status, got {reply:?}");
        };
        assert_eq!(last_assistant_text.as_deref(), Some("seeded work"));

        release.notify_one();
        wait_for_end(&mut rx).await;
    }
}