1#![expect(
2 clippy::cast_possible_truncation,
3 reason = "Quality scores are normalized to the documented 0..=100 display range before narrowing."
4)]
5
6pub type CompactStr = compact_str::CompactString;
26
27pub mod tool_names {
40 pub mod model_facing {
42 pub const EXEC_COMMAND: &str = "exec_command";
43 pub const WRITE_STDIN: &str = "write_stdin";
44 pub const APPLY_PATCH: &str = "apply_patch";
45 pub const RECORD_DECISION: &str = "record_decision";
46 pub const CODE_SEARCH: &str = "code_search";
47 pub const COMPUTER_USE: &str = "computer_use";
48 }
49
50 pub mod dispatchers {
52 pub const UNIFIED_SEARCH: &str = "search_dispatch_internal";
53 pub const UNIFIED_EXEC: &str = "command_session_internal";
54 pub const UNIFIED_FILE: &str = "file_operation_internal";
55 }
56
57 pub mod ids {
59 pub const THINK: &str = "think";
60 pub const SEARCH_TOOLS: &str = "search_tools";
61 pub const MCP: &str = "mcp";
62 pub const MCP_SEARCH_TOOLS: &str = "mcp_search_tools";
63 pub const MCP_GET_TOOL_DETAILS: &str = "mcp_get_tool_details";
64 pub const MCP_LIST_SERVERS: &str = "mcp_list_servers";
65 pub const MCP_CONNECT_SERVER: &str = "mcp_connect_server";
66 pub const MCP_DISCONNECT_SERVER: &str = "mcp_disconnect_server";
67 pub const WEB_SEARCH: &str = "web_search";
68 pub const WEB_FETCH: &str = "web_fetch";
69 pub const FETCH_URL: &str = "fetch_url";
70 pub const LIST: &str = "list";
71 pub const GREP: &str = "grep";
72 pub const FETCH: &str = "fetch";
73 pub const EXEC_PTY_CMD: &str = "exec_pty_cmd";
74 pub const SHELL: &str = "shell";
75 pub const GREP_FILE: &str = "grep_file";
76 pub const LIST_FILES: &str = "list_files";
77 }
78
79 pub mod execution {
81 pub const RUN_PTY_CMD: &str = "run_pty_cmd";
82 pub const CREATE_PTY_SESSION: &str = "create_pty_session";
83 pub const LIST_PTY_SESSIONS: &str = "list_pty_sessions";
84 pub const CLOSE_PTY_SESSION: &str = "close_pty_session";
85 pub const SEND_PTY_INPUT: &str = "send_pty_input";
86 pub const READ_PTY_SESSION: &str = "read_pty_session";
87 pub const RESIZE_PTY_SESSION: &str = "resize_pty_session";
88 pub const EXECUTE_CODE: &str = "execute_code";
89 }
90
91 pub mod files {
93 pub const READ_FILE: &str = "read_file";
94 pub const WRITE_FILE: &str = "write_file";
95 pub const EDIT_FILE: &str = "edit_file";
96 pub const DELETE_FILE: &str = "delete_file";
97 pub const CREATE_FILE: &str = "create_file";
98 pub const SEARCH_REPLACE: &str = "search_replace";
99 pub const FILE_OP: &str = "file_op";
100 pub const MOVE_FILE: &str = "move_file";
101 pub const COPY_FILE: &str = "copy_file";
102 }
103
104 pub mod skills {
106 pub const LIST_SKILLS: &str = "list_skills";
107 pub const LOAD_SKILL: &str = "load_skill";
108 pub const LOAD_SKILL_RESOURCE: &str = "load_skill_resource";
109 }
110
111 pub mod goal {
113 pub const GET_GOAL: &str = "get_goal";
114 pub const UPDATE_GOAL: &str = "update_goal";
115 }
116
117 pub mod diagnostics {
119 pub const GET_ERRORS: &str = "get_errors";
120 }
121
122 pub mod control {
124 pub const REQUEST_USER_INPUT: &str = "request_user_input";
125 pub const MEMORY: &str = "memory";
126 pub const ASK_QUESTIONS: &str = "ask_questions";
127 pub const ASK_USER_QUESTION: &str = "ask_user_question";
128 pub const MATRIX: &str = "matrix";
129 pub const AGENT: &str = "agent";
130 pub const CRON: &str = "cron";
131 pub const CRON_CREATE: &str = "cron_create";
132 pub const CRON_LIST: &str = "cron_list";
133 pub const CRON_DELETE: &str = "cron_delete";
134 }
135
136 pub mod planning {
138 pub const START_PLANNING: &str = "start_planning";
139 pub const TASK_TRACKER: &str = "task_tracker";
140 }
141
142 pub mod subagents {
144 pub const SPAWN_AGENT: &str = "spawn_agent";
145 pub const SPAWN_BACKGROUND_SUBPROCESS: &str = "spawn_background_subprocess";
146 pub const SEND_INPUT: &str = "send_input";
147 pub const WAIT_AGENT: &str = "wait_agent";
148 pub const RESUME_AGENT: &str = "resume_agent";
149 pub const CLOSE_AGENT: &str = "close_agent";
150 pub const ASK_SESSION: &str = "ask_session";
151 pub const ANSWER_SESSION: &str = "answer_session";
152 pub const LIST_SESSIONS: &str = "list_sessions";
153 }
154
155 pub mod aliases {
159 pub const BASH: &str = "bash";
160 pub const EXEC: &str = "exec";
161 pub const CONTAINER_EXEC: &str = "container.exec";
162 pub const REPO_BROWSER_LIST_FILES: &str = "repo_browser.list_files";
163 pub const REPO_BROWSER_READ_FILE: &str = "repo_browser.read_file";
164 pub const REPO_BROWSER_WRITE_FILE: &str = "repo_browser.write_file";
165 }
166
167 pub mod legacy {
172 pub const COMMAND_SESSION: &str = "command_session";
173 pub const UNIFIED_EXEC: &str = "unified_exec";
174 pub const FILE_OPERATION: &str = "file_operation";
175 pub const SEARCH_DISPATCH: &str = "search_dispatch";
176 }
177
178 pub const WILDCARD_ALL: &str = "*";
180
181 pub use aliases::{
183 BASH as BASH_ALIAS, CONTAINER_EXEC as CONTAINER_EXEC_ALIAS, EXEC as EXEC_ALIAS, REPO_BROWSER_LIST_FILES,
184 REPO_BROWSER_READ_FILE, REPO_BROWSER_WRITE_FILE,
185 };
186 pub use control::{
187 AGENT, ASK_QUESTIONS, ASK_USER_QUESTION, CRON, CRON_CREATE, CRON_DELETE, CRON_LIST, MATRIX, MEMORY,
188 REQUEST_USER_INPUT,
189 };
190 pub use diagnostics::GET_ERRORS;
191 pub use dispatchers::{UNIFIED_EXEC, UNIFIED_FILE, UNIFIED_SEARCH};
192 pub use execution::{
193 CLOSE_PTY_SESSION, CREATE_PTY_SESSION, EXECUTE_CODE, LIST_PTY_SESSIONS, READ_PTY_SESSION, RESIZE_PTY_SESSION,
194 RUN_PTY_CMD, SEND_PTY_INPUT,
195 };
196 pub use files::{
197 COPY_FILE, CREATE_FILE, DELETE_FILE, EDIT_FILE, FILE_OP, MOVE_FILE, READ_FILE, SEARCH_REPLACE, WRITE_FILE,
198 };
199 pub use goal::{GET_GOAL, UPDATE_GOAL};
200 pub use ids::{
201 EXEC_PTY_CMD, FETCH, FETCH_URL, GREP, GREP_FILE, LIST, LIST_FILES, MCP, MCP_CONNECT_SERVER,
202 MCP_DISCONNECT_SERVER, MCP_GET_TOOL_DETAILS, MCP_LIST_SERVERS, MCP_SEARCH_TOOLS, SEARCH_TOOLS, SHELL, THINK,
203 WEB_FETCH, WEB_SEARCH,
204 };
205 pub use legacy::{
206 COMMAND_SESSION as LEGACY_COMMAND_SESSION, FILE_OPERATION as LEGACY_FILE_OPERATION,
207 SEARCH_DISPATCH as LEGACY_SEARCH_DISPATCH, UNIFIED_EXEC as LEGACY_UNIFIED_EXEC,
208 };
209 pub use model_facing::{APPLY_PATCH, CODE_SEARCH, COMPUTER_USE, EXEC_COMMAND, RECORD_DECISION, WRITE_STDIN};
210 pub use planning::{START_PLANNING, TASK_TRACKER};
211 pub use skills::{LIST_SKILLS, LOAD_SKILL, LOAD_SKILL_RESOURCE};
212 pub use subagents::{
213 ANSWER_SESSION, ASK_SESSION, CLOSE_AGENT, LIST_SESSIONS, RESUME_AGENT, SEND_INPUT, SPAWN_AGENT,
214 SPAWN_BACKGROUND_SUBPROCESS, WAIT_AGENT,
215 };
216
217 pub mod groups {
220 use super::{
221 aliases, control, diagnostics, dispatchers, execution, files, goal, ids, legacy, model_facing, planning,
222 skills, subagents,
223 };
224 pub const LEGACY: &[&str] = &[
225 legacy::COMMAND_SESSION,
226 legacy::UNIFIED_EXEC,
227 legacy::FILE_OPERATION,
228 legacy::SEARCH_DISPATCH,
229 ];
230 pub const MODEL_FACING: &[&str] = &[
231 model_facing::EXEC_COMMAND,
232 model_facing::WRITE_STDIN,
233 model_facing::APPLY_PATCH,
234 model_facing::RECORD_DECISION,
235 model_facing::CODE_SEARCH,
236 model_facing::COMPUTER_USE,
237 ];
238 pub const DISPATCHERS: &[&str] = &[
239 dispatchers::UNIFIED_SEARCH,
240 dispatchers::UNIFIED_EXEC,
241 dispatchers::UNIFIED_FILE,
242 ];
243 pub const EXECUTION: &[&str] = &[
244 execution::RUN_PTY_CMD,
245 execution::CREATE_PTY_SESSION,
246 execution::LIST_PTY_SESSIONS,
247 execution::CLOSE_PTY_SESSION,
248 execution::SEND_PTY_INPUT,
249 execution::READ_PTY_SESSION,
250 execution::RESIZE_PTY_SESSION,
251 execution::EXECUTE_CODE,
252 ];
253 pub const FILES: &[&str] = &[
254 files::READ_FILE,
255 files::WRITE_FILE,
256 files::EDIT_FILE,
257 files::DELETE_FILE,
258 files::CREATE_FILE,
259 files::SEARCH_REPLACE,
260 files::FILE_OP,
261 files::MOVE_FILE,
262 files::COPY_FILE,
263 ];
264 pub const CONTROL: &[&str] = &[
265 control::REQUEST_USER_INPUT,
266 control::MEMORY,
267 control::ASK_QUESTIONS,
268 control::ASK_USER_QUESTION,
269 control::MATRIX,
270 control::AGENT,
271 control::CRON,
272 control::CRON_CREATE,
273 control::CRON_LIST,
274 control::CRON_DELETE,
275 ];
276 pub const PLANNING: &[&str] = &[planning::START_PLANNING, planning::TASK_TRACKER];
277 pub const SUBAGENTS: &[&str] = &[
278 subagents::SPAWN_AGENT,
279 subagents::SPAWN_BACKGROUND_SUBPROCESS,
280 subagents::SEND_INPUT,
281 subagents::WAIT_AGENT,
282 subagents::RESUME_AGENT,
283 subagents::CLOSE_AGENT,
284 subagents::ASK_SESSION,
285 subagents::ANSWER_SESSION,
286 subagents::LIST_SESSIONS,
287 ];
288 pub const SKILLS: &[&str] = &[skills::LIST_SKILLS, skills::LOAD_SKILL, skills::LOAD_SKILL_RESOURCE];
289 pub const GOAL: &[&str] = &[goal::GET_GOAL, goal::UPDATE_GOAL];
290 pub const DIAGNOSTICS: &[&str] = &[diagnostics::GET_ERRORS];
291 pub const IDS: &[&str] = &[
292 ids::THINK,
293 ids::SEARCH_TOOLS,
294 ids::MCP,
295 ids::MCP_SEARCH_TOOLS,
296 ids::MCP_GET_TOOL_DETAILS,
297 ids::MCP_LIST_SERVERS,
298 ids::MCP_CONNECT_SERVER,
299 ids::MCP_DISCONNECT_SERVER,
300 ids::WEB_SEARCH,
301 ids::WEB_FETCH,
302 ids::FETCH_URL,
303 ids::LIST,
304 ids::GREP,
305 ids::FETCH,
306 ids::EXEC_PTY_CMD,
307 ids::SHELL,
308 ids::GREP_FILE,
309 ids::LIST_FILES,
310 ];
311 pub const ALIASES: &[&str] = &[
313 aliases::BASH,
314 aliases::EXEC,
315 aliases::CONTAINER_EXEC,
316 aliases::REPO_BROWSER_LIST_FILES,
317 aliases::REPO_BROWSER_READ_FILE,
318 aliases::REPO_BROWSER_WRITE_FILE,
319 ];
320 }
321}
322
323pub const fn canonical_tool_name(name: &str) -> &str {
327 name
328}
329
330pub const ERROR_DETECTION_PATTERNS: &[&str] = &[
336 "error",
337 "failed",
338 "exception",
339 "permission denied",
340 "not found",
341 "no such file",
342 "cannot",
343 "could not",
344 "panic",
345 "crash",
346 "unhandled",
347 "fatal",
348 "timeout",
349 "connection refused",
350 "access denied",
351 "stack trace",
352 "traceback",
353 "abort",
354 "terminate",
355];
356
357pub const NETWORK_ERROR_PATTERNS: &[&str] = &["connection", "timeout", "network", "http", "ssl", "tls", "dns", "proxy"];
359
360pub const DEFAULT_VEC_CAPACITY: usize = 32;
362pub const DEFAULT_HASHMAP_CAPACITY: usize = 16;
363pub const DEFAULT_STRING_CAPACITY: usize = 256;
364
365pub const MAX_SEARCH_RESULTS: usize = 5;
367pub const MAX_LIST_ITEMS_SUMMARY: usize = 5;
368pub const OVERFLOW_INDICATOR_PREFIX: &str = "[+]";
369pub const OVERFLOW_INDICATOR_SUFFIX: &str = "more items]";
370
371pub const MAX_FILE_SIZE_FOR_PROCESSING: usize = 100 * 1024 * 1024; pub const MAX_CONTEXT_LINES: usize = 20;
374pub const MAX_OUTPUT_TOKENS: usize = 4000;
375
376pub fn empty_object_schema() -> Value {
379 serde_json::json!({"type": "object"})
380}
381
382use hashbrown::HashMap;
387use serde::{Deserialize, Serialize};
388use serde_json::Value;
389use std::fmt;
390use std::time::SystemTime;
391
392#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
394pub enum ResultCompleteness {
395 Complete,
397 Partial,
399 Truncated,
401 Empty,
403}
404
405impl ResultCompleteness {
406 fn to_static_str(self) -> &'static str {
408 match self {
409 Self::Complete => "complete",
410 Self::Partial => "partial",
411 Self::Truncated => "truncated",
412 Self::Empty => "empty",
413 }
414 }
415}
416
417impl fmt::Display for ResultCompleteness {
418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419 f.write_str(self.to_static_str())
420 }
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize)]
425pub struct ResultMetadata {
426 #[serde(default = "default_confidence")]
428 pub confidence: f32,
429
430 #[serde(default = "default_relevance")]
432 pub relevance: f32,
433
434 pub completeness: ResultCompleteness,
436
437 #[serde(default)]
439 pub result_count: usize,
440
441 #[serde(default)]
443 pub false_positive_likelihood: f32,
444
445 #[serde(default)]
447 pub content_types: Vec<String>,
448
449 #[serde(default)]
451 pub tool_metrics: HashMap<String, Value>,
452}
453
454fn default_confidence() -> f32 {
455 0.5
456}
457
458fn default_relevance() -> f32 {
459 0.5
460}
461
462impl Default for ResultMetadata {
463 fn default() -> Self {
464 Self {
465 confidence: 0.5,
466 relevance: 0.5,
467 completeness: ResultCompleteness::Complete,
468 result_count: 0,
469 false_positive_likelihood: 0.1,
470 content_types: vec![],
471 tool_metrics: HashMap::new(),
472 }
473 }
474}
475
476impl ResultMetadata {
477 #[inline]
479 pub fn quality_score(&self) -> f32 {
480 let weighted = (self.confidence * 0.4) + (self.relevance * 0.4) + (self.false_positive_likelihood * -0.2);
481 weighted.clamp(0.0, 1.0)
482 }
483
484 #[inline]
486 pub fn success(confidence: f32, relevance: f32) -> Self {
487 Self {
488 confidence: confidence.clamp(0.0, 1.0),
489 relevance: relevance.clamp(0.0, 1.0),
490 completeness: ResultCompleteness::Complete,
491 result_count: 1,
492 false_positive_likelihood: 0.05,
493 ..Default::default()
494 }
495 }
496
497 #[inline]
499 pub fn empty() -> Self {
500 Self {
501 completeness: ResultCompleteness::Empty,
502 result_count: 0,
503 confidence: 1.0, ..Default::default()
505 }
506 }
507
508 pub fn error() -> Self {
510 Self {
511 confidence: 0.2,
512 completeness: ResultCompleteness::Empty,
513 ..Default::default()
514 }
515 }
516
517 pub fn merge(&mut self, other: &ResultMetadata) {
519 self.result_count += other.result_count;
520 self.confidence = (self.confidence + other.confidence) / 2.0;
521 self.relevance = (self.relevance + other.relevance) / 2.0;
522
523 for ct in &other.content_types {
525 if !self.content_types.contains(ct) {
526 self.content_types.push(ct.clone());
527 }
528 }
529
530 self.tool_metrics
532 .extend(other.tool_metrics.iter().map(|(k, v)| (k.clone(), v.clone())));
533 }
534}
535
536#[derive(Debug, Clone, Serialize, Deserialize)]
538pub struct EnhancedToolResult {
539 value: Value,
541
542 pub metadata: ResultMetadata,
544
545 timestamp: u64,
547
548 tool_name: CompactStr,
550
551 #[serde(default)]
553 from_cache: bool,
554}
555
556impl EnhancedToolResult {
557 pub fn new(value: Value, metadata: ResultMetadata, tool_name: impl Into<CompactStr>) -> Self {
558 Self {
559 value,
560 metadata,
561 timestamp: SystemTime::now()
562 .duration_since(SystemTime::UNIX_EPOCH)
563 .unwrap_or_default()
564 .as_secs(),
565 tool_name: tool_name.into(),
566 from_cache: false,
567 }
568 }
569
570 pub fn from_cache(value: Value, metadata: ResultMetadata, tool_name: impl Into<CompactStr>) -> Self {
571 Self {
572 value,
573 metadata,
574 timestamp: SystemTime::now()
575 .duration_since(SystemTime::UNIX_EPOCH)
576 .unwrap_or_default()
577 .as_secs(),
578 tool_name: tool_name.into(),
579 from_cache: true,
580 }
581 }
582
583 #[inline]
585 pub fn is_useful(&self) -> bool {
586 self.metadata.quality_score() > 0.3
587 }
588
589 #[inline]
591 pub fn is_high_quality(&self) -> bool {
592 self.metadata.quality_score() > 0.7
593 }
594
595 #[allow(
597 clippy::cast_sign_loss,
598 reason = "Intentional compatibility, platform, or test-only suppression."
599 )] pub fn to_summary(&self) -> String {
601 let quality = ((self.metadata.quality_score() * 100.0).round().max(0.0) as u32).min(100);
602 match self.metadata.completeness {
603 ResultCompleteness::Complete => {
604 format!("{} found {} results (confidence: {}%)", self.tool_name, self.metadata.result_count, quality)
605 }
606 ResultCompleteness::Partial => {
607 format!(
608 "{} found {} results (truncated, confidence: {}%)",
609 self.tool_name, self.metadata.result_count, quality
610 )
611 }
612 ResultCompleteness::Empty => {
613 format!("{} found no results", self.tool_name)
614 }
615 ResultCompleteness::Truncated => {
616 format!("{} found results (truncated due to size, confidence: {}%)", self.tool_name, quality)
617 }
618 }
619 }
620}
621
622pub trait ResultScorer {
624 fn score(&self, result: &Value) -> ResultMetadata;
626
627 fn tool_name(&self) -> &str;
629}
630
631#[cfg(test)]
632mod tool_names_tests;