bohay 0.8.3

Next-Gen Agents multiplexer
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
//! Agent detection (M3, docs/07). Two questions, two very different answers.
//!
//! **Which agent is this?** The pane's running processes (docs/07 §2.1), passed
//! in as `running`. An agent is a program, so this is ground truth; a pane that
//! merely *prints* "claude" is a shell. Where processes can't be seen (Windows,
//! a remote pane) it falls back to text, ranked by how deliberate that text is —
//! spawn command, then OSC title, then output — with names that double as
//! ordinary words (`amp`, `cursor`, `droid`, `grok`) believed only from the
//! first two. Identity is configurable: see `[identity]` in the manifests.
//!
//! **What state is it in?** Inferred from what's on screen via a small
//! **manifest** engine: a set of rules, each tied to a screen region (the OSC
//! title or the recent bottom text), a priority, and one or more conditions
//! (substrings / a spinner glyph). The highest-priority matching rule wins. Built-in rules cover the
//! markers common to modern agent CLIs plus a few per-agent quirks; **users can
//! add or override rules** by dropping `*.toml` files in `~/.bohay/manifests/`
//! (loaded at startup, merged by priority) so detection can be fixed or extended
//! for any agent without recompiling.
//!
//! A recognised agent is *working* only when a rule proves it (a spinner, an
//! interrupt hint) — raw output never counts, so a launching CLI's welcome
//! screen or a scrolling log can't fake the state. Plain shells (no markers to
//! match) fall back to output activity, gated by whether the user typed
//! recently, so keystroke echo at a prompt is never misread as work. bohay's
//! status debounce (docs/07, `QUIET_DWELL`) supplies stability: a momentary
//! non-match can't flip a working agent to idle.

use std::path::Path;

use serde::Deserialize;

use crate::ui::theme::State;

/// One agent bohay can recognise, and how far each identifying string may be
/// trusted. Splitting the two matters because the haystack for `screen` is
/// *whatever the pane happens to be printing*, which nobody controls.
struct KnownAgent {
    /// Canonical name: what the UI shows and `agent.list` returns.
    name: &'static str,
    /// Strings distinctive enough to believe anywhere, pane output included.
    distinct: &'static [&'static str],
    /// Strings that are also ordinary words. Believed only where a human or the
    /// agent itself put them deliberately — the spawned command and the OSC
    /// title — never from incidental output. Without this, `error: cursor is out
    /// of bounds` names the pane cursor, and "for example" named it amp.
    ambiguous: &'static [&'static str],
}

/// Agents we recognise. `distinct`/`ambiguous` are matched as whole words (see
/// [`contains_agent_word`]); the canonical `name` is what gets reported.
const KNOWN_AGENTS: &[KnownAgent] = &[
    KnownAgent {
        name: "claude",
        distinct: &["claude"],
        ambiguous: &[],
    },
    KnownAgent {
        name: "codex",
        distinct: &["codex"],
        ambiguous: &[],
    },
    KnownAgent {
        name: "gemini",
        distinct: &["gemini"],
        ambiguous: &[],
    },
    KnownAgent {
        name: "aider",
        distinct: &["aider"],
        ambiguous: &[],
    },
    KnownAgent {
        name: "opencode",
        distinct: &["opencode"],
        ambiguous: &[],
    },
    KnownAgent {
        name: "copilot",
        distinct: &["copilot"],
        ambiguous: &[],
    },
    KnownAgent {
        name: "kimi",
        distinct: &["kimi"],
        ambiguous: &[],
    },
    KnownAgent {
        name: "qwen",
        distinct: &["qwen"],
        ambiguous: &[],
    },
    KnownAgent {
        name: "kiro",
        distinct: &["kiro"],
        ambiguous: &[],
    },
    // The CLI binary is distinctive even though the brand name is not.
    KnownAgent {
        name: "cursor",
        distinct: &["cursor-agent"],
        ambiguous: &["cursor"],
    },
    KnownAgent {
        name: "amp",
        distinct: &[],
        ambiguous: &["amp"],
    },
    KnownAgent {
        name: "droid",
        distinct: &[],
        ambiguous: &["droid"],
    },
    KnownAgent {
        name: "grok",
        distinct: &[],
        ambiguous: &["grok"],
    },
];

/// The runtime form of [`KnownAgent`]: owned, so `~/.bohay/manifests/*.toml` can
/// refine a built-in agent or teach bohay one it has never heard of.
#[derive(Clone)]
struct AgentIdent {
    name: String,
    distinct: Vec<String>,
    ambiguous: Vec<String>,
}

impl AgentIdent {
    /// Every identifying string, deliberate placement assumed.
    fn all(&self) -> impl Iterator<Item = &String> {
        self.distinct.iter().chain(self.ambiguous.iter())
    }
}

/// The built-in registry, in runtime form.
fn builtin_agents() -> Vec<AgentIdent> {
    KNOWN_AGENTS
        .iter()
        .map(|a| AgentIdent {
            name: a.name.to_string(),
            distinct: a.distinct.iter().map(|s| s.to_string()).collect(),
            ambiguous: a.ambiguous.iter().map(|s| s.to_string()).collect(),
        })
        .collect()
}

// ── markers (matched case-insensitively) ─────────────────────────────────────

/// Confirmation / permission prompts that mean the agent is waiting on the user.
const BLOCKED_PROMPTS: &[&str] = &[
    "do you want to proceed",
    "do you want to continue",
    "waiting for approval",
    "waiting for user confirmation",
    "waiting for confirmation",
    "run this command?",
    "allow command?",
    "allow this command",
    "allow editing file",
    "allow creating file",
    "allow execution",
    "apply this change",
    "confirm tool call",
    "invoke tool",
    "write to this file?",
    "proceed (y)",
    "run (once) (y)",
    "skip (esc or n)",
    "esc or n or p",
    "reject & propose changes",
    "press enter to confirm",
    "enter to submit answer",
    "yes, allow",
    "no, cancel",
    "allow all for this session",
    "allow all for every session",
    "deny with feedback",
    "keep (n)",
    "(y) (enter)",
    "yes (y)",
    "(y/n)",
    "[y/n]",
    "yes/no",
    "❯ 1.",
    "1. yes",
    "press enter to continue",
];

/// OSC-title strings that flag a confirmation (e.g. codex, amp).
const BLOCKED_TITLES: &[&str] = &["action required", "confirmation needed"];

/// Interrupt hints an agent shows only while generating.
const WORKING_HINTS: &[&str] = &[
    "esc to interrupt",
    "esc to cancel",
    "esc to stop",
    "esc interrupt",
    "esc again to cancel",
    "ctrl+c to stop",
    "ctrl+c to interrupt",
    "ctrl-c to interrupt",
    "interrupt to stop",
];

// ── engine ───────────────────────────────────────────────────────────────────

/// The part of the screen a rule looks at.
#[derive(Clone, Copy, PartialEq)]
enum Region {
    /// The OSC window title the agent sets.
    Title,
    /// The recent bottom text of the pane.
    Screen,
}

/// One condition on a region's (lowercased) text. All strings are stored
/// lowercase.
enum Cond {
    /// The region contains at least one of these substrings.
    Any(Vec<String>),
    /// The region contains all of these substrings.
    All(Vec<String>),
    /// The region contains none of these substrings.
    Not(Vec<String>),
    /// A line in the region starts with a spinner glyph — a braille cell
    /// (U+2800..=U+28FF, what most CLIs animate) or a moon phase (U+1F311..=
    /// U+1F318, Kimi's background-agent spinner). A running spinner means work.
    Spinner,
}

impl Cond {
    fn holds(&self, low: &str) -> bool {
        match self {
            Cond::Any(subs) => subs.iter().any(|s| low.contains(s)),
            Cond::All(subs) => subs.iter().all(|s| low.contains(s)),
            Cond::Not(subs) => !subs.iter().any(|s| low.contains(s)),
            Cond::Spinner => low
                .lines()
                .any(|l| l.trim_start().chars().next().is_some_and(is_spinner_glyph)),
        }
    }
}

/// A spinner glyph: a braille cell (the common animated spinner) or a moon
/// phase (Kimi animates 🌑..🌘 for background agents).
fn is_spinner_glyph(c: char) -> bool {
    ('\u{2800}'..='\u{28FF}').contains(&c) || ('\u{1F311}'..='\u{1F318}').contains(&c)
}

/// A detection rule: `state` is chosen when every `cond` holds in `region`.
/// `agent` empty means it applies to every agent.
struct Rule {
    agent: String,
    state: State,
    priority: i32,
    region: Region,
    conds: Vec<Cond>,
}

/// The active detection set: which agents exist and how to recognise them
/// (`agents`), plus the state rules (`rules`). Both come from the built-ins
/// merged with `~/.bohay/manifests/*.toml`.
pub struct Manifests {
    rules: Vec<Rule>,
    agents: Vec<AgentIdent>,
}

impl Manifests {
    /// Just the compiled-in defaults (test helper; production uses `load`).
    #[cfg(test)]
    pub fn builtin() -> Manifests {
        Manifests {
            rules: builtin_rules(),
            agents: builtin_agents(),
        }
    }

    /// Built-in defaults plus every valid `*.toml` in `dir`. Malformed files are
    /// skipped (logged), never fatal, so a bad manifest can't break detection.
    pub fn load(dir: &Path) -> Manifests {
        let mut rules = builtin_rules();
        let mut agents = builtin_agents();
        for mf in load_dir(dir) {
            mf.apply_identity(&mut agents);
            rules.extend(mf.into_rules());
        }
        Manifests { rules, agents }
    }

    /// True if `name` is a recognised agent (not a plain shell). Drives whether
    /// a pane appears in the AGENTS list.
    pub fn is_agent(&self, name: &str) -> bool {
        let low = name.to_lowercase();
        self.agents.iter().any(|a| a.name == low)
    }

    fn evaluate(&self, agent: &str, regions: &Regions) -> Option<State> {
        let mut best: Option<(i32, State)> = None;
        for r in &self.rules {
            if !(r.agent.is_empty() || r.agent == agent) {
                continue;
            }
            let text = regions.get(r.region);
            if r.conds.iter().all(|c| c.holds(text)) && best.is_none_or(|(p, _)| r.priority > p) {
                best = Some((r.priority, r.state));
            }
        }
        best.map(|(_, s)| s)
    }
}

fn any(subs: &[&str]) -> Cond {
    Cond::Any(subs.iter().map(|s| s.to_lowercase()).collect())
}
fn all(subs: &[&str]) -> Cond {
    Cond::All(subs.iter().map(|s| s.to_lowercase()).collect())
}

/// The compiled-in default rules (generic first, then per-agent).
fn builtin_rules() -> Vec<Rule> {
    let gen = |state, priority, region, conds| Rule {
        agent: String::new(),
        state,
        priority,
        region,
        conds,
    };
    let per = |agent: &str, state, priority, region, conds| Rule {
        agent: agent.to_string(),
        state,
        priority,
        region,
        conds,
    };
    vec![
        // Generic: title confirmation, selection menus, permission prompts.
        gen(
            State::Blocked,
            330,
            Region::Title,
            vec![any(BLOCKED_TITLES)],
        ),
        gen(
            State::Blocked,
            320,
            Region::Screen,
            vec![all(&["enter to select", "esc to cancel"])],
        ),
        gen(
            State::Blocked,
            320,
            Region::Screen,
            vec![all(&["enter to confirm", "esc to cancel"])],
        ),
        gen(
            State::Blocked,
            320,
            Region::Screen,
            vec![all(&["enter select", "esc cancel"])],
        ),
        gen(
            State::Blocked,
            300,
            Region::Screen,
            vec![any(BLOCKED_PROMPTS)],
        ),
        // Generic: spinner, then bare interrupt hint.
        gen(State::Working, 120, Region::Title, vec![Cond::Spinner]),
        gen(State::Working, 110, Region::Screen, vec![Cond::Spinner]),
        gen(
            State::Working,
            100,
            Region::Screen,
            vec![any(WORKING_HINTS)],
        ),
        // Per-agent quirks.
        per(
            "gemini",
            State::Blocked,
            310,
            Region::Screen,
            vec![any(&["│ apply this change", "│ allow execution"])],
        ),
        per(
            "droid",
            State::Blocked,
            310,
            Region::Screen,
            vec![any(&["> yes, allow", "> no, cancel"])],
        ),
        per(
            "cursor",
            State::Working,
            105,
            Region::Screen,
            vec![any(&["ctrl+c to stop"])],
        ),
        // Kimi's approval panel (permission prompt) shows the footer
        // "↑/↓ select · N choose · ↵ confirm" while it waits — a very specific
        // three-word combination, so it can't be mistaken for the spinner that
        // was on screen a moment earlier.
        per(
            "kimi",
            State::Blocked,
            310,
            Region::Screen,
            vec![all(&["select", "choose", "confirm"])],
        ),
    ]
}

// ── user manifests (TOML) ────────────────────────────────────────────────────

#[derive(Deserialize)]
struct ManifestFile {
    /// Which agent these rules apply to; `"generic"` (default) means all.
    #[serde(default = "default_generic")]
    agent: String,
    #[serde(default)]
    rule: Vec<RuleSpec>,
    /// How to *recognise* this agent (docs/07). Absent means "leave identity
    /// alone and only add state rules", which is what most manifests want.
    #[serde(default)]
    identity: Option<IdentitySpec>,
}

/// Identity patterns for one agent. Matched as whole words; see
/// [`contains_agent_word`] for why the two lists are not interchangeable.
#[derive(Deserialize)]
struct IdentitySpec {
    /// Distinctive enough to trust anywhere, pane output included.
    #[serde(default)]
    distinct: Vec<String>,
    /// Also an ordinary word, so trusted only in the spawned command or the
    /// agent's own OSC title.
    #[serde(default)]
    ambiguous: Vec<String>,
    /// Replace the built-in patterns instead of adding to them. Needed to
    /// *remove* a default, e.g. dropping `cursor` so only `cursor-agent` counts.
    #[serde(default)]
    replace: bool,
}

#[derive(Deserialize)]
struct RuleSpec {
    /// `working` | `blocked` | `idle`.
    state: String,
    #[serde(default)]
    priority: i32,
    /// `screen` (default) | `title`.
    #[serde(default = "default_screen")]
    region: String,
    /// The region must contain at least one of these.
    #[serde(default)]
    any: Vec<String>,
    /// The region must contain all of these.
    #[serde(default)]
    all: Vec<String>,
    /// The region must contain none of these.
    #[serde(default)]
    not: Vec<String>,
    /// The region must show a running spinner glyph.
    #[serde(default)]
    spinner: bool,
}

fn default_generic() -> String {
    "generic".to_string()
}
fn default_screen() -> String {
    "screen".to_string()
}

fn load_dir(dir: &Path) -> Vec<ManifestFile> {
    let mut out = Vec::new();
    let Ok(entries) = std::fs::read_dir(dir) else {
        return out;
    };
    // Sorted so a merge is deterministic across machines (read_dir order is not).
    let mut paths: Vec<_> = entries
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("toml"))
        .collect();
    paths.sort();
    for path in paths {
        let parsed = std::fs::read_to_string(&path)
            .ok()
            .and_then(|s| toml::from_str::<ManifestFile>(&s).ok());
        match parsed {
            Some(mf) => out.push(mf),
            None => eprintln!(
                "bohay: skipping invalid detection manifest {}",
                path.display()
            ),
        }
    }
    out
}

impl ManifestFile {
    /// Merge this file's `[identity]` into the live registry. A manifest may
    /// refine a built-in agent or introduce one bohay has never heard of, so
    /// detection can follow a new CLI without waiting for a release.
    fn apply_identity(&self, agents: &mut Vec<AgentIdent>) {
        let Some(id) = &self.identity else { return };
        if self.agent.eq_ignore_ascii_case("generic") {
            return; // identity is meaningless without an agent to attach it to
        }
        let name = self.agent.to_lowercase();
        let lc = |v: &Vec<String>| v.iter().map(|s| s.to_lowercase()).collect::<Vec<_>>();
        let entry = match agents.iter_mut().find(|a| a.name == name) {
            Some(e) => e,
            None => {
                // Start empty: seeding the name into `distinct` here would
                // silently outrank a manifest that deliberately declared that
                // same name `ambiguous`. The name-as-default is applied below,
                // and only when the manifest supplied no patterns at all.
                agents.push(AgentIdent {
                    name: name.clone(),
                    distinct: Vec::new(),
                    ambiguous: Vec::new(),
                });
                agents.last_mut().expect("just pushed")
            }
        };
        if id.replace {
            entry.distinct.clear();
            entry.ambiguous.clear();
        }
        entry.distinct.extend(lc(&id.distinct));
        entry.ambiguous.extend(lc(&id.ambiguous));
        entry.distinct.dedup();
        entry.ambiguous.dedup();
        // An agent with no pattern at all could never be matched, so fall back
        // to its own name rather than registering something inert.
        if entry.distinct.is_empty() && entry.ambiguous.is_empty() {
            entry.distinct.push(name);
        }
    }

    fn into_rules(self) -> Vec<Rule> {
        let agent = if self.agent.eq_ignore_ascii_case("generic") {
            String::new()
        } else {
            self.agent.to_lowercase()
        };
        self.rule
            .into_iter()
            .filter_map(|spec| spec.into_rule(&agent))
            .collect()
    }
}

impl RuleSpec {
    fn into_rule(self, agent: &str) -> Option<Rule> {
        let state = match self.state.to_lowercase().as_str() {
            "working" => State::Working,
            "blocked" => State::Blocked,
            "idle" => State::Idle,
            "done" => State::Done,
            _ => return None, // unknown state → skip this rule
        };
        let region = match self.region.to_lowercase().as_str() {
            "title" => Region::Title,
            "screen" => Region::Screen,
            _ => return None,
        };
        let lc = |v: Vec<String>| v.into_iter().map(|s| s.to_lowercase()).collect::<Vec<_>>();
        let mut conds = Vec::new();
        if !self.any.is_empty() {
            conds.push(Cond::Any(lc(self.any)));
        }
        if !self.all.is_empty() {
            conds.push(Cond::All(lc(self.all)));
        }
        if !self.not.is_empty() {
            conds.push(Cond::Not(lc(self.not)));
        }
        if self.spinner {
            conds.push(Cond::Spinner);
        }
        if conds.is_empty() {
            return None; // a rule with no condition would match everything → skip
        }
        Some(Rule {
            agent: agent.to_string(),
            state,
            priority: self.priority,
            region,
            conds,
        })
    }
}

// ── public API ──────────────────────────────────────────────────────────────

/// Result of classifying a pane.
pub struct Detection {
    pub state: State,
    pub agent: String,
}

/// The recent-screen and title regions, lowercased once for matching.
struct Regions {
    screen: String,
    title: String,
}

impl Regions {
    fn get(&self, r: Region) -> &str {
        match r {
            Region::Title => &self.title,
            Region::Screen => &self.screen,
        }
    }
}

/// Classify a pane from its title, bottom-buffer text, whether it produced
/// output recently, whether the user typed into it recently, and the active
/// rule set. `base_command` is the spawned program, used as a fallback label.
#[allow(clippy::too_many_arguments)]
pub fn classify(
    title: Option<&str>,
    bottom: &str,
    recent_activity: bool,
    recent_input: bool,
    base_command: &str,
    known_agent: &str,
    // `running`: command lines actually live in the pane (docs/07). Ground
    // truth when available; `&[]` means "could not tell" (Windows, remote, `ps`
    // failed), never "nothing is running".
    running: &[String],
    manifests: &Manifests,
) -> Detection {
    let regions = Regions {
        screen: bottom.to_lowercase(),
        title: title.map(|t| t.to_lowercase()).unwrap_or_default(),
    };
    // Identity has two regimes, and which one applies is decided by whether we
    // could see the pane's processes at all.
    //
    // `running` non-empty means the scan worked, so it is the *whole* answer: an
    // agent is a program, and a pane that is not running one is a plain shell no
    // matter what it prints. Letting text vote here is what put "amp" and "kiro"
    // in the sidebar for panes running neither.
    //
    // `running` empty means we could not tell (Windows, a remote pane, `ps`
    // failed, or the pane has no child yet). Only then do the text heuristics
    // run — including `known_agent` stickiness, which covers the frames where an
    // agent's UI does not print its own name (Claude Code's bottom rows are a
    // prompt box and a model label, so a repaint would otherwise resolve to the
    // bare shell and read its own redraw as work).
    let agent = if running.is_empty() {
        manifests
            .detect_agent(title, &regions.screen, base_command)
            .or_else(|| {
                manifests
                    .is_agent(known_agent)
                    .then(|| known_agent.to_string())
            })
            .unwrap_or_else(|| base_command.to_string())
    } else {
        manifests
            .agent_in_processes(running)
            .unwrap_or_else(|| base_command.to_string())
    };

    // A recognised agent is *working* only on positive evidence — a spinner or
    // an on-screen generating hint matched by a rule. Its output alone proves
    // nothing: a launching CLI prints a whole welcome screen while completely
    // idle, so no rule match means Idle. Plain shells have no markers to match,
    // so they keep the activity fallback (which powers `wait` on ordinary
    // commands), gated so typing echo isn't misread as output.
    let fallback = if !manifests.is_agent(&agent) && recent_activity && !recent_input {
        State::Working
    } else {
        State::Idle
    };
    let state = manifests.evaluate(&agent, &regions).unwrap_or(fallback);

    Detection { state, agent }
}

/// Name the agent running in a pane, in decreasing order of how deliberate the
/// evidence is: the command the pane was spawned with, then the OSC title the
/// agent sets for itself, then — for distinctive names only — its output.
impl Manifests {
    /// Name the agent from the pane's **running processes** -- the only signal
    /// that is ground truth rather than inference. An agent is a program, not a
    /// word on a screen, so this outranks every text heuristic: a pane merely
    /// *printing* "claude" is not running claude.
    ///
    /// Both pattern classes apply, because a command line is as deliberate as
    /// it gets. Matching is per-argv-token against the bare binary name, so
    /// `/opt/homebrew/bin/amp` counts while `--example` never can.
    fn agent_in_processes(&self, running: &[String]) -> Option<String> {
        for cmd in running {
            let low = cmd.to_lowercase();
            let mut tokens = low.split_whitespace();
            let Some(first) = tokens.next() else { continue };
            let first = binary_name(first);
            if let Some(a) = self.match_binary(first) {
                return Some(a);
            }
            // Several agents ship as a script run by an interpreter, so argv[0]
            // is `node` / `python` and the real name is the script slot: the
            // first non-flag argument. Nothing later counts -- `cargo test
            // --example amp` must not resolve to amp.
            if is_interpreter(first) {
                for t in tokens {
                    if t.starts_with('-') {
                        continue;
                    }
                    return self.match_binary(binary_name(t));
                }
            }
        }
        None
    }

    /// The agent whose patterns name exactly this binary.
    fn match_binary(&self, base: &str) -> Option<String> {
        self.agents
            .iter()
            .find(|a| a.all().any(|p| p == base))
            .map(|a| a.name.clone())
    }

    /// Name the agent running in a pane, in decreasing order of how deliberate
    /// the evidence is: the command the pane was spawned with, then the OSC
    /// title the agent sets for itself, then -- for distinctive names only --
    /// its output.
    fn detect_agent(
        &self,
        title: Option<&str>,
        low_bottom: &str,
        base_command: &str,
    ) -> Option<String> {
        let cmd = base_command.to_lowercase();
        let title = title.map(|t| t.to_lowercase()).unwrap_or_default();

        // Deliberate signals: somebody typed this, or the agent published it.
        for region in [&cmd, &title] {
            if let Some(a) = self
                .agents
                .iter()
                .find(|a| a.all().any(|p| contains_agent_word(region, p)))
            {
                return Some(a.name.clone());
            }
        }
        // Incidental signal: pane output. Only names that can't be ordinary words.
        self.agents
            .iter()
            .find(|a| {
                a.distinct
                    .iter()
                    .any(|p| contains_agent_word(low_bottom, p))
            })
            .map(|a| a.name.clone())
    }
}

/// The bare binary name of an argv token: no directory, no `.exe`, and no
/// leading `-` (login shells appear as `-zsh`).
fn binary_name(token: &str) -> &str {
    token
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(token)
        .trim_start_matches('-')
        .trim_end_matches(".exe")
}

/// Runtimes that execute an agent as a script, so the name to look for is the
/// argument rather than argv[0].
fn is_interpreter(base: &str) -> bool {
    matches!(
        base,
        "node"
            | "nodejs"
            | "bun"
            | "deno"
            | "npx"
            | "pnpm"
            | "yarn"
            | "python"
            | "python3"
            | "py"
            | "uv"
            | "uvx"
            | "ruby"
            | "perl"
            | "env"
            | "sh"
            | "bash"
            | "zsh"
            | "fish"
    )
}

/// True when `needle` appears in `hay` as a **standalone word**.
///
/// A plain substring test is not good enough here: the haystack is whatever the
/// pane happens to be showing, and short agent names hide inside ordinary words
/// — `amp` alone is a substring of *example*, *sample*, *stamped*, *champion*
/// and *implementation*, so a Claude pane printing "for example" renamed itself
/// to the amp agent. Path separators are excluded from the boundary set too, or
/// listing `~/.kiro` names the pane kiro. `-` and `_` still count as boundaries
/// so `claude-code` and `claude_code` keep matching.
fn contains_agent_word(hay: &str, needle: &str) -> bool {
    let boundary = |c: Option<char>| match c {
        None => true,
        Some(c) => !c.is_alphanumeric() && !matches!(c, '.' | '/' | '\\'),
    };
    hay.match_indices(needle).any(|(i, _)| {
        boundary(hay[..i].chars().next_back()) && boundary(hay[i + needle.len()..].chars().next())
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn state(bottom: &str, activity: bool, input: bool) -> State {
        classify(
            Some("claude"),
            bottom,
            activity,
            input,
            "claude",
            "claude",
            &[],
            &Manifests::builtin(),
        )
        .state
    }

    #[test]
    fn permission_prompt_is_blocked() {
        assert_eq!(
            state("Do you want to proceed? (y/n)", true, false),
            State::Blocked
        );
        assert_eq!(
            state("Run this command? [y/n]", false, false),
            State::Blocked
        );
    }

    #[test]
    fn selection_menu_is_blocked_not_working() {
        let d = state(
            "Choose:\n1. Yes\n  Enter to select · Esc to cancel",
            true,
            false,
        );
        assert_eq!(d, State::Blocked);
    }

    #[test]
    fn spinner_is_working_even_while_typing() {
        assert_eq!(
            state("⠹ Thinking… (esc to interrupt)", true, true),
            State::Working
        );
    }

    #[test]
    fn interrupt_hint_is_working() {
        assert_eq!(
            state("· 1.2k tokens · esc to interrupt", true, false),
            State::Working
        );
    }

    #[test]
    fn typing_at_prompt_is_idle() {
        assert_eq!(state("> write me a function", true, true), State::Idle);
    }

    #[test]
    fn agent_output_without_a_marker_is_idle() {
        // A recognised agent is working only on positive evidence. Bare output
        // (no spinner, no interrupt hint) proves nothing — most visibly the
        // welcome screen a CLI prints on launch.
        assert_eq!(state("streaming plain text", true, false), State::Idle);
        assert_eq!(
            state(
                "✻ Welcome to Claude Code!\n\n  /help for help\n\n> ",
                true,
                false
            ),
            State::Idle,
            "a launching agent is idle, not working"
        );
    }

    #[test]
    fn shell_output_is_working_fallback() {
        // Plain shells keep the activity fallback (drives `wait` on commands).
        let d = classify(
            None,
            "compiling foo v0.1.0",
            true,
            false,
            "zsh",
            "",
            &[],
            &Manifests::builtin(),
        );
        assert_eq!(d.state, State::Working);
    }

    #[test]
    fn kimi_moon_spinner_is_working() {
        // Kimi animates a moon phase for background agents; a line starting with
        // one reads as working just like a braille spinner.
        let d = classify(
            Some("kimi"),
            "🌖 running task…",
            true,
            false,
            "kimi",
            "kimi",
            &[],
            &Manifests::builtin(),
        );
        assert_eq!(d.state, State::Working);
    }

    #[test]
    fn kimi_approval_panel_is_blocked() {
        // The approval footer outranks a lingering spinner reading.
        let d = classify(
            Some("kimi"),
            "Run this command?\n rm -rf build\n ↑/↓ select · 1/2 choose · ↵ confirm",
            true,
            false,
            "kimi",
            "kimi",
            &[],
            &Manifests::builtin(),
        );
        assert_eq!(d.state, State::Blocked);
    }

    // An agent's UI does not print its own name on every frame. Switching tabs or
    // clicking into the pane makes it repaint, and that repaint must not
    // re-classify a known agent as a plain shell.
    #[test]
    fn known_agent_stays_idle_when_its_name_is_off_screen() {
        let d = classify(
            None,                    // no OSC title
            "> \n  ? for shortcuts", // repaint: no agent name, no markers
            true,                    // the repaint produced output
            false,                   // and the user did not type
            "zsh",                   // launched through a shell
            "claude",                // but the pane is KNOWN to be claude
            &[],
            &Manifests::builtin(),
        );
        assert_eq!(
            d.state,
            State::Idle,
            "a repaint with no marker must not read as working"
        );
    }

    #[test]
    fn quiet_is_idle() {
        let d = classify(
            None,
            "$ ",
            false,
            false,
            "zsh",
            "",
            &[],
            &Manifests::builtin(),
        );
        assert_eq!(d.state, State::Idle);
        assert_eq!(d.agent, "zsh");
    }

    #[test]
    fn user_manifest_rule_overrides_by_priority() {
        // A user rule with a higher priority flips detection for its agent.
        let toml = r#"
            agent = "claude"
            [[rule]]
            state = "blocked"
            priority = 500
            region = "screen"
            any = ["my custom prompt"]
        "#;
        let mut m = Manifests::builtin();
        m.rules
            .extend(toml::from_str::<ManifestFile>(toml).unwrap().into_rules());
        let d = classify(
            Some("claude"),
            "here is my custom prompt >",
            true,
            false,
            "claude",
            "claude",
            &[],
            &m,
        );
        assert_eq!(d.state, State::Blocked, "user rule applies");
        // The same text for a different agent is unaffected (rule is claude-only).
        let d2 = classify(
            Some("codex"),
            "here is my custom prompt >",
            true,
            false,
            "codex",
            "codex",
            &[],
            &m,
        );
        assert_eq!(d2.state, State::Idle, "user rule is scoped to its agent");
    }

    /// A pane is named after the agent *running in it*, never after a word that
    /// happens to be on screen. `amp` is a substring of "example", "sample",
    /// "stamped" and "implementation", so a Claude pane printing ordinary prose
    /// renamed itself to the amp agent; listing `~/.kiro` renamed a shell to
    /// kiro. Both then propagated to the sidebar, the AGENTS list and the notch.
    #[test]
    fn ordinary_words_do_not_name_an_agent() {
        let m = Manifests::builtin();
        // `known` empty: the pane has no established agent identity yet, which
        // is exactly when a stray word could invent one.
        let named = |title: Option<&str>, screen: &str, base: &str| {
            classify(title, screen, true, false, base, "", &[], &m).agent
        };

        for prose in [
            "for example, run the build",
            "a sample config",
            "cargo test --example foo",
            "stamped output",
            "the implementation examples",
            "champion",
        ] {
            assert_eq!(
                named(Some("zsh"), prose, "zsh"),
                "zsh",
                "ordinary prose must not name an agent: {prose:?}"
            );
        }

        // Path fragments are not agents either.
        assert_eq!(
            named(Some("zsh"), ".kiro/settings/mcp.json\n", "zsh"),
            "zsh",
            "listing ~/.kiro must not turn a shell into the kiro agent"
        );

        // Names that are also ordinary words are believed only where they were
        // placed deliberately: the spawned command or the agent's own title.
        assert_eq!(
            named(Some("zsh"), "error: cursor is out of bounds\n", "zsh"),
            "zsh",
            "a compiler error must not name the pane cursor"
        );
        assert_eq!(
            named(Some("zsh"), "warning: unused variable `droid`\n", "zsh"),
            "zsh"
        );
        assert_eq!(
            named(Some("zsh"), "you have to grok it first\n", "zsh"),
            "zsh"
        );
        assert_eq!(named(Some("amp"), "", "zsh"), "amp", "title names it");
        assert_eq!(named(Some("zsh"), "", "droid"), "droid", "command names it");
        assert_eq!(
            named(Some("zsh"), "cursor-agent v1\n", "zsh"),
            "cursor",
            "the CLI binary is distinctive enough to trust from output"
        );

        // Distinctive names still resolve from output — bare and hyphenated.
        assert_eq!(named(Some("zsh"), "claude\n", "zsh"), "claude");
        assert_eq!(named(Some("zsh"), "claude-code v2\n", "zsh"), "claude");
    }

    /// Identity is configurable, not hardcoded: a manifest can tighten a
    /// built-in agent (drop the ambiguous `cursor`, keep `cursor-agent`) and can
    /// teach bohay an agent it has never heard of, so detection follows a new
    /// CLI without waiting for a release.
    #[test]
    fn user_manifest_can_refine_and_add_agent_identity() {
        let apply = |toml: &str, m: &mut Manifests| {
            toml::from_str::<ManifestFile>(toml)
                .unwrap()
                .apply_identity(&mut m.agents);
        };

        // Built-in: `cursor` is ambiguous, so the title still names it.
        let mut m = Manifests::builtin();
        let named = |m: &Manifests, title: Option<&str>, screen: &str, cmd: &str| {
            classify(title, screen, true, false, cmd, "", &[], m).agent
        };
        assert_eq!(named(&m, Some("cursor"), "", "zsh"), "cursor");

        // Tighten it: only the CLI binary counts now.
        apply(
            r#"
            agent = "cursor"
            [identity]
            distinct = ["cursor-agent"]
            replace = true
        "#,
            &mut m,
        );
        assert_eq!(
            named(&m, Some("cursor"), "", "zsh"),
            "zsh",
            "`replace` drops the built-in ambiguous pattern"
        );
        assert_eq!(named(&m, Some("cursor-agent"), "", "zsh"), "cursor");

        // Teach it an agent that does not exist in the built-in registry.
        let mut m2 = Manifests::builtin();
        assert!(!m2.is_agent("nimbus"));
        apply(
            r#"
            agent = "nimbus"
            [identity]
            distinct = ["nimbus-cli"]
            ambiguous = ["nimbus"]
        "#,
            &mut m2,
        );
        assert!(m2.is_agent("nimbus"), "the new agent is recognised");
        assert_eq!(
            named(&m2, Some("zsh"), "nimbus-cli v3 ready\n", "zsh"),
            "nimbus",
            "a distinct pattern is trusted from pane output"
        );
        assert_eq!(
            named(&m2, Some("zsh"), "the nimbus is a cloud\n", "zsh"),
            "zsh",
            "an ambiguous pattern is not trusted from pane output"
        );
    }

    /// Identity comes from the pane's processes, because an agent is a program
    /// and not a word on a screen. This is the signal that survives a pane
    /// printing prose about other agents — the failure that put "amp" and
    /// "kiro" in the sidebar for panes running neither.
    #[test]
    fn running_process_outranks_screen_text() {
        let m = Manifests::builtin();
        let named = |screen: &str, running: &[String]| {
            classify(Some("zsh"), screen, true, false, "zsh", "", running, &m).agent
        };
        let proc = |c: &str| vec![c.to_string()];

        // The screen is talking about other agents; the process is the truth.
        assert_eq!(
            named("see the claude docs\n", &proc("/opt/homebrew/bin/amp")),
            "amp",
            "a real amp process beats the word claude on screen"
        );
        assert_eq!(
            named(
                "installing opencode from npm\n",
                &proc("node /usr/local/bin/claude")
            ),
            "claude"
        );

        // A shell that merely mentions agents is still just a shell.
        assert_eq!(
            named("see the claude docs\n", &proc("-zsh")),
            "zsh",
            "no agent process means no agent, whatever the screen says"
        );
        assert_eq!(
            named("the copilot subscription page\n", &proc("-zsh")),
            "zsh"
        );
        assert_eq!(named("gemini is a constellation\n", &proc("-zsh")), "zsh");

        // Flags never count as the binary, and .exe is stripped.
        assert_eq!(named("", &proc("cargo test --example amp")), "zsh");
        assert_eq!(named("", &proc("C:\\tools\\droid.exe")), "droid");

        // No scan available (Windows / remote / `ps` failed) → text heuristics,
        // which must keep working rather than reporting "no agents at all".
        assert_eq!(named("claude\n", &[]), "claude");
    }
}