Skip to main content

lean_ctx_server/
agent_tools_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::collections::HashMap;
3use std::fs;
4use std::io::{self, BufRead, BufWriter, Write};
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex};
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10use tokio::sync::RwLock;
11
12use crate::server::registry::{ToolRegistry, build_registry};
13use crate::server::tool_trait::{ShellOutcome, ToolContext, ToolOutput};
14use lean_ctx::core::cache::SessionCache;
15use lean_ctx::core::session::SessionState;
16
17mod release;
18mod source;
19
20use release::protect_output;
21
22const SCHEMA_VERSION: u32 = 1;
23const TRANSPORT_VERSION: u32 = 1;
24const INTERFACE_VERSION: &str = "1.0.0";
25const MAX_POLICY_BYTES: u64 = 64 * 1024;
26const MAX_REQUEST_BYTES: usize = 1024 * 1024;
27const MAX_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
28const MAX_ID_BYTES: usize = 128;
29
30const READ_TOOLS: &[&str] = &[
31    "ctx_compose",
32    "ctx_glob",
33    "ctx_read",
34    "ctx_search",
35    "ctx_symbol",
36    "ctx_tree",
37];
38const WRITE_TOOLS: &[&str] = &["ctx_edit", "ctx_fill", "ctx_patch"];
39const EXEC_TOOLS: &[&str] = &["ctx_shell"];
40
41#[derive(Debug, Deserialize)]
42#[serde(deny_unknown_fields)]
43struct PolicyV1 {
44    schema_version: u32,
45    allow_write: bool,
46    allow_exec: bool,
47    allowed_executables: Vec<String>,
48    allowed_env: Vec<String>,
49    max_timeout_ms: u64,
50    #[serde(default)]
51    selected_gitlab: Option<source::GitLabSource>,
52}
53
54#[derive(Debug, Deserialize)]
55#[serde(deny_unknown_fields)]
56struct RequestV1 {
57    id: String,
58    op: String,
59    #[serde(default)]
60    schema_version: Option<u32>,
61    #[serde(default)]
62    transport_version: Option<u32>,
63    #[serde(default)]
64    agent_tools_interface_version: Option<String>,
65    #[serde(default)]
66    sdk_version: Option<String>,
67    #[serde(default)]
68    tool: Option<String>,
69    #[serde(default)]
70    arguments: Option<Map<String, Value>>,
71}
72
73#[derive(Debug, Serialize)]
74struct ErrorV1 {
75    code: &'static str,
76    message: String,
77}
78
79#[derive(Debug, Serialize)]
80struct ResponseV1<T: Serialize> {
81    id: String,
82    ok: bool,
83    #[serde(skip_serializing_if = "Option::is_none")]
84    result: Option<T>,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    error: Option<ErrorV1>,
87}
88
89#[derive(Debug, Serialize)]
90struct HelloResultV1 {
91    schema_version: u32,
92    transport_version: u32,
93    agent_tools_interface_version: &'static str,
94    engine_version: &'static str,
95    capabilities: Vec<&'static str>,
96    allow_write: bool,
97    allow_exec: bool,
98}
99
100#[derive(Debug, Serialize)]
101struct ToolResultV1 {
102    text: String,
103    content_blocks: Value,
104    original_tokens: usize,
105    output_tokens: usize,
106    saved_tokens: usize,
107    mode: Option<String>,
108    changed: bool,
109    shell: Option<Value>,
110}
111
112struct Session {
113    root: String,
114    policy: PolicyV1,
115    registry: ToolRegistry,
116    cache: Arc<RwLock<SessionCache>>,
117    state: Arc<RwLock<SessionState>>,
118    bm25_cache: lean_ctx::core::bm25_cache::SharedBm25Cache,
119    autonomy: lean_ctx_ext::core::autonomy::AutonomyState,
120    accepted_calls: std::sync::atomic::AtomicU32,
121    source_authority: Option<String>,
122    /// The `call` whose response frame is not written yet: its admission
123    /// capture travels from the call to the frame writer (`serve`), which
124    /// seals the receipt of the frame's bytes before it writes them.
125    frame_call: Mutex<Option<release::FrameCall>>,
126}
127
128enum InputFrame {
129    Data(Vec<u8>),
130    TooLarge,
131}
132
133fn policy_denied() -> ErrorV1 {
134    ErrorV1 {
135        code: "permission_denied",
136        message: "Tool request withheld under the current policy".into(),
137    }
138}
139
140const OUTPUT_WITHHELD: &str =
141    "Tool may have completed; output withheld by policy. Do not retry automatically.";
142
143fn output_withheld() -> ErrorV1 {
144    ErrorV1 {
145        code: "tool_error",
146        message: OUTPUT_WITHHELD.into(),
147    }
148}
149
150/// The error frame of a `call` whose mandatory receipt could not be sealed
151/// (G08): the frame with the tool result is not written; this one is.
152fn receipt_missing_response(id: &str) -> ResponseV1<Value> {
153    ResponseV1 {
154        id: id.to_string(),
155        ok: false,
156        result: None,
157        error: Some(ErrorV1 {
158            code: "tool_error",
159            message: release::not_persisted_message(),
160        }),
161    }
162}
163
164impl Session {
165    fn capabilities(&self) -> Vec<&'static str> {
166        let mut result = READ_TOOLS.to_vec();
167        if self.policy.selected_gitlab.is_some() {
168            result.push("ctx_provider");
169        }
170        if self.policy.allow_write {
171            result.extend_from_slice(WRITE_TOOLS);
172        }
173        if self.policy.allow_exec {
174            result.extend_from_slice(EXEC_TOOLS);
175        }
176        result.sort_unstable();
177        result
178    }
179
180    fn permitted(&self, tool: &str) -> bool {
181        READ_TOOLS.contains(&tool)
182            || (self.policy.selected_gitlab.is_some() && tool == "ctx_provider")
183            || (self.policy.allow_write && WRITE_TOOLS.contains(&tool))
184            || (self.policy.allow_exec && EXEC_TOOLS.contains(&tool))
185    }
186
187    /// One tool call of the session. It runs inside ONE admission capture
188    /// that carries the call's policy snapshot, taken here at entry (as the
189    /// MCP dispatcher does): source admission in the handler, the release
190    /// point and the frame's receipt decide under it. The capture is left
191    /// for the frame writer.
192    fn call(&self, tool: &str, arguments: &Map<String, Value>) -> Result<ToolOutput, ErrorV1> {
193        lean_ctx::core::policy::runtime::REQUEST_PROJECT.sync_scope(
194            std::cell::RefCell::new(Some(PathBuf::from(&self.root))),
195            || {
196                let frame_call = release::FrameCall::open(tool);
197                let capture = frame_call.capture();
198                *self
199                    .frame_call
200                    .lock()
201                    .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(frame_call);
202                lean_ctx::core::context_admission::capture::ADMISSIONS
203                    .sync_scope(Some(capture), || self.call_released(tool, arguments))
204            },
205        )
206    }
207
208    fn call_released(
209        &self,
210        tool: &str,
211        arguments: &Map<String, Value>,
212    ) -> Result<ToolOutput, ErrorV1> {
213        lean_ctx::core::policy::runtime::REQUEST_PROJECT.sync_scope(
214            std::cell::RefCell::new(Some(PathBuf::from(&self.root))),
215            || {
216                let result = self.call_scoped(tool, arguments);
217                match result {
218                    Ok(output) => {
219                        let output = protect_output(tool, output)?;
220                        if output.mode.as_deref() != Some("error") {
221                            self.consolidate_memory();
222                        }
223                        // Maintenance can cross a policy refresh. Recheck before
224                        // returning the previously admitted application output.
225                        if let Some(authority) = &self.source_authority {
226                            source::verify_authority(Path::new(&self.root), authority)?;
227                        }
228                        let output = protect_output(tool, output)?;
229                        crate::tools::ctx_provider::ensure_snapshot_output(
230                            tool,
231                            Some(arguments),
232                            &output.text,
233                        )
234                        .map_err(|_| output_withheld())?;
235                        Ok(output)
236                    }
237                    // Handler/path diagnostics can contain source data. Keep the
238                    // stable error code, but never return unchecked diagnostics.
239                    Err(mut error) => {
240                        if lean_ctx::core::policy::runtime::is_active()
241                            && !(error.code == "tool_error" && error.message == OUTPUT_WITHHELD)
242                        {
243                            error.message = "Tool request withheld under the current policy".into();
244                        }
245                        Err(error)
246                    }
247                }
248            },
249        )
250    }
251
252    fn consolidate_memory(&self) {
253        use lean_ctx::core::consolidation_engine;
254        use lean_ctx_ext::core::autonomy;
255        let calls = self
256            .accepted_calls
257            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
258            .wrapping_add(1);
259        if !autonomy::should_auto_consolidate(&self.autonomy, calls)
260            || crate::tools::LeanCtxServer::guard_role_and_policy(
261                "ctx_knowledge",
262                lean_ctx::core::agent_identity::current_agent_id(),
263            )
264            .is_some()
265        {
266            return;
267        }
268        // Reuse the canonical project session and locked knowledge store. The
269        // SDK's transient read cache must not replace a concurrent user's task.
270        // Stay in the calling authority scope; detached workers lose its policy
271        // and selected-source bindings. Private curation and persistence already
272        // enforce their lease, input budgets, deadlines and current policy.
273        if consolidation_engine::consolidate_latest(
274            &self.root,
275            consolidation_engine::ConsolidationBudgets::default(),
276        )
277        .is_err()
278        {
279            tracing::debug!("SDK memory maintenance skipped; existing memory retained");
280        }
281    }
282
283    fn call_scoped(
284        &self,
285        tool: &str,
286        arguments: &Map<String, Value>,
287    ) -> Result<ToolOutput, ErrorV1> {
288        if let Some(source) = &self.policy.selected_gitlab {
289            // Source selection is an enduring protected-session commitment:
290            // removing or invalidating its policy must not reopen local reads.
291            let authority = self.source_authority.as_deref().ok_or_else(policy_denied)?;
292            source::verify_authority(Path::new(&self.root), authority)?;
293            if tool == "ctx_provider" {
294                source.authorize_query(arguments)?;
295            }
296        }
297        if !self.permitted(tool) {
298            let code = if WRITE_TOOLS.contains(&tool) || EXEC_TOOLS.contains(&tool) {
299                "permission_denied"
300            } else {
301                "unsupported_capability"
302            };
303            return Err(ErrorV1 {
304                code,
305                message: format!("tool is not permitted: {tool}"),
306            });
307        }
308        // Agent Tools v1 (`sdk/contracts/agent-tools-v1.json`) negotiates
309        // `ctx_symbol` and `ctx_fill`, whose MCP tools were removed after
310        // 3.11.4. The contract stays: a symbol lookup runs as `ctx_search
311        // action=symbol`, and `ctx_fill` answers that it has no successor.
312        let symbol_arguments;
313        let (tool, arguments) = match tool {
314            "ctx_symbol" => {
315                let mut args = arguments.clone();
316                args.insert("action".into(), Value::String("symbol".into()));
317                symbol_arguments = args;
318                ("ctx_search", &symbol_arguments)
319            }
320            "ctx_fill" => {
321                return Err(ErrorV1 {
322                    code: "tool_error",
323                    message: "ctx_fill was removed; select context with ctx_compose and read it \
324                              with ctx_read"
325                        .into(),
326                });
327            }
328            _ => (tool, arguments),
329        };
330        if crate::tools::LeanCtxServer::guard_role_and_policy(
331            tool,
332            lean_ctx::core::agent_identity::current_agent_id(),
333        )
334        .is_some()
335        {
336            return Err(policy_denied());
337        }
338        if tool == "ctx_shell" {
339            return self.call_shell(arguments).map(redact_tool_output);
340        }
341        if crate::tools::LeanCtxServer::guard_egress(
342            tool,
343            Some(arguments),
344            lean_ctx::core::agent_identity::current_agent_id(),
345        )
346        .is_some()
347        {
348            return Err(policy_denied());
349        }
350        let handler = self.registry.get(tool).ok_or_else(|| ErrorV1 {
351            code: "unsupported_capability",
352            message: format!("tool is unavailable: {tool}"),
353        })?;
354        let mut resolved_paths = HashMap::new();
355        if let Some(path) = arguments.get("path").and_then(Value::as_str) {
356            let resolved =
357                lean_ctx::core::path_resolve::resolve_tool_path(Some(&self.root), None, path)
358                    .map_err(|message| ErrorV1 {
359                        code: "path_rejected",
360                        message,
361                    })?;
362            resolved_paths.insert(
363                "path".to_string(),
364                if resolved.is_empty() || resolved == "." {
365                    self.root.clone()
366                } else {
367                    resolved
368                },
369            );
370        }
371
372        let context = ToolContext {
373            project_root: self.root.clone(),
374            resolved_paths,
375            cache: Some(self.cache.clone()),
376            bm25_cache: Some(self.bm25_cache.clone()),
377            session: Some(self.state.clone()),
378            ..Default::default()
379        };
380        handler
381            .handle(arguments, &context)
382            .map_err(|error| ErrorV1 {
383                code: "tool_error",
384                message: error.to_string(),
385            })
386            .map(redact_tool_output)
387    }
388
389    fn call_shell(&self, arguments: &Map<String, Value>) -> Result<ToolOutput, ErrorV1> {
390        let prepared = self.prepare_shell(arguments)?;
391        if crate::tools::LeanCtxServer::guard_egress(
392            "ctx_shell",
393            Some(&prepared),
394            lean_ctx::core::agent_identity::current_agent_id(),
395        )
396        .is_some()
397        {
398            return Err(policy_denied());
399        }
400        let argv = arguments["argv"]
401            .as_array()
402            .expect("validated argv")
403            .iter()
404            .map(|value| value.as_str().expect("validated argv item"))
405            .collect::<Vec<_>>();
406        let cwd = arguments["cwd"].as_str().expect("validated cwd");
407        let resolved_cwd =
408            lean_ctx::core::path_resolve::resolve_tool_path(Some(&self.root), None, cwd).map_err(
409                |message| ErrorV1 {
410                    code: "path_rejected",
411                    message,
412                },
413            )?;
414        let resolved_cwd = if resolved_cwd.is_empty() || resolved_cwd == "." {
415            self.root.as_str()
416        } else {
417            resolved_cwd.as_str()
418        };
419        let environment = arguments["env"].as_object().expect("validated env");
420        let timeout_ms = prepared["timeout_ms"].as_u64().expect("validated timeout");
421        let display = prepared["command"].as_str().expect("prepared command");
422        let executable = resolve_allowed_executable(argv[0], &self.root)?;
423        let mut command = std::process::Command::new(executable);
424        command
425            .args(&argv[1..])
426            .current_dir(resolved_cwd)
427            .stdin(std::process::Stdio::null())
428            .stdout(std::process::Stdio::piped())
429            .stderr(std::process::Stdio::piped())
430            .env_clear();
431        for name in ["PATH", "SYSTEMROOT", "TEMP", "TMP"] {
432            if let Some(value) = std::env::var_os(name) {
433                command.env(name, value);
434            }
435        }
436        command.env("LANG", "C").env("LC_ALL", "C").env("TZ", "UTC");
437        command.envs(
438            environment
439                .iter()
440                .map(|(name, value)| (name, value.as_str().expect("validated env value"))),
441        );
442        // Reauthorize immediately before the side effect, after path resolution.
443        if crate::tools::LeanCtxServer::guard_role_and_policy(
444            "ctx_shell",
445            lean_ctx::core::agent_identity::current_agent_id(),
446        )
447        .is_some()
448        {
449            return Err(policy_denied());
450        }
451        // Q13 (Unix): the call runs in a process group of its own, so a
452        // timeout or output limit ends this call's tree and nothing else
453        // (`wait_with_limits_captured` signals a group only while its leader
454        // is the unreaped child). A guard process is attached to that group:
455        // it ends the group when this Engine lets go of it — after the call,
456        // below — or when the Engine is gone, whatever ended it. A host that
457        // ends the Engine therefore still ends running tool processes.
458        // Windows has no group: the call runs in a Job Object of its own
459        // (below).
460        //
461        // No call runs without its guard, at any moment: the call's program
462        // is executed only once the guard is ready, so an Engine that dies in
463        // between leaves nothing running. If no guard can be attached the
464        // program was never executed and the call is refused.
465        let not_executed = |_: std::io::Error| ErrorV1 {
466            code: "tool_error",
467            message: "shell process could not be executed".to_string(),
468        };
469        #[cfg(unix)]
470        let (child, guard) = {
471            use lean_ctx::shell::containment::Refusal;
472            use std::os::unix::process::CommandExt as _;
473            command.process_group(0);
474            match lean_ctx::shell::containment::start_behind_guard(&mut command) {
475                Ok((child, guard)) => (child, Some(guard)),
476                Err(Refusal::NotStarted(error)) => return Err(not_executed(error)),
477                Err(refusal) => {
478                    let reason = match refusal {
479                        Refusal::NoGuard(reason) => reason,
480                        Refusal::NotLeader | Refusal::NotStarted(_) => {
481                            "the process does not lead a group of its own".to_string()
482                        }
483                    };
484                    tracing::warn!("ctx_shell refused, no process guard: {reason}");
485                    return Err(ErrorV1 {
486                        code: "tool_error",
487                        message: "shell process could not be contained".to_string(),
488                    });
489                }
490            }
491        };
492        // Windows (B7): the call runs in a kill-on-close job of its own, held
493        // for the call (`ProcessTree::spawn_contained`).
494        #[cfg(not(unix))]
495        let (child, call_tree) =
496            lean_ctx::shell::process_tree::ProcessTree::spawn_contained(&mut command)
497                .map_err(not_executed)?;
498        let captured = lean_ctx::shell::exec::wait_with_limits_captured(
499            child,
500            MAX_RESPONSE_BYTES / 2,
501            std::time::Duration::from_millis(timeout_ms),
502            true,
503        );
504        // The call is over: whatever it left running in its group is ended by
505        // the guard, which is then reaped within its own budget.
506        // An end that is not confirmed does not fail the call, but the caller
507        // sees it: a fixed, content-free notice in front of the result.
508        #[cfg(unix)]
509        let containment_notice = guard.and_then(|guard| {
510            let ended = guard.finish();
511            if ended != lean_ctx::shell::containment::GuardOutcome::Ended {
512                tracing::warn!("ctx_shell: the call's process group end is {ended:?}");
513            }
514            lean_ctx::shell::containment::end_notice(ended)
515        });
516        #[cfg(not(unix))]
517        let containment_notice: Option<&'static str> = {
518            drop(call_tree); // closing the call's job ends what it left running
519            None
520        };
521        let completeness = captured.completeness;
522        let output = captured.output;
523        let exit_code = lean_ctx::shell::exit_status::exit_code(output.status);
524        if lean_ctx::core::policy::runtime::is_active()
525            && (std::str::from_utf8(&output.stdout).is_err()
526                || std::str::from_utf8(&output.stderr).is_err())
527        {
528            return Err(output_withheld());
529        }
530        let mut raw_output = String::from_utf8_lossy(&output.stdout).into_owned();
531        raw_output.push_str(&String::from_utf8_lossy(&output.stderr));
532        let original_tokens = lean_ctx::core::tokens::count_tokens(&raw_output);
533        // Admission of the ORIGINAL output, before anything shortens it, and
534        // with what the capture knows about its completeness: a truncated,
535        // timed-out or abandoned capture is decided by the gateway's mode
536        // instead of being compressed as if it were whole.
537        let admission = lean_ctx::core::context_admission::admit_tool_output_as(
538            &raw_output,
539            completeness,
540            &lean_ctx::core::patterns::output_class(display),
541        );
542        let Some(admitted) = admission.text.as_deref() else {
543            return Err(output_withheld());
544        };
545        let raw_output = crate::server::policy_guard::protect_result("ctx_shell", admitted)
546            .map_err(|_| output_withheld())?;
547        let raw_output = lean_ctx::core::redaction::redact_text_if_enabled(&raw_output);
548        let text = crate::tools::ctx_shell::handle(
549            display,
550            &raw_output,
551            exit_code,
552            lean_ctx::core::protocol::CrpMode::Compact,
553        );
554        // The gateway's content-free notice stays in front of the compressed
555        // text; compression never sees or drops it.
556        let text = match &admission.notice {
557            Some(notice) => format!("{notice}\n{text}"),
558            None => text,
559        };
560        // Q13: same place, same rule, for an unconfirmed end of the call's
561        // process group. Fixed text; nothing of the run is in it.
562        let text = match containment_notice {
563            Some(notice) => format!("{notice}\n{text}"),
564            None => text,
565        };
566        let output_tokens = lean_ctx::core::tokens::count_tokens(&text);
567        Ok(ToolOutput {
568            text,
569            original_tokens,
570            saved_tokens: original_tokens.saturating_sub(output_tokens),
571            mode: Some("shell".to_string()),
572            path: None,
573            changed: false,
574            shell_outcome: Some(ShellOutcome::Exit(exit_code)),
575            content_blocks: None,
576        })
577    }
578
579    fn prepare_shell(&self, arguments: &Map<String, Value>) -> Result<Map<String, Value>, ErrorV1> {
580        const KEYS: &[&str] = &["argv", "cwd", "env", "timeout_ms"];
581        if arguments.keys().any(|key| !KEYS.contains(&key.as_str())) {
582            return Err(invalid_request("shell arguments are invalid"));
583        }
584        let argv = arguments
585            .get("argv")
586            .and_then(Value::as_array)
587            .ok_or_else(|| invalid_request("argv is required"))?;
588        if argv.is_empty() || argv.len() > 256 {
589            return Err(invalid_request("argv length is invalid"));
590        }
591        let argv: Result<Vec<&str>, ErrorV1> = argv
592            .iter()
593            .map(|value| {
594                value
595                    .as_str()
596                    .filter(|item| !item.is_empty() && !item.contains('\0'))
597                    .ok_or_else(|| invalid_request("argv item is invalid"))
598            })
599            .collect();
600        let argv = argv?;
601        if argv[0].contains('/') || argv[0].contains('\\') {
602            return Err(ErrorV1 {
603                code: "permission_denied",
604                message: "executable must be a bare allowlisted name".to_string(),
605            });
606        }
607        let executable = argv[0];
608        if !self
609            .policy
610            .allowed_executables
611            .iter()
612            .any(|allowed| allowed == executable)
613        {
614            return Err(ErrorV1 {
615                code: "permission_denied",
616                message: format!("executable is not allowed: {executable}"),
617            });
618        }
619
620        let timeout_ms = arguments
621            .get("timeout_ms")
622            .and_then(Value::as_u64)
623            .unwrap_or(self.policy.max_timeout_ms);
624        if !(100..=self.policy.max_timeout_ms).contains(&timeout_ms) {
625            return Err(ErrorV1 {
626                code: "permission_denied",
627                message: "shell timeout exceeds policy".to_string(),
628            });
629        }
630        let environment = arguments
631            .get("env")
632            .and_then(Value::as_object)
633            .ok_or_else(|| invalid_request("env must be an object"))?;
634        for (name, value) in environment {
635            if !value.is_string() || !self.policy.allowed_env.contains(name) {
636                return Err(ErrorV1 {
637                    code: "permission_denied",
638                    message: format!("environment variable is not allowed: {name}"),
639                });
640            }
641        }
642        if arguments.get("cwd").and_then(Value::as_str).is_none() {
643            return Err(invalid_request("cwd must be a string"));
644        }
645
646        let mut prepared = arguments.clone();
647        prepared.remove("argv");
648        prepared.insert(
649            "command".to_string(),
650            Value::String(lean_ctx::shell::platform::join_command(
651                &argv
652                    .iter()
653                    .map(|item| (*item).to_string())
654                    .collect::<Vec<_>>(),
655            )),
656        );
657        prepared.insert("timeout_ms".to_string(), Value::from(timeout_ms));
658        Ok(prepared)
659    }
660}
661
662fn redact_tool_output(mut output: ToolOutput) -> ToolOutput {
663    output.text = crate::server::policy_guard::redact_model_text(&output.text);
664    output
665}
666
667fn invalid_request(message: &str) -> ErrorV1 {
668    ErrorV1 {
669        code: "invalid_request",
670        message: message.to_string(),
671    }
672}
673
674fn resolve_allowed_executable(name: &str, root: &str) -> Result<PathBuf, ErrorV1> {
675    let path = std::env::var_os("PATH").ok_or_else(|| ErrorV1 {
676        code: "permission_denied",
677        message: "trusted executable search path is unavailable".to_string(),
678    })?;
679    for directory in std::env::split_paths(&path).filter(|path| path.is_absolute()) {
680        if directory.starts_with(root) {
681            continue;
682        }
683        #[cfg(windows)]
684        let candidates = if Path::new(name).extension().is_some() {
685            vec![directory.join(name)]
686        } else {
687            vec![
688                directory.join(format!("{name}.exe")),
689                directory.join(format!("{name}.com")),
690            ]
691        };
692        #[cfg(not(windows))]
693        let candidates = vec![directory.join(name)];
694        for candidate in candidates {
695            let Ok(canonical) = candidate.canonicalize() else {
696                continue;
697            };
698            if candidate.starts_with(root) || !canonical.is_file() || canonical.starts_with(root) {
699                continue;
700            }
701            #[cfg(unix)]
702            {
703                use std::os::unix::fs::PermissionsExt;
704                if canonical
705                    .metadata()
706                    .map_or(true, |metadata| metadata.permissions().mode() & 0o111 == 0)
707                {
708                    continue;
709                }
710            }
711            return Ok(canonical);
712        }
713    }
714    Err(ErrorV1 {
715        code: "permission_denied",
716        message: format!("allowed executable was not found on trusted PATH: {name}"),
717    })
718}
719
720pub fn cmd_agent_tools(args: &[String]) {
721    let Ok(runtime) = tokio::runtime::Runtime::new() else {
722        eprintln!("engine: runtime_unavailable");
723        std::process::exit(2);
724    };
725    let result = runtime.block_on(async {
726        tokio::task::block_in_place(|| run(args, io::stdin().lock(), io::stdout().lock()))
727    });
728    if let Err(code) = result {
729        eprintln!("engine: {code}");
730        std::process::exit(2);
731    }
732}
733
734fn run<R: BufRead, W: Write>(args: &[String], reader: R, writer: W) -> Result<(), &'static str> {
735    let (root, policy_path) = parse_args(args)?;
736    let root = canonical_root(&root)?;
737    let policy = read_policy(&policy_path)?;
738    let source_authority = policy
739        .selected_gitlab
740        .as_ref()
741        .map(|source| source.initialize(Path::new(&root)))
742        .transpose()?;
743    let mut state = SessionState::new();
744    state.project_root = Some(root.clone());
745    state.shell_cwd = Some(root.clone());
746    let session = Session {
747        root,
748        policy,
749        registry: build_registry(),
750        cache: Arc::new(RwLock::new(SessionCache::new())),
751        state: Arc::new(RwLock::new(state)),
752        bm25_cache: Arc::new(Mutex::new(None)),
753        autonomy: lean_ctx_ext::core::autonomy::AutonomyState::new(),
754        accepted_calls: std::sync::atomic::AtomicU32::new(0),
755        source_authority,
756        frame_call: Mutex::new(None),
757    };
758    serve(&session, reader, writer)
759}
760
761fn serve<R: BufRead, W: Write>(
762    session: &Session,
763    mut reader: R,
764    writer: W,
765) -> Result<(), &'static str> {
766    let mut writer = BufWriter::new(writer);
767    let mut hello_complete = false;
768    while let Some(frame) = read_frame(&mut reader).map_err(|_| "request_read_failed")? {
769        let response = match frame {
770            InputFrame::TooLarge => {
771                error_response("", "request_too_large", "request exceeds size bound")
772            }
773            InputFrame::Data(line) => match serde_json::from_slice::<RequestV1>(&line) {
774                Ok(request) => handle_request(session, request, &mut hello_complete),
775                Err(_) => error_response("", "invalid_request", "request is not strict JSON v1"),
776            },
777        };
778        let should_close = !response.id.is_empty()
779            && response
780                .result
781                .as_ref()
782                .is_some_and(|value| value.get("closed").and_then(Value::as_bool) == Some(true));
783        let mut encoded = serde_json::to_vec(&response).map_err(|_| "response_write_failed")?;
784        if encoded.len().saturating_add(1) > MAX_RESPONSE_BYTES {
785            encoded = serde_json::to_vec(&error_response(
786                &response.id,
787                "response_too_large",
788                "response exceeds size bound",
789            ))
790            .map_err(|_| "response_write_failed")?;
791        }
792        // The frame as it leaves: one line.
793        encoded.push(b'\n');
794        // G08: a `call` frame is a delivery to the host. Its receipt binds
795        // exactly these bytes and is sealed BEFORE they are written; where
796        // it is mandatory and missing, the frame is replaced by an error
797        // frame and the tool result does not leave.
798        let frame_call = session
799            .frame_call
800            .lock()
801            .unwrap_or_else(std::sync::PoisonError::into_inner)
802            .take();
803        let prepared = match frame_call {
804            Some(call) => {
805                let sealed = lean_ctx::core::policy::runtime::REQUEST_PROJECT.sync_scope(
806                    std::cell::RefCell::new(Some(PathBuf::from(&session.root))),
807                    || call.seal(&session.root, &encoded, !response.ok),
808                );
809                if let Ok(prepared) = sealed {
810                    prepared
811                } else {
812                    encoded = serde_json::to_vec(&receipt_missing_response(&response.id))
813                        .map_err(|_| "response_write_failed")?;
814                    encoded.push(b'\n');
815                    None
816                }
817            }
818            None => None,
819        };
820        writer
821            .write_all(&encoded)
822            .map_err(|_| "response_write_failed")?;
823        writer.flush().map_err(|_| "response_write_failed")?;
824        // OBSERVED: the frame was written and flushed to the session
825        // transport. That the host read it is not observable.
826        if let Some(prepared) = &prepared {
827            release::returned(prepared, &encoded);
828        }
829        if should_close {
830            break;
831        }
832    }
833    Ok(())
834}
835
836fn read_frame<R: BufRead>(reader: &mut R) -> io::Result<Option<InputFrame>> {
837    let mut data = Vec::new();
838    let mut too_large = false;
839    loop {
840        let buffer = reader.fill_buf()?;
841        if buffer.is_empty() {
842            return if data.is_empty() && !too_large {
843                Ok(None)
844            } else if too_large {
845                Ok(Some(InputFrame::TooLarge))
846            } else {
847                Ok(Some(InputFrame::Data(data)))
848            };
849        }
850
851        let newline = buffer.iter().position(|byte| *byte == b'\n');
852        let consumed = newline.map_or(buffer.len(), |index| index + 1);
853        let payload = newline.map_or(buffer, |index| &buffer[..index]);
854        if !too_large {
855            if data.len().saturating_add(payload.len()) > MAX_REQUEST_BYTES {
856                data.clear();
857                too_large = true;
858            } else {
859                data.extend_from_slice(payload);
860            }
861        }
862        reader.consume(consumed);
863        if newline.is_some() {
864            return Ok(Some(if too_large {
865                InputFrame::TooLarge
866            } else {
867                InputFrame::Data(data)
868            }));
869        }
870    }
871}
872
873fn handle_request(session: &Session, request: RequestV1, hello: &mut bool) -> ResponseV1<Value> {
874    if validate_id(&request.id).is_err() {
875        return error_response("", "invalid_request", "id is invalid");
876    }
877    match request.op.as_str() {
878        "hello" => {
879            if *hello {
880                return error_response(&request.id, "invalid_state", "hello already completed");
881            }
882            if request.schema_version != Some(SCHEMA_VERSION)
883                || request.transport_version != Some(TRANSPORT_VERSION)
884                || request.agent_tools_interface_version.as_deref() != Some(INTERFACE_VERSION)
885                || request.sdk_version.as_deref().is_none_or(str::is_empty)
886                || request.tool.is_some()
887                || request.arguments.is_some()
888            {
889                return error_response(
890                    &request.id,
891                    "unsupported_interface",
892                    "hello version or shape is unsupported",
893                );
894            }
895            *hello = true;
896            let result = HelloResultV1 {
897                schema_version: SCHEMA_VERSION,
898                transport_version: TRANSPORT_VERSION,
899                agent_tools_interface_version: INTERFACE_VERSION,
900                engine_version: env!("CARGO_PKG_VERSION"),
901                capabilities: session.capabilities(),
902                allow_write: session.policy.allow_write,
903                allow_exec: session.policy.allow_exec,
904            };
905            success_response(
906                &request.id,
907                serde_json::to_value(result).expect("serializable"),
908            )
909        }
910        "call" => {
911            if !*hello {
912                return error_response(&request.id, "invalid_state", "hello is required first");
913            }
914            if request.schema_version.is_some()
915                || request.transport_version.is_some()
916                || request.agent_tools_interface_version.is_some()
917                || request.sdk_version.is_some()
918            {
919                return error_response(&request.id, "invalid_request", "call shape is invalid");
920            }
921            let Some(tool) = request.tool else {
922                return error_response(&request.id, "invalid_request", "tool is required");
923            };
924            let arguments = request.arguments.unwrap_or_default();
925            // `changed` of v1: a write tool applied its change (not a dry run).
926            let applied = WRITE_TOOLS.contains(&tool.as_str())
927                && arguments.get("dry_run").and_then(Value::as_bool) != Some(true);
928            match session.call(&tool, &arguments) {
929                Ok(output) => {
930                    let result = ToolResultV1 {
931                        // v1 clients require original = output + saved. These
932                        // legacy accounting counters are not measured egress.
933                        output_tokens: output.original_tokens.saturating_sub(output.saved_tokens),
934                        original_tokens: output.original_tokens,
935                        saved_tokens: output.saved_tokens,
936                        mode: output.mode,
937                        changed: output.changed || applied,
938                        shell: agent_shell_outcome(output.shell_outcome.as_ref()),
939                        content_blocks: serde_json::to_value(
940                            output.content_blocks.unwrap_or_default(),
941                        )
942                        .expect("serializable content blocks"),
943                        text: output.text,
944                    };
945                    success_response(
946                        &request.id,
947                        serde_json::to_value(result).expect("serializable"),
948                    )
949                }
950                Err(error) => ResponseV1 {
951                    id: request.id,
952                    ok: false,
953                    result: None,
954                    error: Some(error),
955                },
956            }
957        }
958        "close" => {
959            if !*hello
960                || request.schema_version.is_some()
961                || request.transport_version.is_some()
962                || request.agent_tools_interface_version.is_some()
963                || request.sdk_version.is_some()
964                || request.tool.is_some()
965                || request.arguments.is_some()
966            {
967                return error_response(&request.id, "invalid_request", "close shape is invalid");
968            }
969            success_response(&request.id, serde_json::json!({ "closed": true }))
970        }
971        _ => error_response(&request.id, "invalid_request", "unknown operation"),
972    }
973}
974
975fn success_response(id: &str, result: Value) -> ResponseV1<Value> {
976    ResponseV1 {
977        id: id.to_string(),
978        ok: true,
979        result: Some(result),
980        error: None,
981    }
982}
983
984fn agent_shell_outcome(outcome: Option<&ShellOutcome>) -> Option<Value> {
985    match outcome {
986        Some(ShellOutcome::Exit(code)) => Some(serde_json::json!({ "exitCode": code })),
987        Some(other) => other.structured(),
988        None => None,
989    }
990}
991
992fn error_response(id: &str, code: &'static str, message: &str) -> ResponseV1<Value> {
993    ResponseV1 {
994        id: id.to_string(),
995        ok: false,
996        result: None,
997        error: Some(ErrorV1 {
998            code,
999            message: message.to_string(),
1000        }),
1001    }
1002}
1003
1004fn validate_id(id: &str) -> Result<(), ()> {
1005    let bytes = id.as_bytes();
1006    if bytes.is_empty() || bytes.len() > MAX_ID_BYTES || id.chars().any(char::is_control) {
1007        Err(())
1008    } else {
1009        Ok(())
1010    }
1011}
1012
1013fn parse_args(args: &[String]) -> Result<(PathBuf, PathBuf), &'static str> {
1014    let mut root = None;
1015    let mut policy = None;
1016    let mut index = 0;
1017    while index < args.len() {
1018        let flag = args[index].as_str();
1019        index += 1;
1020        let value = args.get(index).ok_or("invalid_request")?;
1021        match flag {
1022            "--project-root" if root.is_none() => root = Some(PathBuf::from(value)),
1023            "--policy-file" if policy.is_none() => policy = Some(PathBuf::from(value)),
1024            _ => return Err("invalid_request"),
1025        }
1026        index += 1;
1027    }
1028    Ok((
1029        root.ok_or("invalid_request")?,
1030        policy.ok_or("invalid_request")?,
1031    ))
1032}
1033
1034fn canonical_root(root: &Path) -> Result<String, &'static str> {
1035    if lean_ctx::core::pathutil::is_broad_or_unsafe_root(root) {
1036        return Err("unsafe_root");
1037    }
1038    let root = fs::canonicalize(root).map_err(|_| "unsafe_root")?;
1039    if !root.is_dir() || lean_ctx::core::pathutil::is_broad_or_unsafe_root(&root) {
1040        return Err("unsafe_root");
1041    }
1042    Ok(root.to_string_lossy().into_owned())
1043}
1044
1045fn read_policy(path: &Path) -> Result<PolicyV1, &'static str> {
1046    let metadata = fs::symlink_metadata(path).map_err(|_| "policy_unavailable")?;
1047    if !metadata.file_type().is_file() || metadata.len() > MAX_POLICY_BYTES {
1048        return Err("policy_unavailable");
1049    }
1050    #[cfg(unix)]
1051    {
1052        use std::os::unix::fs::PermissionsExt;
1053        if metadata.permissions().mode() & 0o077 != 0 {
1054            return Err("policy_permissions");
1055        }
1056    }
1057    let bytes = fs::read(path).map_err(|_| "policy_unavailable")?;
1058    let policy: PolicyV1 = serde_json::from_slice(&bytes).map_err(|_| "invalid_policy")?;
1059    let executable_policy_valid = (!policy.allow_exec && policy.allowed_executables.is_empty())
1060        || (policy.allow_exec
1061            && !policy.allowed_executables.is_empty()
1062            && is_canonical_names(&policy.allowed_executables, is_executable_name));
1063    if policy.schema_version != SCHEMA_VERSION
1064        || !executable_policy_valid
1065        || !is_canonical_names(&policy.allowed_env, is_env_name)
1066        || !(100..=120_000).contains(&policy.max_timeout_ms)
1067    {
1068        return Err("invalid_policy");
1069    }
1070    Ok(policy)
1071}
1072
1073fn is_canonical_names(values: &[String], valid: fn(&str) -> bool) -> bool {
1074    values.windows(2).all(|pair| pair[0] < pair[1]) && values.iter().all(|value| valid(value))
1075}
1076
1077fn is_executable_name(value: &str) -> bool {
1078    !value.is_empty()
1079        && Path::new(value).file_name().and_then(|name| name.to_str()) == Some(value)
1080        && value
1081            .chars()
1082            .all(|character| character.is_alphanumeric() || "._+-".contains(character))
1083}
1084
1085fn is_env_name(value: &str) -> bool {
1086    let mut characters = value.chars();
1087    !matches!(
1088        value.to_ascii_uppercase().as_str(),
1089        "COMSPEC"
1090            | "DYLD_INSERT_LIBRARIES"
1091            | "DYLD_LIBRARY_PATH"
1092            | "HOME"
1093            | "LD_LIBRARY_PATH"
1094            | "LD_PRELOAD"
1095            | "PATH"
1096            | "PATHEXT"
1097            | "PYTHONPATH"
1098            | "RUSTC_WRAPPER"
1099            | "SHELL"
1100    ) && characters
1101        .next()
1102        .is_some_and(|first| first.is_alphabetic() || first == '_')
1103        && characters.all(|character| character.is_alphanumeric() || character == '_')
1104}
1105
1106#[cfg(test)]
1107#[path = "agent_tools_cmd_tests.rs"]
1108mod tests;
1109
1110#[cfg(all(test, unix))]
1111mod shell_gate_tests;