-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtools.rs
More file actions
6829 lines (6518 loc) · 256 KB
/
Copy pathtools.rs
File metadata and controls
6829 lines (6518 loc) · 256 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
// Built-in tools the agent can call. OpenAI function-calling schema.
// All file ops are confined to the workspace root; bash runs with cwd=workspace
// and a real timeout+kill. read_file returns plain content (optional N|hash| gutter);
// edit uses search/replace, optionally pinned by an 8-char line hash (`anchor`).
use crate::config::{Approval, Config};
use crate::tooling::builtin::git::{
git_add, git_branch, git_commit, git_diff, git_log, git_pull, git_push, git_show, git_status,
workspace_activity,
};
use crate::tooling::builtin::memory::{knowledge_tool, memory_tool};
use crate::workspace;
use serde_json::{json, Value};
pub use crate::fetch_tool::execute_fetch;
pub use crate::search_tool::execute_web_search;
pub use crate::test_env::execute_test_env;
/// Read a bounded resource through the core unified reader. Workspace paths
/// retain the exact paging semantics of `read_file`; every other supported
/// scheme is resolved by its owned store rather than passed to a shell.
pub async fn execute_unified_read(
args: &Value,
cfg: &Config,
session_file: Option<&std::path::Path>,
) -> Outcome {
let Some(uri) = args
.get("path")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
else {
return Outcome::err("read requires string field 'path'");
};
if uri.starts_with("http://") || uri.starts_with("https://") {
return crate::fetch_tool::execute_fetch(&json!({"url": uri}), cfg).await;
}
read_non_http(uri, args, cfg, session_file)
}
pub fn kind_for_read_args(args: &Value) -> ToolKind {
if args
.get("path")
.and_then(Value::as_str)
.is_some_and(|path| {
path.starts_with("http://")
|| path.starts_with("https://")
|| path.starts_with("issue://")
|| path.starts_with("pr://")
})
{
ToolKind::Destructive
} else {
ToolKind::ReadOnly
}
}
fn read_non_http(
uri: &str,
args: &Value,
cfg: &Config,
session_file: Option<&std::path::Path>,
) -> Outcome {
const ARCHIVE_ENTRY_MAX: u64 = 2 * 1024 * 1024;
const ARCHIVE_MAX_ENTRIES: usize = 256;
if uri.starts_with("skill://") {
let resolver =
crate::skills::configured(&cfg.workspace, crate::config::home_dir().as_deref());
if let Ok(body) = resolver.read(uri) {
return Outcome::ok(body);
}
if let Ok((name, rel)) = crate::skills::split_skill_uri(uri) {
if rel.is_empty() {
for rel_path in [
format!(".catalyst-code/skills/{name}/SKILL.md"),
format!(".omp/skills/{name}/SKILL.md"),
] {
let candidate = cfg.workspace.join(&rel_path);
if let Ok(body) = std::fs::read_to_string(&candidate) {
return Outcome::ok(body);
}
}
return crate::subagent::discover_skills_full(&cfg.workspace)
.into_iter()
.find(|skill| skill.name == name)
.map(|skill| Outcome::ok(skill.body))
.or_else(|| {
crate::harness_docs::embedded_skill_body(&name)
.map(|body| Outcome::ok(body.to_string()))
})
.unwrap_or_else(|| {
Outcome::err(format!("read: skill '{name}' was not found"))
});
} else if let Some(body) = crate::harness_docs::embedded_skill_path(&name, &rel) {
return Outcome::ok(body.to_string());
}
}
return Outcome::err(format!("read: skill URI '{uri}' was not found"));
}
if let Some(id) = uri.strip_prefix("memory://") {
if id.is_empty() || id.contains('/') || id.contains('\\') || id.contains("..") {
return Outcome::err("read: unsafe memory URI");
}
return crate::memory::get_memory(&cfg.workspace, id)
.map(|memory| Outcome::ok(memory.content))
.unwrap_or_else(|e| Outcome::err(format!("read: memory '{id}' unavailable: {e}")));
}
if uri == "rule://" || uri.starts_with("rule://") {
return read_rule_uri(uri, cfg);
}
if let Some(rest) = uri.strip_prefix("agent://") {
return read_agent_or_history_uri("agent", rest, cfg, session_file);
}
if let Some(rest) = uri.strip_prefix("history://") {
return read_agent_or_history_uri("history", rest, cfg, session_file);
}
if let Some(rest) = uri.strip_prefix("issue://") {
return read_github_ref("issue", rest);
}
if let Some(rest) = uri.strip_prefix("pr://") {
return read_github_ref("pr", rest);
}
if let Some(name) = uri.strip_prefix("local://") {
if name.is_empty()
|| name.starts_with('/')
|| name.contains('\\')
|| name.split('/').any(|part| part.is_empty() || part == "..")
{
return Outcome::err("read: unsafe local URI");
}
let rel = format!(".catalyst-code/local/{name}");
return read_file(&rel, args, cfg);
}
if let Some(run_id) = uri.strip_prefix("artifact://") {
if run_id.is_empty()
|| run_id.len() > 128
|| !run_id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
{
return Outcome::err("read: unsafe artifact URI");
}
let Some(session_file) = session_file else {
return Outcome::err(
"read: artifact resolution is unavailable outside an owned session",
);
};
return crate::session::read_job_artifact(session_file, run_id)
.map(|artifact| {
Outcome::ok(smart_truncate(
&artifact.to_string(),
cfg.max_read_bytes as usize,
))
})
.unwrap_or_else(|| {
Outcome::err(format!("read: owned artifact '{run_id}' was not found"))
});
}
if let Some((archive, entry)) = split_archive_entry(uri) {
if entry.is_empty()
|| entry.starts_with('/')
|| entry.contains('\\')
|| entry.split('/').any(|part| part == "..")
{
return Outcome::err("read: unsafe archive entry path");
}
let archive_path = match resolve_ws(cfg, archive) {
Ok(path) => path,
Err(e) => return Outcome::err(e),
};
let file = match std::fs::File::open(&archive_path) {
Ok(file) => file,
Err(e) => return Outcome::err(format!("read: archive {archive:?} failed: {e}")),
};
let mut zip = match zip::ZipArchive::new(file) {
Ok(zip) => zip,
Err(e) => {
return Outcome::err(format!(
"read: {archive:?} is not a supported zip archive: {e}"
))
}
};
if zip.len() > ARCHIVE_MAX_ENTRIES {
return Outcome::err(format!(
"read: archive has {} entries (max {ARCHIVE_MAX_ENTRIES})",
zip.len()
));
}
let mut member = match zip.by_name(entry) {
Ok(member) => member,
Err(_) => return Outcome::err(format!("read: archive entry {entry:?} was not found")),
};
if member.is_dir()
|| member.size() > ARCHIVE_ENTRY_MAX
|| member.size() > cfg.max_read_bytes
{
return Outcome::err(format!(
"read: archive entry exceeds {} byte limit",
ARCHIVE_ENTRY_MAX.min(cfg.max_read_bytes)
));
}
use std::io::Read;
let mut body = String::with_capacity(member.size() as usize);
if let Err(e) = member.read_to_string(&mut body) {
return Outcome::err(format!("read: archive entry is not UTF-8 text: {e}"));
}
return Outcome::ok(body);
}
if uri.starts_with("omp://") || uri.starts_with("catcode://") {
return read_harness_docs_uri(uri);
}
read_file(uri, args, cfg)
}
fn read_harness_docs_uri(uri: &str) -> Outcome {
match crate::harness_docs::read_uri(uri) {
Ok(body) => Outcome::ok(body),
Err(e) => Outcome::err(e),
}
}
fn is_archive_name(path: &str) -> bool {
let lower = path.to_ascii_lowercase();
lower.ends_with(".zip")
|| lower.ends_with(".jar")
|| lower.ends_with(".war")
|| lower.ends_with(".ear")
|| lower.ends_with(".apk")
}
fn split_archive_entry(uri: &str) -> Option<(&str, &str)> {
if let Some((archive, entry)) = uri.split_once("!/") {
return Some((archive, entry));
}
let idx = uri.rfind(':')?;
if idx == 0 {
return None;
}
let archive = &uri[..idx];
let entry = &uri[idx + 1..];
if !is_archive_name(archive) || entry.is_empty() {
return None;
}
if crate::read_summary::split_path_and_sel(uri).1.is_some() && !entry.contains('/') {
// `foo.zip:50-80` is a line selector, not an archive member.
return None;
}
Some((archive, entry))
}
fn read_rule_uri(uri: &str, cfg: &Config) -> Outcome {
let rest = uri.strip_prefix("rule://").unwrap_or("");
let name = rest.trim_matches('/');
if name.contains("..") || name.contains('\\') {
return Outcome::err("read: unsafe rule URI");
}
let mut candidates = Vec::new();
if let Some(omp) = crate::project_guidance::nearest_omp_dir(&cfg.workspace) {
if name.is_empty() || name.eq_ignore_ascii_case("RULES.md") {
candidates.push(omp.join("RULES.md"));
} else {
candidates.push(omp.join(name));
candidates.push(omp.join("rules").join(name));
if !name.ends_with(".md") {
candidates.push(omp.join(format!("{name}.md")));
candidates.push(omp.join("rules").join(format!("{name}.md")));
}
}
}
candidates.push(cfg.workspace.join(".catalyst-code/RULES.md"));
candidates.push(cfg.workspace.join(".omp/RULES.md"));
for path in candidates {
if let Ok(body) = std::fs::read_to_string(&path) {
return Outcome::ok(body);
}
}
Outcome::err("read: no sticky RULES.md found")
}
fn read_agent_or_history_uri(
kind: &str,
rest: &str,
cfg: &Config,
session_file: Option<&std::path::Path>,
) -> Outcome {
let id = rest.split(['/', '?', '#']).next().unwrap_or(rest).trim();
if id.is_empty()
|| id.len() > 128
|| !id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.')
{
return Outcome::err(format!("read: unsafe {kind} URI"));
}
if let Some(session_file) = session_file {
if let Some(artifact) = crate::session::read_job_artifact(session_file, id) {
return Outcome::ok(smart_truncate(
&artifact.to_string(),
cfg.max_read_bytes as usize,
));
}
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
if let Some(parked) = crate::session::load_parked_agents(session_file, now)
.into_iter()
.find(|a| a.run_id == id || a.target == id || a.agent == id)
{
let role = |m: &crate::message::Message| {
if m.is_assistant() {
"assistant"
} else if m.is_user() {
"user"
} else if m.is_system() {
"system"
} else {
"tool"
}
};
let body = if kind == "history" {
parked
.messages
.iter()
.filter_map(|m| m.content_text().map(|t| format!("{}: {t}", role(m))))
.collect::<Vec<_>>()
.join("\n\n")
} else {
parked
.messages
.iter()
.rev()
.find(|m| m.is_assistant())
.and_then(|m| m.content_text())
.unwrap_or("(no output)")
.to_string()
};
return Outcome::ok(smart_truncate(&body, cfg.max_read_bytes as usize));
}
}
Outcome::err(format!("read: {kind}://{id} was not found"))
}
fn read_github_ref(kind: &str, spec: &str) -> Outcome {
let spec = spec.trim_matches('/');
if spec.is_empty() || spec.contains("..") || spec.contains('\\') {
return Outcome::err(format!("read: unsafe {kind} URI"));
}
let parts: Vec<&str> = spec.split('/').collect();
let (repo, number) = match parts.as_slice() {
[number] => (None, *number),
[owner, repo, number] => (Some(format!("{owner}/{repo}")), *number),
_ => return Outcome::err(format!("read: {kind}:// expects N or owner/repo/N")),
};
if !number.bytes().all(|b| b.is_ascii_digit()) {
return Outcome::err(format!("read: {kind} number must be digits"));
}
let mut cmd = std::process::Command::new("gh");
cmd.arg(kind)
.arg("view")
.arg(number)
.args(["--json", "title,body,state,url,author,number"]);
if let Some(repo) = repo {
cmd.args(["--repo", &repo]);
}
match cmd.output() {
Ok(output) if output.status.success() => {
Outcome::ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
Ok(output) => Outcome::err(format!(
"read: gh {kind} view failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
)),
Err(error) => Outcome::err(format!("read: gh is unavailable ({error})")),
}
}
/// Description shown to the model for the `bash` tool. OS-selected so the
/// model emits matching syntax: PowerShell on Windows, bash on Unix. The
/// Model-facing description of the `bash` tool. When sandboxing is enabled the
/// guest is always Linux `bash`, so Windows users are no longer told to emit
/// PowerShell. Delegates to the sandbox policy (single source of truth).
pub(crate) fn bash_tool_desc() -> &'static str {
crate::sandbox::policy::bash_tool_description()
}
/// One-shot replaceability hint appended to bash tool results when the command
/// is a pure reimplementation of a native tool (session audit 2026-08: ~25% of
/// bash calls). Advisory only — never blocks execution.
pub fn bash_native_tool_hint(command: &str) -> Option<String> {
let mut s = command.trim();
if s.is_empty() {
return None;
}
// Drop leading comment-only lines.
loop {
let Some(first) = s.lines().next() else {
break;
};
let t = first.trim();
if t.is_empty() || t.starts_with('#') {
s = s[first.len()..]
.trim_start_matches(['\r', '\n'])
.trim_start();
continue;
}
break;
}
// Strip leading `cd <dir> &&` / `cd <dir>;` chains (common habit).
for _ in 0..5 {
let bytes = s.as_bytes();
if bytes.len() < 4 || &bytes[..3] != b"cd " {
break;
}
// Find end of cd argument then separator.
let rest = &s[3..];
// Skip optional quotes roughly by taking until whitespace/;&|.
let end = if rest.starts_with('\'') || rest.starts_with('"') {
let q = rest.as_bytes()[0];
if let Some(i) = rest.as_bytes().iter().skip(1).position(|&b| b == q) {
i + 2
} else {
break;
}
} else {
rest.find(|c: char| c.is_whitespace() || c == ';' || c == '&' || c == '|')
.unwrap_or(rest.len())
};
let after = rest[end..].trim_start();
if let Some(stripped) = after.strip_prefix("&&") {
s = stripped.trim_start();
continue;
}
if let Some(stripped) = after.strip_prefix(';') {
s = stripped.trim_start();
continue;
}
break;
}
let first_line = s.lines().next().unwrap_or(s).trim();
// First token
let tok = first_line.split_whitespace().next().unwrap_or("");
let tok = tok.rsplit('/').next().unwrap_or(tok);
let complex = first_line.contains('|')
&& !(first_line.matches('|').count() == 1
&& (first_line.contains("| head")
|| first_line.contains("|head")
|| first_line.contains("| wc")
|| first_line.contains("|wc")
|| first_line.contains("| tail")
|| first_line.contains("|tail")));
let chained = first_line.contains("&&") || first_line.contains("||");
let hint = match tok {
"git" => {
let sub = first_line.split_whitespace().nth(1).unwrap_or("");
match sub {
"status" if !chained => Some(
"Prefer the native `git_status` tool over bash `git status` (core, always available).",
),
"diff" if !chained => Some(
"Prefer the native `git_diff` tool over bash `git diff` (core). For a commit use `git_show`.",
),
"log" if !chained => Some(
"Prefer the native `git_log` tool over bash `git log` (core, always available).",
),
"show" if !chained => Some(
"Prefer the native `git_show` tool over bash `git show` (core, always available).",
),
"add" => Some(
"Prefer `load_tools` group `git` then `git_add` over bash `git add`.",
),
"commit" => Some(
"Prefer `load_tools` group `git` then `git_commit` over bash `git commit`.",
),
"push" => Some(
"Prefer `load_tools` group `git` then `git_push` over bash `git push`.",
),
"pull" => Some(
"Prefer `load_tools` group `git` then `git_pull` over bash `git pull`.",
),
"branch" | "switch" | "checkout" => Some(
"Prefer `load_tools` group `git` then `git_branch` over bash branch/switch/checkout.",
),
_ => None,
}
}
"rg" | "grep" if !complex => Some(
"Prefer the native `grep` tool over bash rg/grep (use head_limit/offset instead of `| head`/`| wc`).",
),
"find" if !complex && !chained => Some(
"Prefer the native `glob` tool over bash `find` for in-workspace file discovery.",
),
"ls" | "tree" if !complex && !chained => Some(
"Prefer the native `list_dir` tool over bash `ls` for workspace directories.",
),
"cat" | "head" | "tail" if !complex => Some(
"Prefer the native `read_file` tool (offset/limit) over bash cat/head/tail for workspace files.",
),
"sed" if first_line.contains("sed -n") || first_line.contains("sed -n") => Some(
"Prefer the native `read_file` tool with offset/limit over `sed -n 'A,Bp'`.",
),
"curl" | "wget"
if !first_line.contains(" -X ")
&& !first_line.contains("--data")
&& !first_line.contains(" -d ")
&& !first_line.contains(" -F ") =>
{
Some("Prefer the native `fetch` tool over bash curl/wget for simple HTTP GET.")
}
"nohup" | "pkill" | "kill" | "killall" | "ps" | "pgrep" => Some(
"Prefer the native `process` tool (load_tools process) over bash nohup/pkill/ps for app servers.",
),
"rm" | "mkdir" | "mv" | "cp" | "touch" if !complex && !chained => Some(
"Prefer native `delete`/`mkdir`/`rename`/`write_file` over bash file ops when in-workspace.",
),
_ => None,
}?;
Some(hint.to_string())
}
/// Oh My Pi: refuse bash that is a 1:1 reimplementation of a native tool.
/// Complex pipelines still run (hint-only).
pub fn bash_shadow_block(command: &str) -> Option<String> {
let hint = bash_native_tool_hint(command)?;
let first = command.trim().lines().next().unwrap_or("").trim();
let simple = !first.contains('|') && !first.contains("&&") && !first.contains("||");
if !simple {
return None;
}
let tok = first
.split_whitespace()
.next()
.unwrap_or("")
.rsplit('/')
.next()
.unwrap_or("");
match tok {
"rg" | "grep" | "find" | "ls" | "tree" | "cat" | "head" | "tail" | "sed" => Some(format!(
"blocked: {hint} Re-issue with the native tool (this bash form is a 1:1 shadow)."
)),
"git" => {
let sub = first.split_whitespace().nth(1).unwrap_or("");
matches!(sub, "status" | "diff" | "log" | "show")
.then(|| format!("blocked: {hint} Re-issue with the native git_* tool."))
}
_ => None,
}
}
pub use crate::tooling::policy::{
classify, is_parallel_wave_call, leading_parallel_wave_len, sequential_run_len,
};
pub use crate::tooling::scheduler::execute_parallel_wave;
pub use crate::tooling::ToolKind;
/// Map the built-in `mcp` surface args to a [`ToolKind`] for the approval gate.
/// Delegates to [`crate::mcp::surface_approval_class`] so remote `call` tools are
/// reclassified live (CORE_REVIEW Wave 5).
pub fn kind_for_mcp_args(args: &serde_json::Value) -> ToolKind {
match crate::mcp::surface_approval_class(args) {
crate::mcp::ApprovalClass::ReadOnly => ToolKind::ReadOnly,
crate::mcp::ApprovalClass::Mutating | crate::mcp::ApprovalClass::Destructive => {
ToolKind::Destructive
}
}
}
/// Internal sentinel returned by the `finish` tool. The orchestrator treats this
/// as loop exit; the UI/session see [`FINISH_MESSAGE`] instead.
pub const FINISH_SENTINEL: &str = "__finish__";
/// Human-readable tool_result shown when the agent calls `finish`.
pub const FINISH_MESSAGE: &str = "This turn has finished";
/// Tools always included in the main agent's request schema (cheap, high-use).
pub use crate::tooling::schema::{
deferred_tool_names, definitions, is_builtin, is_core_tool, is_deferred_tool,
};
/// Outcome of a tool call. For bash we need a future with timeout+kill, so
/// destructive/bash execution is split: execute() handles sync tools;
/// execute_bash() is async and takes a runtime handle.
#[derive(Clone)]
pub struct Outcome {
pub ok: bool,
pub output: String,
/// Optional unified-diff rendering of the change (edit/patch/write_file).
/// Surfaced to the TUI as a separate `diff` event field so the model's
/// tool-result content (output) stays compact — the diff is for humans.
pub diff: Option<String>,
}
/// Execute a (non-bash) tool call synchronously. `cfg` provides confinement+limits.
/// bash is handled separately by execute_bash (async, timeout+kill). Async dispatch
/// paths MUST intercept `read`/`read_file`; this fallback deliberately supports
/// non-HTTP resources only because a synchronous function cannot drive fetch.
pub fn execute(name: &str, args: &Value, cfg: &Config) -> Outcome {
let s = |k: &str| args.get(k).and_then(|v| v.as_str()).unwrap_or("");
match name {
"read_file" | "read" => {
let path = s("path");
if path.starts_with("http://") || path.starts_with("https://") {
Outcome::err("read: HTTP(S) requires an async dispatch path")
} else {
read_non_http(path, args, cfg, cfg.session_file.as_deref())
}
}
"todo_read" => todo_read(cfg),
"todo_write" => todo_write(args, cfg),
"todo" => todo_op(args, cfg),
// Sentinel stays internal; main.rs / subagent map it to a human-readable
// tool_result ("This turn has finished") before emitting to the UI.
"finish" => Outcome::ok(FINISH_SENTINEL),
"patch" => apply_patch(args, cfg),
"diagnostics" => Outcome::err("diagnostics must be dispatched through execute_diagnostics (async)"),
"fetch" => Outcome::err("fetch must be dispatched through execute_fetch (async)"),
"web_search" => Outcome::err("web_search must be dispatched through execute_web_search (async)"),
name if crate::browser::is_browser_tool(name) => Outcome::err("browser tools must be dispatched through execute_browser (async)"),
"spawn" | "subagent" | "task" => Outcome::err("subagent must be dispatched through execute_subagent (async)"),
"hub" => Outcome::err("hub must be dispatched through execute_hub (async)"),
"contact_supervisor" | "intercom" => Outcome::err("intercom tools must be dispatched through execute_intercom (async, subagent context only)"),
"ask" => Outcome::err("ask must be dispatched through request_ask (async, orchestrator loop only)"),
"load_tools" => Outcome::err(
"load_tools must be dispatched through handle_load_tools (orchestrator loop only)",
),
"edit" => {
if let Some(input) = args.get("input").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
crate::hashline::execute(input, cfg)
} else {
let path = s("path");
match args.get("edits").and_then(|v| v.as_array()) {
Some(e) if !e.is_empty() && !path.is_empty() => execute_edit(path, e, cfg),
_ => Outcome::err("edit requires either non-empty 'input' (hashline) or 'path' plus a non-empty 'edits' array"),
}
}
}
"write_file" | "write" => {
let path = s("path");
match require_string_arg(args, "content") {
Ok(content) => write_file(path, content, cfg),
Err(e) => Outcome::err(e),
}
}
"delete" => delete_path(s("path"), cfg),
"rename" => rename_path(s("from"), s("to"), cfg),
"mkdir" => mkdir_path(s("path"), cfg),
"list_dir" => list_dir(s("path"), cfg),
"grep" => grep(s("pattern"), args, cfg),
"glob" => glob(s("pattern"), cfg),
"bulk_read" => bulk_read(args, cfg),
"bulk_write" => bulk_write(args, cfg),
"bulk_edit" => bulk_edit(args, cfg),
"git_status" => git_status(args, cfg),
"git_diff" => git_diff(args, cfg),
"git_log" => git_log(args, cfg),
"git_show" => git_show(args, cfg),
"workspace_activity" => workspace_activity(args, cfg),
"git_add" => git_add(args, cfg),
"git_commit" => git_commit(args, cfg),
"git_push" => git_push(args, cfg),
"git_pull" => git_pull(args, cfg),
"git_branch" => git_branch(args, cfg),
"memory" => memory_tool(args, cfg),
"knowledge" => knowledge_tool(args, cfg),
"collections" => collections_tool(args, cfg),
"goal_write_plan" => Outcome::err(
"goal_write_plan must be dispatched through handle_goal_write_plan (async, goal mode only)",
),
"snapshot_edit" => crate::tooling::ide::execute_snapshot_edit(args, cfg),
"ast_edit" => Outcome::err("ast_edit must be dispatched asynchronously"),
"bulk" => Outcome::err("bulk must be dispatched through execute_bulk (async)"),
other => Outcome::err(format!("unknown tool: {other}")),
}
}
impl Outcome {
pub fn ok(msg: impl Into<String>) -> Self {
Self {
ok: true,
output: msg.into(),
diff: None,
}
}
pub fn err(msg: impl Into<String>) -> Self {
Self {
ok: false,
output: msg.into(),
diff: None,
}
}
}
/// Require a string argument key to be present. Null or non-string values fail.
/// Empty string is allowed when the key exists (explicit wipe).
fn require_string_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
match args.get(key) {
Some(Value::String(s)) => Ok(s.as_str()),
Some(_) => Err(format!("'{key}' must be a string")),
None => Err(format!("missing required '{key}'")),
}
}
// ---- file tools ----
/// Resolve a tool path against the workspace root. Approval::Never means
/// approval-free host access only when the host backend is active; an enabled
/// sandbox always preserves workspace confinement so file tools cannot bypass
/// the guest boundary and reach arbitrary host paths.
pub(crate) fn resolve_ws(cfg: &Config, input: &str) -> Result<std::path::PathBuf, String> {
if matches!(cfg.approval, Approval::Never) && !crate::sandbox::is_sandbox_enabled() {
workspace::resolve_unconfined(&cfg.workspace, input)
} else {
workspace::resolve(&cfg.workspace, input)
}
}
fn read_file(input: &str, args: &Value, cfg: &Config) -> Outcome {
let (path_part, path_sel) = crate::read_summary::split_path_and_sel(input);
let path = match resolve_ws(cfg, path_part) {
Ok(p) => p,
Err(e) => return Outcome::err(e),
};
let meta = match std::fs::metadata(&path) {
Ok(m) => m,
Err(e) => return Outcome::err(format!("read_file {input:?} failed: {e}")),
};
if meta.is_dir() {
return Outcome::ok(crate::read_summary::directory_tree(&path, path_part, 2, 12));
}
let mut offset = args.get("offset").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
let mut limit = args
.get("limit")
.and_then(|v| v.as_u64())
.map(|n| n as usize);
let multi_ranges = path_sel
.as_ref()
.map(|s| s.ranges.len() > 1)
.unwrap_or(false);
if !multi_ranges {
if let Some(sel) = path_sel.as_ref() {
if let Some((start, end)) = sel.ranges.first().copied() {
offset = start;
if let Some(e) = end {
limit = Some(e.saturating_sub(start).saturating_add(1));
}
}
}
}
let paging = offset > 0 || limit.is_some() || multi_ranges;
let raw = path_sel.as_ref().map(|s| s.raw).unwrap_or(false);
let conflicts = path_sel.as_ref().map(|s| s.conflicts).unwrap_or(false);
if meta.len() > cfg.max_read_bytes && !paging && !conflicts {
return Outcome::err(format!(
"read_file {input:?} is {} bytes (max {}); pass offset/limit or path:N-M to page, or use grep to slice it",
meta.len(),
cfg.max_read_bytes
));
}
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(e) => return Outcome::err(format!("read_file {input:?} failed: {e}")),
};
crate::file_snapshot::record(path_part, &content);
let (lines, _trailing) = split_lines(&content);
let line_numbers = args
.get("line_numbers")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if conflicts {
return Outcome::ok(render_conflict_index(path_part, &content, &lines));
}
if multi_ranges {
let mut out = format!(
"[{path_part}#{}]\n",
crate::read_summary::file_tag(&content)
);
for (start, end) in &path_sel.as_ref().unwrap().ranges {
let start_idx = start.saturating_sub(1).min(lines.len());
let end_idx = match end {
Some(e) => (*e).min(lines.len()),
None => lines.len(),
};
if end_idx < start_idx {
continue;
}
if end_idx.saturating_sub(start_idx) > cfg.max_read_lines {
return Outcome::err(format!(
"read_file {input:?} window is {} lines (max {}); pass a smaller range",
end_idx.saturating_sub(start_idx),
cfg.max_read_lines
));
}
out.push_str(&format!(
"# {path_part} lines {}-{} of {}\n",
start_idx + 1,
end_idx,
lines.len()
));
format_read_lines(
&mut out,
&lines[start_idx..end_idx],
start_idx,
line_numbers && !raw,
);
}
return Outcome::ok(out);
}
// Oh My Pi: bare read of parseable source → structural summary, not a dump.
if !raw && !paging && offset == 0 && limit.is_none() {
if let Some(summary) = crate::read_summary::structural_summary(path_part, &content) {
return Outcome::ok(summary);
}
}
const AUTO_WINDOW: usize = 200;
let auto_window = !raw && offset == 0 && limit.is_none() && lines.len() > AUTO_WINDOW;
if offset > 0 || limit.is_some() || auto_window {
let start = if auto_window {
0
} else {
offset.saturating_sub(1).min(lines.len())
};
let end = if auto_window {
AUTO_WINDOW.min(lines.len())
} else {
match limit {
Some(n) => start.saturating_add(n).min(lines.len()),
None => lines.len(),
}
};
if !auto_window && end - start > cfg.max_read_lines {
return Outcome::err(format!(
"read_file {input:?} window is {} lines (max {}); pass a smaller limit",
end - start,
cfg.max_read_lines
));
}
let window = &lines[start..end];
let mut out = format!(
"[{path_part}#{}]\n",
crate::read_summary::file_tag(&content)
);
if auto_window {
out.push_str(&format!(
"# {path_part} lines 1-{end} of {} (auto-windowed; pass offset/limit or path:N-M to page)\n",
lines.len()
));
let outline = crate::codebase_index::file_outline(path_part, &content, 40);
if !outline.is_empty() {
out.push_str(&outline);
}
} else {
out.push_str(&format!(
"# {path_part} lines {}-{} of {}\n",
start + 1,
end,
lines.len()
));
}
format_read_lines(&mut out, window, start, line_numbers && !raw);
return Outcome::ok(out);
}
if lines.len() > cfg.max_read_lines {
return Outcome::err(format!(
"read_file {input:?} has {} lines (max {}); pass offset/limit or path:N-M to page it",
lines.len(),
cfg.max_read_lines
));
}
if line_numbers && !raw {
let mut out = format!(
"[{path_part}#{}]\n",
crate::read_summary::file_tag(&content)
);
format_read_lines(&mut out, &lines, 0, true);
return Outcome::ok(out);
}
Outcome::ok(content)
}
fn render_conflict_index(rel: &str, content: &str, lines: &[String]) -> String {
let mut regions: Vec<(usize, usize)> = Vec::new();
let mut start: Option<usize> = None;
for (i, line) in lines.iter().enumerate() {
if line.starts_with("<<<<<<<") {
start = Some(i);
} else if line.starts_with(">>>>>>>") {
if let Some(s) = start.take() {
regions.push((s + 1, i + 1));
}
}
}
let mut out = format!("[{rel}#{}]\n", crate::read_summary::file_tag(content));
if regions.is_empty() {
out.push_str("# no unresolved conflict markers\n");
return out;
}
out.push_str(&format!("# {} conflict region(s)\n", regions.len()));
for (n, (a, b)) in regions.iter().enumerate() {
out.push_str(&format!("#{n} L{a}-{b} {rel}:{a}-{b}\n"));
}
out
}
/// 8-char FNV-1a of a source line (no trailing newline). Stable pin for
/// `edit.anchor` so a drifted search still lands on the same line.
pub(crate) fn line_content_hash(line: &str) -> String {
let mut h: u64 = 0xcbf29ce484222325;
for &b in line.as_bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x100000001b3);
}
format!("{h:016x}")[..8].to_string()
}
/// Pull an 8-char hex hash out of an `anchor` field or a copied
/// `N|hhhhhhhh|…` / `N|hhhhhhhh` gutter prefix.
fn parse_line_anchor(raw: &str) -> Option<String> {
let t = raw.trim();
if t.len() == 8 && t.bytes().all(|b| b.is_ascii_hexdigit()) {
return Some(t.to_ascii_lowercase());
}
// `12|deadbeef|fn main` or `12|deadbeef` (model copied the gutter).
let mut parts = t.splitn(3, '|');
let _lineno = parts.next()?;
let hash = parts.next()?.trim();
if hash.len() == 8 && hash.bytes().all(|b| b.is_ascii_hexdigit()) {
return Some(hash.to_ascii_lowercase());
}
None
}
/// Strip a leading `N|` or `N|hhhhhhhh|` gutter the model may have copied
/// from a line_numbers read. Returns (maybe_hash, remainder).
fn strip_edit_gutter(search: &str) -> (Option<String>, &str) {
let bytes = search.as_bytes();
let mut i = 0usize;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
if i == 0 || i >= bytes.len() || bytes[i] != b'|' {
return (None, search);
}
let rest = &search[i + 1..];
if rest.len() >= 9 {
let hash = &rest[..8];
if hash.bytes().all(|b| b.is_ascii_hexdigit()) && rest.as_bytes()[8] == b'|' {
return (Some(hash.to_ascii_lowercase()), &rest[9..]);
}
}
(None, rest)
}
/// Byte ranges of whole lines whose content hash equals `hash`.
fn find_lines_by_hash(content: &str, hash: &str) -> Vec<(usize, usize)> {
let want = hash.to_ascii_lowercase();
let mut out = Vec::new();
let mut offset = 0usize;
for line in content.split_inclusive('\n') {
let body = line.strip_suffix('\n').unwrap_or(line);
let body = body.strip_suffix('\r').unwrap_or(body);
if line_content_hash(body) == want {
// Exclude the trailing newline so a stale-search fallback
// replaces the line body, not the line break ("TWO" stays
// "TWO\nthree", not "TWOthree").
out.push((offset, offset + body.len()));
}
offset += line.len();
}
out
}
fn format_read_lines(out: &mut String, lines: &[String], start_idx: usize, line_numbers: bool) {
if line_numbers {
let width = ((start_idx + lines.len()).max(1).ilog10() as usize) + 1;
for (i, l) in lines.iter().enumerate() {
let n = start_idx + i + 1;
let hash = line_content_hash(l);
out.push_str(&format!("{n:>width$}|{hash}|{l}\n"));
}
} else {
for l in lines {
out.push_str(l);
out.push('\n');
}
}
}
/// Atomically write `content` to `path`: unique sibling temp, fsync, rename.
/// Uses [`crate::fsutil::atomic_write_str`] so concurrent writers (two sessions,
/// bulk+edit) never collide on a fixed `*.catalyst-code-tmp` name.
pub(crate) fn atomic_write_file(path: &std::path::Path, content: &str) -> std::io::Result<()> {
crate::fsutil::atomic_write_str(path, content)