-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeferred_tools.rs
More file actions
429 lines (399 loc) · 13 KB
/
Copy pathdeferred_tools.rs
File metadata and controls
429 lines (399 loc) · 13 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
//! Shared deferred-tool group expansion, session enable helpers, and
//! intent-based tool suggestions for the main + subagent loops.
//!
//! Keeps `handle_load_tools` / subagent load_tools / auto-enable tails from
//! drifting apart (core-agentic-loop wiring audit 2026-08).
use serde_json::Value;
use crate::tools;
/// Expand a tool name or group alias into concrete deferred tool names.
/// `goal_write_plan` is never expanded (planning-phase only).
pub fn expand_tool_request(name: &str) -> Vec<String> {
match name.trim() {
"" => Vec::new(),
"all" => tools::deferred_tool_names()
.iter()
.filter(|n| **n != "goal_write_plan")
.map(|s| (*s).to_string())
.collect(),
"git" => vec![
"git_add".into(),
"git_commit".into(),
"git_push".into(),
"git_pull".into(),
"git_branch".into(),
],
"web" => vec!["fetch".into(), "web_search".into()],
"bulk" => vec![
"bulk".into(),
"bulk_read".into(),
"bulk_write".into(),
"bulk_edit".into(),
],
"runtime" => vec!["eval".into()],
"ide" => vec![
"lsp_rename".into(),
"snapshot_edit".into(),
"ast_edit".into(),
],
"process" => vec!["process".into()],
"debug" => vec!["debug".into()],
"mcp" => vec!["mcp".into()],
"browser" => crate::browser::MVP_TOOL_NAMES
.iter()
.map(|s| (*s).to_string())
.collect(),
other => vec![other.to_string()],
}
}
/// Expand a list of names/groups, sort + dedup.
pub fn expand_tool_requests(names: &[String]) -> Vec<String> {
let mut expanded: Vec<String> = Vec::new();
for n in names {
expanded.extend(expand_tool_request(n));
}
expanded.sort();
expanded.dedup();
expanded
}
/// Parse `tools` array + optional `tool` string from load_tools args.
pub fn names_from_load_args(args: &Value) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
if let Some(arr) = args.get("tools").and_then(|v| v.as_array()) {
for v in arr {
if let Some(s) = v.as_str() {
let t = s.trim();
if !t.is_empty() {
names.push(t.to_string());
}
}
}
}
if let Some(s) = args.get("tool").and_then(|v| v.as_str()) {
let t = s.trim();
if !t.is_empty() {
names.push(t.to_string());
}
}
names
}
/// Intent → deferred groups the model should load for this prompt.
/// Conservative: only clear signals. Used for auto-enable + suggestion tail.
pub fn intent_deferred_groups(prompt: &str) -> Vec<&'static str> {
let p = prompt.to_lowercase();
let mut groups: Vec<&'static str> = Vec::new();
let push = |g: &'static str, groups: &mut Vec<&'static str>| {
if !groups.contains(&g) {
groups.push(g);
}
};
// Web / browser
if p.contains("browser")
|| p.contains("playwright")
|| p.contains("puppeteer")
|| p.contains("headless")
|| p.contains("screenshot the")
|| p.contains("screenshot")
|| p.contains("web ui")
|| p.contains("webui")
|| p.contains(" end-to-end")
|| p.contains("e2e ")
|| p.contains(" e2e")
|| p.contains("open the page")
|| p.contains("open the site")
|| p.contains("drive the ui")
|| (p.contains("navigate")
&& (p.contains("http") || p.contains("page") || p.contains("url")))
|| p.contains("click the")
|| p.contains("fill the form")
{
push("browser", &mut groups);
}
if p.contains("http://")
|| p.contains("https://")
|| p.contains("fetch ")
|| p.contains("curl ")
|| p.contains("web search")
|| p.contains("search the web")
|| p.contains("look up docs")
|| p.contains("documentation for")
|| p.contains("npm package")
|| p.contains("crates.io")
|| p.contains("official docs")
{
push("web", &mut groups);
}
// IDE / structural edit — explicit signals plus any code-change task so
// ast_edit / snapshot_edit / lsp_rename are in schema without a load hop.
if p.contains("ast_edit")
|| p.contains("refactor")
|| p.contains("rename symbol")
|| p.contains("rename the")
|| p.contains("rename across")
|| p.contains("tree-sitter")
|| p.contains("language server")
|| p.contains(" go to definition")
|| p.contains("find references")
|| p.contains("structural edit")
|| crate::task_fingerprint::looks_like_code_task(prompt)
{
push("ide", &mut groups);
}
// Git mutators
if p.contains("git commit")
|| p.contains("git push")
|| p.contains("git pull")
|| p.contains("create a branch")
|| p.contains("checkout branch")
|| p.contains("stage ")
|| p.contains("commit the")
|| p.contains("commit my")
|| p.contains("push to origin")
|| p.contains("push these")
{
push("git", &mut groups);
}
// Process / servers
if p.contains("long-running")
|| p.contains("dev server")
|| p.contains("background process")
|| p.contains("nohup")
|| p.contains("keep running")
|| (p.contains("start") && (p.contains("server") || p.contains("listener")))
|| p.contains("run the server")
{
push("process", &mut groups);
}
// MCP — also when the prompt just says "mcp" as a word
if p.contains("mcp") || p.contains("model context protocol") {
push("mcp", &mut groups);
}
// Debug / DAP
if p.contains("breakpoint")
|| p.contains("debugger")
|| p.contains(" step through")
|| p.contains("dap ")
|| p.contains("debug this")
|| p.contains("debug the")
{
push("debug", &mut groups);
}
// Bulk multi-file
if p.contains("bulk_")
|| p.contains("many files")
|| p.contains("all files matching")
|| p.contains("every file in")
|| p.contains("across the codebase")
|| p.contains("rename across")
{
push("bulk", &mut groups);
}
// Runtime eval
if p.contains("eval python")
|| p.contains("eval javascript")
|| p.contains("repl ")
|| p.contains("run a snippet")
{
push("runtime", &mut groups);
}
// Platform test envs
if p.contains("test_env")
|| p.contains("windows vm")
|| p.contains("podman")
|| p.contains("ephemeral container")
|| p.contains("test on windows")
|| p.contains("test on linux")
{
// freeform name, not a group alias with expand — still list for hints
push("test_env", &mut groups);
}
groups
}
/// Whether the prompt looks like multi-agent / large-scope work.
pub fn looks_like_multi_agent_task(prompt: &str) -> bool {
let p = prompt.to_lowercase();
if p.contains("subagent")
|| p.contains("parallel review")
|| p.contains("fan out")
|| p.contains("fan-out")
|| p.contains("multiple agents")
|| p.contains("scout then")
|| p.contains("delegate to")
{
return true;
}
// Heuristic: long multi-step coding prompts.
let words = p.split_whitespace().count();
if words < 40 {
return false;
}
let multi_area = [
" and also ",
" then ",
" across ",
" several ",
" multiple files",
" whole codebase",
" entire ",
" end-to-end",
" comprehensively",
" deep dive",
" audit ",
" refactor the",
]
.iter()
.filter(|s| p.contains(**s))
.count();
multi_area >= 2 || (words >= 80 && multi_area >= 1)
}
/// Build a compact `[RELEVANT TOOLS]` / multi-agent hint tail.
pub fn relevant_tools_tail(
prompt: &str,
already_enabled: &std::collections::HashSet<String>,
mcp_server_names: &[String],
browser_available: bool,
) -> String {
let mut parts: Vec<String> = Vec::new();
let groups = intent_deferred_groups(prompt);
let mut suggest: Vec<String> = Vec::new();
for g in groups {
if g == "test_env" {
if !already_enabled.contains("test_env") {
suggest.push("test_env (load_tools tool:\"test_env\")".into());
}
continue;
}
let expanded = expand_tool_request(g);
let needs = expanded
.iter()
.any(|n| !tools::is_core_tool(n) && !already_enabled.contains(n));
if needs {
if g == "browser" && !browser_available {
continue;
} else {
suggest.push(format!("{g} → load_tools tools:[\"{g}\"]"));
}
}
}
if !suggest.is_empty() {
parts.push(format!(
"[RELEVANT TOOLS] — deferred groups matching this prompt (call load_tools before first use):\n- {}",
suggest.join("\n- ")
));
}
if !mcp_server_names.is_empty() {
let any_mcp = already_enabled.contains("mcp");
parts.push(format!(
"[CONFIGURED MCP] servers: {}.{}\nUse `load_tools` group `mcp` then `mcp` action=list/call (transports are user-config only).",
mcp_server_names.join(", "),
if any_mcp {
" (mcp tool already enabled this session.)"
} else {
""
}
));
}
if looks_like_multi_agent_task(prompt) {
parts.push(
"[MULTI-AGENT] This task looks multi-area or large — prefer the core `subagent` tool \
(scout → worker/reviewer, or parallel `tasks`) instead of doing everything serially. \
Children escalate with contact_supervisor. Apply `/skill:pi-subagents` for the full playbook when needed."
.into(),
);
}
if parts.is_empty() {
String::new()
} else {
parts.join("\n\n")
}
}
/// Browser backend compiled in?
pub fn browser_feature_available() -> bool {
cfg!(any(feature = "chromium-cdp", feature = "native-browser"))
}
/// Apply config always-on deferred groups into a set (names only).
pub fn seed_always_on_groups(groups: &[String], into: &mut std::collections::HashSet<String>) {
for g in groups {
for n in expand_tool_request(g) {
if n == "goal_write_plan" {
continue;
}
if tools::is_deferred_tool(&n) {
into.insert(n);
}
}
}
}
/// Auto-enable intent groups into the session set; returns newly added names.
pub fn auto_enable_intent_groups(
prompt: &str,
into: &mut std::collections::HashSet<String>,
) -> Vec<String> {
let mut added = Vec::new();
for g in intent_deferred_groups(prompt) {
if g == "browser" && !browser_feature_available() {
continue;
}
if g == "test_env" {
if tools::is_deferred_tool("test_env") && into.insert("test_env".into()) {
added.push("test_env".into());
}
continue;
}
for n in expand_tool_request(g) {
if n == "goal_write_plan" {
continue;
}
if tools::is_deferred_tool(&n) && into.insert(n.clone()) {
added.push(n);
}
}
}
added.sort();
added.dedup();
added
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expand_git_and_browser() {
let g = expand_tool_request("git");
assert!(g.contains(&"git_add".to_string()));
let b = expand_tool_request("browser");
assert!(b.iter().any(|n| n == "browser_create"));
}
#[test]
fn intent_detects_browser_and_web() {
let g = intent_deferred_groups("Please drive the web UI with the browser and click submit");
assert!(g.contains(&"browser"));
let w = intent_deferred_groups("fetch https://example.com/docs");
assert!(w.contains(&"web"));
}
#[test]
fn core_read_uris_do_not_request_runtime_group() {
assert_eq!(expand_tool_request("runtime"), vec!["eval"]);
for prompt in ["read skill://worker", "open memory://project-fact"] {
assert!(
!intent_deferred_groups(prompt).contains(&"runtime"),
"{prompt}"
);
assert!(
!relevant_tools_tail(prompt, &std::collections::HashSet::new(), &[], false)
.contains("load_tools"),
"{prompt}"
);
}
}
#[test]
fn intent_enables_ide_on_implement() {
let g = intent_deferred_groups("implement the memory save path in core/src/memory.rs");
assert!(g.contains(&"ide"), "{g:?}");
}
#[test]
fn multi_agent_heuristic() {
assert!(looks_like_multi_agent_task(
"Use subagents to scout the codebase then implement fixes in parallel"
));
assert!(!looks_like_multi_agent_task("fix the typo"));
}
}