-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubagent.rs
More file actions
5908 lines (5688 loc) · 225 KB
/
Copy pathsubagent.rs
File metadata and controls
5908 lines (5688 loc) · 225 KB
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
// Subagent system: a port of pi-subagents' delegation/orchestration features,
// adapted to this harness's single-process, Rust-core architecture.
//
// Subagents are nested agentic loops (see run_agent) that share the workspace,
// tools, and API key but run with a focused system prompt and an optional tool
// allowlist. They are defined as markdown files with YAML frontmatter
// (agents/*.md), discovered from builtin (embedded), user, and project scopes.
//
// Execution modes (the `subagent` tool):
// - single: { agent, task, async, ... }
// - parallel:{ tasks: [...], concurrency, worktree, async }
// - chain: { chain: [...], async } // async detaches the whole chain
// - management: { action: list|get|create|update|delete|status|interrupt|resume|doctor }
//
// Coordination (see intercom.rs) is wired in here: a subagent whose resolved
// tools include `contact_supervisor`/`intercom` gets those tools + bridge
// instructions, and can prompt the orchestrator for decisions or talk to peer
// subagents when the setup allows it.
use crate::config::{Config, ResolvedProvider, SubagentConfig};
use crate::intercom::{execute_contact_supervisor, execute_intercom};
use crate::logging::{estimate_messages_tokens, grounded_estimate, TurnTimer};
use crate::message::{self, Message};
use crate::protocol::{emit, Event, ModelInfo};
use crate::tools::{self, Outcome};
use crate::State;
use futures_util::FutureExt;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::panic::AssertUnwindSafe;
use std::path::Path;
use std::sync::{Arc, Mutex};
use tokio_util::sync::CancellationToken;
// ---------------------------------------------------------------------------
// Frontmatter parsing (port of frontmatter.ts)
// ---------------------------------------------------------------------------
/// Parse YAML-ish frontmatter (key: value, flat only) + markdown body.
pub fn parse_frontmatter(content: &str) -> (HashMap<String, String>, String) {
let mut fm: HashMap<String, String> = HashMap::new();
let normalized = content.replace("\r\n", "\n");
if !normalized.starts_with("---") {
return (fm, normalized.trim().to_string());
}
let end = match normalized.find("\n---") {
// Require i > 3 so an immediately-closed fence ("---\n---…", empty
// frontmatter) doesn't slice [4..3] and panic. With i == 3 the block is
// empty; treat the whole content as the body (the caller skips agents
// with no parsed `name`).
Some(i) if i > 3 => i,
_ => return (fm, normalized),
};
let block = &normalized[4..end];
let body = normalized[end + 4..].trim().to_string();
for line in block.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if let Some(colon) = line.find(':') {
let key = line[..colon].trim().to_string();
let mut val = line[colon + 1..].trim().to_string();
// strip surrounding quotes
if val.len() >= 2
&& ((val.starts_with('"') && val.ends_with('"'))
|| (val.starts_with('\'') && val.ends_with('\'')))
{
val = val[1..val.len() - 1].to_string();
}
fm.insert(key, val);
}
}
(fm, body)
}
// ---------------------------------------------------------------------------
// Agent config
// ---------------------------------------------------------------------------
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub enum SystemPromptMode {
Replace,
Append,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub enum ContextKind {
Fresh,
Fork,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub enum AgentSource {
Builtin,
User,
Project,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct AgentConfig {
pub name: String,
pub description: String,
pub tools: Vec<String>,
pub model: Option<String>,
pub fallback_models: Vec<String>,
pub thinking: Option<String>,
pub system_prompt_mode: SystemPromptMode,
pub inherit_project_context: bool,
pub inherit_skills: bool,
pub default_context: Option<ContextKind>,
pub system_prompt: String,
pub source: AgentSource,
pub file_path: String,
pub skills: Vec<String>,
pub output: Option<String>,
pub default_reads: Vec<String>,
pub default_progress: bool,
pub max_subagent_depth: Option<u32>,
pub completion_guard: bool,
pub disabled: bool,
}
impl AgentConfig {
/// Map a pi-style tool name to this harness's tool name.
pub fn normalize_tool(name: &str) -> &str {
match name {
"read" => "read_file",
"find" | "search" => "glob",
"ls" | "dir" => "list_dir",
"write" => "write_file",
"bash" | "shell" | "sh" => "bash",
"ast_grep" => "ast_edit",
// bash, edit, grep, glob, list_dir, patch, diagnostics, subagent,
// contact_supervisor, intercom, todo_* pass through unchanged.
other => other,
}
}
}
// ---------------------------------------------------------------------------
// Built-in agents (embedded fallback; .catalyst-code/agents/*.md overrides)
// ---------------------------------------------------------------------------
fn builtin_agents() -> Vec<AgentConfig> {
let mk = |name: &str,
desc: &str,
tools: &str,
thinking: Option<&str>,
append: bool,
inherit_ctx: bool,
default_ctx: Option<ContextKind>,
prompt: &str| {
AgentConfig {
name: name.to_string(),
description: desc.to_string(),
tools: tools
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
model: None,
fallback_models: vec![],
thinking: thinking.map(|s| s.to_string()),
system_prompt_mode: if append {
SystemPromptMode::Append
} else {
SystemPromptMode::Replace
},
inherit_project_context: inherit_ctx,
inherit_skills: false,
default_context: default_ctx,
system_prompt: prompt.to_string(),
source: AgentSource::Builtin,
file_path: format!("<builtin:{name}>"),
skills: vec![],
output: if name == "scout" {
Some("context.md".into())
} else {
None
},
default_reads: if name == "worker" || name == "reviewer" {
vec!["context.md".into(), "plan.md".into()]
} else {
vec![]
},
default_progress: name == "worker" || name == "scout",
max_subagent_depth: None,
completion_guard: false,
disabled: false,
}
};
vec![
mk(
"scout",
"Fast codebase recon that returns compressed context for handoff",
"read_file, grep, glob, list_dir, bash, write_file, memory, knowledge, git_status, git_diff, git_log, git_show, diagnostics, workspace_activity, load_tools, intercom",
Some("low"),
false,
true,
None,
SCOUT_PROMPT,
),
mk(
"researcher",
"Web/docs research with sources and a concise research brief",
"read_file, grep, glob, list_dir, bash, write_file, memory, knowledge, collections, git_status, git_log, diagnostics, workspace_activity, load_tools, intercom, fetch, web_search, browser_create, browser_navigate, browser_snapshot, browser_click, browser_fill, browser_type, browser_screenshot, browser_close, browser_list_sessions",
Some("low"),
false,
true,
None,
RESEARCHER_PROMPT,
),
mk(
"planner",
"A concrete implementation plan from existing context; reads and plans, does not edit",
"read_file, grep, glob, list_dir, bash, memory, knowledge, git_status, git_diff, git_log, git_show, diagnostics, workspace_activity, todo_read, todo_write, load_tools, intercom",
Some("high"),
false,
true,
Some(ContextKind::Fork),
PLANNER_PROMPT,
),
mk(
"worker",
"Implementation agent for normal tasks and approved oracle handoffs",
"read_file, grep, glob, list_dir, bash, edit, write_file, patch, delete, rename, mkdir, memory, knowledge, collections, git_status, git_diff, git_log, git_show, git_add, git_commit, git_branch, diagnostics, workspace_activity, todo_read, todo_write, bulk, bulk_read, bulk_write, bulk_edit, load_tools, fetch, web_search, process, lsp, ast_edit, snapshot_edit, browser_create, browser_navigate, browser_snapshot, browser_click, browser_fill, browser_type, browser_press, browser_screenshot, browser_close, browser_list_sessions, browser_wait, browser_scroll, contact_supervisor",
Some("high"),
false,
true,
Some(ContextKind::Fork),
WORKER_PROMPT,
),
mk(
"reviewer",
"Code review and small fixes against the task/plan, tests, edge cases, simplicity",
"read_file, grep, glob, list_dir, bash, edit, write_file, patch, memory, knowledge, git_status, git_diff, git_log, git_show, diagnostics, workspace_activity, todo_read, load_tools, intercom",
Some("high"),
false,
true,
None,
REVIEWER_PROMPT,
),
mk(
"context-builder",
"Stronger setup pass before planning: gathers context and writes handoff material",
"read_file, grep, glob, list_dir, bash, write_file, memory, knowledge, git_status, git_diff, git_log, git_show, diagnostics, workspace_activity, load_tools, intercom",
Some("low"),
false,
true,
None,
CONTEXT_BUILDER_PROMPT,
),
mk(
"oracle",
"High-context decision-consistency oracle; challenges assumptions, prevents drift",
"read_file, grep, glob, list_dir, bash, memory, knowledge, git_status, git_diff, git_log, diagnostics, workspace_activity, load_tools, intercom",
Some("high"),
false,
true,
Some(ContextKind::Fork),
ORACLE_PROMPT,
),
mk(
"delegate",
"Lightweight general delegate that behaves close to the parent session",
"read_file, grep, glob, list_dir, bash, edit, write_file, patch, memory, knowledge, git_status, git_diff, git_log, git_show, diagnostics, workspace_activity, todo_read, todo_write, load_tools, fetch, web_search, contact_supervisor",
None,
true,
true,
None,
DELEGATE_PROMPT,
),
mk(
"librarian",
"Read-only source and official documentation researcher",
"read_file, grep, glob, list_dir, bash, memory, knowledge, git_status, git_log, diagnostics, load_tools, intercom, fetch, web_search, lsp",
Some("low"),
false,
true,
None,
LIBRARIAN_PROMPT,
),
mk(
"designer",
"UI/UX implementer that reuses the project's visual system",
"read_file, grep, glob, list_dir, bash, edit, write_file, patch, delete, rename, mkdir, memory, knowledge, collections, git_status, git_diff, git_log, git_show, git_add, git_commit, git_branch, diagnostics, workspace_activity, todo_read, todo_write, bulk, bulk_read, bulk_write, bulk_edit, load_tools, fetch, web_search, process, lsp, ast_edit, snapshot_edit, browser_create, browser_navigate, browser_snapshot, browser_click, browser_fill, browser_type, browser_press, browser_screenshot, browser_close, browser_list_sessions, browser_wait, browser_scroll, contact_supervisor",
Some("high"),
false,
true,
Some(ContextKind::Fork),
DESIGNER_PROMPT,
),
mk(
"sonic",
"Strictly mechanical edits or data collection",
"read_file, grep, glob, list_dir, bash, edit, write_file, patch, memory, load_tools, contact_supervisor",
Some("low"),
false,
true,
None,
SONIC_PROMPT,
),
mk(
"security-reviewer",
"Read-only, evidence-backed security review",
"read_file, grep, glob, list_dir, bash, memory, knowledge, git_status, git_diff, git_log, diagnostics, load_tools, intercom, lsp",
Some("high"),
false,
true,
None,
SECURITY_REVIEWER_PROMPT,
),
mk(
"task",
"General-purpose OMP default writer",
"read_file, grep, glob, list_dir, bash, edit, write_file, patch, memory, knowledge, git_status, git_diff, git_log, git_show, diagnostics, workspace_activity, todo_read, todo_write, load_tools, fetch, web_search, contact_supervisor",
Some("high"),
true,
true,
None,
TASK_PROMPT,
),
]
}
const SCOUT_PROMPT: &str = "You are a scouting subagent. Move fast, but do not guess. Use targeted search and selective reading over reading whole files unless the task clearly needs broader coverage.\n\nFocus on the minimum context another agent needs to act: relevant entry points, key types/interfaces/functions, data flow and dependencies, files likely to need changes, and constraints/risks/open questions.\n\nWorking rules:\n- Use grep, glob, list_dir, and read_file to map the area before diving deeper.\n- Use bash only for non-interactive inspection.\n- Cite exact file paths and line ranges.\n- If told to write output, write it to the provided path and keep the final response short.\n- If blocked or needing a decision, use contact_supervisor with reason \"need_decision\" and wait for the reply.\n\nOutput format:\n# Code Context\n## Files Retrieved (exact paths + line ranges + why)\n## Key Code (critical types/functions/snippets)\n## Architecture (how pieces connect)\n## Start Here (first file another agent should open + why)";
const RESEARCHER_PROMPT: &str = "You are a research subagent. Gather external evidence: official docs, specs, benchmarks, recent changes. Return a concise research brief with source links, confidence level, gaps, and decision implications. Do not edit code. If blocked or needing a decision, use contact_supervisor with reason \"need_decision\" and wait for the reply.";
const PLANNER_PROMPT: &str = "You are a planning subagent. Produce a concrete, actionable implementation plan from the supplied context. Read and plan; do not edit code. Include: goals, affected files, step-by-step changes, risks, validation steps, and open questions. Treat inherited forked context as reference-only — do not continue prior conversations. If a decision is missing that blocks planning, use contact_supervisor with reason \"need_decision\" and wait.";
const WORKER_PROMPT: &str = "You are `worker`: the implementation subagent. You are the single writer thread. Execute the assigned task or approved direction with narrow, coherent edits. The main agent and user remain the decision authority.\n\nFirst understand the inherited context, supplied files, plan, and explicit task. Then implement carefully and minimally. If implementation reveals an unapproved decision required to continue safely, pause and escalate with contact_supervisor (reason \"need_decision\") and wait for the reply before continuing. Use reason \"progress_update\" only for concise non-blocking updates.\n\nWorking rules:\n- Prefer narrow, correct changes over broad rewrites.\n- Do not add speculative scaffolding.\n- Do not leave TODOs or silent scope changes.\n- Use bash for inspection, validation, and tests.\n- Read supplied context/plan first.\n- If your task expects edits and you made none, do not return a success summary.\n\nFinal response shape:\nImplemented X.\nChanged files: Y.\nValidation: Z.\nOpen risks/questions: R.\nRecommended next step: N.";
const REVIEWER_PROMPT: &str = "You are a disciplined review subagent. Inspect, evaluate, and report findings with evidence. Do not guess; verify from code, tests, docs, or requirements.\n\nReview: implementation vs intent, correctness/edge-cases, test coverage, unintended side effects/regressions, and simplicity/readability. Return concise, evidence-backed findings with file/line references. Make small fixes only if asked. If blocked or needing a decision, use contact_supervisor/intercom with reason \"need_decision\" and wait.";
const CONTEXT_BUILDER_PROMPT: &str = "You are a context-building subagent. Gather the code context another agent needs before planning or implementation. Read every relevant file, follow imports/callers/tests/docs/config, and write handoff material (e.g. context.md) plus a compact meta-prompt. Do not implement features. If blocked, use contact_supervisor with reason \"need_decision\" and wait.";
const ORACLE_PROMPT: &str = "You are the oracle: a high-context decision-consistency subagent. Prevent the main agent from making hidden, conflicting, or inconsistent decisions by treating inherited forked context as the authoritative contract. You are not the primary executor and do not edit files.\n\nReconstruct inherited decisions/constraints/open questions; identify drift between the current trajectory and those decisions; surface contradictions and hidden assumptions. Prefer narrow corrections over broad pivots. If you need clarification, use contact_supervisor with reason \"need_decision\" and wait for the reply.\n\nOutput shape:\nInherited decisions:\nDiagnosis:\nDrift / contradiction check:\nRecommendation:\nRisks:\nNeed from main agent:\nSuggested execution prompt (only if a worker handoff is warranted):";
const DELEGATE_PROMPT: &str = "You are a delegated agent. Execute the assigned task using the provided tools. Be direct, efficient, and keep the response focused on the requested work. If blocked or needing a decision, use contact_supervisor with reason \"need_decision\" and wait for the reply.";
const LIBRARIAN_PROMPT: &str = "You are a read-only source and documentation researcher. Ground every claim in project source or official documentation. Check node_modules and vendored sources before searching externally. Never edit project files.";
const DESIGNER_PROMPT: &str = "You are a UI/UX implementation specialist. Reuse existing design tokens, components, and primitives rather than inventing a second visual system. Avoid generic AI-slop and glassmorphism. Implement complete interaction states and preserve accessibility.";
const SONIC_PROMPT: &str = "You are sonic. Perform strictly mechanical edits or data collection only. Make no design or architecture decisions, and create no extra files. If the assignment requires judgment, stop and contact the supervisor.";
const SECURITY_REVIEWER_PROMPT: &str = "You are a read-only security reviewer. Report only evidence-backed vulnerabilities; do not edit files or provide exploit payloads. Every finding must include file:line evidence and severity.";
const TASK_PROMPT: &str = "You are a general-purpose task agent. Hyperfocus the assigned task and use the full provided tool set when needed. Prefer editing existing files and do not create extra Markdown files.";
// ---------------------------------------------------------------------------
// Discovery
// ---------------------------------------------------------------------------
/// Resolve an agent's intercom target name (stable per run).
pub fn subagent_target(run_id: &str, agent: &str, index: Option<usize>) -> String {
let suffix = index.map(|i| format!("-{}", i + 1)).unwrap_or_default();
let clean = |s: &str| {
s.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
.collect::<String>()
.to_lowercase()
};
let rid = run_id.replace('-', "");
let mut rid_end = rid.len().min(8);
while rid_end > 0 && !rid.is_char_boundary(rid_end) {
rid_end -= 1;
}
format!("subagent-{}-{}{}", clean(agent), &rid[..rid_end], suffix)
}
/// Discover all agents: builtin (lowest) < user < project (project wins on name).
/// Applies settings overrides (model/fallback/thinking/disabled).
pub fn discover_agents(workspace: &Path, cfg: &SubagentConfig) -> Vec<AgentConfig> {
let mut by_name: HashMap<String, AgentConfig> = HashMap::new();
if !cfg.disable_builtins {
for mut a in builtin_agents() {
apply_overrides(&mut a, cfg);
if !a.disabled {
by_name.insert(a.name.clone(), a);
}
}
}
if let Some(home) = crate::config::home_dir() {
load_agent_dir(&home.join(".omp/agents"), AgentSource::User, &mut by_name);
load_agent_dir(
&home.join(".catalyst-code/agents"),
AgentSource::User,
&mut by_name,
);
}
if let Some(omp) = crate::project_guidance::nearest_omp_dir(workspace) {
load_agent_dir(&omp.join("agents"), AgentSource::Project, &mut by_name);
}
load_agent_dir(
&workspace.join(".omp/agents"),
AgentSource::Project,
&mut by_name,
);
load_agent_dir(
&workspace.join(".catalyst-code/agents"),
AgentSource::Project,
&mut by_name,
);
let mut v: Vec<AgentConfig> = by_name.into_values().collect();
v.sort_by(|a, b| a.name.cmp(&b.name));
v
}
fn load_agent_dir(dir: &Path, source: AgentSource, by_name: &mut HashMap<String, AgentConfig>) {
let Ok(rd) = std::fs::read_dir(dir) else {
return;
};
for e in rd.flatten() {
let p = e.path();
if p.is_dir() {
load_agent_dir(&p, source.clone(), by_name);
continue;
}
if p.extension().and_then(|x| x.to_str()) != Some("md") {
continue;
}
let Ok(content) = std::fs::read_to_string(&p) else {
continue;
};
let (fm, body) = parse_frontmatter(&content);
let name = match fm.get("name").and_then(|s| s.split_whitespace().next()) {
Some(n) => n.to_string(),
None => continue,
};
let tools_str = fm.get("tools").cloned().unwrap_or_default();
let a = AgentConfig {
name: name.clone(),
description: fm.get("description").cloned().unwrap_or_default(),
tools: tools_str
.split(',')
.map(|s| AgentConfig::normalize_tool(s.trim()).to_string())
.filter(|s| !s.is_empty())
.collect(),
model: normalize_model_pin(fm.get("model").map(String::as_str)),
fallback_models: fm
.get("fallbackModels")
.map(|s| s.split(',').map(|x| x.trim().to_string()).collect())
.unwrap_or_default(),
thinking: fm.get("thinking").cloned(),
system_prompt_mode: match fm.get("systemPromptMode").map(|s| s.as_str()) {
Some("append") => SystemPromptMode::Append,
_ => SystemPromptMode::Replace,
},
inherit_project_context: fm
.get("inheritProjectContext")
.map(|s| s == "true")
.unwrap_or(false),
inherit_skills: fm
.get("inheritSkills")
.map(|s| s == "true")
.unwrap_or(false),
default_context: match fm.get("defaultContext").map(|s| s.as_str()) {
Some("fork") => Some(ContextKind::Fork),
Some("fresh") => Some(ContextKind::Fresh),
_ => None,
},
system_prompt: body,
source: source.clone(),
file_path: p.display().to_string(),
skills: fm
.get("skills")
.map(|s| s.split(',').map(|x| x.trim().to_string()).collect())
.unwrap_or_default(),
output: fm.get("output").cloned(),
default_reads: fm
.get("defaultReads")
.map(|s| s.split(',').map(|x| x.trim().to_string()).collect())
.unwrap_or_default(),
default_progress: fm
.get("defaultProgress")
.map(|s| s == "true")
.unwrap_or(false),
max_subagent_depth: fm.get("maxSubagentDepth").and_then(|s| s.parse().ok()),
completion_guard: fm
.get("completionGuard")
.map(|s| s == "true")
.unwrap_or(false),
disabled: fm.get("disabled").map(|s| s == "true").unwrap_or(false),
};
if !a.disabled {
by_name.insert(name, a);
}
}
}
fn apply_overrides(a: &mut AgentConfig, cfg: &SubagentConfig) {
if let Some(ov) = cfg.agent_overrides.get(&a.name) {
if let Some(m) = &ov.model {
a.model = normalize_model_pin(Some(m.as_str()));
}
if !ov.fallback_models.is_empty() {
a.fallback_models = ov.fallback_models.clone();
}
if let Some(t) = &ov.thinking {
a.thinking = Some(t.clone());
}
if ov.disabled {
a.disabled = true;
}
}
}
pub fn find_agent<'a>(agents: &'a [AgentConfig], name: &str) -> Option<&'a AgentConfig> {
// allow package.name syntax: code-analysis.scout → scout
let bare = name.rsplit('.').next().unwrap_or(name);
agents.iter().find(|a| a.name == name || a.name == bare)
}
// ---------------------------------------------------------------------------
// Skills (SKILL.md discovery + injection)
// ---------------------------------------------------------------------------
pub(crate) fn discover_skills(workspace: &Path) -> Vec<(String, String, String)> {
let home = crate::config::home_dir();
let mut out = Vec::new();
let mut seen = std::collections::HashSet::new();
for skill in crate::skills::configured(workspace, home.as_deref()).discover() {
let skill_md = skill.path.join("SKILL.md");
let Ok(content) = std::fs::read_to_string(&skill_md) else {
continue;
};
let (fm, _) = parse_frontmatter(&content);
if fm
.get("deprecated")
.map(|v| v.eq_ignore_ascii_case("true"))
.unwrap_or(false)
{
continue;
}
let name = fm.get("name").cloned().unwrap_or(skill.name);
if !seen.insert(name.to_lowercase()) {
continue;
}
let desc = fm.get("description").cloned().unwrap_or_default();
out.push((name, desc, skill_md.display().to_string()));
}
out
}
/// A discoverable skill with its parsed body content — used by the `skills`
/// event and `apply_skill` command so the core (which has unrestricted FS
/// access) can read global skills under ~/.catalyst-code/skills that the
/// read_file tool cannot reach (it rejects absolute / `..` paths).
#[derive(Clone)]
#[allow(dead_code)]
pub(crate) struct SkillEntry {
pub name: String,
pub description: String,
pub location: String,
pub body: String,
/// Optional skill stage from frontmatter (candidate|trusted|needs_revision|deprecated).
pub stage: String,
/// Optional version from frontmatter.
pub version: String,
}
/// Like `discover_skills` but also returns the parsed SKILL.md body (frontmatter
/// stripped). Same precedence (project then user; first wins on name) and the
/// same deprecated-skill filter.
pub(crate) fn discover_skills_full(workspace: &Path) -> Vec<SkillEntry> {
let home = crate::config::home_dir();
let mut out = Vec::new();
let mut seen = std::collections::HashSet::new();
for skill in crate::skills::configured(workspace, home.as_deref()).discover() {
let skill_md = skill.path.join("SKILL.md");
let Ok(content) = std::fs::read_to_string(&skill_md) else {
continue;
};
let (fm, body) = parse_frontmatter(&content);
if fm
.get("deprecated")
.map(|v| v.eq_ignore_ascii_case("true"))
.unwrap_or(false)
{
continue;
}
let name = fm.get("name").cloned().unwrap_or(skill.name);
if !seen.insert(name.to_lowercase()) {
continue;
}
out.push(SkillEntry {
name,
description: fm.get("description").cloned().unwrap_or_default(),
location: skill_md.display().to_string(),
body,
stage: fm.get("stage").cloned().unwrap_or_default(),
version: fm.get("version").cloned().unwrap_or_default(),
});
}
out
}
/// Suggest a skill whose name+description semantically matches the prompt, so
/// the agent can apply it without remembering `/skill:<name>`. Mirrors the
/// memory relevant-tail: tf·idf cosine over the skill corpus (down-weights
/// common tokens so a skill isn't suggested just for sharing "all"/"use").
/// Returns a short hint string, or None when no skill clears the relevance bar.
pub(crate) fn relevant_skill_hint(workspace: &Path, prompt: &str) -> Option<String> {
let prompt = prompt.trim();
if prompt.is_empty() {
return None;
}
let skills = discover_skills(workspace);
if skills.len() < 2 {
return None;
}
let n = skills.len() as f64;
let mut df: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
for (name, desc, _loc) in &skills {
let toks: std::collections::HashSet<String> =
crate::memory::significant_tokens(&format!("{name} {desc}"))
.into_iter()
.collect();
for t in toks {
*df.entry(t).or_insert(0) += 1;
}
}
let idf: std::collections::HashMap<String, f64> = df
.into_iter()
.map(|(t, d)| (t, (n / d.max(1) as f64).ln().max(0.0)))
.collect();
let q = skill_tfidf(prompt, &idf);
if q.is_empty() {
return None;
}
let mut best: Option<(usize, f64)> = None;
for (i, (name, desc, _loc)) in skills.iter().enumerate() {
if name == "pi-subagents" {
continue;
}
let v = skill_tfidf(&format!("{name} {desc}"), &idf);
let score = crate::memory::cosine_sim(&q, &v);
if score > 0.0 && best.is_none_or(|b| score > b.1) {
best = Some((i, score));
}
}
let (i, score) = best?;
if score < 0.05 {
return None;
}
let (name, desc, loc) = &skills[i];
let ident = std::path::Path::new(loc)
.parent()
.and_then(|p| p.file_name())
.and_then(|x| x.to_str())
.map(|x| x.trim().to_string())
.filter(|x| !x.is_empty())
.unwrap_or_else(|| name.clone());
let d = desc.trim();
Some(format!(
"[RELEVANT SKILL] — '{ident}' (score {score:.2}) matches this task. \
Apply with /skill:{ident} if useful; read it first if applying.{rest}",
rest = if d.is_empty() {
String::new()
} else {
format!("\n {d}")
}
))
}
/// tf·idf-weighted bag over significant tokens, against a precomputed idf map.
fn skill_tfidf(
text: &str,
idf: &std::collections::HashMap<String, f64>,
) -> std::collections::HashMap<String, f64> {
let mut v: std::collections::HashMap<String, f64> = std::collections::HashMap::new();
for t in crate::memory::significant_tokens(text) {
let w = idf.get(&t).copied().unwrap_or(1.0);
*v.entry(t).or_insert(0.0) += w;
}
v
}
fn skills_injection(workspace: &Path, names: &[String]) -> String {
if names.is_empty() {
return String::new();
}
let all = discover_skills(workspace);
let mut blocks = String::new();
for name in names {
if name == "false" {
continue;
}
if let Some((n, d, loc)) = all.iter().find(|(n, _, _)| n == name) {
blocks.push_str(&format!(
" <skill>\n <name>{n}</name>\n <description>{d}</description>\n <location>{loc}</location>\n </skill>\n"
));
}
}
if blocks.is_empty() {
return String::new();
}
format!("The following skills are available to this subagent. Use read_file to load a skill file when the task matches its description.\n<available_skills>\n{blocks}</available_skills>")
}
// ---------------------------------------------------------------------------
// Intercom bridge instructions
// ---------------------------------------------------------------------------
pub const INTERCOM_BRIDGE_MARKER: &str = "Intercom orchestration channel:";
pub fn bridge_instruction(orchestrator_target: &str) -> String {
format!("{INTERCOM_BRIDGE_MARKER}\nThe inherited thread is reference-only. Do not continue that conversation or send questions/status/completion handoffs to the supervisor in normal assistant text.\n\nUse contact_supervisor first. It resolves the supervisor \"{orchestrator_target}\" automatically.\n- Need a decision, blocked, approval, or scope ambiguity: contact_supervisor({{ reason: \"need_decision\", message: \"<question>\" }}). After a need_decision, stay alive and continue only after the reply arrives.\n- Meaningful progress or unexpected discoveries that change the plan: contact_supervisor({{ reason: \"progress_update\", message: \"UPDATE: <summary>\" }}).\n- Generic intercom is lower-level plumbing/fallback for peer subagents: intercom({{ action: \"ask\", to: \"<peer>\", message: \"...\" }}).\n\nDo not use contact_supervisor/intercom for routine completion handoffs. If no coordination is needed, return a focused task result.")
}
/// Decide whether intercom tools are injected for a subagent run, given the
/// bridge mode and the run's context kind.
pub fn bridge_active(mode: &crate::config::IntercomBridgeMode, ctx: Option<&ContextKind>) -> bool {
use crate::config::IntercomBridgeMode;
match mode {
IntercomBridgeMode::Off => false,
IntercomBridgeMode::ForkOnly => ctx == Some(&ContextKind::Fork),
IntercomBridgeMode::Always => true,
}
}
// ---------------------------------------------------------------------------
// Recursion guard
// ---------------------------------------------------------------------------
pub fn resolve_max_depth(cfg: &SubagentConfig) -> u32 {
std::env::var("CATALYST_CODE_SUBAGENT_MAX_DEPTH")
.ok()
.and_then(|s| s.parse().ok())
.filter(|n: &u32| *n == 0 || *n >= 1)
.unwrap_or(cfg.max_depth)
}
pub fn child_max_depth(parent: u32, agent: Option<u32>) -> u32 {
match agent {
Some(a) => parent.min(a),
None => parent,
}
}
// ---------------------------------------------------------------------------
// Tool defs available to a subagent (filtered by agent.tools + bridge)
// ---------------------------------------------------------------------------
fn all_tool_names() -> &'static [&'static str] {
&[
// FS / search / shell
"read_file",
"read",
"edit",
"write_file",
"write",
"delete",
"rename",
"mkdir",
"list_dir",
"grep",
"glob",
"bash",
"patch",
// Bulk
"bulk",
"bulk_read",
"bulk_write",
"bulk_edit",
// Planning / control
"todo_write",
"todo_read",
"todo",
"goal_write_plan",
"finish",
"ask",
"load_tools",
// Quality / web / intelligence
"diagnostics",
"fetch",
"web_search",
"knowledge",
"collections",
"memory",
// Git / workspace
"git_status",
"git_diff",
"git_log",
"git_show",
"git_add",
"git_commit",
"git_push",
"git_pull",
"git_branch",
"workspace_activity",
// Agents / env / runtime / ide / browser / mcp
"subagent",
"task",
"hub",
"spawn",
"contact_supervisor",
"intercom",
"test_env",
"eval",
"read",
"lsp",
"snapshot_edit",
"ast_edit",
"debug",
"mcp",
"process",
"browser_create",
"browser_close",
"browser_list_sessions",
"browser_navigate",
"browser_back",
"browser_reload",
"browser_snapshot",
"browser_find",
"browser_click",
"browser_fill",
"browser_type",
"browser_press",
"browser_scroll",
"browser_wait",
"browser_evaluate",
"browser_screenshot",
"browser_show",
"browser_hide",
]
}
/// Resolve the tool-name allowlist for a subagent (same set offered in the
/// schema). Empty `agent.tools` → core read-only defaults (not "all tools").
fn subagent_allowed_names(
agent: &AgentConfig,
bridge: bool,
depth: u32,
max_depth: u32,
) -> Vec<String> {
let allow_subagent = agent.tools.iter().any(|t| t == "subagent") && depth + 1 < max_depth;
let mut names: Vec<String> = if agent.tools.is_empty() {
all_tool_names()
.iter()
.copied()
.filter(|n| {
tools::is_core_tool(n)
&& !matches!(
*n,
"bash"
| "write_file"
| "write"
| "edit"
| "patch"
| "delete"
| "rename"
| "mkdir"
| "subagent"
| "task"
| "hub"
| "todo"
| "todo_write"
| "spawn"
| "load_tools"
)
})
.map(|s| s.to_string())
.collect()
} else {
let mut acc: Vec<String> = Vec::new();
for t in &agent.tools {
let n = AgentConfig::normalize_tool(t);
let expanded = crate::deferred_tools::expand_tool_request(n);
if expanded.len() == 1 && expanded[0] == n {
if n == "subagent" && !allow_subagent {
continue;
}
acc.push(n.to_string());
} else {
for e in expanded {
if e != "goal_write_plan" {
acc.push(e);
}
}
}
}
acc.sort();
acc.dedup();
acc
};
if bridge {
for t in ["contact_supervisor", "intercom"] {
if !names.iter().any(|n| n == t) {
names.push(t.to_string());
}
}
}
if allow_subagent && !names.iter().any(|n| n == "subagent") {
names.push("subagent".into());
}
if !names.iter().any(|n| n == "finish") {
names.push("finish".into());
}
if !names.iter().any(|n| n == "load_tools") {
names.push("load_tools".into());
}
let has_hub = tools::definitions()
.iter()
.any(|d| d.get("function").and_then(|f| f.get("name")) == Some(&json!("hub")));
let aliases = [
("read_file", "read"),
("write_file", "write"),
("todo_write", "todo"),
("subagent", "task"),
];
for (source, alias) in aliases {
if names.iter().any(|n| n == source) && !names.iter().any(|n| n == alias) {
names.push(alias.to_string());
}
}
if has_hub
&& ["intercom", "process", "contact_supervisor"]
.iter()
.any(|source| names.iter().any(|n| n == source))
&& !names.iter().any(|n| n == "hub")
{
names.push("hub".into());
}
names.sort();
names.dedup();
names
}
/// Build the tool-definition list a subagent may call, applying the agent's
/// allowlist and the intercom bridge. `depth`/`max_depth` gate the `subagent`
/// tool (nested fanout only when allowed and below the depth cap).
/// When `plugin_manager` is provided, enabled plugin tools whose names appear
/// in the allowlist (or are not restricted) are merged — same as the main loop.
#[allow(dead_code)] // public API + tests; runtime uses with_plugins
pub fn subagent_tool_defs(
agent: &AgentConfig,
bridge: bool,
depth: u32,
max_depth: u32,
) -> Vec<Value> {
subagent_tool_defs_with_plugins(agent, bridge, depth, max_depth, None)
}
/// Like [`subagent_tool_defs`] but merges plugin-declared tools from `pm`.
pub fn subagent_tool_defs_with_plugins(
agent: &AgentConfig,
bridge: bool,
depth: u32,
max_depth: u32,
pm: Option<&crate::plugins::PluginManager>,
) -> Vec<Value> {
let all = tools::definitions();
let by_name: HashMap<&str, &Value> = all
.iter()
.map(|d| {
(
d.get("function")
.and_then(|f| f.get("name"))
.and_then(|v| v.as_str())
.unwrap_or(""),
d,
)
})
.collect();
let names = subagent_allowed_names(agent, bridge, depth, max_depth);
let disabled: std::collections::HashSet<String> =
pm.map(|p| p.disabled_tools()).unwrap_or_default();
let mut defs: Vec<Value> = names
.iter()
.filter(|n| !disabled.contains(n.as_str()))
.filter_map(|n| by_name.get(n.as_str()).map(|v| (*v).clone()))
.collect();
// Merge plugin tools: include if allowlist is empty-default (RO core only
// would have no plugin names) OR name is explicitly listed, OR agent listed
// a wildcard-ish "*" — we treat explicit listing only. Also include plugin
// tools when the agent tools list contains the plugin tool name.
if let Some(pm) = pm {
let name_set: std::collections::HashSet<&str> = names.iter().map(|s| s.as_str()).collect();
let mut reserved: std::collections::HashSet<String> = defs
.iter()
.filter_map(|d| {
d.get("function")
.and_then(|f| f.get("name"))
.and_then(|v| v.as_str())
.map(String::from)
})
.collect();
for d in pm.tool_definitions() {
let n = d
.get("function")
.and_then(|f| f.get("name"))
.and_then(|v| v.as_str())