magi-cli 0.278.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
//! Chat turns over `omp --mode rpc`.
//!
//! A chat turn whose agent is `kind = "omp"` keeps one RPC process for the
//! whole turn 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`;
//! - the turn ends only when the session is settled - no run, no queued input,
//!   no background job left - so work the agent started in the background
//!   finishes inside the turn.
//!
//! 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;

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 a turn was running.
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).
    pub steer: bool,
    /// Commit the durable draft only after omp admits the prompt.
    pub accepted: Option<AdmissionCallback>,
}

/// Turn-scoped connection between a chat turn 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.
    pub input: Box<dyn Fn() -> Result<Option<Input>> + Send + Sync>,
    stopped: AtomicBool,
}

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

    /// Did the operator stop this turn?
    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,
    /// 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)
}

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

impl LiveGuard<'_> {
    fn check_stop(&self, settled: bool) -> 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 {
            self.hooks.stopped.store(true, Ordering::SeqCst);
            let _ = std::fs::remove_file(&self.hooks.stop);
        }
        if settled || requested {
            let _ = std::fs::remove_file(&self.hooks.live);
        }
        Ok(requested)
    }
}

impl Drop for LiveGuard<'_> {
    fn drop(&mut self) {
        let _ = self.check_stop(true);
    }
}

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,
    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;
    }
}

/// Drive one chat turn: send `prompt`, deliver input the hooks hand over,
/// honour a stop request, and return once every prompt has finished and the
/// session is settled. 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,
) -> Result<Ended>
where
    W: AsyncWrite + Unpin,
    R: AsyncRead + Unpin,
{
    let hooks = hooks.as_deref();
    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::default(),
        current: String::new(),
        last: String::new(),
        // 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 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 {
        // A stopped turn ends as soon as its prompts answered: closing stdin
        // disposes the session, which cancels whatever was still running.
        let finishing = outstanding.is_empty() && (settled || ended.stopped);
        if let Some(guard) = &guard
            && !ended.stopped
            && (finishing || guard.hooks.stop.exists())
            && guard.check_stop(finishing)?
        {
            ended.stopped = true;
            driver.live.stopping = true;
            driver.send(json!({"id": "abort", "type": "abort"})).await?;
        }
        if finishing {
            break;
        }
        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());
                            }
                        } 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);
                        if frame.get("status").and_then(Value::as_str) == 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);
                    }
                    "session_settled" => settled = true,
                    "message_start" => {
                        if frame.pointer("/message/role").and_then(Value::as_str) == Some("assistant") {
                            driver.current.clear();
                        }
                    }
                    "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();
                        }
                    }
                    "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 !text.trim().is_empty() {
                                driver.last = text;
                            }
                            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 {
                    if !ended.stopped && admission.is_none() {
                        match (hooks.input)() {
                            Ok(Some(input)) => {
                                sent += 1;
                                let id = format!("p{sent}");
                                let behavior = if input.steer { "steer" } else { "followUp" };
                                driver
                                    .send(json!({
                                        "id": id, "type": "prompt", "message": input.text,
                                        "streamingBehavior": behavior,
                                    }))
                                    .await?;
                                admission = Some((id.clone(), input.accepted));
                                outstanding.push(id);
                                settled = false;
                                driver.live.steered = sent;
                                driver.dirty = true;
                            }
                            Ok(None) => {}
                            Err(error) => tracing::warn!("chat input for the running turn: {error:#}"),
                        }
                    }
                }
                if !ended.stopped {
                    driver.publish(hooks);
                }
            }
        }
    }
    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};

    /// 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 || Ok(queued.lock().unwrap().pop())),
        ))
    }

    #[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.check_stop(true).unwrap());
        assert!(hooks.stopped());
        assert!(!request_stop(&hooks.live, &hooks.stop).unwrap());
    }

    #[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 driven = tokio::spawn(drive(w, r, "x".into(), None, 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;
        server.finish(None).await;
        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"));
    }
}