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//!
26//! (#8235) `checklist` adds `todo_write` — the model-facing write path onto
27//! the session's per-agent checklist (`session.get_agents`'s `todos`),
28//! registered on the same daemon-session registry and under the same
29//! restriction as the goal tools. Goal slots and the checklist are different
30//! surfaces: five standing objectives that survive compaction versus the
31//! ordered steps of the task in hand.
32
33pub mod bash;
34pub mod checklist;
35pub mod delegate;
36pub mod finish_task;
37pub mod fs;
38pub mod goals;
39pub mod recall_session;
40pub mod registry;
41pub mod skill;
42pub mod telemetry;
43pub mod traits;
44pub mod trusty_search;
45
46// Flat re-exports for `crate::tools::*` convenience.
47#[allow(unused_imports)]
48pub use bash::{BASH_TOOL_NAME, BashTool};
49// #8235: `todo_write` — the session checklist's model-facing write path.
50pub use checklist::{MAX_TODOS, TODO_WRITE_TOOL_NAME, TodoError, TodoStore, TodoWriteTool};
51#[allow(unused_imports)]
52pub use delegate::{DELEGATE_TO_AGENT_TOOL_NAME, DelegateToAgentTool, EngineerCompletionSignal};
53pub use finish_task::{
54    FINISH_TASK_TOOL_NAME, FinishStatus, FinishTaskArgs, FinishTaskTool, render_finish_summary,
55};
56pub use fs::{
57    EditTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, WRITE_FILES_TOOL_NAME, WriteFileTool,
58    WriteFilesTool,
59};
60pub use goals::{CLEAR_GOAL_TOOL_NAME, ClearGoalTool, SET_GOAL_TOOL_NAME, SetGoalTool};
61pub use recall_session::{RECALL_SESSION_TOOL_NAME, RecallSessionTool};
62pub use registry::ToolRegistry;
63pub use skill::{USE_SKILL_TOOL_NAME, UseSkillTool};
64pub use telemetry::{RecallTelemetry, SearchTelemetry, ToolTelemetry};
65pub use traits::{
66    AgentOutput, AgentRunner, HistoryMessage, RunContext, SearchProvider, SearchResult,
67    ServiceTier, SkillResolver, ToolExecutor, ToolResult,
68};
69pub use trusty_search::{SEARCH_CODE_TOOL_NAME, TrustySearchTool};
70
71// ── Registry integration tests for the FS tools ──────────────────────────────
72
73#[cfg(test)]
74mod fs_registry_tests {
75    use std::sync::Arc;
76
77    use serde_json::json;
78
79    use super::{EditTool, ReadFileTool, ToolRegistry, WriteFileTool};
80
81    /// All three FS tools register and appear in `schemas()`.
82    ///
83    /// Why: Verifies the complete tool plug-in lifecycle — register, schema emit,
84    /// dispatch — for the fs tool set as a group.
85    /// What: Registers `read_file`, `write_file`, and `edit`; asserts all three
86    /// schema names and that `dispatch_gated` routes to each.
87    /// Test: This test.
88    #[tokio::test]
89    async fn fs_tools_register_and_appear_in_schemas() {
90        let tmp = tempfile::tempdir().expect("tempdir");
91        let mut reg = ToolRegistry::new();
92        reg.register(Arc::new(ReadFileTool::new(tmp.path())));
93        reg.register(Arc::new(WriteFileTool::new(tmp.path())));
94        reg.register(Arc::new(EditTool::new(tmp.path())));
95
96        assert!(reg.contains("read_file"), "read_file must be registered");
97        assert!(reg.contains("write_file"), "write_file must be registered");
98        assert!(reg.contains("edit"), "edit must be registered");
99
100        let schemas = reg.schemas();
101        assert_eq!(schemas.len(), 3, "exactly three tools");
102
103        let names: Vec<&str> = schemas
104            .iter()
105            .filter_map(|s| s["function"]["name"].as_str())
106            .collect();
107        assert!(names.contains(&"read_file"));
108        assert!(names.contains(&"write_file"));
109        assert!(names.contains(&"edit"));
110    }
111
112    /// `dispatch_gated` routes `write_file` correctly.
113    ///
114    /// Why: Verifies the dispatch path end-to-end for an fs tool.
115    /// What: Register `write_file`, dispatch with valid args, assert file written.
116    /// Test: This test.
117    #[tokio::test]
118    async fn dispatch_gated_routes_write_file() {
119        let tmp = tempfile::tempdir().expect("tempdir");
120        let mut reg = ToolRegistry::new();
121        reg.register(Arc::new(WriteFileTool::new(tmp.path())));
122
123        let result = reg
124            .dispatch_gated(
125                "write_file",
126                json!({"path": "via_registry.txt", "content": "registry dispatch test"}),
127                None,
128            )
129            .await;
130
131        assert!(
132            !result.is_error(),
133            "dispatch should succeed: {}",
134            result.content()
135        );
136        let content = std::fs::read_to_string(tmp.path().join("via_registry.txt")).expect("read");
137        assert_eq!(content, "registry dispatch test");
138    }
139
140    /// `dispatch_gated` routes `read_file` and returns content.
141    ///
142    /// Why: Verifies the read dispatch path end-to-end.
143    /// What: Write a file, register `read_file`, dispatch, assert content in result.
144    /// Test: This test.
145    #[tokio::test]
146    async fn dispatch_gated_routes_read_file() {
147        let tmp = tempfile::tempdir().expect("tempdir");
148        std::fs::write(tmp.path().join("test.txt"), "hello from registry").expect("seed");
149
150        let mut reg = ToolRegistry::new();
151        reg.register(Arc::new(ReadFileTool::new(tmp.path())));
152
153        let result = reg
154            .dispatch_gated("read_file", json!({"path": "test.txt"}), None)
155            .await;
156
157        assert!(
158            !result.is_error(),
159            "dispatch should succeed: {}",
160            result.content()
161        );
162        assert!(result.content().contains("hello from registry"));
163    }
164
165    /// `dispatch_gated` routes `edit` and the file is modified.
166    ///
167    /// Why: Verifies the edit dispatch path end-to-end.
168    /// What: Write `old`, register `edit`, dispatch replace, assert `new` on disk.
169    /// Test: This test.
170    #[tokio::test]
171    async fn dispatch_gated_routes_edit() {
172        let tmp = tempfile::tempdir().expect("tempdir");
173        std::fs::write(tmp.path().join("target.py"), "x = 0\n").expect("seed");
174
175        let mut reg = ToolRegistry::new();
176        reg.register(Arc::new(EditTool::new(tmp.path())));
177
178        let result = reg
179            .dispatch_gated(
180                "edit",
181                json!({"path": "target.py", "old_string": "x = 0", "new_string": "x = 99"}),
182                None,
183            )
184            .await;
185
186        assert!(
187            !result.is_error(),
188            "dispatch should succeed: {}",
189            result.content()
190        );
191        let content = std::fs::read_to_string(tmp.path().join("target.py")).expect("read");
192        assert!(content.contains("x = 99"));
193    }
194}