Skip to main content

kian_loop/
tools.rs

1//! Built-in local `ToolProvider` + `ExecBackend`.
2//!
3//! The built-in tool set is local fs + exec, confined to a root
4//! directory. Two disciplines are baked in:
5//!
6//! - **Log-before-execute** is enforced by the loop (it appends the
7//!   `tool/call` event *before* invoking this provider); side-effecting
8//!   built-ins (`fs_write`, `exec`) rely on that ordering for their audit
9//!   trail.
10//! - **Never block a tokio worker**: every fs operation and every local
11//!   process runs inside `spawn_blocking`, so a sleeping tool cannot stall
12//!   concurrent drains (AGENTS.md async gotcha).
13
14use std::collections::BTreeMap;
15use std::io::Read;
16use std::path::{Path, PathBuf};
17use std::process::{Command, Stdio};
18use std::sync::Arc;
19use std::time::{Duration, Instant};
20
21use futures::future::BoxFuture;
22use kian_core::seams::{
23    ExecBackend, ExecCommand, ExecError, ExecResult, ToolCall, ToolError, ToolProvider, ToolResult,
24    ToolSchema,
25};
26use kian_core::secrets::{ExecEnvPolicy, SecretRedactor};
27use serde_json::{Value, json};
28
29/// Default wall-clock bound for one local exec, milliseconds.
30pub const DEFAULT_EXEC_TIMEOUT_MS: u64 = 30_000;
31
32/// Poll interval of the exec timeout watchdog.
33const EXEC_POLL_MS: u64 = 5;
34
35// ---------------------------------------------------------------------------
36// LocalExecBackend (ExecBackend seam built-in, local)
37// ---------------------------------------------------------------------------
38
39/// Local command execution via `spawn_blocking` (DESIGN §6.2 `ExecBackend`
40/// built-). argv is executed directly — never a shell string.
41///
42/// secret hygiene, applied at this (the only) local spawn site:
43///
44/// - **Environment**: [`ExecEnvPolicy`] bounds what the child inherits.
45///   The default is today's full inheritance (the config-compat
46///   clause); allowlist mode clears the environment and passes only
47///   the listed variables plus `DRY_RUN` — server secrets never reach
48///   the child, so a child-side `env` dump has nothing to leak.
49/// - **Output**: every stdout/stderr byte passes the [`SecretRedactor`]
50///   before leaving this backend, so no caller (tool result, event
51///   stream, transcript envelope) can observe a secret verbatim. The
52///   default redactor keeps pattern scanning on; assembly layers the
53///   configured secret values on top.
54#[derive(Debug, Clone)]
55pub struct LocalExecBackend {
56    default_timeout_ms: u64,
57    env_policy: ExecEnvPolicy,
58    redactor: SecretRedactor,
59}
60
61impl LocalExecBackend {
62    #[must_use]
63    pub fn new() -> Self {
64        Self {
65            default_timeout_ms: DEFAULT_EXEC_TIMEOUT_MS,
66            env_policy: ExecEnvPolicy::Inherit,
67            redactor: SecretRedactor::patterns_only(),
68        }
69    }
70
71    /// Overrides the timeout applied when a command carries none.
72    #[must_use]
73    pub fn with_default_timeout(mut self, timeout_ms: u64) -> Self {
74        self.default_timeout_ms = timeout_ms;
75        self
76    }
77
78    /// Sets the child environment policy. `Inherit` (the
79    /// default) keeps today's full-passthrough behavior.
80    #[must_use]
81    pub fn with_env_policy(mut self, policy: ExecEnvPolicy) -> Self {
82        self.env_policy = policy;
83        self
84    }
85
86    /// Sets the output redactor. The default is
87    /// patterns-only; assembly builds the full redactor from the
88    /// configured secret env names.
89    #[must_use]
90    pub fn with_redactor(mut self, redactor: SecretRedactor) -> Self {
91        self.redactor = redactor;
92        self
93    }
94}
95
96impl Default for LocalExecBackend {
97    fn default() -> Self {
98        Self::new()
99    }
100}
101
102impl ExecBackend for LocalExecBackend {
103    fn exec(&self, cmd: ExecCommand) -> BoxFuture<'static, Result<ExecResult, ExecError>> {
104        let default_timeout = self.default_timeout_ms;
105        let env_policy = self.env_policy.clone();
106        let redactor = self.redactor.clone();
107        Box::pin(async move {
108            // A blocking child process must never run on a runtime worker
109            // (AGENTS.md): the whole spawn/poll/collect runs on the
110            // dedicated blocking pool.
111            tokio::task::spawn_blocking(move || {
112                run_blocking(cmd, default_timeout, &env_policy, &redactor)
113            })
114            .await
115            .map_err(|e| ExecError::Spawn(format!("blocking join failed: {e}")))?
116        })
117    }
118}
119
120/// The blocking-side exec: spawn, watchdog-poll `try_wait`, kill on
121/// timeout, collect output via dedicated reader threads (so a child
122/// filling the pipe buffer cannot deadlock the watchdog).
123fn run_blocking(
124    cmd: ExecCommand,
125    default_timeout_ms: u64,
126    env_policy: &ExecEnvPolicy,
127    redactor: &SecretRedactor,
128) -> Result<ExecResult, ExecError> {
129    let argv = &cmd.argv;
130    let Some(program) = argv.first() else {
131        return Err(ExecError::Spawn("argv must not be empty".into()));
132    };
133    let mut command = Command::new(program);
134    command
135        .args(&argv[1..])
136        .envs(&cmd.env)
137        .stdin(Stdio::null())
138        .stdout(Stdio::piped())
139        .stderr(Stdio::piped());
140    // allowlist mode replaces the inherited environment with
141    // the closed set (configured names + DRY_RUN); `None` (inherit)
142    // leaves the spawn command's environment untouched.
143    if let Some(child_env) = env_policy.resolve() {
144        command.env_clear().envs(&child_env);
145    }
146    if let Some(cwd) = &cmd.cwd {
147        command.current_dir(cwd);
148    }
149    let mut child = command
150        .spawn()
151        .map_err(|e| ExecError::Spawn(format!("{program}: {e}")))?;
152
153    let stdout_t = ReaderThread::spawn(child.stdout.take());
154    let stderr_t = ReaderThread::spawn(child.stderr.take());
155
156    let timeout = Duration::from_millis(cmd.timeout_ms.unwrap_or(default_timeout_ms));
157    let deadline = Instant::now() + timeout;
158    let mut timed_out = false;
159    let mut exit_code = None;
160    loop {
161        match child.try_wait().map_err(|e| ExecError::Io(e.to_string()))? {
162            Some(status) => {
163                exit_code = status.code();
164                break;
165            }
166            None => {
167                if Instant::now() >= deadline {
168                    timed_out = true;
169                    let _ = child.kill();
170                    let _ = child.wait();
171                    break;
172                }
173                std::thread::sleep(Duration::from_millis(EXEC_POLL_MS));
174            }
175        }
176    }
177    // the redaction pass runs before the result leaves the
178    // backend — every caller (tool/result event, transcript envelopes,
179    // retries) only ever sees scrubbed bytes. The same pass now
180    // emits its provenance report, merged across stdout/stderr and
181    // carried on the result.
182    let (stdout, stdout_report) = redactor.redact_with_report(&stdout_t.join());
183    let (stderr, stderr_report) = redactor.redact_with_report(&stderr_t.join());
184    Ok(ExecResult {
185        exit_code,
186        stdout,
187        stderr,
188        timed_out,
189        redactions: kian_core::secrets::merge_redaction_reports(
190            stdout_report.into_iter().chain(stderr_report),
191        ),
192    })
193}
194
195/// Reads a piped child stream to EOF on its own OS thread (`None` — an
196/// uninherited stream — reads as empty).
197struct ReaderThread {
198    handle: Option<std::thread::JoinHandle<String>>,
199}
200
201impl ReaderThread {
202    fn spawn<R: Read + Send + 'static>(reader: Option<R>) -> Self {
203        Self {
204            handle: Some(std::thread::spawn(move || match reader {
205                Some(mut reader) => {
206                    let mut buf = Vec::new();
207                    // Best effort: a child killed mid-write may close early.
208                    let _ = reader.read_to_end(&mut buf);
209                    String::from_utf8_lossy(&buf).into_owned()
210                }
211                None => String::new(),
212            })),
213        }
214    }
215
216    fn join(mut self) -> String {
217        self.handle
218            .take()
219            .and_then(|h| h.join().ok())
220            .unwrap_or_default()
221    }
222}
223
224// ---------------------------------------------------------------------------
225// LocalTools (ToolProvider seam built-in: fs + exec)
226// ---------------------------------------------------------------------------
227
228/// The built-in local tool set, confined to `root`:
229///
230/// - `exec` — `{ "argv": [..], "cwd"?: string, "timeout_ms"?: u64 }`
231///   (side-effecting; runs via [`LocalExecBackend`]).
232/// - `fs_list` — `{ "path": string }` (relative to `root`)
233/// - `fs_read` — `{ "path": string }`
234/// - `fs_write` — `{ "path": string, "content": string }` (side-effecting)
235///
236/// Tool names are dotless: strict OpenAI-compatible endpoints
237/// validate `tools[n].function.name` against `^[a-zA-Z0-9_-]+$` and
238/// reject the pre-rename dotted spelling (`fs.list` et al.) with HTTP
239/// 400. The dotted legacy names are still ACCEPTED by [`ToolProvider::
240/// invoke`] (but never advertised) so sessions recorded before the
241/// rename keep working when replayed.
242///
243/// Tool schemas are exposed sorted by name — the request-body
244/// serialization freezes the `tools` array order (contract), so the
245/// built-in set must be deterministic.
246#[derive(Debug, Clone)]
247pub struct LocalTools {
248    root: PathBuf,
249    exec: LocalExecBackend,
250}
251
252impl LocalTools {
253    /// Creates the tool set rooted at `root` (the directory is created if
254    /// missing). Call this at assembly time, not inside a drain.
255    pub fn new(root: impl Into<PathBuf>) -> Self {
256        let root = root.into();
257        std::fs::create_dir_all(&root)
258            .unwrap_or_else(|e| panic!("LocalTools root {root:?} cannot be created: {e}"));
259        Self {
260            root,
261            exec: LocalExecBackend::new(),
262        }
263    }
264
265    #[must_use]
266    pub fn with_exec_timeout(mut self, timeout_ms: u64) -> Self {
267        self.exec = self.exec.with_default_timeout(timeout_ms);
268        self
269    }
270
271    /// sets the exec child environment policy (forwarded to
272    /// the inner [`LocalExecBackend`]).
273    #[must_use]
274    pub fn with_env_policy(mut self, policy: kian_core::secrets::ExecEnvPolicy) -> Self {
275        self.exec = self.exec.with_env_policy(policy);
276        self
277    }
278
279    /// sets the exec output redactor (forwarded to the inner
280    /// [`LocalExecBackend`]).
281    #[must_use]
282    pub fn with_redactor(mut self, redactor: kian_core::secrets::SecretRedactor) -> Self {
283        self.exec = self.exec.with_redactor(redactor);
284        self
285    }
286
287    #[must_use]
288    pub fn root(&self) -> &Path {
289        &self.root
290    }
291
292    fn schema_list() -> Vec<ToolSchema> {
293        vec![
294            ToolSchema {
295                name: "exec".into(),
296                description: "Run a local command (argv vector, no shell).".into(),
297                parameters: json!({
298                    "type": "object",
299                    "properties": {
300                        "argv": {
301                            "type": "array",
302                            "items": {"type": "string"},
303                            "description": "command and arguments"
304                        },
305                        "cwd": {"type": "string"},
306                        "timeout_ms": {"type": "integer"}
307                    },
308                    "required": ["argv"]
309                }),
310            },
311            ToolSchema {
312                name: "fs_list".into(),
313                description: "List entries of a directory under the workspace root.".into(),
314                parameters: json!({
315                    "type": "object",
316                    "properties": {"path": {"type": "string"}},
317                    "required": ["path"]
318                }),
319            },
320            ToolSchema {
321                name: "fs_read".into(),
322                description: "Read a text file under the workspace root.".into(),
323                parameters: json!({
324                    "type": "object",
325                    "properties": {"path": {"type": "string"}},
326                    "required": ["path"]
327                }),
328            },
329            ToolSchema {
330                name: "fs_write".into(),
331                description: "Write a text file under the workspace root (side-effecting).".into(),
332                parameters: json!({
333                    "type": "object",
334                    "properties": {
335                        "path": {"type": "string"},
336                        "content": {"type": "string"}
337                    },
338                    "required": ["path", "content"]
339                }),
340            },
341        ]
342    }
343}
344
345/// Validates that a parsed fs path stays inside the root (the one lexical
346/// rule shared with the worker-side executor, `kian_core::fs`).
347fn confine(rel: String) -> Result<String, ToolError> {
348    kian_core::fs::confine_path(&rel)
349        .map(|()| rel)
350        .map_err(ToolError::InvalidCall)
351}
352
353impl ToolProvider for LocalTools {
354    fn schemas(&self) -> Vec<ToolSchema> {
355        let mut schemas = Self::schema_list();
356        schemas.sort_by(|a, b| a.name.cmp(&b.name));
357        schemas
358    }
359
360    fn invoke(&self, call: ToolCall) -> BoxFuture<'static, Result<ToolResult, ToolError>> {
361        // Resolve and validate arguments on the calling task (cheap, pure);
362        // only the I/O side goes to the blocking pool.
363        let parsed: Result<ParsedCall, ToolError> = match call.name.as_str() {
364            "exec" => parse_exec(&call.arguments).map(ParsedCall::Exec),
365            // Dotted legacy spellings (legacy history) stay invocable
366            // but are never advertised in `schemas()`.
367            "fs_list" | "fs.list" => parse_path_only(&call.arguments)
368                .and_then(confine)
369                .map(ParsedCall::List),
370            "fs_read" | "fs.read" => parse_path_only(&call.arguments)
371                .and_then(confine)
372                .map(ParsedCall::Read),
373            "fs_write" | "fs.write" => parse_write(&call.arguments)
374                .and_then(|(p, c)| confine(p).map(|p| (p, c)))
375                .map(|(p, c)| ParsedCall::Write(p, c)),
376            other => Err(ToolError::InvalidCall(format!("unknown tool {other:?}"))),
377        };
378        let call_id = call.id;
379        let root = self.root.clone();
380        let exec = self.exec.clone();
381        Box::pin(async move {
382            // the exec arm carries the redaction provenance report
383            // from the backend onto the ToolResult (the loop copies it
384            // into the `tool/result` payload); every other arm leaves
385            // it empty (nothing was redacted).
386            let mut redactions = Vec::new();
387            let output = match parsed? {
388                ParsedCall::Exec(cmd) => {
389                    // Errors of execution itself are honest tool-level
390                    // failures, surfaced as is_error results.
391                    match exec.exec(cmd).await {
392                        Ok(r) => {
393                            redactions = r.redactions;
394                            (
395                                json!({
396                                    "exit_code": r.exit_code,
397                                    "stdout": r.stdout,
398                                    "stderr": r.stderr,
399                                    "timed_out": r.timed_out,
400                                }),
401                                r.exit_code != Some(0),
402                            )
403                        }
404                        Err(e) => (json!({"error": e.to_string()}), true),
405                    }
406                }
407                ParsedCall::List(rel) => {
408                    blocking_io(move || {
409                        let dir = root.join(&rel);
410                        let mut names: Vec<String> = Vec::new();
411                        for entry in std::fs::read_dir(&dir).map_err(|e| e.to_string())? {
412                            let entry = entry.map_err(|e| e.to_string())?;
413                            names.push(entry.file_name().to_string_lossy().into_owned());
414                        }
415                        names.sort();
416                        Ok(json!({"entries": names}).with_error_flag(false))
417                    })
418                    .await
419                }
420                ParsedCall::Read(rel) => {
421                    blocking_io(move || {
422                        let path = root.join(&rel);
423                        let content = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
424                        Ok(json!({"content": content}).with_error_flag(false))
425                    })
426                    .await
427                }
428                ParsedCall::Write(rel, content) => {
429                    blocking_io(move || {
430                        let path = root.join(&rel);
431                        if let Some(parent) = path.parent() {
432                            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
433                        }
434                        std::fs::write(&path, content).map_err(|e| e.to_string())?;
435                        Ok(json!({"written": true}).with_error_flag(false))
436                    })
437                    .await
438                }
439            };
440            let (value, is_error) = output;
441            Ok(ToolResult {
442                call_id,
443                output: value,
444                is_error,
445                redactions,
446            })
447        })
448    }
449}
450
451enum ParsedCall {
452    Exec(ExecCommand),
453    List(String),
454    Read(String),
455    Write(String, String),
456}
457
458// ---------------------------------------------------------------------------
459// FilteredTools (config-filterable mounted surface)
460// ---------------------------------------------------------------------------
461
462/// A config-driven allowlist over another [`ToolProvider`].
463///
464/// `AgentDef.tools` names the agent's mounted surface; this wrapper
465/// enforces it at the provider edge: schemas not in the list are hidden
466/// from the request body (prefix minimization — the model never sees
467/// tools the agent may not call), and invoking a hidden name is an
468/// honest [`ToolError::InvalidCall`], never a silent passthrough.
469///
470/// The wrapper is *narrow*: it only ever removes from the inner
471/// surface, so the caller-supplied schema order (the frozen tools
472/// array order) is preserved.
473#[derive(Clone)]
474pub struct FilteredTools {
475    inner: Arc<dyn ToolProvider>,
476    allow: std::collections::BTreeSet<String>,
477}
478
479impl FilteredTools {
480    /// Wraps `inner` so only `allow`-listed tool names are visible.
481    /// Names in `allow` that the inner provider does not mount are
482    /// harmless (they simply never surface); use
483    /// [`unmatched_tool_names`] for the assembly-time fail-closed check.
484    #[must_use]
485    pub fn new(inner: Arc<dyn ToolProvider>, allow: &[String]) -> Self {
486        Self {
487            inner,
488            allow: allow.iter().cloned().collect(),
489        }
490    }
491}
492
493impl ToolProvider for FilteredTools {
494    fn schemas(&self) -> Vec<ToolSchema> {
495        self.inner
496            .schemas()
497            .into_iter()
498            .filter(|s| self.allow.contains(&s.name))
499            .collect()
500    }
501
502    fn invoke(&self, call: ToolCall) -> BoxFuture<'static, Result<ToolResult, ToolError>> {
503        if !self.allow.contains(&call.name) {
504            return Box::pin(std::future::ready(Err(ToolError::InvalidCall(format!(
505                "tool {:?} is not in this agent's mounted surface",
506                call.name
507            )))));
508        }
509        self.inner.invoke(call)
510    }
511}
512
513/// The `listed` tool names that appear nowhere in `mounted` — the
514/// assembly-time fail-closed check for `AgentDef.tools`: a typo'd name
515/// refuses boot instead of silently shrinking the agent's surface.
516#[must_use]
517pub fn unmatched_tool_names(listed: &[String], mounted: &[ToolSchema]) -> Vec<String> {
518    let mounted_names: std::collections::BTreeSet<&str> =
519        mounted.iter().map(|s| s.name.as_str()).collect();
520    listed
521        .iter()
522        .filter(|n| !mounted_names.contains(n.as_str()))
523        .cloned()
524        .collect()
525}
526
527/// `Value` helper carrying the honest error flag through the match arms.
528trait WithErrorFlag {
529    fn with_error_flag(self, is_error: bool) -> (Value, bool);
530}
531
532impl WithErrorFlag for Value {
533    fn with_error_flag(self, is_error: bool) -> (Value, bool) {
534        (self, is_error)
535    }
536}
537
538/// Runs a blocking fs operation on the blocking pool and converts I/O
539/// failures into honest `is_error` tool results.
540async fn blocking_io<F>(f: F) -> (Value, bool)
541where
542    F: FnOnce() -> Result<(Value, bool), String> + Send + 'static,
543{
544    match tokio::task::spawn_blocking(f).await {
545        Ok(Ok(pair)) => pair,
546        Ok(Err(e)) => json!({"error": e}).with_error_flag(true),
547        Err(e) => (json!({"error": format!("blocking join failed: {e}")}), true),
548    }
549}
550
551fn parse_exec(args: &Value) -> Result<ExecCommand, ToolError> {
552    let argv = args
553        .get("argv")
554        .and_then(Value::as_array)
555        .filter(|a| !a.is_empty())
556        .and_then(|a| {
557            a.iter()
558                .map(|v| v.as_str().map(str::to_owned))
559                .collect::<Option<Vec<_>>>()
560        })
561        .ok_or_else(|| ToolError::InvalidCall("'argv' must be a non-empty string array".into()))?;
562    Ok(ExecCommand {
563        argv,
564        env: BTreeMap::new(),
565        cwd: args.get("cwd").and_then(Value::as_str).map(str::to_owned),
566        timeout_ms: args.get("timeout_ms").and_then(Value::as_u64),
567    })
568}
569
570fn parse_path_only(args: &Value) -> Result<String, ToolError> {
571    args.get("path")
572        .and_then(Value::as_str)
573        .map(str::to_owned)
574        .filter(|p| !p.is_empty())
575        .ok_or_else(|| ToolError::InvalidCall("'path' must be a non-empty string".into()))
576}
577
578fn parse_write(args: &Value) -> Result<(String, String), ToolError> {
579    let path = parse_path_only(args)?;
580    let content = args
581        .get("content")
582        .and_then(Value::as_str)
583        .map(str::to_owned)
584        .ok_or_else(|| ToolError::InvalidCall("'content' must be a string".into()))?;
585    Ok((path, content))
586}
587
588#[cfg(test)]
589mod tests {
590    use std::path::PathBuf;
591    use std::sync::Arc;
592
593    use super::{FilteredTools, LocalExecBackend, LocalTools, unmatched_tool_names};
594    use kian_core::seams::{ExecBackend, ExecCommand, ToolCall, ToolProvider};
595
596    fn temp_root() -> PathBuf {
597        let p = std::env::temp_dir().join(format!("kian-loop-tools-{}", uuid::Uuid::new_v4()));
598        std::fs::create_dir_all(&p).unwrap();
599        p
600    }
601
602    fn call(id: &str, name: &str, arguments: serde_json::Value) -> ToolCall {
603        ToolCall {
604            id: id.into(),
605            name: name.into(),
606            arguments,
607        }
608    }
609
610    #[tokio::test]
611    async fn fs_read_write_list_round_trip_within_root() {
612        let root = temp_root();
613        let tools = LocalTools::new(&root);
614
615        let write = tools
616            .invoke(call(
617                "c1",
618                "fs_write",
619                serde_json::json!({"path": "notes/a.txt", "content": "hello kian"}),
620            ))
621            .await
622            .unwrap();
623        assert!(!write.is_error);
624        let read = tools
625            .invoke(call(
626                "c2",
627                "fs_read",
628                serde_json::json!({"path": "notes/a.txt"}),
629            ))
630            .await
631            .unwrap();
632        assert_eq!(
633            read.output.get("content").and_then(|v| v.as_str()),
634            Some("hello kian")
635        );
636        let list = tools
637            .invoke(call("c3", "fs_list", serde_json::json!({"path": "notes"})))
638            .await
639            .unwrap();
640        assert_eq!(
641            list.output.get("entries"),
642            Some(&serde_json::json!(["a.txt"]))
643        );
644        let _ = std::fs::remove_dir_all(&root);
645    }
646
647    /// pre-rename history carries the dotted spellings — they
648    /// stay invocable (never advertised) so replayed sessions work.
649    #[tokio::test]
650    async fn dotted_legacy_tool_names_stay_invocable() {
651        let root = temp_root();
652        let tools = LocalTools::new(&root);
653        let write = tools
654            .invoke(call(
655                "c1",
656                "fs.write",
657                serde_json::json!({"path": "legacy.txt", "content": "old dialect"}),
658            ))
659            .await
660            .unwrap();
661        assert!(!write.is_error);
662        let read = tools
663            .invoke(call(
664                "c2",
665                "fs.read",
666                serde_json::json!({"path": "legacy.txt"}),
667            ))
668            .await
669            .unwrap();
670        assert_eq!(
671            read.output.get("content").and_then(|v| v.as_str()),
672            Some("old dialect")
673        );
674        // ...but the advertised surface is dotless only.
675        let advertised: Vec<String> = tools.schemas().into_iter().map(|s| s.name).collect();
676        assert!(!advertised.contains(&"fs.read".to_string()));
677        let _ = std::fs::remove_dir_all(&root);
678    }
679
680    #[tokio::test]
681    async fn fs_path_escape_is_rejected() {
682        let root = temp_root();
683        let tools = LocalTools::new(&root);
684        let err = tools
685            .invoke(call(
686                "c1",
687                "fs_read",
688                serde_json::json!({"path": "../escape.txt"}),
689            ))
690            .await
691            .unwrap_err();
692        assert!(matches!(err, kian_core::seams::ToolError::InvalidCall(_)));
693        let _ = std::fs::remove_dir_all(&root);
694    }
695
696    #[tokio::test]
697    async fn fs_read_of_missing_file_is_an_honest_error_result() {
698        let root = temp_root();
699        let tools = LocalTools::new(&root);
700        let res = tools
701            .invoke(call(
702                "c1",
703                "fs_read",
704                serde_json::json!({"path": "nope.txt"}),
705            ))
706            .await
707            .unwrap();
708        assert!(res.is_error);
709        let _ = std::fs::remove_dir_all(&root);
710    }
711
712    #[tokio::test]
713    async fn exec_echo_returns_output() {
714        let exec = LocalExecBackend::new();
715        let res = exec
716            .exec(ExecCommand {
717                argv: vec!["echo".into(), "42".into()],
718                env: Default::default(),
719                cwd: None,
720                timeout_ms: Some(5_000),
721            })
722            .await
723            .unwrap();
724        assert_eq!(res.exit_code, Some(0));
725        assert_eq!(res.stdout.trim(), "42");
726        assert!(!res.timed_out);
727    }
728
729    #[tokio::test]
730    async fn exec_timeout_kills_and_reports_timed_out() {
731        let exec = LocalExecBackend::new();
732        let started = std::time::Instant::now();
733        let res = exec
734            .exec(ExecCommand {
735                argv: vec!["sleep".into(), "30".into()],
736                env: Default::default(),
737                cwd: None,
738                timeout_ms: Some(150),
739            })
740            .await
741            .unwrap();
742        assert!(res.timed_out);
743        assert_eq!(res.exit_code, None);
744        assert!(started.elapsed() < std::time::Duration::from_secs(5));
745    }
746
747    #[tokio::test]
748    async fn exec_via_tool_reports_nonzero_exit_as_error_result() {
749        let root = temp_root();
750        let tools = Arc::new(LocalTools::new(&root));
751        let res = tools
752            .invoke(call("c1", "exec", serde_json::json!({"argv": ["false"]})))
753            .await
754            .unwrap();
755        assert!(res.is_error);
756        assert_eq!(res.output.get("exit_code"), Some(&serde_json::json!(1)));
757        let _ = std::fs::remove_dir_all(&root);
758    }
759
760    #[test]
761    fn schemas_are_deterministic_and_sorted() {
762        let tools = LocalTools::new(temp_root());
763        let schemas = tools.schemas();
764        let names: Vec<&str> = schemas.iter().map(|s| s.name.as_str()).collect();
765        assert_eq!(names, ["exec", "fs_list", "fs_read", "fs_write"]);
766        assert_eq!(names, {
767            let mut sorted = names.clone();
768            sorted.sort();
769            sorted
770        });
771    }
772
773    /// regression: strict OpenAI-compatible endpoints validate
774    /// `tools[n].function.name` against `^[a-zA-Z0-9_-]{1,64}$` and
775    /// answer HTTP 400 otherwise (verified live against real DeepSeek).
776    /// Every advertised built-in name must match.
777    #[test]
778    fn advertised_tool_names_match_the_strict_endpoint_pattern() {
779        let tools = LocalTools::new(temp_root());
780        for s in tools.schemas() {
781            assert!(
782                !s.name.is_empty()
783                    && s.name.len() <= 64
784                    && s.name
785                        .chars()
786                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
787                "tool name {:?} violates ^[a-zA-Z0-9_-]{{1,64}}$",
788                s.name
789            );
790        }
791    }
792
793    #[tokio::test]
794    async fn unknown_tool_and_bad_args_are_invalid_calls() {
795        let tools = LocalTools::new(temp_root());
796        assert!(
797            tools
798                .invoke(call("c1", "nope", serde_json::json!({})))
799                .await
800                .is_err()
801        );
802        assert!(
803            tools
804                .invoke(call("c2", "fs_read", serde_json::json!({"path": 3})))
805                .await
806                .is_err()
807        );
808        assert!(
809            tools
810                .invoke(call("c3", "exec", serde_json::json!({"argv": []})))
811                .await
812                .is_err()
813        );
814    }
815
816    // -- FilteredTools --------------------------------------------
817
818    // -- exec secret hygiene (env allowlist + output redaction) --
819
820    /// SAFETY: each name is written by exactly one test with a constant
821    /// value (idempotent re-writes); the names are unique to these
822    /// tests, so parallel tests never contend on the same variable.
823    fn set_env_once(name: &'static str, value: &'static str) {
824        unsafe {
825            std::env::set_var(name, value);
826        }
827    }
828
829    /// The acceptance test: a worker that dumps its environment (or
830    /// echoes a configured secret) must persist **no** configured secret
831    /// through the exec tool result — the exact live leak from the
832    /// run, now redacted at the tool edge before the result is emitted.
833    #[tokio::test]
834    async fn exec_env_dump_persists_no_configured_secret() {
835        const NAME: &str = "KIAN_LOOP_TEST_SECRET";
836        const VALUE: &str = "kian-loop-test-secret-value-0123456789";
837        set_env_once(NAME, VALUE);
838        let root = temp_root();
839        let redactor = kian_core::secrets::SecretRedactor::from_env_names(&[NAME.to_string()]);
840        let tools = LocalTools::new(&root).with_redactor(redactor);
841        let res = tools
842            .invoke(call(
843                "c1",
844                "exec",
845                serde_json::json!({"argv": ["bash", "-c", format!("echo {NAME}=${NAME}").as_str()]}),
846            ))
847            .await
848            .unwrap();
849        assert!(!res.is_error, "the command itself succeeds");
850        let stdout = res.output.get("stdout").and_then(|v| v.as_str()).unwrap();
851        assert!(!stdout.contains(VALUE), "secret value must not persist");
852        assert!(
853            stdout.contains(&format!("{NAME}=[REDACTED:{NAME}]")),
854            "the redaction marker names the variable: {stdout:?}"
855        );
856        let _ = std::fs::remove_dir_all(&root);
857    }
858
859    /// Allowlist mode: the child inherits only the listed variables
860    /// (plus DRY_RUN) — an environment dump from the child contains no
861    /// server secret, because the child never saw one.
862    #[tokio::test]
863    async fn exec_allowlist_environment_hides_secrets_from_children() {
864        const ALLOWED: &str = "KIAN_LOOP_TEST_ALLOW";
865        const SECRET: &str = "KIAN_LOOP_TEST_SECRET2";
866        set_env_once(ALLOWED, "visible");
867        set_env_once(SECRET, "hidden-value-abcdefghij");
868        let root = temp_root();
869        let tools =
870            LocalTools::new(&root).with_env_policy(kian_core::secrets::ExecEnvPolicy::allowlist(
871                &["PATH".to_string(), ALLOWED.to_string()],
872            ));
873        let res = tools
874            .invoke(call(
875                "c1",
876                "exec",
877                serde_json::json!({"argv": ["bash", "-c", format!("echo allowed=${ALLOWED} secret=${SECRET}").as_str()]}),
878            ))
879            .await
880            .unwrap();
881        assert!(!res.is_error);
882        let stdout = res.output.get("stdout").and_then(|v| v.as_str()).unwrap();
883        assert!(
884            stdout.contains("allowed=visible"),
885            "listed var passes: {stdout:?}"
886        );
887        assert!(
888            stdout.contains("secret=") && !stdout.contains("hidden-value-abcdefghij"),
889            "unlisted secret never reached the child: {stdout:?}"
890        );
891        let _ = std::fs::remove_dir_all(&root);
892    }
893
894    /// Default redaction is patterns-on: even with no configured names,
895    /// token-shaped output never leaves the backend verbatim.
896    #[tokio::test]
897    async fn exec_default_backend_redacts_token_patterns() {
898        let exec = LocalExecBackend::new();
899        let res = exec
900            .exec(ExecCommand {
901                argv: vec![
902                    "bash".into(),
903                    "-c".into(),
904                    "echo ghp_abcdefghijklmnopqrstuvwx".into(),
905                ],
906                env: Default::default(),
907                cwd: None,
908                timeout_ms: Some(5_000),
909            })
910            .await
911            .unwrap();
912        assert_eq!(res.stdout.trim(), "[REDACTED:token]");
913    }
914
915    // -- redaction provenance through the local exec path ---------
916
917    /// The local exec path carries the report on the ExecResult and on
918    /// the ToolResult, while the model-visible `output` keeps exactly
919    /// the four legacy fields (no report inside it).
920    #[tokio::test]
921    async fn local_exec_result_carries_the_redaction_report() {
922        const NAME: &str = "KIAN_LOOP_TEST_SECRET69";
923        const VALUE: &str = "kian69-known-secret-value-abcdefgh";
924        set_env_once(NAME, VALUE);
925        let root = temp_root();
926        let redactor = kian_core::secrets::SecretRedactor::from_env_names(&[NAME.to_string()]);
927        let tools = LocalTools::new(&root).with_redactor(redactor);
928
929        // Backend level: report rides the ExecResult, merged across
930        // stdout and stderr (the known value echoes once in each).
931        let backend = LocalExecBackend::new().with_redactor(
932            kian_core::secrets::SecretRedactor::from_env_names(&[NAME.to_string()]),
933        );
934        let r = backend
935            .exec(ExecCommand {
936                argv: vec![
937                    "bash".into(),
938                    "-c".into(),
939                    format!("echo {VALUE}; echo {VALUE} >&2"),
940                ],
941                env: Default::default(),
942                cwd: None,
943                timeout_ms: Some(5_000),
944            })
945            .await
946            .unwrap();
947        assert_eq!(
948            r.redactions,
949            vec![kian_core::secrets::Redaction {
950                kind: kian_core::secrets::RedactionKind::KnownValue,
951                name: NAME.to_string(),
952                count: 2,
953            }],
954            "stdout + stderr counts merge into one entry"
955        );
956
957        // Tool level: the ToolResult carries the report; the output has
958        // exactly the four legacy keys and no report inside it.
959        let res = tools
960            .invoke(call(
961                "c1",
962                "exec",
963                serde_json::json!({"argv": ["bash", "-c", format!("echo {NAME}=${NAME}").as_str()]}),
964            ))
965            .await
966            .unwrap();
967        assert!(!res.is_error);
968        let mut keys: Vec<&str> = res
969            .output
970            .as_object()
971            .unwrap()
972            .keys()
973            .map(String::as_str)
974            .collect();
975        keys.sort_unstable();
976        assert_eq!(keys, ["exit_code", "stderr", "stdout", "timed_out"]);
977        assert_eq!(res.redactions.len(), 1);
978        assert_eq!(res.redactions[0].name, NAME);
979
980        // A clean run reports nothing: empty report, key omitted.
981        let clean = tools
982            .invoke(call("c2", "exec", serde_json::json!({"argv": ["true"]})))
983            .await
984            .unwrap();
985        assert!(clean.redactions.is_empty());
986        let _ = std::fs::remove_dir_all(&root);
987    }
988
989    #[test]
990    fn filtered_tools_hides_unlisted_schemas_and_preserves_order() {
991        let local = Arc::new(LocalTools::new(temp_root()));
992        let allow = vec!["exec".to_string(), "fs_read".to_string()];
993        let filtered = FilteredTools::new(local.clone() as Arc<dyn ToolProvider>, &allow);
994        let names: Vec<String> = filtered.schemas().into_iter().map(|s| s.name).collect();
995        assert_eq!(names, ["exec", "fs_read"], "inner (sorted) order kept");
996    }
997
998    #[tokio::test]
999    async fn filtered_tools_invoke_is_fail_closed_for_hidden_names() {
1000        let local = Arc::new(LocalTools::new(temp_root()));
1001        let allow = vec!["fs_read".to_string()];
1002        let filtered = FilteredTools::new(local as Arc<dyn ToolProvider>, &allow);
1003        // Listed name passes through to the inner provider.
1004        assert!(
1005            filtered
1006                .invoke(call("c1", "fs_read", serde_json::json!({"path": 3})))
1007                .await
1008                .is_err(),
1009            "inner validation still applies"
1010        );
1011        // Hidden name: honest InvalidCall, never a silent passthrough.
1012        let err = filtered
1013            .invoke(call("c2", "exec", serde_json::json!({"argv": ["true"]})))
1014            .await
1015            .unwrap_err();
1016        assert!(matches!(
1017            err,
1018            kian_core::seams::ToolError::InvalidCall(ref m) if m.contains("mounted surface")
1019        ));
1020    }
1021
1022    #[test]
1023    fn unmatched_tool_names_flags_typos_for_fail_closed_boot() {
1024        let mounted = LocalTools::new(temp_root()).schemas();
1025        assert!(unmatched_tool_names(&["exec".into()], &mounted).is_empty());
1026        // The pre-rename dotted spelling no longer exists — flagged.
1027        assert_eq!(
1028            unmatched_tool_names(&["fs.read".into()], &mounted),
1029            vec!["fs.read".to_string()]
1030        );
1031    }
1032}