返回 CodeWhale
activity.rs
根目录 / crates / engine / src / tools / activity.rs
1 //! Typed operation activity for the Engine owner contract.
2 //!
3 //! The Engine reports *what kind* of work a dispatched call is doing (reading,
4 //! editing, desktop control, ...) with a bounded canonical action identity, without arguments, command or
5 //! result. Classification reuses the resolvers dispatch already trusts:
6 //! [`canonical_action_alias`] for action families and the MCP pool's resolved
7 //! server map for MCP tools. A call that neither resolves to a concrete
8 //! operation nor to a registered tool reports nothing.
9
10 use codewhale_protocol::engine_owner::{OwnerActivityKind, OwnerOperationOutcome};
11 use serde_json::Value;
12
13 use super::spec::{RichToolResult, ToolError};
14 use codewhale_execpolicy::canonical_action::{canonical_action_alias, is_action_family};
15
16 /// Activity kind for a resolved (non-MCP) operation name.
17 fn kind_for_operation(operation: &str) -> OwnerActivityKind {
18 use OwnerActivityKind as Kind;
19 match operation {
20 "read_file" | "list_dir" | "read_media" => Kind::Reading,
21 "write_file" | "edit_file" | "apply_patch" | "fim_edit" => Kind::Editing,
22 "file_search" | "grep_files" => Kind::Searching,
23 "run_tests" | "run_verifiers" => Kind::Testing,
24 "exec_shell"
25 | "exec_shell_wait"
26 | "exec_shell_interact"
27 | "exec_shell_cancel"
28 | "task_gate_run"
29 | "automation_run"
30 | "rlm_eval" => Kind::Executing,
31 "web_search" | "fetch_url" | "wait_for_dev_server" | "rlm_open" => Kind::Browsing,
32 "memory_search" => Kind::Memory,
33 _ => Kind::Tool,
34 }
35 }
36
37 /// Classify a call the tool registry is about to dispatch.
38 ///
39 /// The caller only asks for names the registry has registered; interpreter
40 /// and MCP dispatch classify separately. Action families resolve through
41 /// [`canonical_action_alias`]; an action the wrapper would refuse (missing,
42 /// or not in the alias table) reports nothing.
43 #[must_use]
44 pub fn registry_activity_kind(tool_name: &str, input: &Value) -> Option<OwnerActivityKind> {
45 if is_action_family(tool_name) {
46 // Every family wrapper but the shell refuses an actionless call
47 // (`required_action`); the shell defaults to `run`.
48 let explicit = input.get("action").and_then(Value::as_str).is_some();
49 if !explicit && !matches!(tool_name, "bash" | "Bash") {
50 return None;
51 }
52 let operation = canonical_action_alias(tool_name, input);
53 return (operation != tool_name).then(|| kind_for_operation(operation));
54 }
55 Some(kind_for_operation(canonical_action_alias(tool_name, input)))
56 }
57
58 #[must_use]
59 pub fn action_id(tool_name: &str, input: &Value) -> String {
60 let id = canonical_action_alias(tool_name, input);
61 if !id.is_empty() && id.len() <= 256 && !id.chars().any(char::is_control) {
62 id.to_owned()
63 } else {
64 "tool".to_owned()
65 }
66 }
67
68 /// Classify an MCP call by the server the pool resolved it to, not by the
69 /// model-facing name. Desktop-control servers report `Computer`; everything
70 /// else is a generic `Tool`.
71 #[must_use]
72 pub fn mcp_activity_kind(server: &str) -> OwnerActivityKind {
73 if super::subagent::is_machine_control_tool(&format!("mcp_{server}_tool")) {
74 OwnerActivityKind::Computer
75 } else {
76 OwnerActivityKind::Tool
77 }
78 }
79
80 /// Typed outcome for a finished call. `cancelled` only reclassifies a failure:
81 /// a call that succeeded before the token fired still succeeded.
82 #[must_use]
83 pub fn operation_outcome(
84 outcome: &Result<RichToolResult, ToolError>,
85 cancelled: bool,
86 ) -> OwnerOperationOutcome {
87 match outcome {
88 Ok(result) if result.result.success => OwnerOperationOutcome::Succeeded,
89 _ if cancelled => OwnerOperationOutcome::Cancelled,
90 Ok(_) => OwnerOperationOutcome::Failed,
91 Err(ToolError::Cancelled { .. }) => OwnerOperationOutcome::Cancelled,
92 // Only a policy refusal is a denial. Bad input, an escaped path or a
93 // missing tool is the call failing, and the pet should show it.
94 Err(ToolError::PermissionDenied { .. }) => OwnerOperationOutcome::Denied,
95 Err(
96 ToolError::InvalidInput { .. }
97 | ToolError::MissingField { .. }
98 | ToolError::PathEscape { .. }
99 | ToolError::NotAvailable { .. }
100 | ToolError::ExecutionFailed { .. }
101 | ToolError::Timeout { .. },
102 ) => OwnerOperationOutcome::Failed,
103 }
104 }
105
106 #[cfg(test)]
107 mod tests {
108 use super::*;
109 use crate::tools::spec::ToolResult;
110 use serde_json::json;
111
112 use OwnerActivityKind as Kind;
113
114 #[test]
115 fn primitives_and_action_families_resolve_through_the_canonical_alias() {
116 let none = json!({});
117 assert_eq!(registry_activity_kind("read", &none), Some(Kind::Reading));
118 assert_eq!(action_id("read", &none), "read_file");
119 assert_eq!(action_id("Git", &json!({"action": "diff"})), "git_diff");
120 assert_eq!(action_id("mcp_example_custom", &none), "mcp_example_custom");
121 for unsafe_id in ["", "bad\nname", &"鲸".repeat(86)] {
122 assert_eq!(action_id(unsafe_id, &none), "tool");
123 }
124 assert_eq!(registry_activity_kind("write", &none), Some(Kind::Editing));
125 assert_eq!(registry_activity_kind("edit", &none), Some(Kind::Editing));
126 let cases = [
127 ("File", "read", Kind::Reading),
128 ("File", "patch", Kind::Editing),
129 ("File", "search_content", Kind::Searching),
130 ("Run", "tests", Kind::Testing),
131 ("Web", "fetch", Kind::Browsing),
132 ("Git", "status", Kind::Tool),
133 ("rlm", "eval", Kind::Executing),
134 ("rlm", "open", Kind::Browsing),
135 ("Bash", "run", Kind::Executing),
136 ];
137 for (family, action, kind) in cases {
138 assert_eq!(
139 registry_activity_kind(family, &json!({"action": action})),
140 Some(kind),
141 "{family}.{action}"
142 );
143 }
144 // The shell defaults an actionless call to `run`.
145 assert_eq!(
146 registry_activity_kind("bash", &json!({"command": "ls"})),
147 Some(Kind::Executing)
148 );
149 }
150
151 #[test]
152 fn refused_or_unresolved_calls_report_nothing() {
153 // Wrappers refuse an actionless or unknown action: nothing ran.
154 assert_eq!(registry_activity_kind("File", &json!({"path": "a"})), None);
155 assert_eq!(
156 registry_activity_kind("Web", &json!({"action": "teleport"})),
157 None
158 );
159 assert_eq!(registry_activity_kind("rlm", &json!({})), None);
160 assert_eq!(
161 registry_activity_kind("tasks", &json!({"action": "nope"})),
162 None
163 );
164 }
165
166 #[test]
167 fn shipped_desktop_control_servers_are_computer_activity() {
168 for server in ["codewhale-cu", "computer-use", "local-computer_use"] {
169 assert_eq!(mcp_activity_kind(server), Kind::Computer, "{server}");
170 }
171 assert_eq!(mcp_activity_kind("github"), Kind::Tool);
172 }
173
174 #[test]
175 fn cancellation_does_not_rewrite_a_successful_call() {
176 let ok = Ok(RichToolResult::plain(ToolResult::success("done")));
177 assert_eq!(
178 operation_outcome(&ok, true),
179 OwnerOperationOutcome::Succeeded,
180 "a call that finished before the token fired still succeeded"
181 );
182 let failed = Ok(RichToolResult::plain(ToolResult::error("boom")));
183 assert_eq!(
184 operation_outcome(&failed, false),
185 OwnerOperationOutcome::Failed
186 );
187 assert_eq!(
188 operation_outcome(&failed, true),
189 OwnerOperationOutcome::Cancelled
190 );
191 let denied = Err(ToolError::permission_denied("no"));
192 assert_eq!(
193 operation_outcome(&denied, false),
194 OwnerOperationOutcome::Denied
195 );
196 assert_eq!(
197 operation_outcome(&Err(ToolError::cancelled("stop")), false),
198 OwnerOperationOutcome::Cancelled
199 );
200 for failure in [
201 ToolError::Timeout { seconds: 5 },
202 ToolError::execution_failed("x"),
203 ToolError::invalid_input("bad"),
204 ToolError::missing_field("path"),
205 ToolError::not_available("gone"),
206 ] {
207 assert_eq!(
208 operation_outcome(&Err(failure), false),
209 OwnerOperationOutcome::Failed
210 );
211 }
212 }
213 }
214
214 lines RUST