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