Skip to main content

trusty_code/tools/
mod.rs

1//! Tool system for tcode — traits, registry, and the delegate tool.
2//!
3//! Why: The PM loop and sub-agent loops need a polymorphic tool dispatch layer
4//! so new capabilities (web search, file ops, memory, etc.) plug in without
5//! touching the core orchestration code. This module is the assembly point.
6//! What: Re-exports `ToolExecutor`, `AgentRunner`, `RunContext`, `AgentOutput`,
7//! `SearchProvider`, `SearchResult`, `SkillResolver`, and `ToolResult` from
8//! `traits`; `ToolRegistry` from `registry`; `DelegateToAgentTool` from
9//! `delegate`; `FinishTaskTool` (#2072) from `finish_task`; `UseSkillTool`
10//! plus `USE_SKILL_TOOL_NAME` (#2069's progressive-disclosure on-invoke
11//! loader; the constant lets #2070's compaction pin skill outputs by tool
12//! name) from `skill`; `BASH_TOOL_NAME` (#2279's verify-before-finish
13//! gate matches bash tool calls by this literal) from `bash`; and
14//! `RecallSessionTool` plus `RECALL_SESSION_TOOL_NAME` (#2348's
15//! session-scoped memory query — registered only on `task::executor`'s
16//! daemon-session path, never on `run_task`'s one-shot/bake-off path) from
17//! `recall_session`.
18//! Test: Unit tests live in each submodule; integration tests use
19//! `DelegateToAgentTool` with a `MockAgentRunner`.
20//!
21//! (#2347) `goals` adds `set_goal`/`clear_goal` — the model-facing write path
22//! onto `agent_loop::GoalSlots`, registered only in the daemon-session PM
23//! registry (`task::executor::run_and_record`), never in `run_task`'s
24//! one-shot/bake-off path or a delegated engineer's registry.
25
26pub mod bash;
27pub mod delegate;
28pub mod finish_task;
29pub mod fs;
30pub mod goals;
31pub mod recall_session;
32pub mod registry;
33pub mod skill;
34pub mod telemetry;
35pub mod traits;
36pub mod trusty_search;
37
38// Flat re-exports for `crate::tools::*` convenience.
39#[allow(unused_imports)]
40pub use bash::{BASH_TOOL_NAME, BashTool};
41#[allow(unused_imports)]
42pub use delegate::{DelegateToAgentTool, EngineerCompletionSignal};
43pub use finish_task::{
44    FINISH_TASK_TOOL_NAME, FinishStatus, FinishTaskArgs, FinishTaskTool, render_finish_summary,
45};
46pub use fs::{
47    EditTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, WRITE_FILES_TOOL_NAME, WriteFileTool,
48    WriteFilesTool,
49};
50pub use goals::{CLEAR_GOAL_TOOL_NAME, ClearGoalTool, SET_GOAL_TOOL_NAME, SetGoalTool};
51pub use recall_session::{RECALL_SESSION_TOOL_NAME, RecallSessionTool};
52pub use registry::ToolRegistry;
53pub use skill::{USE_SKILL_TOOL_NAME, UseSkillTool};
54pub use telemetry::{RecallTelemetry, SearchTelemetry, ToolTelemetry};
55pub use traits::{
56    AgentOutput, AgentRunner, HistoryMessage, RunContext, SearchProvider, SearchResult,
57    ServiceTier, SkillResolver, ToolExecutor, ToolResult,
58};
59pub use trusty_search::{SEARCH_CODE_TOOL_NAME, TrustySearchTool};
60
61// ── Registry integration tests for the FS tools ──────────────────────────────
62
63#[cfg(test)]
64mod fs_registry_tests {
65    use std::sync::Arc;
66
67    use serde_json::json;
68
69    use super::{EditTool, ReadFileTool, ToolRegistry, WriteFileTool};
70
71    /// All three FS tools register and appear in `schemas()`.
72    ///
73    /// Why: Verifies the complete tool plug-in lifecycle — register, schema emit,
74    /// dispatch — for the fs tool set as a group.
75    /// What: Registers `read_file`, `write_file`, and `edit`; asserts all three
76    /// schema names and that `dispatch_gated` routes to each.
77    /// Test: This test.
78    #[tokio::test]
79    async fn fs_tools_register_and_appear_in_schemas() {
80        let tmp = tempfile::tempdir().expect("tempdir");
81        let mut reg = ToolRegistry::new();
82        reg.register(Arc::new(ReadFileTool::new(tmp.path())));
83        reg.register(Arc::new(WriteFileTool::new(tmp.path())));
84        reg.register(Arc::new(EditTool::new(tmp.path())));
85
86        assert!(reg.contains("read_file"), "read_file must be registered");
87        assert!(reg.contains("write_file"), "write_file must be registered");
88        assert!(reg.contains("edit"), "edit must be registered");
89
90        let schemas = reg.schemas();
91        assert_eq!(schemas.len(), 3, "exactly three tools");
92
93        let names: Vec<&str> = schemas
94            .iter()
95            .filter_map(|s| s["function"]["name"].as_str())
96            .collect();
97        assert!(names.contains(&"read_file"));
98        assert!(names.contains(&"write_file"));
99        assert!(names.contains(&"edit"));
100    }
101
102    /// `dispatch_gated` routes `write_file` correctly.
103    ///
104    /// Why: Verifies the dispatch path end-to-end for an fs tool.
105    /// What: Register `write_file`, dispatch with valid args, assert file written.
106    /// Test: This test.
107    #[tokio::test]
108    async fn dispatch_gated_routes_write_file() {
109        let tmp = tempfile::tempdir().expect("tempdir");
110        let mut reg = ToolRegistry::new();
111        reg.register(Arc::new(WriteFileTool::new(tmp.path())));
112
113        let result = reg
114            .dispatch_gated(
115                "write_file",
116                json!({"path": "via_registry.txt", "content": "registry dispatch test"}),
117                None,
118            )
119            .await;
120
121        assert!(
122            !result.is_error(),
123            "dispatch should succeed: {}",
124            result.content()
125        );
126        let content = std::fs::read_to_string(tmp.path().join("via_registry.txt")).expect("read");
127        assert_eq!(content, "registry dispatch test");
128    }
129
130    /// `dispatch_gated` routes `read_file` and returns content.
131    ///
132    /// Why: Verifies the read dispatch path end-to-end.
133    /// What: Write a file, register `read_file`, dispatch, assert content in result.
134    /// Test: This test.
135    #[tokio::test]
136    async fn dispatch_gated_routes_read_file() {
137        let tmp = tempfile::tempdir().expect("tempdir");
138        std::fs::write(tmp.path().join("test.txt"), "hello from registry").expect("seed");
139
140        let mut reg = ToolRegistry::new();
141        reg.register(Arc::new(ReadFileTool::new(tmp.path())));
142
143        let result = reg
144            .dispatch_gated("read_file", json!({"path": "test.txt"}), None)
145            .await;
146
147        assert!(
148            !result.is_error(),
149            "dispatch should succeed: {}",
150            result.content()
151        );
152        assert!(result.content().contains("hello from registry"));
153    }
154
155    /// `dispatch_gated` routes `edit` and the file is modified.
156    ///
157    /// Why: Verifies the edit dispatch path end-to-end.
158    /// What: Write `old`, register `edit`, dispatch replace, assert `new` on disk.
159    /// Test: This test.
160    #[tokio::test]
161    async fn dispatch_gated_routes_edit() {
162        let tmp = tempfile::tempdir().expect("tempdir");
163        std::fs::write(tmp.path().join("target.py"), "x = 0\n").expect("seed");
164
165        let mut reg = ToolRegistry::new();
166        reg.register(Arc::new(EditTool::new(tmp.path())));
167
168        let result = reg
169            .dispatch_gated(
170                "edit",
171                json!({"path": "target.py", "old_string": "x = 0", "new_string": "x = 99"}),
172                None,
173            )
174            .await;
175
176        assert!(
177            !result.is_error(),
178            "dispatch should succeed: {}",
179            result.content()
180        );
181        let content = std::fs::read_to_string(tmp.path().join("target.py")).expect("read");
182        assert!(content.contains("x = 99"));
183    }
184}