aft_base/host_tool_names.rs
1//! The names a host registers AFT's command tool and patch tool under.
2//!
3//! The engine renders reply text that tells the agent which tool to call next
4//! ("Prefer `read` tool over bash.", "use apply_patch for this destructive
5//! change"). Most hosts register those two tools as `bash` and `apply_patch`,
6//! but OpenCode 2 registers them as `shell` and `patch`, the names its own
7//! timeline renders natively.
8//!
9//! The names belong to the caller, not to the project: one engine process (the
10//! subc daemon's module, or a standalone bridge) serves every head and session
11//! bound to a root, and an OpenCode 1 head, an OpenCode 2 session and a Pi
12//! session can all be bound to the same root at once. So the names travel on
13//! each request, in the `host_tool_names` envelope field beside `session_id`
14//! and `worker_session`, set by the plugin and never taken from the agent's
15//! arguments. A request without the field gets the default names, so every
16//! host that does not send it renders exactly the text it always did.
17
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20
21/// The default names, used by every host that does not say otherwise.
22pub const DEFAULT_SHELL_TOOL: &str = "bash";
23pub const DEFAULT_PATCH_TOOL: &str = "apply_patch";
24
25/// Host-facing names for AFT's command tool (engine command `bash`) and patch
26/// tool (engine command `apply_patch`). Only reply text uses them; the engine
27/// commands keep their own names.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct HostToolNames {
30 pub bash: String,
31 pub apply_patch: String,
32}
33
34impl Default for HostToolNames {
35 fn default() -> Self {
36 Self {
37 bash: DEFAULT_SHELL_TOOL.to_string(),
38 apply_patch: DEFAULT_PATCH_TOOL.to_string(),
39 }
40 }
41}
42
43/// Whether `name` is a tool name OpenCode 1 and 2 accept for a registration:
44/// at most 64 characters, an ASCII letter first, then ASCII letters, digits,
45/// `_` or `-`.
46fn valid_tool_name(name: &str) -> bool {
47 let mut chars = name.chars();
48 let Some(first) = chars.next() else {
49 return false;
50 };
51 name.len() <= 64
52 && first.is_ascii_alphabetic()
53 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
54}
55
56/// Request envelope field that carries the caller's tool names; see the
57/// module documentation.
58pub const HOST_TOOL_NAMES_FIELD: &str = "host_tool_names";
59
60impl HostToolNames {
61 /// Parse the `host_tool_names` envelope field of one request.
62 ///
63 /// Absent means the default names. The field is an object whose keys are
64 /// the engine command names (`bash`, `apply_patch`); a key it leaves out
65 /// keeps that tool's default name. Any other key, a non-string value, or
66 /// a name the hosts would refuse to register is an error.
67 pub fn from_request_field(value: Option<&Value>) -> Result<Self, String> {
68 let mut names = Self::default();
69 let Some(value) = value else {
70 return Ok(names);
71 };
72 let Some(object) = value.as_object() else {
73 return Err("host_tool_names must be an object".to_string());
74 };
75 for (key, entry) in object {
76 let slot = match key.as_str() {
77 "bash" => &mut names.bash,
78 "apply_patch" => &mut names.apply_patch,
79 other => {
80 return Err(format!(
81 "host_tool_names has unknown key `{other}`; expected `bash` or `apply_patch`"
82 ));
83 }
84 };
85 let Some(name) = entry.as_str() else {
86 return Err(format!("host_tool_names.{key} must be a string"));
87 };
88 if !valid_tool_name(name) {
89 return Err(format!(
90 "host_tool_names.{key} is not a valid tool name: {name:?}"
91 ));
92 }
93 *slot = name.to_string();
94 }
95 Ok(names)
96 }
97
98 /// The name the agent calls AFT's command tool by.
99 pub fn shell(&self) -> &str {
100 &self.bash
101 }
102
103 /// The name the agent calls AFT's patch tool by.
104 pub fn patch(&self) -> &str {
105 &self.apply_patch
106 }
107
108 /// Rewrite the hashline steering sentences that tell the agent to fall back
109 /// to the patch tool, so they name the tool the host registered.
110 ///
111 /// The steering text is a fixed table shared with the transport contract,
112 /// so it is rendered with the default name and renamed here, at the one
113 /// place a rejection becomes a reply. Only the phrase "use apply_patch" is
114 /// a reference to the tool; the rest of the sentence is left untouched.
115 pub fn name_patch_tool_in(&self, text: &str) -> String {
116 if self.apply_patch == DEFAULT_PATCH_TOOL {
117 return text.to_string();
118 }
119 text.replace(
120 &format!("use {DEFAULT_PATCH_TOOL}"),
121 &format!("use {}", self.apply_patch),
122 )
123 }
124}
125
126pub fn supports_tool(bare_name: &str) -> bool {
127 matches!(
128 bare_name,
129 "bash"
130 | "powershell"
131 | "status"
132 | "read"
133 | "write"
134 | "edit"
135 | "apply_patch"
136 | "grep"
137 | "glob"
138 | "search"
139 | "outline"
140 | "zoom"
141 | "inspect"
142 | "callgraph"
143 | "conflicts"
144 | "ast_search"
145 | "ast_replace"
146 | "delete"
147 | "move"
148 | "import"
149 | "safety"
150 | "bash_status"
151 | "bash_kill"
152 | "bash_write"
153 | "bash_watch"
154 )
155}
156
157/// Internal plumbing commands the harness consumer (NOT the agent) invokes over
158/// a bound route. These are NOT agent-facing tools — they carry no agent surface
159/// and never reach the model — so they're not in the manifest /
160/// `is_subc_agent_core_tool`, but the plugin must reach dispatch with them over
161/// subc for background-bash delivery and safety undo/restore to work.
162///
163/// This is a DELIBERATELY TIGHT allowlist, kept separate from the agent
164/// core-tool gate so it cannot widen the fail-closed backstop in
165/// `handle_tool_call`. Every entry is session-scoped (the bind session is
166/// reinjected by `run_tool_call`, overriding any body `session_id`) and carries
167/// NO config/trust surface, so admitting them does not reopen the
168/// `configure`-bypass hole the gate exists to close. The untrusted-bind bash
169/// denial fires BEFORE this allowlist (`is_bash_family_tool` matches every
170/// `bash_*` name), so untrusted binds still cannot observe bash state:
171/// - `bash_abort_inflight`: abort-only per-session cancellation of foreground
172/// bash calls that are still wait-registered; explicit background and PTY
173/// tasks are not registered and are therefore untouched.
174/// - `bash_status`: read-only per-session task snapshot; required so a
175/// respawned module can report rehydrated detached tasks by task id. It is
176/// also an agent tool (see `is_subc_agent_core_tool`); it stays listed here
177/// so the plugins' own status polling keeps being treated as plumbing (for
178/// example, it is not counted by the repeated-call breaker).
179/// - `bash_drain_completions` / `bash_ack_completions`: per-session completion
180/// registry plumbing for the bg_events wake lane (drain = PureRead,
181/// ack = Mutating in `command_lane`).
182/// - `undo_preview` / `checkpoint_paths` / `safety_purge_paths`: read-only
183/// permission-preview reads over the session's own backup/checkpoint state —
184/// the plugin safety tool calls them BEFORE `aft_safety undo`/`restore`/
185/// `purge` to know which paths to ask permission for. Without them, safety
186/// undo/restore/purge fails over subc.
187/// - `bash_kill` / `bash_write` / `bash_notify` / `bash_unnotify` /
188/// `bash_wait_detach`: the rest of the background-bash consumer surface the
189/// plugins invoke natively (kill a task, drive a PTY, register/remove a
190/// watch, detach a wait-mode command when a user message arrives). All are
191/// session-scoped task plumbing; the untrusted-bind bash denial still fires
192/// first for every `bash_*` name. `bash_kill` and `bash_write` are also agent
193/// tools; like `bash_status`, they stay listed here so the plugins' own calls
194/// keep being treated as plumbing.
195/// - `bash_regex_match`: pure regex compilation and matching for the plugins'
196/// `bash_watch` validation and output scan; its parameters are only a regex
197/// pattern and text, with no session or configuration privileges.
198/// - `bash_artifact_owned`: read-only yes/no answer for the requesting
199/// session's registered bash outputs and sandbox scratch files/directories.
200/// Plugins ask before raising an external-directory prompt for a read. It
201/// reads no content and grants nothing; the answer is scoped to the session.
202/// - `bash_owned_tasks`: read-only active task ids from the bound session's
203/// persisted owner records, used to clean up deliberately stopped workers.
204/// - `inspect_tier2_run`: the retired background Tier-2 trigger that older
205/// plugin builds still send on session idle; it answers success and does
206/// nothing.
207/// - `hashline_preflight`: parse-only, zero-mutation permission preflight for
208/// the session's enabled hashline edit surface; it returns affected paths
209/// before the plugin requests edit permission.
210pub fn is_subc_native_plumbing_tool(name: &str) -> bool {
211 matches!(
212 name,
213 "bash_abort_inflight"
214 | "bash_status"
215 | "bash_drain_completions"
216 | "bash_ack_completions"
217 | "undo_preview"
218 | "checkpoint_paths"
219 | "safety_purge_paths"
220 | "bash_kill"
221 | "bash_write"
222 | "bash_notify"
223 | "bash_unnotify"
224 | "bash_wait_detach"
225 | "bash_regex_match"
226 | "bash_artifact_owned"
227 | "bash_owned_tasks"
228 | "inspect_tier2_run"
229 | "hashline_preflight"
230 )
231}
232
233/// Is this particular call the plugins' own background plumbing rather than an
234/// agent's tool call? Used to keep slow plumbing calls out of the warning log.
235///
236/// Names only on the plumbing allowlist are always plumbing. `bash_status`,
237/// `bash_kill` and `bash_write` are on both lists, so for them the arguments
238/// decide: an agent's call through the tool catalog is spelled with the
239/// catalog's required camelCase `taskId` (see `translate_bash_task_tool`),
240/// while the plugins' native calls use the snake_case `task_id`. The request
241/// carries no other marker of who sent it.
242pub fn is_native_plumbing_call(name: &str, arguments: &Value) -> bool {
243 if !is_subc_native_plumbing_tool(name) {
244 return false;
245 }
246 if !supports_tool(name) {
247 return true;
248 }
249 let has_catalog_task_id = |value: &Value| value.get("taskId").is_some();
250 let agent_spelled =
251 has_catalog_task_id(arguments) || arguments.get("params").is_some_and(has_catalog_task_id);
252 !agent_spelled
253}
254
255use subc_protocol::manifest::ExecutionMode;
256
257/// Classify externally observable effects, not AFT's internal cache/index writes.
258/// The catalog conservatively classifies tools; individual calls can narrow that
259/// classification when their operation is explicitly read-only.
260pub fn tool_execution_mode(name: &str) -> ExecutionMode {
261 match crate::tool_gate::canonical_tool_name(name).unwrap_or(name) {
262 "bash" | "powershell" | "write" | "edit" | "apply_patch" | "ast_grep_replace"
263 | "aft_delete" | "aft_move" | "aft_import" | "aft_safety" | "bash_kill" | "bash_write" => {
264 ExecutionMode::Mutating
265 }
266 _ => ExecutionMode::Pure,
267 }
268}
269
270pub fn tool_call_is_mutating(name: &str, args: &Value) -> bool {
271 match crate::tool_gate::canonical_tool_name(name) {
272 Some("aft_safety") if matches!(args["op"].as_str(), Some("history" | "list")) => false,
273 Some("ast_grep_replace") if args["dryRun"].as_bool() == Some(true) => false,
274 _ => tool_execution_mode(name) == ExecutionMode::Mutating,
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use serde_json::json;
282
283 #[test]
284 fn absent_parameter_keeps_the_default_names() {
285 let names = HostToolNames::from_request_field(None).unwrap();
286 assert_eq!(names.shell(), "bash");
287 assert_eq!(names.patch(), "apply_patch");
288 }
289
290 #[test]
291 fn opencode_2_names_are_accepted() {
292 let names = HostToolNames::from_request_field(Some(
293 &json!({"bash": "shell", "apply_patch": "patch"}),
294 ))
295 .unwrap();
296 assert_eq!(names.shell(), "shell");
297 assert_eq!(names.patch(), "patch");
298 }
299
300 #[test]
301 fn a_missing_key_keeps_that_tools_default() {
302 let names = HostToolNames::from_request_field(Some(&json!({"bash": "shell"}))).unwrap();
303 assert_eq!(names.shell(), "shell");
304 assert_eq!(names.patch(), "apply_patch");
305 }
306
307 #[test]
308 fn malformed_parameters_are_refused() {
309 for bad in [
310 json!("shell"),
311 json!({"shell": "shell"}),
312 json!({"bash": 1}),
313 json!({"bash": ""}),
314 json!({"bash": "has space"}),
315 json!({"bash": "9lives"}),
316 ] {
317 assert!(
318 HostToolNames::from_request_field(Some(&bad)).is_err(),
319 "{bad} should be refused"
320 );
321 }
322 }
323
324 fn request(params: serde_json::Value) -> crate::protocol::RawRequest {
325 serde_json::from_value(params).expect("raw request")
326 }
327
328 #[test]
329 fn a_request_reads_its_own_envelope_field() {
330 let names = json!({"bash": "shell", "apply_patch": "patch"});
331 let top = request(json!({"id": "1", "command": "bash", "host_tool_names": names}));
332 assert_eq!(top.host_tool_names().shell(), "shell");
333 assert!(top.sent_host_tool_names().is_some());
334 // The bridge nests a bash request's arguments under `params`.
335 let nested =
336 request(json!({"id": "2", "command": "bash", "params": {"host_tool_names": names}}));
337 assert_eq!(nested.host_tool_names().patch(), "patch");
338 let absent = request(json!({"id": "3", "command": "bash"}));
339 assert_eq!(absent.host_tool_names(), HostToolNames::default());
340 assert!(absent.sent_host_tool_names().is_none());
341 // A bad value only changes wording, so it falls back instead of failing.
342 let bad = request(json!({"id": "4", "command": "bash", "host_tool_names": "shell"}));
343 assert_eq!(bad.host_tool_names(), HostToolNames::default());
344 }
345
346 #[test]
347 fn patch_steering_is_renamed_only_for_a_non_default_name() {
348 let steer = "enable backups or use apply_patch for this destructive change";
349 assert_eq!(HostToolNames::default().name_patch_tool_in(steer), steer);
350 let v2 = HostToolNames {
351 bash: "shell".into(),
352 apply_patch: "patch".into(),
353 };
354 assert_eq!(
355 v2.name_patch_tool_in(steer),
356 "enable backups or use patch for this destructive change"
357 );
358 }
359}