返回 CodeWhale
web_tool.rs
根目录 / crates / engine / src / tools / web_tool.rs
1 //! Canonical action-based wrapper for web tools.
2 //!
3 //! The model sees one tool: `Web` with an `action` parameter
4 //! (search | fetch | wait). The per-action legacy execution aliases were
5 //! removed in v0.9.3.
6
7 use async_trait::async_trait;
8 use serde_json::{Value, json};
9
10 use super::dev_server_readiness::WaitForDevServerTool;
11 use super::fetch_url::FetchUrlTool;
12 use super::spec::{
13 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
14 };
15 use super::web_search::WebSearchTool;
16 use codewhale_tools::required_action;
17
18 pub struct WebTool {
19 name: &'static str,
20 }
21
22 impl WebTool {
23 pub const fn new(name: &'static str) -> Self {
24 Self { name }
25 }
26
27 const ACTIONS: &'static [&'static str] = &["search", "fetch", "wait"];
28
29 /// Policy-side resolution: approval and parallel-safety predicates cannot
30 /// fail, so a missing action resolves to the most conservative answer.
31 /// Execution does not share this fallback — see `required_action`.
32 fn resolve_action<'a>(&self, input: &'a Value) -> &'a str {
33 input
34 .get("action")
35 .and_then(Value::as_str)
36 .unwrap_or("search")
37 }
38
39 fn required_action(&self, input: &Value) -> Result<String, ToolError> {
40 required_action(input, self.name, Self::ACTIONS)
41 }
42
43 fn strip_action(&self, input: Value) -> Result<Value, ToolError> {
44 let mut input = input;
45 if let Some(obj) = input.as_object_mut() {
46 obj.remove("action");
47 Ok(input)
48 } else {
49 Err(ToolError::invalid_input("Web tool input must be an object"))
50 }
51 }
52 }
53
54 #[async_trait]
55 impl ToolSpec for WebTool {
56 fn name(&self) -> &'static str {
57 self.name
58 }
59
60 fn model_visible(&self) -> bool {
61 self.name == "Web"
62 }
63
64 fn description(&self) -> &'static str {
65 "Search the web, fetch a known URL, or wait for a local dev server. fetch retrieves a canonical URL directly; search finds sources when the URL is unknown. Web actions are read-only and network-policy aware."
66 }
67
68 fn input_schema(&self) -> Value {
69 json!({
70 "type": "object",
71 "properties": {
72 "action": {
73 "type": "string",
74 "enum": ["search", "fetch", "wait"],
75 "description": "Action to perform"
76 },
77 "query": {
78 "type": "string",
79 "description": "Search query (action=search)"
80 },
81 "q": {
82 "type": "string",
83 "description": "Search query alias (action=search)"
84 },
85 "search_query": {
86 "type": "array",
87 "description": "Advanced search query array (action=search)",
88 "items": {
89 "type": "object",
90 "properties": {
91 "q": { "type": "string" },
92 "query": { "type": "string" },
93 "max_results": { "type": "integer" },
94 "recency": {
95 "oneOf": [
96 { "type": "string", "enum": ["day", "week", "month", "year"] },
97 { "type": "integer", "minimum": 1, "maximum": 3650 }
98 ]
99 },
100 "domains": { "type": "array", "items": { "type": "string" } },
101 "locale": {
102 "type": "string",
103 "description": "BCP 47-style result locale tag such as zh-CN or ja-JP"
104 }
105 }
106 }
107 },
108 "max_results": {
109 "type": "integer",
110 "description": "Maximum search results (action=search)"
111 },
112 "timeout_ms": {
113 "type": "integer",
114 "description": "Timeout in milliseconds (action=search, fetch, or wait)"
115 },
116 "recency": {
117 "oneOf": [
118 { "type": "string", "enum": ["day", "week", "month", "year"] },
119 { "type": "integer", "minimum": 1, "maximum": 3650 }
120 ],
121 "description": "Requested freshness window (action=search)"
122 },
123 "domains": {
124 "type": "array",
125 "items": { "type": "string" },
126 "description": "Restrict search results to domains (action=search)"
127 },
128 "locale": {
129 "type": "string",
130 "description": "Requested result locale as a BCP 47-style tag such as zh-CN or ja-JP (action=search); malformed values are ignored and backends that cannot honor the region report it as degraded"
131 },
132 "url": {
133 "type": "string",
134 "description": "URL to fetch (action=fetch) or healthcheck URL (action=wait)"
135 },
136 "format": {
137 "type": "string",
138 "enum": ["text", "markdown", "raw"],
139 "description": "Post-processing for fetched response (action=fetch)"
140 },
141 "max_bytes": {
142 "type": "integer",
143 "description": "Truncate fetched response after this many bytes (action=fetch)"
144 },
145 "fields": {
146 "type": "array",
147 "items": { "type": "string" },
148 "description": "Optional JSONPath projections for JSON responses (action=fetch). Supports $, .field, [index], [*], and ['field']; for example $.items[*].name. Recursive descent (..) and filters are not supported; returns matches under fields."
149 },
150 "host": {
151 "type": "string",
152 "description": "Loopback host to poll (action=wait)"
153 },
154 "port": {
155 "type": "integer",
156 "description": "TCP port to wait for (action=wait)"
157 },
158 "poll_interval_ms": {
159 "type": "integer",
160 "description": "Delay between readiness probes in milliseconds (action=wait)"
161 }
162 },
163 "required": ["action"]
164 })
165 }
166
167 fn capabilities(&self) -> Vec<ToolCapability> {
168 vec![ToolCapability::ReadOnly, ToolCapability::Network]
169 }
170
171 fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement {
172 let action = self.resolve_action(input);
173 let Ok(inner) = self.strip_action(input.clone()) else {
174 return ApprovalRequirement::Required;
175 };
176 match action {
177 "fetch" => FetchUrlTool.approval_requirement_for(&inner),
178 "search" => WebSearchTool.approval_requirement_for(&inner),
179 "wait" => WaitForDevServerTool.approval_requirement_for(&inner),
180 _ => ApprovalRequirement::Required,
181 }
182 }
183
184 fn is_read_only_for(&self, _input: &Value) -> bool {
185 true
186 }
187
188 fn supports_parallel_for(&self, input: &Value) -> bool {
189 matches!(self.resolve_action(input), "search" | "fetch")
190 }
191
192 fn starts_detached_for(&self, _input: &Value) -> bool {
193 false
194 }
195
196 fn refusal_before_approval(&self, input: &Value, context: &ToolContext) -> Option<ToolResult> {
197 super::web::consent::planned_search_refusal(self.name, input, context)
198 .map(ToolResult::success)
199 }
200
201 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
202 let action = self.required_action(&input)?;
203 let input = self.strip_action(input)?;
204
205 match action.as_str() {
206 "search" => WebSearchTool.execute(input, context).await,
207 "fetch" => FetchUrlTool.execute(input, context).await,
208 "wait" => WaitForDevServerTool.execute(input, context).await,
209 other => Err(ToolError::invalid_input(format!(
210 "Unknown Web action \"{other}\"; nothing was run. Pass one of: {}.",
211 Self::ACTIONS.join(", ")
212 ))),
213 }
214 }
215 }
216
217 #[cfg(test)]
218 mod tests {
219 use super::*;
220 use serde_json::json;
221 use tempfile::tempdir;
222
223 async fn err(input: Value) -> String {
224 let tmp = tempdir().expect("tempdir");
225 let ctx = ToolContext::new(tmp.path().to_path_buf());
226 WebTool::new("Web")
227 .execute(input, &ctx)
228 .await
229 .expect_err("call must be refused")
230 .to_string()
231 }
232
233 /// `Web{url: ...}` meant `fetch`; defaulting turned it into a search.
234 #[tokio::test]
235 async fn missing_action_does_not_silently_search() {
236 let message = err(json!({"url": "https://example.com"})).await;
237 assert!(message.contains("requires an `action`"), "{message}");
238 assert!(message.contains("nothing was run"), "{message}");
239 assert!(message.contains("search, fetch, wait"), "{message}");
240 }
241
242 #[tokio::test]
243 async fn unknown_action_names_the_actions_that_dispatch() {
244 let message = err(json!({"action": "get", "url": "https://example.com"})).await;
245 assert!(message.contains("get"), "{message}");
246 assert!(message.contains("search, fetch, wait"), "{message}");
247 }
248
249 #[test]
250 fn fetch_runs_in_parallel_and_keeps_its_approval() {
251 let web = WebTool::new("Web");
252 let fetch = json!({"action": "fetch", "url": "https://example.com"});
253 assert!(web.supports_parallel_for(&fetch));
254 assert!(!web.supports_parallel_for(&json!({"action": "wait", "port": 3000})));
255 assert_eq!(
256 web.approval_requirement_for(&fetch),
257 ApprovalRequirement::Required
258 );
259 assert_eq!(
260 web.approval_requirement_for(&json!("not an object")),
261 ApprovalRequirement::Required
262 );
263 }
264
265 #[test]
266 fn advertised_actions_match_the_actions_that_dispatch() {
267 let schema = WebTool::new("Web").input_schema();
268 let advertised: Vec<&str> = schema["properties"]["action"]["enum"]
269 .as_array()
270 .expect("action enum")
271 .iter()
272 .map(|value| value.as_str().expect("string"))
273 .collect();
274 assert_eq!(advertised, WebTool::ACTIONS);
275 }
276 }
277
277 lines RUST