magi-cli 0.281.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
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
//! Chat over `omp --mode rpc`.
//!
//! A chat turn whose agent is `kind = "omp"` keeps one RPC process instead of
//! a single `omp -p` call. That gives the web Chat what the operator gets in
//! their own terminal:
//!
//! - the reply streams: the driver publishes the in-progress text and the tool
//!   it is running to [`Hooks::live`], which `GET /api/talks/{id}/live` serves;
//! - a message sent while the agent works is delivered into the running
//!   session (`prompt` with `streamingBehavior: "steer"`), not parked for the
//!   next turn;
//! - the operator can stop the agent: the stop file makes the driver send
//!   `abort`;
//! - with [`Resident`] hooks the process outlives the turn: every answer is
//!   published as the agent yields, the next message is prompted into the same
//!   process, and an answer the agent gives on its own (a background job
//!   finished) reaches the chat too. The driver leaves after an idle period.
//!   Without them, the turn ends once the session is settled.
//!
//! The wire is omp's JSONL RPC protocol (`omp://rpc.md`), protocol version 1.
//! Every frame the answer extraction in `agent` reads (`message_end`,
//! `turn_end`, `agent_end`, `tool_execution_start`) is appended to the seat's
//! stdout log, behind a synthesized `{"type":"session"}` line from
//! `get_state`, so the stored `<stem>.out` reads exactly like an `omp -p
//! --mode=json` stream.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};

use crate::agent::Captured;

/// How often queued input, the stop file and the live snapshot are checked.
const TICK: Duration = Duration::from_millis(500);

/// Longest tool summary shown in the live snapshot.
const ACTIVITY_CHARS: usize = 160;

/// Commit the durable draft after RPC prompt admission.
pub type AdmissionCallback = Box<dyn FnOnce() -> Result<()> + Send>;

/// Input that arrived while the session was open.
pub struct Input {
    /// The prompt text for the agent.
    pub text: String,
    /// Steer the running agent (operator input) rather than queue it after the
    /// current run (automatic notices). Ignored while the session is idle.
    pub steer: bool,
    /// Commit the durable draft only after omp admits the prompt.
    pub accepted: Option<AdmissionCallback>,
}

/// What a poll for queued input found.
pub enum Poll {
    /// Nothing to deliver now.
    Nothing,
    /// Deliver this input.
    Input(Input),
    /// The conversation changed under the session (closed, deleted, another
    /// agent or persona): leave as soon as it is idle.
    Exit,
}

/// Receives each finished answer of a resident session, in order, as the
/// agent yields, with the context size the last model call reported.
pub type Publish = Box<dyn Fn(&str, Option<u64>, &crate::agent::SeatState) + Send + Sync>;

/// Keep the session open after it settles.
pub struct Resident {
    /// See [`Publish`].
    pub publish: Publish,
    /// Leave after the session has been idle this long.
    pub idle_exit: Duration,
    /// Take no new work once the session is this old; leave when idle.
    pub max_age: Duration,
}

/// Connection between a chat and its RPC driver.
pub struct Hooks {
    /// Where the in-progress reply is published.
    pub live: PathBuf,
    /// A file whose appearance asks the driver to abort the agent.
    pub stop: PathBuf,
    /// Takes input queued since the last call; called on every tick with
    /// whether the session is idle (no prompt owed and settled).
    pub input: Box<dyn Fn(bool) -> Result<Poll> + Send + Sync>,
    /// Outlive the turn; `None` ends it once the session is settled.
    pub resident: Option<Resident>,
    stopped: AtomicBool,
}

impl Hooks {
    /// Hooks publishing to `live`, watching `stop`, and pulling `input`.
    pub fn new(
        live: PathBuf,
        stop: PathBuf,
        input: Box<dyn Fn(bool) -> Result<Poll> + Send + Sync>,
    ) -> Self {
        Self {
            live,
            stop,
            input,
            resident: None,
            stopped: AtomicBool::new(false),
        }
    }

    /// Keep the session after it settles.
    pub fn resident(mut self, resident: Resident) -> Self {
        self.resident = Some(resident);
        self
    }

    /// Did the operator stop running work?
    pub fn stopped(&self) -> bool {
        self.stopped.load(Ordering::SeqCst)
    }
}

tokio::task_local! {
    static HOOKS: Arc<Hooks>;
}

/// Run `fut` with `hooks` available to the omp RPC driver it spawns.
pub async fn with_hooks<F: Future>(hooks: Arc<Hooks>, fut: F) -> F::Output {
    HOOKS.scope(hooks, fut).await
}

/// The hooks of the chat turn this task belongs to, if any.
pub(crate) fn current() -> Option<Arc<Hooks>> {
    HOOKS.try_with(Arc::clone).ok()
}

/// The in-progress reply, as the web Chat shows it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Live {
    /// Identifies this RPC invocation, including across fallback attempts.
    #[serde(default)]
    pub turn: String,
    /// The assistant text streamed so far (the latest message with text).
    pub text: String,
    /// The tool currently running, summarized.
    pub activity: Option<String>,
    /// The operator asked to stop and the abort was sent.
    pub stopping: bool,
    /// Messages delivered into the running session.
    pub steered: u32,
    /// The agent is working: a prompt is owed or the session is not settled.
    #[serde(default)]
    pub busy: bool,
    /// The process stays after the turn ([`Resident`]).
    #[serde(default)]
    pub resident: bool,
    /// When this snapshot was written.
    pub at: Option<Timestamp>,
}

/// Read a live snapshot; `None` when absent or unreadable.
pub fn read_live(path: &Path) -> Option<Live> {
    serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}

fn stop_lock(stop: &Path) -> Result<std::fs::File> {
    let file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(stop.with_extension("lock"))?;
    crate::pr_head::lock_file(&file)?;
    Ok(file)
}

/// Accept a stop only while the identified driver is taking commands.
pub fn request_stop(live: &Path, stop: &Path) -> Result<bool> {
    let Some(snapshot) = read_live(live) else {
        return Ok(false);
    };
    let _lock = stop_lock(stop)?;
    if !read_live(live).is_some_and(|current| current.turn == snapshot.turn) {
        return Ok(false);
    }
    std::fs::write(stop, snapshot.turn.as_bytes())?;
    Ok(true)
}

/// Ask the identified idle session to relinquish its lease without aborting
/// work that might start before it sees the request.
pub(crate) fn request_leave(live: &Path, stop: &Path) -> Result<bool> {
    let Some(snapshot) = read_live(live).filter(|live| live.resident && !live.busy) else {
        return Ok(false);
    };
    let _lock = stop_lock(stop)?;
    if !read_live(live).is_some_and(|current| current.turn == snapshot.turn) {
        return Ok(false);
    }
    std::fs::write(stop.with_extension("leave"), snapshot.turn.as_bytes())?;
    Ok(true)
}

struct LiveGuard<'a> {
    hooks: &'a Hooks,
    turn: String,
}

impl LiveGuard<'_> {
    /// Consume a stop request addressed to this driver.
    fn take_stop(&self) -> Result<bool> {
        let _lock = stop_lock(&self.hooks.stop)?;
        let requested = std::fs::read_to_string(&self.hooks.stop).is_ok_and(|id| id == self.turn);
        if requested {
            let _ = std::fs::remove_file(&self.hooks.stop);
        }
        Ok(requested)
    }

    fn take_leave(&self) -> Result<bool> {
        let path = self.hooks.stop.with_extension("leave");
        if !path.exists() {
            return Ok(false);
        }
        let _lock = stop_lock(&self.hooks.stop)?;
        let requested = std::fs::read_to_string(&path).is_ok_and(|id| id == self.turn);
        if requested {
            let _ = std::fs::remove_file(path);
        }
        Ok(requested)
    }

    /// Withdraw the snapshot under the stop fence, so no stop is accepted
    /// once the driver stopped taking commands.
    fn retire(&self) {
        let lock = stop_lock(&self.hooks.stop);
        if std::fs::read_to_string(&self.hooks.stop).is_ok_and(|id| id == self.turn) {
            let _ = std::fs::remove_file(&self.hooks.stop);
        }
        let leave = self.hooks.stop.with_extension("leave");
        if std::fs::read_to_string(&leave).is_ok_and(|id| id == self.turn) {
            let _ = std::fs::remove_file(leave);
        }
        let _ = std::fs::remove_file(&self.hooks.live);
        drop(lock);
    }
}

impl Drop for LiveGuard<'_> {
    fn drop(&mut self) {
        self.retire();
    }
}

fn write_live(path: &Path, live: &Live) {
    let Ok(body) = serde_json::to_vec(live) else {
        return;
    };
    let tmp = path.with_extension("json.tmp");
    if std::fs::write(&tmp, body).is_ok() && std::fs::rename(&tmp, path).is_err() {
        // A reader may hold the old snapshot open on Windows; the next tick
        // writes again.
        let _ = std::fs::remove_file(&tmp);
    }
}

/// A prompt omp finished with an error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PromptError {
    pub message: String,
    pub http_status: Option<u64>,
    pub code: Option<String>,
}

/// How a driven turn ended.
#[derive(Debug, Default)]
pub(crate) struct Ended {
    /// The last error any prompt of the turn reported.
    pub error: Option<PromptError>,
    /// Error notices omp sent outside any prompt.
    pub notices: Vec<String>,
    /// The operator stopped the turn.
    pub stopped: bool,
    /// The final text of each answer the agent gave in this turn, in order;
    /// more than one when input was steered into the running session.
    pub answers: Vec<String>,
}

fn push_answer(answers: &mut Vec<String>, text: &str) {
    let text = text.trim();
    if !text.is_empty() && answers.last().is_none_or(|last| last != text) {
        answers.push(text.to_owned());
    }
}

/// How long to keep reading omp's stdout after closing its stdin.
const EXIT_DRAIN: Duration = Duration::from_secs(15);

fn summarize(tool: &str, args: &Value) -> String {
    let detail = ["i", "command", "path", "pattern", "query", "url", "task"]
        .iter()
        .find_map(|key| args.get(key).and_then(Value::as_str))
        .map(|s| s.split_whitespace().collect::<Vec<_>>().join(" "));
    let mut out = match detail {
        Some(detail) if !detail.is_empty() => format!("{tool}: {detail}"),
        _ => tool.to_owned(),
    };
    if out.chars().count() > ACTIVITY_CHARS {
        out = out.chars().take(ACTIVITY_CHARS).collect::<String>() + "…";
    }
    out
}

fn prompt_error(value: &Value) -> PromptError {
    match value {
        Value::String(message) => PromptError {
            message: message.clone(),
            http_status: None,
            code: None,
        },
        _ => PromptError {
            message: value
                .get("message")
                .and_then(Value::as_str)
                .unwrap_or("omp reported an error")
                .to_owned(),
            http_status: value.get("httpStatus").and_then(Value::as_u64),
            code: value.get("code").and_then(Value::as_str).map(str::to_owned),
        },
    }
}

struct Driver<W> {
    writer: W,
    log: Captured,
    live: Live,
    /// Text of the assistant message streaming now.
    current: String,
    /// Text of the last assistant message that had any.
    last: String,
    /// Assistant messages with text seen so far, and how many of them were
    /// already handed to [`Resident::publish`].
    seen: u64,
    published: u64,
    /// Input-side context the last assistant message reported.
    context: Option<u64>,
    session: Option<String>,
    dirty: bool,
}

impl<W: AsyncWrite + Unpin> Driver<W> {
    async fn send(&mut self, frame: Value) -> Result<()> {
        let mut line = serde_json::to_vec(&frame)?;
        line.push(b'\n');
        self.writer
            .write_all(&line)
            .await
            .context("write to omp rpc")?;
        self.writer.flush().await.context("flush omp rpc")
    }

    fn record(&self, line: &str) {
        if let Ok(mut log) = self.log.lock() {
            log.extend_from_slice(line.as_bytes());
            log.push(b'\n');
        }
    }

    fn refresh(&mut self) {
        let text = if self.current.trim().is_empty() {
            &self.last
        } else {
            &self.current
        };
        if self.live.text != *text {
            self.live.text.clone_from(text);
            self.dirty = true;
        }
    }

    fn publish(&mut self, hooks: Option<&Hooks>) {
        if !self.dirty {
            return;
        }
        if let Some(hooks) = hooks {
            self.live.at = Some(Timestamp::now());
            write_live(&hooks.live, &self.live);
        }
        self.dirty = false;
    }

    /// Mark the session working or idle. Idle clears the streamed text: it
    /// is in the transcript by then.
    fn set_busy(&mut self, busy: bool) {
        if self.live.busy != busy {
            self.live.busy = busy;
            if !busy {
                self.live.text.clear();
                self.live.activity = None;
            }
            self.dirty = true;
        }
    }

    /// The last answer and the context the session had reached, once, if
    /// the agent gave a new answer since the last call.
    fn take_answer(&mut self) -> Option<(String, Option<u64>)> {
        let text = self.last.trim();
        (self.seen > self.published && !text.is_empty()).then(|| {
            self.published = self.seen;
            (text.to_owned(), self.context)
        })
    }
}

/// The agent yielded (a prompt answered, or the session settled on its own):
/// hand a resident chat the new answer. The idle snapshot goes out first, so
/// a reader that sees the reply in the transcript never sees a busy session.
fn deliver<W: AsyncWrite + Unpin>(
    driver: &mut Driver<W>,
    hooks: Option<&Hooks>,
    resident: Option<&Resident>,
    idle: bool,
    checkpoint: &impl Fn(Option<String>) -> Result<crate::agent::SeatState>,
) -> Result<()> {
    let Some(resident) = resident else {
        return Ok(());
    };
    let Some((text, context)) = driver.take_answer() else {
        return Ok(());
    };
    if idle {
        driver.set_busy(false);
        driver.publish(hooks);
    }
    let seat = checkpoint(driver.session.clone())?;
    (resident.publish)(&text, context, &seat);
    Ok(())
}

/// Drive a chat session: send `prompt`, deliver input the hooks hand over,
/// honour a stop request, and return once every prompt has finished and the
/// session is settled - or, for a [`Resident`] session, once it has been idle
/// long enough or was asked to leave. Dropping `writer` on return closes omp's
/// stdin, which ends the process.
pub(crate) async fn drive<W, R>(
    writer: W,
    reader: R,
    prompt: String,
    hooks: Option<Arc<Hooks>>,
    log: Captured,
    checkpoint: impl Fn(Option<String>) -> Result<crate::agent::SeatState>,
) -> Result<Ended>
where
    W: AsyncWrite + Unpin,
    R: AsyncRead + Unpin,
{
    let hooks = hooks.as_deref();
    let resident = hooks.and_then(|hooks| hooks.resident.as_ref());
    let mut lines = BufReader::new(reader).lines();
    loop {
        let line = lines
            .next_line()
            .await
            .context("read omp rpc")?
            .context("omp exited before it was ready")?;
        if serde_json::from_str::<Value>(&line)
            .is_ok_and(|frame| frame.get("type").and_then(Value::as_str) == Some("ready"))
        {
            break;
        }
    }

    let mut driver = Driver {
        writer,
        log,
        live: Live {
            busy: true,
            resident: resident.is_some(),
            ..Live::default()
        },
        current: String::new(),
        last: String::new(),
        seen: 0,
        published: 0,
        context: None,
        session: None,
        // Publish at once: the snapshot's presence tells the web a stop can
        // still be honoured.
        dirty: true,
    };
    driver
        .send(json!({"id": "filter", "type": "set_event_filter", "events": null, "messageUpdates": "delta"}))
        .await?;
    driver
        .send(json!({"id": "state", "type": "get_state"}))
        .await?;
    driver
        .send(json!({"id": "p0", "type": "prompt", "message": prompt}))
        .await?;

    let guard = hooks.map(|hooks| LiveGuard {
        hooks,
        turn: format!("{}-{}", std::process::id(), Timestamp::now()),
    });
    if let Some(guard) = &guard {
        let _lock = stop_lock(&guard.hooks.stop)?;
        driver.live.turn.clone_from(&guard.turn);
        driver.publish(hooks);
    }
    let started = Instant::now();
    let mut idle_since: Option<Instant> = None;
    let mut leaving = false;
    let mut admission: Option<(String, Option<AdmissionCallback>)> = None;
    let mut outstanding = vec!["p0".to_owned()];
    let mut settled = false;
    let mut sent = 0u32;
    let mut ended = Ended::default();
    let mut tick = tokio::time::interval(TICK);
    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    loop {
        let idle = outstanding.is_empty() && settled;
        if idle {
            idle_since.get_or_insert_with(Instant::now);
        } else {
            idle_since = None;
        }
        driver.set_busy(!idle);
        if !leaving
            && let Some(guard) = &guard
            && guard.take_leave()?
        {
            leaving = true;
        }
        // A stopped turn ends as soon as its prompts answered: closing stdin
        // disposes the session, which cancels whatever was still running.
        let done = if ended.stopped {
            outstanding.is_empty()
        } else {
            match resident {
                Some(resident) => {
                    idle && (leaving
                        || ended.error.is_some()
                        || idle_since.is_some_and(|since| since.elapsed() >= resident.idle_exit)
                        || started.elapsed() >= resident.max_age)
                }
                None => idle,
            }
        };
        if done {
            break;
        }
        if let Some(guard) = &guard
            && !ended.stopped
            && guard.hooks.stop.exists()
            && guard.take_stop()?
        {
            if idle {
                // Nothing is running: a stop only ends the residency.
                leaving = true;
            } else {
                guard.hooks.stopped.store(true, Ordering::SeqCst);
                ended.stopped = true;
                driver.live.stopping = true;
                driver.dirty = true;
                driver.send(json!({"id": "abort", "type": "abort"})).await?;
            }
            continue;
        }
        tokio::select! {
            line = lines.next_line() => {
                let Some(line) = line.context("read omp rpc")? else {
                    bail!("omp exited before the turn finished");
                };
                let Ok(frame) = serde_json::from_str::<Value>(&line) else {
                    continue;
                };
                match frame.get("type").and_then(Value::as_str).unwrap_or_default() {
                    "response" => {
                        let id = frame.get("id").and_then(Value::as_str).unwrap_or_default();
                        let ok = frame.get("success").and_then(Value::as_bool).unwrap_or(false);
                        if admission.as_ref().is_some_and(|(pending, _)| pending == id) {
                            let (_, accepted) = admission.take().expect("matching admission");
                            if ok && let Some(accepted) = accepted {
                                accepted()?;
                            }
                        }
                        if id == "state" {
                            if let Some(session) = frame
                                .pointer("/data/sessionId")
                                .and_then(Value::as_str)
                            {
                                driver.record(&json!({"type": "session", "id": session}).to_string());
                                driver.session = Some(session.to_owned());
                            }
                        } else if !ok && outstanding.iter().any(|p| p == id) {
                            // Refused before admission: no prompt_result follows.
                            outstanding.retain(|p| p != id);
                            ended.error = Some(prompt_error(
                                frame.get("error").unwrap_or(&Value::Null),
                            ));
                        }
                    }
                    "prompt_result" => {
                        let id = frame.get("id").and_then(Value::as_str).unwrap_or_default();
                        if admission.as_ref().is_some_and(|(pending, _)| pending == id) {
                            let (_, accepted) = admission.take().expect("matching admission");
                            if let Some(accepted) = accepted {
                                accepted()?;
                            }
                        }
                        outstanding.retain(|p| p != id);
                        let status = frame.get("status").and_then(Value::as_str);
                        if status == Some("error") {
                            ended.error = Some(prompt_error(
                                frame.get("error").unwrap_or(&Value::Null),
                            ));
                        }
                        settled = frame
                            .get("sessionSettled")
                            .and_then(Value::as_bool)
                            .unwrap_or(false);
                        // Each prompt the agent answered: a steered turn
                        // replies to every message, not only the last one.
                        push_answer(&mut ended.answers, &driver.last);
                        if status != Some("aborted") && !ended.stopped {
                            let idle = outstanding.is_empty() && settled;
                            deliver(&mut driver, hooks, resident, idle, &checkpoint)?;
                        }
                    }
                    "session_settled" => {
                        settled = true;
                        if !ended.stopped {
                            // An answer the agent gave on its own, after a
                            // background job woke it, settles here.
                            push_answer(&mut ended.answers, &driver.last);
                            let idle = outstanding.is_empty();
                            deliver(&mut driver, hooks, resident, idle, &checkpoint)?;
                        }
                    }
                    "message_start" => {
                        if frame.pointer("/message/role").and_then(Value::as_str) == Some("assistant") {
                            driver.current.clear();
                            driver.set_busy(true);
                        }
                    }
                    "message_update" => {
                        let event = frame.get("assistantMessageEvent");
                        if event.and_then(|e| e.get("type")).and_then(Value::as_str) == Some("text_delta")
                            && let Some(delta) = event.and_then(|e| e.get("delta")).and_then(Value::as_str)
                        {
                            driver.current.push_str(delta);
                            driver.refresh();
                        }
                    }
                    "agent_start" => {
                        // The agent woke without a prompt (a background job
                        // delivered its result): the session is busy again.
                        settled = false;
                    }
                    "message_end" | "turn_end" | "agent_end" => {
                        if frame.get("type").and_then(Value::as_str) == Some("message_end")
                            && frame.pointer("/message/role").and_then(Value::as_str) == Some("assistant")
                        {
                            let text: String = frame
                                .pointer("/message/content")
                                .and_then(Value::as_array)
                                .into_iter()
                                .flatten()
                                .filter(|part| part.get("type").and_then(Value::as_str) == Some("text"))
                                .filter_map(|part| part.get("text").and_then(Value::as_str))
                                .collect();
                            if let Some(context) =
                                frame.get("message").and_then(crate::agent::omp_message_context)
                            {
                                driver.context = Some(context);
                            }
                            if !text.trim().is_empty() {
                                driver.last = text;
                                driver.seen += 1;
                            }
                            driver.current.clear();
                            driver.refresh();
                        }
                        driver.record(&line);
                    }
                    "tool_execution_start" => {
                        let tool = frame.get("toolName").and_then(Value::as_str).unwrap_or("tool");
                        driver.live.activity =
                            Some(summarize(tool, frame.get("args").unwrap_or(&Value::Null)));
                        driver.dirty = true;
                        driver.record(&line);
                    }
                    "tool_execution_end" => {
                        driver.live.activity = None;
                        driver.dirty = true;
                    }
                    "notice" => {
                        if let Some(notice) = error_notice(&line) {
                            ended.notices.push(notice);
                        }
                    }
                    _ => {}
                }
            }
            _ = tick.tick() => {
                if let Some(hooks) = hooks
                    && !ended.stopped
                    && !leaving
                    && ended.error.is_none()
                    && resident.is_none_or(|resident| started.elapsed() < resident.max_age)
                    && admission.is_none()
                {
                    match (hooks.input)(idle) {
                        Ok(Poll::Input(input)) => {
                            sent += 1;
                            let id = format!("p{sent}");
                            let mut frame = json!({"id": id, "type": "prompt", "message": input.text});
                            if !idle {
                                frame["streamingBehavior"] =
                                    json!(if input.steer { "steer" } else { "followUp" });
                            }
                            driver.send(frame).await?;
                            admission = Some((id.clone(), input.accepted));
                            outstanding.push(id);
                            settled = false;
                            driver.set_busy(true);
                            driver.live.steered = sent;
                            driver.dirty = true;
                        }
                        Ok(Poll::Exit) => leaving = true,
                        Ok(_) => {}
                        Err(error) => tracing::warn!("chat input for the running session: {error:#}"),
                    }
                }
                if !ended.stopped {
                    driver.publish(hooks);
                }
            }
        }
    }
    // Earlier answers are already in the transcript. Hand over any new
    // completed assistant text from an aborted prompt before the stop note.
    if ended.stopped && driver.published > 0 {
        deliver(&mut driver, hooks, resident, false, &checkpoint)?;
    }
    drop(guard);
    push_answer(&mut ended.answers, &driver.last);
    // omp keeps writing after the turn (UI updates, shutdown notices) and
    // exits 1 when its stdout breaks, so close stdin and read to EOF.
    let Driver { writer, .. } = driver;
    drop(writer);
    let drained = tokio::time::timeout(EXIT_DRAIN, async {
        while let Ok(Some(line)) = lines.next_line().await {
            if let Some(notice) = error_notice(&line) {
                ended.notices.push(notice);
            }
        }
    })
    .await;
    if drained.is_err() {
        tracing::warn!("omp kept its stdout open after the turn ended");
    }
    Ok(ended)
}

/// An error `notice` frame's message: omp reports persistence and restore
/// failures that way, outside any prompt.
fn error_notice(line: &str) -> Option<String> {
    let frame: Value = serde_json::from_str(line).ok()?;
    (frame.get("type").and_then(Value::as_str) == Some("notice")
        && frame.get("level").and_then(Value::as_str) == Some("error"))
    .then(|| {
        frame
            .get("message")
            .and_then(Value::as_str)
            .unwrap_or("omp reported an error")
            .to_owned()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, duplex};

    async fn drive(
        writer: DuplexStream,
        reader: DuplexStream,
        prompt: String,
        hooks: Option<Arc<Hooks>>,
        log: Captured,
    ) -> Result<Ended> {
        super::drive(writer, reader, prompt, hooks, log, |session| {
            let mut seat = crate::agent::SeatState::new("chat", "test", 0);
            seat.captured_session = session;
            seat.turns = 1;
            Ok(seat)
        })
        .await
    }

    /// The test plays omp: reads the driver's commands, answers with frames.
    /// One pipe per direction, like a child's stdin and stdout, so the driver
    /// closing its stdin is visible while its stdout stays readable.
    struct Server {
        lines: tokio::io::Lines<BufReader<DuplexStream>>,
        out: DuplexStream,
    }

    impl Server {
        async fn emit(&mut self, frame: Value) {
            let mut line = frame.to_string().into_bytes();
            line.push(b'\n');
            self.out.write_all(&line).await.unwrap();
        }

        async fn command(&mut self) -> Value {
            let line = self.lines.next_line().await.unwrap().expect("a command");
            serde_json::from_str(&line).unwrap()
        }

        async fn handshake(&mut self) {
            self.emit(json!({"type": "ready", "protocolVersion": 1}))
                .await;
            assert_eq!(self.command().await["type"], "set_event_filter");
            assert_eq!(self.command().await["type"], "get_state");
            self.emit(json!({"type": "response", "id": "state", "command": "get_state", "success": true, "data": {"sessionId": "s-1"}})).await;
        }

        async fn answer(&mut self, text: &str) {
            self.emit(
                json!({"type": "message_start", "message": {"role": "assistant", "content": []}}),
            )
            .await;
            self.emit(json!({"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "delta": text}})).await;
            self.emit(json!({"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": text}]}})).await;
        }
    }

    fn pair() -> (Server, DuplexStream, DuplexStream) {
        let (stdin_driver, stdin_server) = duplex(1 << 16);
        let (stdout_server, stdout_driver) = duplex(1 << 16);
        (
            Server {
                lines: BufReader::new(stdin_server).lines(),
                out: stdout_server,
            },
            stdin_driver,
            stdout_driver,
        )
    }

    impl Server {
        /// Wait for the driver to close stdin, then write more output the
        /// way omp does at shutdown, which must still be read, and exit.
        async fn finish(mut self, notice: Option<&str>) {
            assert!(
                self.lines.next_line().await.unwrap().is_none(),
                "stdin closed"
            );
            self.emit(json!({"type": "extension_ui_request", "method": "setWidget"}))
                .await;
            if let Some(message) = notice {
                self.emit(json!({"type": "notice", "level": "error", "message": message}))
                    .await;
            }
        }
    }

    fn hooks(dir: &Path, queued: Arc<Mutex<Vec<Input>>>) -> Arc<Hooks> {
        Arc::new(Hooks::new(
            dir.join("live.json"),
            dir.join("stop"),
            Box::new(move |_idle| {
                Ok(queued
                    .lock()
                    .unwrap()
                    .pop()
                    .map_or(Poll::Nothing, Poll::Input))
            }),
        ))
    }

    #[tokio::test]
    async fn waits_for_settle_and_logs_an_extractable_stream() {
        let (mut server, w, r) = pair();
        let log: Captured = Arc::default();
        let driven = tokio::spawn(drive(w, r, "hello".into(), None, Arc::clone(&log)));
        server.handshake().await;
        let prompt = server.command().await;
        assert_eq!(prompt["message"], "hello");
        server.answer("working on it").await;
        // The agent yielded but a background job is still running.
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": false})).await;
        server.answer("all done").await;
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(
            !driven.is_finished(),
            "an unsettled session keeps the turn open"
        );
        server.emit(json!({"type": "session_settled"})).await;
        // omp keeps writing after the turn; a reader that went away would
        // break its stdout and make it exit 1.
        server.finish(Some("session file could not be saved")).await;
        let ended = driven.await.unwrap().unwrap();
        assert!(ended.error.is_none() && !ended.stopped);
        assert_eq!(ended.notices, ["session file could not be saved"]);
        assert_eq!(ended.answers, ["working on it", "all done"]);
        let stdout = String::from_utf8(log.lock().unwrap().clone()).unwrap();
        assert!(stdout.contains(r#""type":"session""#) && stdout.contains("s-1"));
        assert_eq!(
            crate::agent::answer_text(crate::config::AgentKind::Omp, &stdout),
            "all done"
        );
    }

    #[tokio::test]
    async fn steers_queued_input_and_publishes_the_live_reply() {
        let dir = tempfile::tempdir().unwrap();
        let queued = Arc::new(Mutex::new(Vec::new()));
        let hooks = hooks(dir.path(), Arc::clone(&queued));
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(
            w,
            r,
            "first".into(),
            Some(Arc::clone(&hooks)),
            Arc::default(),
        ));
        server.handshake().await;
        server.command().await;
        server
            .emit(json!({"type": "message_start", "message": {"role": "assistant", "content": []}}))
            .await;
        server.emit(json!({"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "delta": "partial"}})).await;
        server.emit(json!({"type": "tool_execution_start", "toolName": "bash", "args": {"command": "cargo   test"}})).await;
        let admitted = Arc::new(AtomicBool::new(false));
        let acknowledged = Arc::clone(&admitted);
        queued.lock().unwrap().push(Input {
            text: "also check docs".into(),
            steer: true,
            accepted: Some(Box::new(move || {
                acknowledged.store(true, Ordering::SeqCst);
                Ok(())
            })),
        });
        let steer = server.command().await;
        assert_eq!(steer["message"], "also check docs");
        assert_eq!(steer["streamingBehavior"], "steer");
        tokio::time::sleep(TICK * 2).await;
        let live = read_live(&dir.path().join("live.json")).expect("a live snapshot");
        assert_eq!(live.text, "partial");
        assert_eq!(live.activity.as_deref(), Some("bash: cargo test"));
        assert_eq!(live.steered, 1);
        assert!(!admitted.load(Ordering::SeqCst));
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": false})).await;
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(
            !driven.is_finished(),
            "the steered prompt is still owed an answer"
        );
        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "completed", "sessionSettled": true})).await;
        server.finish(None).await;
        driven.await.unwrap().unwrap();
        assert!(admitted.load(Ordering::SeqCst));
        assert!(
            !dir.path().join("live.json").exists(),
            "no stop can be honoured once the commands ended"
        );
    }

    #[test]
    fn stop_admission_and_settlement_share_a_fence() {
        let dir = tempfile::tempdir().unwrap();
        let hooks = hooks(dir.path(), Arc::default());
        let guard = LiveGuard {
            hooks: &hooks,
            turn: "first".into(),
        };
        write_live(
            &hooks.live,
            &Live {
                turn: guard.turn.clone(),
                ..Live::default()
            },
        );
        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
        assert!(guard.take_stop().unwrap());
        guard.retire();
        assert!(
            !request_stop(&hooks.live, &hooks.stop).unwrap(),
            "a retired driver accepts no stop"
        );
    }

    fn resident_hooks(
        dir: &Path,
        queued: Arc<Mutex<Vec<Poll>>>,
        published: Arc<Mutex<Vec<String>>>,
        idle_exit: Duration,
    ) -> Arc<Hooks> {
        Arc::new(
            Hooks::new(
                dir.join("live.json"),
                dir.join("stop"),
                Box::new(move |_idle| Ok(queued.lock().unwrap().pop().unwrap_or(Poll::Nothing))),
            )
            .resident(Resident {
                publish: Box::new(move |text, _, seat| {
                    assert_eq!(seat.captured_session.as_deref(), Some("s-1"));
                    published.lock().unwrap().push(text.to_owned());
                }),
                idle_exit,
                max_age: Duration::from_secs(3600),
            }),
        )
    }

    async fn until(mut done: impl FnMut() -> bool) {
        let deadline = Instant::now() + Duration::from_secs(10);
        while !done() {
            assert!(Instant::now() < deadline, "condition never held");
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    #[tokio::test]
    async fn a_resident_session_answers_each_message_and_its_own_wakeups() {
        let dir = tempfile::tempdir().unwrap();
        let queued = Arc::new(Mutex::new(Vec::new()));
        let published = Arc::new(Mutex::new(Vec::new()));
        let hooks = resident_hooks(
            dir.path(),
            Arc::clone(&queued),
            Arc::clone(&published),
            Duration::from_secs(3600),
        );
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(
            w,
            r,
            "first".into(),
            Some(Arc::clone(&hooks)),
            Arc::default(),
        ));
        server.handshake().await;
        server.command().await;
        server.answer("first answer").await;
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
        until(|| published.lock().unwrap().len() == 1).await;
        let live = read_live(&hooks.live).expect("a resident session keeps its snapshot");
        assert!(live.resident && !live.busy && live.text.is_empty());
        assert!(!driven.is_finished(), "a settled resident session stays");

        // The next message is a fresh prompt into the same process.
        queued.lock().unwrap().push(Poll::Input(Input {
            text: "second".into(),
            steer: true,
            accepted: None,
        }));
        let next = server.command().await;
        assert_eq!(next["message"], "second");
        assert!(
            next.get("streamingBehavior").is_none(),
            "idle input starts a run"
        );
        server.answer("second answer").await;
        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "completed", "sessionSettled": true})).await;

        // A background job wakes the agent without any prompt.
        server.emit(json!({"type": "agent_start"})).await;
        server.answer("the build finished").await;
        server.emit(json!({"type": "session_settled"})).await;
        until(|| published.lock().unwrap().len() == 3).await;
        assert_eq!(
            *published.lock().unwrap(),
            ["first answer", "second answer", "the build finished"]
        );

        // A stop while nothing runs only ends the residency.
        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
        server.finish(None).await;
        let ended = driven.await.unwrap().unwrap();
        assert!(!ended.stopped && !hooks.stopped());
        assert!(!hooks.live.exists());
    }

    #[tokio::test]
    async fn a_resident_session_leaves_when_idle_or_asked() {
        let dir = tempfile::tempdir().unwrap();
        let published = Arc::new(Mutex::new(Vec::new()));
        let hooks = resident_hooks(
            dir.path(),
            Arc::default(),
            Arc::clone(&published),
            Duration::from_millis(200),
        );
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
        server.handshake().await;
        server.command().await;
        server.answer("done").await;
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
        server.finish(None).await;
        driven.await.unwrap().unwrap();
        assert_eq!(*published.lock().unwrap(), ["done"]);

        let queued = Arc::new(Mutex::new(vec![Poll::Exit]));
        let hooks = resident_hooks(
            dir.path(),
            queued,
            Arc::default(),
            Duration::from_secs(3600),
        );
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
        server.handshake().await;
        server.command().await;
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
        server.finish(None).await;
        driven.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn resident_leave_releases_the_session_without_a_stop() {
        let dir = tempfile::tempdir().unwrap();
        let published = Arc::new(Mutex::new(Vec::new()));
        let hooks = resident_hooks(
            dir.path(),
            Arc::default(),
            Arc::clone(&published),
            Duration::from_secs(3600),
        );
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(
            w,
            r,
            "x".into(),
            Some(Arc::clone(&hooks)),
            Arc::default(),
        ));
        server.handshake().await;
        server.command().await;
        assert!(!request_leave(&hooks.live, &hooks.stop).unwrap());
        server.answer("done").await;
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
        until(|| published.lock().unwrap().len() == 1).await;
        assert!(request_leave(&hooks.live, &hooks.stop).unwrap());
        tokio::time::timeout(Duration::from_secs(5), server.finish(None))
            .await
            .unwrap();
        assert!(!driven.await.unwrap().unwrap().stopped);
        assert!(!hooks.live.exists());
        assert!(!hooks.stop.with_extension("leave").exists());
    }

    #[tokio::test]
    async fn expired_resident_does_not_poll_busy_input() {
        let dir = tempfile::tempdir().unwrap();
        let polled = Arc::new(AtomicBool::new(false));
        let observed = Arc::clone(&polled);
        let hooks = Arc::new(
            Hooks::new(
                dir.path().join("live.json"),
                dir.path().join("stop"),
                Box::new(move |_| {
                    observed.store(true, Ordering::SeqCst);
                    Ok(Poll::Input(Input {
                        text: "next".into(),
                        steer: true,
                        accepted: None,
                    }))
                }),
            )
            .resident(Resident {
                publish: Box::new(|_, _, _| {}),
                idle_exit: Duration::from_secs(3600),
                max_age: Duration::ZERO,
            }),
        );
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
        server.handshake().await;
        server.command().await;
        tokio::time::sleep(TICK * 2).await;
        assert!(!polled.load(Ordering::SeqCst));
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
        server.finish(None).await;
        driven.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn a_resident_answer_carries_the_context_it_reached() {
        let dir = tempfile::tempdir().unwrap();
        let got = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&got);
        let hooks = Arc::new(
            Hooks::new(
                dir.path().join("live.json"),
                dir.path().join("stop"),
                Box::new(|_| Ok(Poll::Nothing)),
            )
            .resident(Resident {
                publish: Box::new(move |text, context, _| {
                    sink.lock().unwrap().push((text.to_owned(), context));
                }),
                idle_exit: Duration::ZERO,
                max_age: Duration::from_secs(3600),
            }),
        );
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
        server.handshake().await;
        server.command().await;
        server.emit(json!({"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "answer"}], "usage": {"input": 1200, "cacheRead": 800}}})).await;
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
        server.finish(None).await;
        driven.await.unwrap().unwrap();
        assert_eq!(*got.lock().unwrap(), [("answer".to_owned(), Some(2000))]);
    }

    #[tokio::test]
    async fn resident_stop_keeps_only_the_new_answer() {
        let dir = tempfile::tempdir().unwrap();
        let queued = Arc::new(Mutex::new(Vec::new()));
        let published = Arc::new(Mutex::new(Vec::new()));
        let hooks = resident_hooks(
            dir.path(),
            Arc::clone(&queued),
            Arc::clone(&published),
            Duration::from_secs(3600),
        );
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(
            w,
            r,
            "x".into(),
            Some(Arc::clone(&hooks)),
            Arc::default(),
        ));
        server.handshake().await;
        server.command().await;
        server.answer("first answer").await;
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
        until(|| published.lock().unwrap().len() == 1).await;
        queued.lock().unwrap().push(Poll::Input(Input {
            text: "second".into(),
            steer: true,
            accepted: None,
        }));
        assert_eq!(server.command().await["id"], "p1");
        server.answer("second answer").await;
        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
        assert_eq!(server.command().await["type"], "abort");
        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "aborted", "sessionSettled": false})).await;
        server.finish(None).await;
        assert!(driven.await.unwrap().unwrap().stopped);
        assert_eq!(
            *published.lock().unwrap(),
            ["first answer", "second answer"]
        );
    }

    #[tokio::test]
    async fn resident_error_after_an_answer_preserves_the_error() {
        let dir = tempfile::tempdir().unwrap();
        let queued = Arc::new(Mutex::new(Vec::new()));
        let published = Arc::new(Mutex::new(Vec::new()));
        let hooks = resident_hooks(
            dir.path(),
            Arc::clone(&queued),
            Arc::clone(&published),
            Duration::from_secs(3600),
        );
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
        server.handshake().await;
        server.command().await;
        server.answer("first answer").await;
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
        until(|| published.lock().unwrap().len() == 1).await;
        queued.lock().unwrap().push(Poll::Input(Input {
            text: "second".into(),
            steer: true,
            accepted: None,
        }));
        assert_eq!(server.command().await["id"], "p1");
        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "error", "sessionSettled": true, "error": "second failed"})).await;
        server.finish(None).await;
        let ended = driven.await.unwrap().unwrap();
        assert_eq!(ended.error.unwrap().message, "second failed");
        assert_eq!(*published.lock().unwrap(), ["first answer"]);
    }

    #[tokio::test]
    async fn a_stop_request_aborts_and_ends_without_waiting_for_background_work() {
        let dir = tempfile::tempdir().unwrap();
        let hooks = hooks(dir.path(), Arc::default());
        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(
            w,
            r,
            "long job".into(),
            Some(Arc::clone(&hooks)),
            Arc::default(),
        ));
        server.handshake().await;
        server.command().await;
        while !hooks.live.exists() {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
        assert_eq!(server.command().await["type"], "abort");
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "aborted", "sessionSettled": false})).await;
        server.finish(None).await;
        let ended = driven.await.unwrap().unwrap();
        assert!(ended.stopped && hooks.stopped());
        assert!(!hooks.stop.exists(), "the request is consumed");
    }

    #[tokio::test]
    async fn reports_prompt_errors_and_early_exit() {
        let (mut server, w, r) = pair();
        let dir = tempfile::tempdir().unwrap();
        let hooks = resident_hooks(
            dir.path(),
            Arc::default(),
            Arc::default(),
            Duration::from_secs(3600),
        );
        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
        server.handshake().await;
        server.command().await;
        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "error", "sessionSettled": true,
            "error": {"message": "rate limited", "httpStatus": 429, "retryable": true}})).await;
        tokio::time::timeout(Duration::from_secs(5), server.finish(None))
            .await
            .expect("a failed resident session exits promptly");
        let ended = driven.await.unwrap().unwrap();
        let error = ended.error.unwrap();
        assert_eq!(
            (error.message.as_str(), error.http_status),
            ("rate limited", Some(429))
        );

        let (mut server, w, r) = pair();
        let driven = tokio::spawn(drive(w, r, "x".into(), None, Arc::default()));
        server.handshake().await;
        server.command().await;
        drop(server);
        let error = driven.await.unwrap().unwrap_err();
        assert!(format!("{error:#}").contains("exited before the turn finished"));
    }
}