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
//! Agent lanes (#344): which terminal panes are running a coding agent,
//! which one, and whether it is working, waiting for the user, or idle.
//!
//! Claude Code, Codex CLI, aider and gemini-cli all run in a pane, so croft
//! is already where the agents live; everything in the agent-cockpit series
//! starts from knowing that. The foreground process of every pane is
//! already sampled for the name pill, so an agent is recognised from that
//! name against a small table — built in, extended by `agents.json` in the
//! config directory without a rebuild — and its status is judged from two
//! things the pane already has: how long since it last produced output, and
//! what its last screen rows say. An agent that stays in the foreground
//! never emits OSC 133 marks, which is why "waiting" cannot come from the
//! shell integration and has to be read off the screen.
use std::path::{Path, PathBuf};
use std::time::Duration;
use regex::Regex;
/// One recognised agent: the badge it wears, the process names that mean
/// it, and the prompt shapes that mean it is waiting on the user.
#[derive(Debug, Clone)]
pub struct AgentKind {
/// The badge text (`claude`).
pub name: String,
/// Foreground process names, matched case-insensitively against the
/// sampled name's basename.
pub process: Vec<String>,
/// Regexes a recent screen row matches when the agent is waiting for
/// input: a permission question, a `>` prompt, a Y/n.
pub prompt: Vec<Regex>,
/// The command line a new worktree lane starts this agent with (#348):
/// typed into the lane's fresh shell. The built-ins launch as their own
/// name; a row may set its own (`claude --model opus`). A NEW row
/// without one opens a plain shell, while a row that replaces a
/// built-in and OMITS it keeps the built-in's command (such rows
/// usually exist to fix a prompt pattern, not to unteach the launch);
/// a blank `launch` on such a row is the explicit way to unteach it.
pub launch: Option<String>,
}
/// What an agent in a pane is doing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentStatus {
/// Output is still flowing.
Working,
/// Quiet, and the last rows look like a prompt for the user.
Waiting,
/// Quiet, and nothing on screen asks for anything.
Idle,
}
impl AgentStatus {
/// The glyph the pane pill and the status chip show beside the name.
pub fn glyph(self) -> char {
match self {
AgentStatus::Working => '\u{25cf}', // ● output flowing
AgentStatus::Waiting => '\u{25d0}', // ◐ waiting on you
AgentStatus::Idle => '\u{25cb}', // ○ quiet
}
}
}
/// An agent seated in a pane, as the pane carries it between samples.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentLane {
pub name: String,
pub status: AgentStatus,
}
/// The transitions the rest of the cockpit consumes (#345, #358, #347).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentEvent {
/// An agent appeared in the pane.
Seated { pane: String, agent: String },
/// It went from quiet to producing output.
Working { pane: String, agent: String },
/// It stopped and its screen asks for the user: once per prompt.
Waiting { pane: String, agent: String },
/// It is no longer the pane's foreground process.
Gone { pane: String, agent: String },
}
/// No output for this long is "quiet"; a sample inside it is Working.
pub const QUIET_AFTER: Duration = Duration::from_secs(3);
/// The user-editable table beside the other config files.
pub fn agents_path() -> PathBuf {
crate::prefs::config_dir().join("agents.json")
}
/// Starter `agents.json`, seeded on first open. Rows here EXTEND the
/// built-in table; a row whose `name` matches a built-in replaces it.
pub const TEMPLATE: &str = r##"// croft agent lanes: which foreground processes are coding agents, and what
// their screen looks like when they are waiting for you (#344).
//
// Built in: claude, codex, aider, gemini. Add a row to teach croft another
// agent without a rebuild; a row named like a built-in replaces it.
// name: the badge shown on the pane pill
// process: foreground process names that mean this agent
// prompt: regexes a recent screen row matches when it is waiting on you
// launch: the command a new worktree lane (Cmd+K Shift+L) starts the agent
// with, when `lane_agent` in settings.json names this row (#348);
// the built-ins launch as their own name; a NEW row without one
// opens a plain shell, while a row replacing a built-in keeps the
// built-in's command unless it sets its own or a blank one
[
// { "name": "goose", "process": ["goose"], "prompt": ["^\\s*>\\s*$", "\\(y/n\\)"], "launch": "goose" }
]
"##;
/// One raw `agents.json` row.
#[derive(serde::Deserialize)]
struct AgentRow {
name: String,
#[serde(default)]
process: Vec<String>,
#[serde(default)]
prompt: Vec<String>,
#[serde(default)]
launch: Option<String>,
}
/// The table of agents croft recognises.
#[derive(Debug, Clone, Default)]
pub struct AgentTable {
kinds: Vec<AgentKind>,
/// `agents.json` prompt patterns that did not compile and were dropped,
/// so the reload status can say so instead of an agent that silently
/// never reads as waiting.
dropped_patterns: usize,
}
fn kind(name: &str, process: &[&str], prompt: &[&str]) -> AgentKind {
AgentKind {
name: name.to_string(),
process: process.iter().map(|p| p.to_string()).collect(),
prompt: prompt.iter().filter_map(|p| Regex::new(p).ok()).collect(),
// Each built-in is started by the command that is also its name.
launch: Some(name.to_string()),
}
}
impl AgentTable {
/// The agents croft knows without any configuration.
pub fn builtin() -> Self {
// The prompt shapes are what each agent prints when it stops for the
// user, anchored to the affordance rather than to a word: a bare
// `Allow` or a trailing `?` matched ordinary output ("Allowed
// origins: …", a rhetorical question in prose) and read as waiting.
let yes_no = ["\\(y/n\\)", "\\[Y/n\\]", "\\[y/N\\]"];
let claude = [
"Do you want to.*\\?",
"Esc to cancel",
"^\\s*\u{276f}\\s*\\d+\\.\\s",
"^\\s*[>\u{276f}]\\s*$",
];
let codex = [
"^\\s*Allow command",
"^\\s*[\u{276f}\u{203a}]\\s*\\d+\\.\\s",
"^\\s*[>\u{276f}\u{203a}]\\s*$",
];
let aider = ["^\\s*[>\u{276f}]\\s*$", "\\(Y\\)es"];
let gemini = [
"^\\s*[>\u{276f}\u{203a}]\\s*$",
"^\\s*(Allow|Approve).*\\?\\s*$",
];
fn with<'a>(own: &[&'a str], yes_no: &[&'a str]) -> Vec<&'a str> {
own.iter().chain(yes_no.iter()).copied().collect()
}
Self {
kinds: vec![
kind("claude", &["claude"], &with(&claude, &yes_no)),
kind("codex", &["codex"], &with(&codex, &yes_no)),
kind("aider", &["aider"], &with(&aider, &yes_no)),
kind("gemini", &["gemini"], &with(&gemini, &yes_no)),
],
dropped_patterns: 0,
}
}
/// The built-in table plus whatever `path` adds; a missing or broken file
/// is the built-in table alone, never a failed start.
pub fn load(path: &Path) -> Self {
match std::fs::read_to_string(path) {
Ok(json) => Self::from_json(&json),
Err(_) => Self::builtin(),
}
}
/// The built-in table extended by rows from `agents.json` text. A row
/// named like a built-in replaces it; a row with no usable regex still
/// badges the pane (it just never reads as waiting).
pub fn from_json(json: &str) -> Self {
let rows: Vec<AgentRow> =
serde_json::from_str(&crate::keymap::strip_line_comments(json)).unwrap_or_default();
let mut table = Self::builtin();
for row in rows {
let name = row.name.trim().to_lowercase();
if name.is_empty() {
continue;
}
let process: Vec<String> = if row.process.is_empty() {
vec![name.clone()]
} else {
row.process
.iter()
.map(|p| p.trim().to_lowercase())
.collect()
};
let mut prompt: Vec<Regex> = Vec::with_capacity(row.prompt.len());
for pat in &row.prompt {
match Regex::new(pat) {
Ok(re) => prompt.push(re),
Err(_) => table.dropped_patterns += 1,
}
}
// Omitted and blank are different answers: a row that says
// nothing about launching has no opinion, a row that says
// `"launch": ""` is asking for no command.
let launch_omitted = row.launch.is_none();
let launch = row
.launch
.as_deref()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(str::to_string);
match table.kinds.iter_mut().find(|k| k.name == name) {
Some(existing) => {
// A row that replaces a built-in but says nothing about
// launching keeps the built-in's command: the row is
// usually there to fix a prompt pattern, not to unteach
// croft how to start the agent. A blank one is the
// explicit way to unteach it.
let launch = if launch_omitted {
existing.launch.clone()
} else {
launch
};
*existing = AgentKind {
name: name.clone(),
process,
prompt,
launch,
};
}
None => table.kinds.push(AgentKind {
name: name.clone(),
process,
prompt,
launch,
}),
}
}
table
}
/// The agent a foreground process name means, if any. The name may be a
/// path (`/opt/homebrew/bin/claude`) and any case.
pub fn classify(&self, process_name: &str) -> Option<&AgentKind> {
let base = process_name
.rsplit('/')
.next()
.unwrap_or(process_name)
.trim()
.to_lowercase();
if base.is_empty() {
return None;
}
self.kinds
.iter()
.find(|k| k.process.iter().any(|p| p.eq_ignore_ascii_case(&base)))
}
pub fn names(&self) -> Vec<&str> {
self.kinds.iter().map(|k| k.name.as_str()).collect()
}
/// The command a worktree lane starts `agent` with (#348), by row name
/// in any case; `None` for an unknown agent or a row with no launch line.
pub fn launch_line(&self, agent: &str) -> Option<&str> {
let want = agent.trim();
self.kinds
.iter()
.find(|k| k.name.eq_ignore_ascii_case(want))
.and_then(|k| k.launch.as_deref())
}
/// How many `agents.json` prompt patterns failed to compile.
pub fn dropped_patterns(&self) -> usize {
self.dropped_patterns
}
}
/// What an agent is doing, from how long its pane has been quiet and what
/// its last screen rows say. `quiet_after` is the threshold ([`QUIET_AFTER`]
/// in the app; tests pass 0 to judge the screen alone).
pub fn judge(
kind: &AgentKind,
quiet_for: Duration,
last_rows: &[String],
quiet_after: Duration,
) -> AgentStatus {
if quiet_for < quiet_after {
return AgentStatus::Working;
}
let asks = last_rows
.iter()
.rev()
.filter(|r| !r.trim().is_empty())
.take(6)
.any(|row| kind.prompt.iter().any(|re| re.is_match(row)));
if asks {
AgentStatus::Waiting
} else {
AgentStatus::Idle
}
}
/// The events one sample produces for a pane, given what it carried before
/// and what it carries now. `Waiting` fires only on the way INTO waiting, so
/// a prompt that sits on screen across many samples notifies once.
pub fn transition(
pane: &str,
prev: Option<&AgentLane>,
next: Option<&AgentLane>,
) -> Vec<AgentEvent> {
let pane = pane.to_string();
match (prev, next) {
(None, None) => Vec::new(),
(None, Some(n)) => {
let mut ev = vec![AgentEvent::Seated {
pane: pane.clone(),
agent: n.name.clone(),
}];
if n.status == AgentStatus::Waiting {
ev.push(AgentEvent::Waiting {
pane,
agent: n.name.clone(),
});
}
ev
}
(Some(p), None) => vec![AgentEvent::Gone {
pane,
agent: p.name.clone(),
}],
(Some(p), Some(n)) if p.name != n.name => {
let mut ev = vec![
AgentEvent::Gone {
pane: pane.clone(),
agent: p.name.clone(),
},
AgentEvent::Seated {
pane: pane.clone(),
agent: n.name.clone(),
},
];
if n.status == AgentStatus::Waiting {
ev.push(AgentEvent::Waiting {
pane,
agent: n.name.clone(),
});
}
ev
}
(Some(p), Some(n)) => match (p.status, n.status) {
(a, b) if a == b => Vec::new(),
(_, AgentStatus::Waiting) => vec![AgentEvent::Waiting {
pane,
agent: n.name.clone(),
}],
(_, AgentStatus::Working) => vec![AgentEvent::Working {
pane,
agent: n.name.clone(),
}],
(_, AgentStatus::Idle) => Vec::new(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rows(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn the_builtin_table_recognises_the_four_agents_by_name_or_path() {
let t = AgentTable::builtin();
assert_eq!(t.names(), ["claude", "codex", "aider", "gemini"]);
for (proc_name, want) in [
("claude", "claude"),
("/opt/homebrew/bin/claude", "claude"),
("Codex", "codex"),
("aider", "aider"),
("gemini", "gemini"),
] {
assert_eq!(
t.classify(proc_name).map(|k| k.name.as_str()),
Some(want),
"{proc_name}"
);
}
for not in ["zsh", "node", "cargo", "", "claudette", "/usr/bin/vim"] {
assert!(t.classify(not).is_none(), "{not:?} is not an agent");
}
}
#[test]
fn agents_json_extends_the_table_without_a_rebuild_and_can_replace_a_builtin() {
let t = AgentTable::from_json(
r#"// a comment
[
{ "name": "goose", "process": ["goose", "goose-cli"], "prompt": ["^\\s*>\\s*$"] },
{ "name": "claude", "process": ["claude", "claude-code"], "prompt": ["Proceed\\?"] }
]"#,
);
assert_eq!(
t.classify("goose-cli").map(|k| k.name.as_str()),
Some("goose")
);
let claude = t
.classify("claude-code")
.expect("the replaced row matches its new process");
assert_eq!(claude.name, "claude");
assert_eq!(
claude.prompt.len(),
1,
"the row replaced the built-in prompts"
);
assert_eq!(t.names().len(), 5);
assert_eq!(t.dropped_patterns(), 0);
let bad = AgentTable::from_json(r#"[{ "name": "x", "prompt": ["(unclosed", "ok"] }]"#);
assert_eq!(
bad.dropped_patterns(),
1,
"a pattern that does not compile is counted"
);
assert_eq!(bad.classify("x").unwrap().prompt.len(), 1);
// A broken file is the built-in table, not a failed start.
assert_eq!(AgentTable::from_json("{ not json").names().len(), 4);
assert_eq!(
AgentTable::load(Path::new("/definitely/missing.json"))
.names()
.len(),
4
);
// TEMPLATE parses (comments stripped) to zero rows.
assert_eq!(AgentTable::from_json(TEMPLATE).names().len(), 4);
}
#[test]
fn a_row_can_name_the_command_a_lane_starts_the_agent_with() {
// The built-ins launch as their own name; a row sets its own, a row
// replacing a built-in without one keeps the built-in's, a blank one
// is none, and lookup is by row name in any case.
let t = AgentTable::builtin();
assert_eq!(t.launch_line("claude"), Some("claude"));
assert_eq!(t.launch_line("Codex"), Some("codex"), "any case");
assert_eq!(t.launch_line("goose"), None, "unknown agent");
let t = AgentTable::from_json(
r#"[
{ "name": "goose", "launch": " goose session --resume " },
{ "name": "claude", "prompt": ["Proceed\\?"] },
{ "name": "quiet", "launch": " " }
]"#,
);
assert_eq!(
t.launch_line("goose"),
Some("goose session --resume"),
"trimmed"
);
assert_eq!(
t.launch_line("claude"),
Some("claude"),
"a replacing row without a launch keeps the built-in's"
);
assert_eq!(t.launch_line("quiet"), None, "a blank launch is none");
let t = AgentTable::from_json(r#"[{ "name": "claude", "launch": "claude --model opus" }]"#);
assert_eq!(t.launch_line("claude"), Some("claude --model opus"));
// Omitted inherits; blank is an explicit "no command", even on a
// row that replaces a built-in.
let t = AgentTable::from_json(r#"[{ "name": "claude", "launch": " " }]"#);
assert_eq!(
t.launch_line("claude"),
None,
"a blank launch on a replacing row unteaches the built-in's"
);
}
#[test]
fn status_is_working_while_output_flows_then_waiting_or_idle_by_the_screen() {
let t = AgentTable::builtin();
let claude = t.classify("claude").unwrap();
let prompt = rows(&["Edited src/main.rs", "", "Do you want to proceed? (y/n)"]);
let quiet = rows(&["Edited src/main.rs", "Done."]);
let after = Duration::from_secs(3);
assert_eq!(
judge(claude, Duration::from_millis(500), &prompt, after),
AgentStatus::Working
);
assert_eq!(
judge(claude, Duration::from_secs(10), &prompt, after),
AgentStatus::Waiting
);
assert_eq!(
judge(claude, Duration::from_secs(10), &quiet, after),
AgentStatus::Idle
);
// A bare prompt line counts, and so does Claude Code's numbered
// permission menu; a question ten rows up does not.
assert_eq!(
judge(claude, after, &rows(&["> "]), after),
AgentStatus::Waiting
);
assert_eq!(
judge(
claude,
after,
&rows(&["Do you want to make this edit?", "\u{276f} 1. Yes"]),
after
),
AgentStatus::Waiting
);
// Ordinary output that merely contains a question mark or the word
// "Allow" is not a prompt.
let gemini = t.classify("gemini").unwrap();
for (kind, row) in [
(claude, "Allowed origins: https://example.com"),
(claude, " Do you want to know more"),
(gemini, "Does that make sense?"),
(claude, "if (x == 1) { return y; } // ?"),
] {
assert_eq!(
judge(kind, after, &rows(&[row]), after),
AgentStatus::Idle,
"{row:?}"
);
}
assert_eq!(
judge(gemini, after, &rows(&["Allow this tool call?"]), after),
AgentStatus::Waiting
);
let mut buried = vec!["Allow this? (y/n)".to_string()];
buried.extend((0..8).map(|i| format!("log line {i}")));
assert_eq!(judge(claude, after, &buried, after), AgentStatus::Idle);
}
#[test]
fn waiting_fires_once_per_prompt_and_seated_gone_bracket_the_lane() {
let lane = |s| AgentLane {
name: "claude".into(),
status: s,
};
let pane = "Terminal 2";
assert_eq!(
transition(pane, None, Some(&lane(AgentStatus::Working))),
vec![AgentEvent::Seated {
pane: pane.into(),
agent: "claude".into()
}]
);
let waiting = vec![AgentEvent::Waiting {
pane: pane.into(),
agent: "claude".into(),
}];
assert_eq!(
transition(
pane,
Some(&lane(AgentStatus::Working)),
Some(&lane(AgentStatus::Waiting))
),
waiting
);
assert_eq!(
transition(
pane,
Some(&lane(AgentStatus::Waiting)),
Some(&lane(AgentStatus::Waiting))
),
Vec::<AgentEvent>::new(),
"a prompt that stays on screen fires once"
);
assert_eq!(
transition(
pane,
Some(&lane(AgentStatus::Waiting)),
Some(&lane(AgentStatus::Working))
),
vec![AgentEvent::Working {
pane: pane.into(),
agent: "claude".into()
}]
);
assert_eq!(
transition(
pane,
Some(&lane(AgentStatus::Working)),
Some(&lane(AgentStatus::Idle))
),
Vec::<AgentEvent>::new()
);
assert_eq!(
transition(pane, Some(&lane(AgentStatus::Idle)), None),
vec![AgentEvent::Gone {
pane: pane.into(),
agent: "claude".into()
}]
);
// Seated straight into a prompt is one Seated and one Waiting.
assert_eq!(
transition(pane, None, Some(&lane(AgentStatus::Waiting))).len(),
2
);
// A different agent taking the pane is Gone then Seated.
let other = AgentLane {
name: "aider".into(),
status: AgentStatus::Working,
};
let ev = transition(pane, Some(&lane(AgentStatus::Idle)), Some(&other));
assert!(
matches!(ev[0], AgentEvent::Gone { .. }) && matches!(ev[1], AgentEvent::Seated { .. })
);
}
}