-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmod.rs
More file actions
7143 lines (6699 loc) · 283 KB
/
Copy pathmod.rs
File metadata and controls
7143 lines (6699 loc) · 283 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
use async_trait::async_trait;
use regex::Regex;
use serde::Serialize;
use serde_json::Value;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex, OnceLock};
use tokio::sync::mpsc;
mod budget;
pub mod compaction;
mod doom_loop;
pub mod registry;
mod subagent;
pub use registry::AgentRegistry;
pub use subagent::SubagentHarness;
use crate::clarification::ClarificationHub;
use crate::tool_runtime::{with_tool_exec_and_progress_scope, ToolExecCtx, ToolProgressEmitter};
use self::budget::{
tool_intent_signature, typed_failure_key, BudgetController, BudgetDecision, BudgetLimits,
ProgressKind,
};
use crate::bus::{
BusMessage, InboundMessage, LogEvent, OutboundMessage, RunBudgetSnapshot, RunFailureKind,
RunLifecycleEvent, RunOutcome, RunStuckReason, TelemetryEvent, METADATA_RUN_ID,
};
use crate::config::{ResolvedShellPolicy, ShellPolicyMode};
use crate::hooks::{
run_post_tool_hooks, run_pre_tool_hooks, run_user_prompt_hooks, HookObservationMeta,
HookSessionInfo, PreToolOutcome, ToolCallHookContext, UserPromptHookOutcome,
};
use crate::logging::LoggerHandle;
use crate::memory::{MemoryMessage, SharedReply, TodoRow};
use crate::session::SessionManager;
use crate::skills::{SharedSkillRegistry, SkillRegistry};
use crate::tool_activity::SharedToolExecutionActivity;
use crate::tools::ToolRegistry;
use crate::traits::{Memory, Provider, Tool, ToolErrorCode, ToolResult};
use crate::NodeHandle;
use crate::{ActorError, ActorLogic};
use futures::{future::join_all, FutureExt};
use std::panic::AssertUnwindSafe;
static REDACTED_THINKING_STRIP_RE: OnceLock<Regex> = OnceLock::new();
async fn load_harness_todos_for_step(
memory: &NodeHandle<MemoryMessage>,
chat_id: &str,
) -> Option<Vec<TodoRow>> {
let (tx, rx) = tokio::sync::oneshot::channel();
memory
.send_packet(MemoryMessage::LoadHarnessTodos {
chat_id: chat_id.to_string(),
reply: SharedReply::new(tx),
})
.await
.ok()?;
rx.await.ok()?.ok().flatten()
}
fn format_harness_todos_step_block(rows: &[TodoRow]) -> String {
let mut s = String::from("\n\n--- Harness todos (this step) ---\n");
for (i, row) in rows.iter().enumerate() {
let icon = match row.status.as_str() {
"completed" => "[x]",
"in_progress" => "[~]",
_ => "[ ]",
};
s.push_str(&format!("{}. {} {}\n", i + 1, icon, row.content));
}
s
}
async fn persist_terminal_assistant_message(
mem: &mut impl Memory,
logger_tx: &LoggerHandle,
name: &str,
chat_id: &str,
text: &str,
) {
if let Err(e) = mem
.add_message(crate::utils::ChatMessage::assistant(text))
.await
{
let _ = logger_tx.send(BusMessage::Log(
LogEvent::warn(
name,
&format!("Failed to persist terminal assistant message: {}", e),
)
.with_chat_id(chat_id),
));
}
}
fn metadata_truthy(meta: &HashMap<String, serde_json::Value>, key: &str) -> bool {
meta.get(key)
.map(|v| {
v.as_bool().unwrap_or(false)
|| v.as_str()
.map(|s| s.eq_ignore_ascii_case("true") || s == "1")
.unwrap_or(false)
})
.unwrap_or(false)
}
fn ensure_run_id(inbound: &mut InboundMessage) -> Result<String, String> {
if let Some(run_id) = inbound
.metadata
.get(METADATA_RUN_ID)
.and_then(|value| value.as_str())
.map(str::trim)
.filter(|run_id| !run_id.is_empty())
{
return Ok(run_id.to_string());
}
if inbound.channel.eq_ignore_ascii_case("tauri") {
return Err("Tauri inbound messages require a non-empty isanagent_run_id".to_string());
}
let run_id = format!("legacy-{}", uuid::Uuid::new_v4());
inbound.metadata.insert(
METADATA_RUN_ID.to_string(),
serde_json::Value::String(run_id.clone()),
);
Ok(run_id)
}
fn text_looks_like_research_request(content: &str) -> bool {
static RESEARCH_REQUEST_RE: OnceLock<Option<Regex>> = OnceLock::new();
RESEARCH_REQUEST_RE
.get_or_init(|| {
Regex::new(
r"(?ix)
\b(?:
research(?:er|ers|ing|ed)? |
literature |
papers? |
state[-\s]+of[-\s]+the[-\s]+art |
surveys? |
arxiv |
evidence |
cite |
compare\s+methods
)\b",
)
.ok()
})
.as_ref()
.is_some_and(|regex| regex.is_match(content))
}
fn context_has_tool_call(context: &[crate::utils::ChatMessage], tool_name: &str) -> bool {
context.iter().any(|msg| {
msg.tool_calls.as_ref().is_some_and(|calls| {
calls
.iter()
.any(|tc| tc.function.name.eq_ignore_ascii_case(tool_name))
})
})
}
/// Default context token budget (conservative for most models).
/// Uses char_count / 4 as the token estimate (same heuristic as compaction logic).
const MAX_CONTEXT_TOKENS_DEFAULT: usize = 120_000;
/// After this many *consecutive* doom-loop detections, stop nudging and terminate the run with a
/// "stuck" message. Detection itself already requires 3 repeated calls, so this gives the model
/// two corrective nudges before a hard stop rather than letting it spin to `max_iterations`.
const DOOM_LOOP_HARD_STOP_AFTER: usize = 3;
/// Approximate token count for one message: text content **plus** tool_call argument bytes, /4.
/// Counting tool_call args matters for tool-heavy turns — omitting them under-counts the context
/// and lets the compaction threshold fire late. Shared by context trimming and the
/// auto-compaction threshold so both estimate consistently.
fn estimate_message_tokens(msg: &crate::utils::ChatMessage) -> usize {
let text_len = msg.content.as_ref().map_or(0, |c| c.text_content().len());
let args_len = msg.tool_calls.as_ref().map_or(0, |tcs| {
tcs.iter()
.map(|t| t.function.arguments.len())
.sum::<usize>()
});
(text_len + args_len) / 4
}
/// Approximate token count for a whole context (sum of [`estimate_message_tokens`]).
fn estimate_context_tokens(context: &[crate::utils::ChatMessage]) -> usize {
context.iter().map(estimate_message_tokens).sum()
}
/// Best available context-size estimate for the compaction trigger: the larger of the bytes/4
/// heuristic and the last LLM call's exact `usage.prompt_tokens`. The heuristic under-counts the
/// code/JSON/non-English payloads this agent produces, while `prompt_tokens` is the provider's
/// ground-truth input count — so the max guards against silently overflowing the context window.
fn effective_context_tokens(estimate: usize, last_prompt_tokens: Option<u32>) -> usize {
estimate.max(last_prompt_tokens.unwrap_or(0) as usize)
}
/// Trim context from the front (oldest messages) to stay within a token budget.
/// Preserves the system message at index 0 and never splits tool_call/tool pairs.
/// A marker message is inserted only when messages were actually removed.
fn trim_context_to_budget(context: &mut Vec<crate::utils::ChatMessage>, max_tokens: usize) {
// Token estimation heuristic: 1 token ≈ 4 characters for English text (text + tool_call args).
let estimate_msg_tokens = estimate_message_tokens;
// Quick check: under budget or too small to trim
if context.len() <= 2 {
return;
}
let total: usize = context.iter().map(&estimate_msg_tokens).sum();
if total <= max_tokens {
return;
}
// Always remove from index 1 (after system message).
// Tool call/response pairs are removed atomically.
// Track remaining tokens to avoid O(N^2) re-computation.
let mut remaining = total;
let trim_pos: usize = 1;
let mut trimmed = false;
while remaining > max_tokens && trim_pos + 1 < context.len() {
if context[trim_pos].role == "assistant" && context[trim_pos].tool_calls.is_some() {
// Find the end of the tool response block
let mut block_end = trim_pos + 1;
while block_end < context.len() && context[block_end].role == "tool" {
block_end += 1;
}
// Subtract the tokens for this entire block
for msg in context[trim_pos..block_end].iter() {
remaining = remaining.saturating_sub(estimate_msg_tokens(msg));
}
context.drain(trim_pos..block_end);
trimmed = true;
} else {
remaining = remaining.saturating_sub(estimate_msg_tokens(&context[trim_pos]));
context.remove(trim_pos);
trimmed = true;
}
}
// Only insert marker when we actually removed something
if trimmed {
context.insert(
1,
crate::utils::ChatMessage::user(
"[Earlier conversation messages were trimmed to fit context window]",
),
);
}
}
/// Repair context so every assistant message with `tool_calls` is followed by a tool-role
/// response for each `tool_call_id`. This prevents 400 errors from strict providers (e.g.
/// DeepSeek) when a previous reasoning loop was cancelled mid-tool-execution, leaving
/// orphaned assistant messages in memory without their corresponding tool responses.
fn repair_tool_call_context(context: &mut Vec<crate::utils::ChatMessage>) {
let mut i = 0;
while i < context.len() {
// A tool result without an immediately preceding assistant tool-call
// block is invalid for strict providers. It can be left behind by
// legacy/corrupt history, so discard it before context trimming.
if context[i].role == "tool" {
context.remove(i);
continue;
}
let tool_call_ids: Vec<String> = match &context[i].tool_calls {
Some(calls) if context[i].role == "assistant" && !calls.is_empty() => {
calls.iter().map(|tc| tc.id.clone()).collect()
}
_ => {
i += 1;
continue;
}
};
// Keep at most one response for each requested id. Mismatched,
// id-less, and duplicate tool rows are orphaned protocol records and
// would make strict providers reject the whole request.
let requested: HashSet<String> = tool_call_ids.iter().cloned().collect();
let mut responded: HashSet<String> = HashSet::new();
let mut j = i + 1;
while j < context.len() && context[j].role == "tool" {
let keep = context[j]
.tool_call_id
.as_deref()
.is_some_and(|id| requested.contains(id) && responded.insert(id.to_string()));
if keep {
j += 1;
} else {
context.remove(j);
}
}
// Append placeholder tool responses for any missing tool_call_ids at end of tool block
let missing: Vec<String> = tool_call_ids
.into_iter()
.filter(|id| !responded.contains(id))
.collect();
for id in missing {
context.insert(
j,
crate::utils::ChatMessage::tool(
"[Cancelled — tool execution interrupted]",
&id,
None,
),
);
j += 1;
}
i = j;
}
}
fn should_nudge_research_depth(
inbound: &crate::bus::InboundMessage,
context: &[crate::utils::ChatMessage],
) -> bool {
if !text_looks_like_research_request(&inbound.content) {
return false;
}
let searched = context_has_tool_call(context, "web_search")
|| context_has_tool_call(context, "arxiv_search");
if !searched {
return false;
}
let has_deep_source_reads = context_has_tool_call(context, "web_fetch")
|| context_has_tool_call(context, "arxiv_fetch")
|| context_has_tool_call(context, "hf_hub_file_fetch")
|| context_has_tool_call(context, "read_file");
!has_deep_source_reads
}
pub const WAIT_SIGNAL_PREFIX: &str = "ISANAGENT_WAIT_FOR_USER:";
pub const WAITING_FOR_USER_RESULT_PREFIX: &str = "WAITING:";
enum ToolExecutionFinished {
Completed(ToolResult),
Cancelled,
Waiting(String), // The ticket ID
}
impl ToolExecutionFinished {
fn error(code: ToolErrorCode, message: impl Into<String>) -> Self {
Self::Completed(ToolResult::error(code, message))
}
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
struct InvalidToolArguments {
error: InvalidToolArgumentsDetail,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
struct InvalidToolArgumentsDetail {
code: &'static str,
diagnostic: String,
}
impl InvalidToolArguments {
fn from_json_error(error: serde_json::Error) -> Self {
Self {
error: InvalidToolArgumentsDetail {
code: "invalid_tool_arguments",
diagnostic: format!(
"Malformed JSON at line {} column {} ({:?})",
error.line(),
error.column(),
error.classify()
),
},
}
}
fn to_tool_result(&self) -> ToolResult {
let content = serde_json::to_string(self).unwrap_or_else(|_| {
r#"{"error":{"code":"invalid_tool_arguments","diagnostic":"Malformed JSON"}}"#
.to_string()
});
ToolResult::error_with_content(
ToolErrorCode::InvalidToolArguments,
self.error.diagnostic.clone(),
content,
)
}
}
fn parse_tool_arguments(raw: &str) -> Result<Value, InvalidToolArguments> {
serde_json::from_str(raw).map_err(InvalidToolArguments::from_json_error)
}
fn extract_exec_command(args: &Value) -> Option<String> {
args.get("command")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Append post_tool verification-hook output (build/test/lint results) to a tool result, preserving
/// Ok/Err polarity so the model sees it alongside the tool's own output and can self-correct.
fn append_post_tool_output(mut result: ToolResult, hook_out: &str) -> ToolResult {
let note = format!("\n\n[post-tool hook]\n{hook_out}");
// `result` is owned, so append onto the existing buffer in place rather than allocating a
// fresh string and copying the (potentially large) tool output into it.
result.content.push_str(¬e);
result
}
/// Lowercase and collapse every run of whitespace (spaces, tabs, newlines) to a single space so a
/// destructive command can't slip past a single-spaced approval pattern via `rm -rf`, a tab, or a
/// mid-command line break.
fn normalize_command_for_matching(s: &str) -> String {
let lowercase = s.to_ascii_lowercase();
let mut result = String::with_capacity(lowercase.len());
let mut words = lowercase.split_whitespace();
if let Some(first) = words.next() {
result.push_str(first);
for word in words {
result.push(' ');
result.push_str(word);
}
}
result
}
fn should_require_shell_approval(command: &str, patterns: &[String]) -> bool {
// Pad with spaces so matching is on whole-word boundaries: a bare `.contains()` on the
// normalized command would let a pattern like `rm` match any command containing `terminal`,
// `platform`, `firmware`, `alarm`, `warm`, `harm`, etc. ("terminal".contains("rm") is true),
// forcing spurious approval prompts. Padding both sides keeps the whitespace-robustness (a
// run of spaces/tabs/newlines was already collapsed to one) while only matching real tokens.
let normalized = format!(" {} ", normalize_command_for_matching(command));
patterns.iter().any(|p| {
let np = normalize_command_for_matching(p);
// Ignore empty/whitespace-only patterns: `contains("")` is always true and would otherwise
// force approval on *every* command — a silent config footgun.
if np.is_empty() {
return false;
}
normalized.contains(&format!(" {} ", np))
})
}
/// Parse a user's reply to a shell-approval prompt. **Deny by default**: the command runs only when
/// the reply is composed *entirely* of affirmative or neutral-filler words AND carries at least one
/// explicit affirmative. Any unrecognized token — a negation ("never", "nope", "can't"), a caveat,
/// or stray prose — forces a deny.
///
/// This allowlist posture (rather than a denylist) is deliberate: it fixes the original
/// `contains("approve") && !contains("deny")` parse that read "do not approve" as APPROVED, and it
/// also closes the broader class a denylist misses, where an affirmative word is buried in a
/// negative sentence ("never approve", "i can't approve", "approve? actually nope"). The prompt
/// constrains the choices to approve/deny with `allow_empty = false`, so the strictness is
/// UX-compatible; an unrecognized reply simply skips execution and the user can re-confirm.
#[cfg(test)]
fn shell_approval_reply_is_grant(reply: &str) -> bool {
matches!(
classify_approval_reply(reply),
ApprovalReply::Grant | ApprovalReply::AlwaysThisRun
)
}
/// Four-way approval reply classification for ALTAI CLI / TUI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ApprovalReply {
Grant,
AlwaysThisRun,
Deny,
Abort,
}
fn classify_approval_reply(reply: &str) -> ApprovalReply {
const AFFIRM: &[&str] = &[
"approve",
"approved",
"approves",
"yes",
"yep",
"yeah",
"y",
"ok",
"okay",
"k",
"allow",
"allowed",
"confirm",
"confirmed",
"accept",
"accepted",
"proceed",
"go",
"sure",
];
const FILLER: &[&str] = &[
"please", "it", "this", "that", "ahead", "now", "run", "do", "for",
];
const ALWAYS: &[&str] = &["always"];
const ABORT: &[&str] = &["abort", "cancel", "quit", "stop"];
let r = reply.trim().to_ascii_lowercase();
if r.is_empty() {
return ApprovalReply::Deny;
}
let tokens: Vec<&str> = r
.split(|c: char| !c.is_alphanumeric())
.filter(|t| !t.is_empty())
.collect();
if tokens.iter().any(|t| ABORT.contains(t))
&& !tokens.iter().any(|t| AFFIRM.contains(t) || ALWAYS.contains(t))
{
return ApprovalReply::Abort;
}
// "always" / "always for this run" — allow only known filler around always.
if tokens.iter().any(|t| ALWAYS.contains(t)) {
let ok = tokens
.iter()
.all(|t| ALWAYS.contains(t) || FILLER.contains(t) || AFFIRM.contains(t));
if ok {
return ApprovalReply::AlwaysThisRun;
}
return ApprovalReply::Deny;
}
let mut saw_affirmative = false;
for tok in &tokens {
if AFFIRM.contains(tok) {
saw_affirmative = true;
} else if !FILLER.contains(tok) {
return ApprovalReply::Deny;
}
}
if saw_affirmative {
ApprovalReply::Grant
} else {
ApprovalReply::Deny
}
}
fn command_preview_with_flag(command: &str) -> (String, bool) {
const MAX_PREVIEW: usize = 160;
if command.len() <= MAX_PREVIEW {
(command.to_string(), false)
} else {
(format!("{}…", &command[..MAX_PREVIEW]), true)
}
}
fn command_preview(command: &str) -> String {
command_preview_with_flag(command).0
}
fn shell_policy_mode_for_session(
policy: &ResolvedShellPolicy,
unattended_session: bool,
) -> ShellPolicyMode {
if unattended_session {
policy.unattended_mode
} else {
policy.interactive_mode
}
}
fn edit_policy_mode_for_session(
policy: &ResolvedShellPolicy,
unattended_session: bool,
) -> ShellPolicyMode {
if unattended_session {
policy.unattended_edit_mode
} else {
policy.interactive_edit_mode
}
}
/// Reason shown when the edit policy blocks a mutation. Unattended sessions
/// default to Deny independently of plan mode, so the message distinguishes the
/// two cases rather than hardcoding "plan mode active" everywhere (PR #62 review #2).
fn edit_policy_block_reason(unattended_session: bool) -> &'static str {
if unattended_session {
"File edit blocked by policy: unattended edit mode is active."
} else {
"File edit blocked by policy: plan mode active — finalize or apply the plan first."
}
}
/// Tools that execute model-authored code/commands on the host or a session. All of these run
/// arbitrary code, so they share the shell-policy approval gate — not just `exec`. Keying the
/// gate on this category (rather than the literal name `"exec"`) is what stops `execution_run`
/// / `execution_run_background` / `python_run` from bypassing approval entirely.
fn is_code_exec_tool(tool_name: &str) -> bool {
matches!(
tool_name,
"exec" | "python_run" | "execution_run" | "execution_run_background"
)
}
/// Tools that mutate a workspace file and therefore need the edit policy gate.
fn is_file_mutate_tool(tool_name: &str) -> bool {
matches!(tool_name, "write_file" | "edit_file")
}
/// Code-exec tools that run *arbitrary* code (Python source / session cells) where the
/// destructive-shell-pattern heuristic does not meaningfully apply, so any such call is
/// treated as approval-worthy in ask/deny mode.
fn is_arbitrary_code_tool(tool_name: &str) -> bool {
matches!(
tool_name,
"python_run" | "execution_run" | "execution_run_background"
)
}
/// Extract the command/code a code-exec tool will run. `exec` carries it in `command`; the
/// execution / python tools carry it in `code`.
fn extract_code_exec_command(tool_name: &str, args: &Value) -> Option<String> {
let key = if tool_name == "exec" {
"command"
} else {
"code"
};
args.get(key)
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Whether a code-exec call needs approval in ask/deny mode. Arbitrary-code tools always do;
/// shell `exec` only when the command matches a destructive pattern (preserves existing UX).
fn code_exec_requires_approval(tool_name: &str, command: &str, patterns: &[String]) -> bool {
is_arbitrary_code_tool(tool_name) || should_require_shell_approval(command, patterns)
}
#[cfg(test)]
mod code_exec_gate_tests {
use super::*;
use serde_json::json;
#[test]
fn category_covers_all_code_exec_tools() {
assert!(is_code_exec_tool("exec"));
assert!(is_code_exec_tool("python_run"));
assert!(is_code_exec_tool("execution_run"));
assert!(is_code_exec_tool("execution_run_background"));
assert!(!is_code_exec_tool("read_file"));
assert!(!is_code_exec_tool("web_search"));
}
#[test]
fn file_mutate_category_covers_write_and_edit_only() {
assert!(is_file_mutate_tool("write_file"));
assert!(is_file_mutate_tool("edit_file"));
assert!(!is_file_mutate_tool("read_file"));
assert!(!is_file_mutate_tool("exec"));
assert!(!is_file_mutate_tool("list_dir"));
assert!(!is_file_mutate_tool("search_text"));
}
#[test]
fn edit_block_reason_distinguishes_unattended_and_plan_mode() {
// PR #62 review #2: the Deny message must match why the edit was blocked.
let unattended = edit_policy_block_reason(true);
assert!(unattended.contains("unattended"), "{unattended}");
assert!(!unattended.contains("plan mode"), "{unattended}");
let plan = edit_policy_block_reason(false);
assert!(plan.contains("plan mode"), "{plan}");
}
#[test]
fn extracts_command_for_exec_and_code_for_execution_tools() {
assert_eq!(
extract_code_exec_command("exec", &json!({"command": " ls -la "})).as_deref(),
Some("ls -la")
);
assert_eq!(
extract_code_exec_command("execution_run", &json!({"code": "print(1)"})).as_deref(),
Some("print(1)")
);
assert_eq!(
extract_code_exec_command("python_run", &json!({"code": "import os"})).as_deref(),
Some("import os")
);
// wrong key / empty -> None
assert!(extract_code_exec_command("execution_run", &json!({"command": "x"})).is_none());
assert!(extract_code_exec_command("exec", &json!({"command": " "})).is_none());
}
#[test]
fn arbitrary_code_always_requires_approval_benign_exec_does_not() {
let patterns = vec!["rm -rf".to_string()];
// Arbitrary-code tools: even benign code requires approval (closes the bypass).
assert!(code_exec_requires_approval(
"execution_run",
"print('hi')",
&patterns
));
assert!(code_exec_requires_approval("python_run", "1+1", &patterns));
// Shell `exec`: benign command does NOT require approval (preserves existing UX)...
assert!(!code_exec_requires_approval("exec", "ls -la", &patterns));
// ...but a destructive one does.
assert!(code_exec_requires_approval(
"exec",
"rm -rf /tmp/x",
&patterns
));
}
#[test]
fn approval_match_is_whitespace_insensitive() {
let patterns = vec!["rm -rf".to_string()];
// Extra spaces, tabs, and a mid-command newline must not bypass the gate.
assert!(should_require_shell_approval("rm -rf /tmp/x", &patterns));
assert!(should_require_shell_approval("rm\t-rf /tmp/x", &patterns));
assert!(should_require_shell_approval("rm\n-rf /tmp/x", &patterns));
assert!(should_require_shell_approval("RM -RF /tmp/x", &patterns));
// A benign command still does not match.
assert!(!should_require_shell_approval("ls -la", &patterns));
}
#[test]
fn approval_match_is_word_boundary_not_substring() {
// A bare `rm` pattern must match the real command but NOT words that merely contain "rm"
// (the substring false positive: "terminal".contains("rm") is true).
let patterns = vec!["rm".to_string()];
assert!(should_require_shell_approval("rm -rf /tmp/x", &patterns));
assert!(should_require_shell_approval(
"echo hi && rm file",
&patterns
));
assert!(!should_require_shell_approval("terminal --help", &patterns));
assert!(!should_require_shell_approval(
"warm up the cache",
&patterns
));
assert!(!should_require_shell_approval(
"npm run platform",
&patterns
));
assert!(!should_require_shell_approval("check firmware", &patterns));
}
#[test]
fn empty_pattern_does_not_force_approval_on_everything() {
// `contains("")` is always true; an empty/whitespace pattern must be ignored.
let patterns = vec!["".to_string(), " ".to_string()];
assert!(!should_require_shell_approval("ls -la", &patterns));
// An empty pattern alongside a real one must not suppress the real match.
let mixed = vec!["".to_string(), "rm -rf".to_string()];
assert!(should_require_shell_approval("rm -rf /tmp/x", &mixed));
assert!(!should_require_shell_approval("ls", &mixed));
}
#[test]
fn approval_reply_is_deny_default() {
// The regression: "do not approve" must NOT grant.
assert!(!shell_approval_reply_is_grant("do not approve"));
assert!(!shell_approval_reply_is_grant("don't approve"));
assert!(!shell_approval_reply_is_grant("deny"));
assert!(!shell_approval_reply_is_grant("no"));
assert!(!shell_approval_reply_is_grant("reject this"));
assert!(!shell_approval_reply_is_grant(""));
assert!(!shell_approval_reply_is_grant(" "));
// Ambiguous / unrelated text is denied (safe default).
assert!(!shell_approval_reply_is_grant("hmm let me think"));
// Affirmative word buried in a negative reply must NOT grant (the denylist gap).
assert!(!shell_approval_reply_is_grant("never approve"));
assert!(!shell_approval_reply_is_grant("i can't approve"));
assert!(!shell_approval_reply_is_grant("approve? actually nope"));
assert!(!shell_approval_reply_is_grant("disapprove"));
assert!(!shell_approval_reply_is_grant("i approve... no wait, deny"));
// Explicit grants (incl. affirmative + neutral filler).
assert!(shell_approval_reply_is_grant("approve"));
assert!(shell_approval_reply_is_grant("Approved"));
assert!(shell_approval_reply_is_grant("yes"));
assert!(shell_approval_reply_is_grant("ok"));
assert!(shell_approval_reply_is_grant("allow"));
assert!(shell_approval_reply_is_grant("approve please"));
assert!(shell_approval_reply_is_grant("approve this"));
assert!(shell_approval_reply_is_grant("go ahead"));
// "do" is neutral filler: it rescues genuine affirmatives ("yes do it") without weakening
// deny-default — a negation always carries another non-filler token (see "do not approve"
// above), and "do" on its own is not affirmative.
assert!(shell_approval_reply_is_grant("yes do it"));
assert!(shell_approval_reply_is_grant("yes, please do"));
assert!(!shell_approval_reply_is_grant("do it"));
}
#[test]
fn approval_reply_classifies_always_and_abort() {
assert_eq!(
classify_approval_reply("always"),
ApprovalReply::AlwaysThisRun
);
assert_eq!(
classify_approval_reply("always for this run"),
ApprovalReply::AlwaysThisRun
);
assert_eq!(classify_approval_reply("abort"), ApprovalReply::Abort);
assert_eq!(classify_approval_reply("cancel"), ApprovalReply::Abort);
assert_eq!(classify_approval_reply("deny"), ApprovalReply::Deny);
assert!(shell_approval_reply_is_grant("always"));
assert!(!shell_approval_reply_is_grant("abort"));
}
#[test]
fn append_post_tool_output_preserves_polarity() {
// Appends to a success, preserving its typed status.
let ok = append_post_tool_output(ToolResult::success("applied"), "tests passed");
assert_eq!(ok.content, "applied\n\n[post-tool hook]\ntests passed");
assert!(!ok.is_error());
// Appends to an error without replacing its typed root cause.
let err = append_post_tool_output(
ToolResult::error(ToolErrorCode::ExecutionFailed, "boom"),
"lint output",
);
assert_eq!(err.content, "Error: boom\n\n[post-tool hook]\nlint output");
assert_eq!(err.error_code(), Some(ToolErrorCode::ExecutionFailed));
}
}
#[cfg(test)]
mod context_hardening_tests {
use super::*;
fn assistant_with_calls(ids: &[&str]) -> crate::utils::ChatMessage {
let mut message = crate::utils::ChatMessage::assistant("");
message.content = None;
message.tool_calls = Some(
ids.iter()
.map(|id| crate::utils::ToolCallRequest {
id: (*id).to_string(),
tool_type: "function".to_string(),
extra_content: None,
function: crate::utils::ToolCallFunction {
name: "read_file".to_string(),
arguments: "{}".to_string(),
},
})
.collect(),
);
message
}
#[test]
fn research_detection_uses_word_and_phrase_boundaries() {
for positive in [
"Research this topic",
"review the papers",
"give me state-of-the-art evidence",
"cite primary sources",
"compare methods",
] {
assert!(text_looks_like_research_request(positive), "{positive}");
}
for negative in [
"I am excited about this",
"the paperclip is broken",
"surveying the room",
"compare methodologies later",
] {
assert!(!text_looks_like_research_request(negative), "{negative}");
}
}
#[test]
fn repair_removes_orphan_mismatched_and_duplicate_tool_results() {
let mut context = vec![
crate::utils::ChatMessage::system("system"),
crate::utils::ChatMessage::tool("orphan", "orphan", None),
assistant_with_calls(&["a", "b"]),
crate::utils::ChatMessage::tool("first", "a", None),
crate::utils::ChatMessage::tool("duplicate", "a", None),
crate::utils::ChatMessage::tool("wrong", "other", None),
crate::utils::ChatMessage::user("next"),
];
repair_tool_call_context(&mut context);
let tool_ids: Vec<_> = context
.iter()
.filter(|message| message.role == "tool")
.filter_map(|message| message.tool_call_id.as_deref())
.collect();
assert_eq!(tool_ids, ["a", "b"]);
assert!(context.iter().all(|message| {
message
.content
.as_ref()
.is_none_or(|content| !content.text_content().contains("orphan"))
}));
}
#[test]
fn trimming_keeps_assistant_tool_blocks_atomic() {
let mut context = vec![
crate::utils::ChatMessage::system("system"),
crate::utils::ChatMessage::user(&"x".repeat(400)),
assistant_with_calls(&["call"]),
crate::utils::ChatMessage::tool("result", "call", None),
crate::utils::ChatMessage::user("recent"),
];
trim_context_to_budget(&mut context, 1);
assert!(!context.iter().any(|message| message.role == "tool"));
assert!(!context
.iter()
.any(|message| message.role == "assistant" && message.tool_calls.is_some()));
}
}
fn hook_observe_telemetry(
hook_tool_ctx: Option<&Arc<ToolCallHookContext>>,
inbound: &crate::bus::InboundMessage,
is_subagent: bool,
event: TelemetryEvent,
) {
let Some(hc) = hook_tool_ctx else {
return;
};
let Some(obs) = hc.observation.as_ref() else {
return;
};
let meta = HookObservationMeta {
channel: inbound.channel.as_str(),
chat_id: inbound.chat_id.as_str(),
thread_id: inbound.thread_id.as_deref(),
is_subagent,
metadata: &inbound.metadata,
};
obs.try_emit(event, meta);
}
fn shell_command_uses_grep_like(command: &str) -> bool {
let lower = command.to_ascii_lowercase();
lower.contains("grep ")
|| lower.contains("| grep")
|| lower.contains("cat ")
|| lower.contains("wc ")
}
async fn log_tool_invocation_start(
logger_tx: &LoggerHandle,
outbound_tx: &mpsc::Sender<BusMessage>,
hook_tool_ctx: Option<&Arc<ToolCallHookContext>>,
agent_name: &str,
inbound: &crate::bus::InboundMessage,
tc: &crate::utils::ToolCallRequest,
is_subagent: bool,
) {
let tool_name = &tc.function.name;
let args_str = &tc.function.arguments;
let _ = logger_tx.send(BusMessage::Log(
LogEvent::info(agent_name, &format!("Invoking tool: {}", tool_name))
.with_chat_id(&inbound.chat_id),
));
let _ = outbound_tx
.send(BusMessage::Telemetry(TelemetryEvent::ToolCall {
chat_id: inbound.chat_id.clone(),
channel: inbound.channel.clone(),
tool_name: tool_name.to_string(),
args: args_str.clone(),
tool_call_id: Some(tc.id.clone()),
background_job_id: crate::bus::get_background_job_id(&inbound.metadata),
}))
.await;
let _ = outbound_tx
.send(BusMessage::Telemetry(TelemetryEvent::ToolCallStarted {
chat_id: inbound.chat_id.clone(),
tool_name: tool_name.to_string(),
args: args_str.clone(),
tool_call_id: Some(tc.id.clone()),
background_job_id: crate::bus::get_background_job_id(&inbound.metadata),
}))
.await;
hook_observe_telemetry(
hook_tool_ctx,
inbound,
is_subagent,
TelemetryEvent::ToolCall {
chat_id: inbound.chat_id.clone(),
channel: inbound.channel.clone(),
tool_name: tool_name.to_string(),
args: args_str.clone(),
tool_call_id: Some(tc.id.clone()),
background_job_id: crate::bus::get_background_job_id(&inbound.metadata),
},
);
hook_observe_telemetry(
hook_tool_ctx,
inbound,
is_subagent,
TelemetryEvent::ToolCallStarted {
chat_id: inbound.chat_id.clone(),
tool_name: tool_name.to_string(),
args: args_str.clone(),
tool_call_id: Some(tc.id.clone()),