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
//! Tool Registry
//!
//! Manages the collection of available tools that can be invoked by agents.
use super::error::{Result, ToolError};
use super::r#trait::{Tool, ToolExecutionContext, ToolResult};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
/// Per-tool parameter aliases that LLMs commonly confuse.
/// Format: (tool_name, wrong_param, correct_param).
/// Applied before validation so models that send slight variations still work.
const PARAM_ALIASES: &[(&str, &str, &str)] = &[
// grep/glob: LLMs often send "query" instead of "pattern"
("grep", "query", "pattern"),
("glob", "query", "pattern"),
// file tools: "file", "file_path", "filepath" → "path"
("read_file", "file", "path"),
("read_file", "file_path", "path"),
("read_file", "filepath", "path"),
("write_file", "file", "path"),
("write_file", "file_path", "path"),
("write_file", "filepath", "path"),
("edit_file", "file", "path"),
("edit_file", "file_path", "path"),
("edit_file", "filepath", "path"),
// edit_file: Claude Code sends old_string/new_string → old_text/new_text
("edit_file", "old_string", "old_text"),
("edit_file", "new_string", "new_text"),
("doc_parser", "file", "path"),
("doc_parser", "file_path", "path"),
// write: "text", "body" → "content"
("write_file", "text", "content"),
("write_file", "body", "content"),
// bash: "cmd" → "command"
("bash", "cmd", "command"),
// search tools: "pattern" → "query"
("web_search", "pattern", "query"),
("exa_search", "pattern", "query"),
("brave_search", "pattern", "query"),
("memory_search", "pattern", "query"),
];
/// Normalize tool input by mapping common LLM parameter name mistakes
/// to the correct parameter name. Only remaps if the correct name is absent.
fn normalize_tool_input(tool_name: &str, mut input: Value) -> Value {
if let Some(obj) = input.as_object_mut() {
for &(tool, wrong, correct) in PARAM_ALIASES {
if tool == tool_name
&& !obj.contains_key(correct)
&& let Some(val) = obj.remove(wrong)
{
tracing::debug!(
"Normalized tool param: {}.{} → {}.{}",
tool_name,
wrong,
tool_name,
correct
);
obj.insert(correct.to_string(), val);
}
}
}
input
}
/// Registry of available tools.
///
/// Thread-safe via internal `RwLock` — all methods take `&self`, allowing
/// runtime registration/removal through a shared `Arc<ToolRegistry>`.
/// Cap on how many EXTENDED tools stay active per session (#603). Once the
/// working set exceeds this, the least-recently-used tools are evicted so the
/// per-turn schema cost can't drift back toward the full ~95-tool baseline over
/// a long session. Evicted tools re-activate on next use (JIT-on-execute), so
/// nothing breaks — the set just stays small. Core tools are never counted here
/// (they always ship).
pub(crate) const MAX_ACTIVE_EXTENDED: usize = 24;
pub struct ToolRegistry {
tools: RwLock<HashMap<String, Arc<dyn Tool>>>,
/// EXTENDED tools each session has activated via `tool_search` or a by-name
/// call (lazy-tools mode), mapped to a monotonic last-touch sequence for
/// LRU eviction (#603). Lives here because both the agent loop and the
/// `tool_search` tool already share this registry's `Arc`.
session_active: RwLock<HashMap<uuid::Uuid, HashMap<String, u64>>>,
/// Monotonic counter stamping each activation/touch for LRU ordering.
activation_seq: std::sync::atomic::AtomicU64,
}
impl ToolRegistry {
/// Create a new empty tool registry
pub fn new() -> Self {
Self {
tools: RwLock::new(HashMap::new()),
session_active: RwLock::new(HashMap::new()),
activation_seq: std::sync::atomic::AtomicU64::new(0),
}
}
/// Mark EXTENDED tools as active for a session (or refresh their recency),
/// so subsequent requests include their schemas. Called on the JIT-on-execute
/// path when a non-core tool is actually used — so recency tracks real use.
/// Evicts the least-recently-used tools once the session exceeds
/// [`MAX_ACTIVE_EXTENDED`] (#603).
pub fn activate_tools(&self, session_id: uuid::Uuid, names: impl IntoIterator<Item = String>) {
use std::sync::atomic::Ordering;
let mut map = self.session_active.write().unwrap();
let set = map.entry(session_id).or_default();
for name in names {
let seq = self.activation_seq.fetch_add(1, Ordering::Relaxed);
set.insert(name, seq);
}
// LRU eviction: keep only the most-recently-touched MAX_ACTIVE_EXTENDED.
if set.len() > MAX_ACTIVE_EXTENDED {
let mut by_recency: Vec<(u64, String)> =
set.iter().map(|(n, &s)| (s, n.clone())).collect();
// Newest first, so `skip(MAX)` leaves the oldest to evict.
by_recency.sort_unstable_by_key(|&(s, _)| std::cmp::Reverse(s));
for (_, name) in by_recency.into_iter().skip(MAX_ACTIVE_EXTENDED) {
set.remove(&name);
}
}
}
/// The EXTENDED tools currently active for a session (empty if none yet).
pub fn active_tools(&self, session_id: uuid::Uuid) -> std::collections::HashSet<String> {
self.session_active
.read()
.unwrap()
.get(&session_id)
.map(|m| m.keys().cloned().collect())
.unwrap_or_default()
}
/// Register a tool (takes `&self` — safe through shared `Arc`)
pub fn register(&self, tool: Arc<dyn Tool>) {
let name = tool.name().to_string();
tracing::debug!("Registered tool: {}", name);
self.tools.write().unwrap().insert(name, tool);
}
/// Unregister a tool by name. Returns true if it existed.
pub fn unregister(&self, name: &str) -> bool {
self.tools.write().unwrap().remove(name).is_some()
}
/// Get a tool by name
pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
self.tools.read().unwrap().get(name).cloned()
}
/// Check if a tool is registered
pub fn has_tool(&self, name: &str) -> bool {
self.tools.read().unwrap().contains_key(name)
}
/// List all registered tool names
pub fn list_tools(&self) -> Vec<String> {
self.tools.read().unwrap().keys().cloned().collect()
}
/// Get tool definitions in LLM format
pub fn get_tool_definitions(&self) -> Vec<crate::brain::provider::Tool> {
self.tools
.read()
.unwrap()
.values()
.map(|tool| crate::brain::provider::Tool {
name: tool.name().to_string(),
description: tool.description().to_string(),
input_schema: tool.input_schema(),
})
.collect()
}
/// Lazy-tools mode: only the schemas for the CORE set plus any EXTENDED
/// tools the session has activated via `tool_search`. Keeps a "reply yes"
/// turn from shipping all ~95 schemas (~20k tokens) when it needs none.
/// A tool the agent hasn't discovered yet is simply omitted — calling
/// `tool_search` activates it for subsequent requests.
pub fn get_tool_definitions_filtered(
&self,
active_extended: &std::collections::HashSet<String>,
) -> Vec<crate::brain::provider::Tool> {
use crate::brain::tools::catalog;
self.tools
.read()
.unwrap()
.values()
.filter(|tool| {
let name = tool.name();
catalog::is_core(name) || active_extended.contains(name)
})
.map(|tool| crate::brain::provider::Tool {
name: tool.name().to_string(),
description: tool.description().to_string(),
input_schema: tool.input_schema(),
})
.collect()
}
/// Find EXTENDED (non-core) tools matching a free-text query, ranked by
/// how well the query terms hit the tool's name + description. Powers the
/// `tool_search` discovery tool. Returns `(name, category, description)`,
/// best matches first, capped at `limit`.
pub fn search_tools(&self, query: &str, limit: usize) -> Vec<(String, String, String)> {
use crate::brain::tools::catalog;
let q = query.to_ascii_lowercase();
let terms: Vec<&str> = q.split_whitespace().filter(|t| t.len() > 1).collect();
let mut scored: Vec<(i32, String, String, String)> = self
.tools
.read()
.unwrap()
.values()
.filter(|tool| !catalog::is_core(tool.name()))
.map(|tool| {
let name = tool.name().to_string();
let desc = tool.description().to_string();
let category = catalog::tool_category(&name).to_string();
let hay = format!("{name} {category} {desc}").to_ascii_lowercase();
let mut score = 0i32;
for term in &terms {
if name.to_ascii_lowercase().contains(term) {
score += 5; // name hit is the strongest signal
} else if category.contains(term) {
score += 3;
} else if hay.contains(term) {
score += 1;
}
}
(score, name, category, desc)
})
.filter(|(score, ..)| *score > 0)
.collect();
// Highest score first; stable tie-break by name for determinism.
scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
scored
.into_iter()
.take(limit)
.map(|(_, name, category, desc)| (name, category, desc))
.collect()
}
/// Full provider-format definitions for a specific set of tool names (used
/// by `tool_search` to hand the agent the exact schemas it just discovered).
pub fn definitions_for(
&self,
names: &std::collections::HashSet<String>,
) -> Vec<crate::brain::provider::Tool> {
self.tools
.read()
.unwrap()
.values()
.filter(|tool| names.contains(tool.name()))
.map(|tool| crate::brain::provider::Tool {
name: tool.name().to_string(),
description: tool.description().to_string(),
input_schema: tool.input_schema(),
})
.collect()
}
/// Execute a tool by name
pub async fn execute(
&self,
name: &str,
input: Value,
context: &ToolExecutionContext,
) -> Result<ToolResult> {
// Resolve the tool. On an unknown name, try the tool-name self-heal
// (a weaker model guessing `tg_send_message` for `telegram_send`,
// issue #176) before giving up. The healed name is used for param
// normalization and logging so everything downstream sees the real
// tool.
let (tool, resolved_name) = match self.get(name) {
Some(t) => (t, name.to_string()),
None => {
let registered = self.list_tools();
match super::tool_name_heal::resolve_tool_name(name, ®istered) {
Some(real) => {
tracing::warn!(
"Self-healed tool name: '{}' → '{}' (model called a near-miss name)",
name,
real
);
let t = self
.get(&real)
.ok_or_else(|| ToolError::NotFound(name.to_string()))?;
(t, real)
}
None => return Err(ToolError::NotFound(name.to_string())),
}
}
};
let name = resolved_name.as_str();
// JIT discovery (#214): when lazy_tools is on, a tool the model called
// by name but never surfaced via `tool_search` is absent from the
// system prompt, so the model is guessing its params blind. Activate it
// now, BEFORE validation, so even if THIS call fails on bad params the
// next request carries the real schema and the model self-corrects
// instead of looping. No-op for CORE tools (always present); harmless
// when lazy_tools is off (the active set is never consulted).
if !crate::brain::tools::catalog::is_core(name) {
self.activate_tools(context.session_id, [name.to_string()]);
}
// Normalize LLM parameter name mistakes before validation
let input = normalize_tool_input(name, input);
// Validate input
tool.validate_input(&input)?;
// Plan-mode write/bash gate: while a session is Editing (pre-init
// or design prose) or has a frozen Active design .md, some tools
// are deterministically refused with an instructive reason. Checked
// after validation so the model's params are sane, before approval
// so the user is never prompted for a call that cannot run.
if let Some(reason) = super::plan_gate::check_plan_gate(
context.session_id,
name,
&tool.capabilities(),
&input,
)
.await
{
tracing::info!("Plan gate denied tool '{}': session is plan-gated", name);
return Ok(ToolResult::error(reason));
}
// Check if approval is required
if tool.requires_approval() && !context.auto_approve {
return Err(ToolError::ApprovalRequired(format!(
"Tool '{}' requires approval before execution",
name
)));
}
// Execute the tool
tracing::info!("Executing tool: {}", name);
let is_md_write = tool
.capabilities()
.contains(&crate::brain::tools::r#trait::ToolCapability::WriteFiles)
&& super::plan_gate::write_targets_session_md(context.session_id, &input).await;
let result = tool.execute(input, context).await?;
// Editing mirror: a successful write to the session plan .md syncs
// the full body into the JSON `description` (tasks stay empty), so
// the .md remains the Editing source of truth and every JSON reader
// (TUI chrome, Telegram sections) sees the fresh design. Advisory
// template warnings are logged, never blocking.
if result.success && is_md_write {
let warnings = crate::utils::plan_files::sync_md_to_json(context.session_id).await;
if !warnings.is_empty() {
tracing::debug!(
"Plan .md template warnings after write: {}",
warnings.join("; ")
);
}
}
if result.success {
tracing::info!("Tool '{}' executed successfully", name);
} else {
tracing::warn!(
"Tool '{}' failed: {:?}",
name,
result.error.as_deref().unwrap_or("unknown error")
);
}
Ok(result)
}
/// Get the number of registered tools
pub fn count(&self) -> usize {
self.tools.read().unwrap().len()
}
}
impl Default for ToolRegistry {
fn default() -> Self {
Self::new()
}
}