Skip to main content

kaish_kernel/
dispatch.rs

1//! Command dispatch — the single execution path for all commands.
2//!
3//! The `CommandDispatcher` trait defines how a single command is resolved and
4//! executed. The Kernel implements this trait with the full dispatch chain:
5//! user tools → builtins → .kai scripts → external commands → backend tools.
6//!
7//! `PipelineRunner` calls `dispatcher.dispatch()` for each command in a
8//! pipeline, handling I/O routing (stdin piping, redirects) around each call.
9//!
10//! ```text
11//! Stmt::Command ──┐
12//!                  ├──▶ execute_pipeline() ──▶ PipelineRunner::run(dispatcher, commands, ctx)
13//! Stmt::Pipeline ──┘                                  │
14//!                                               for each command:
15//!                                                 dispatcher.dispatch(cmd, ctx)
16//!                                                     │
17//!                                               ┌─────┼──────────────┐
18//!                                               │     │              │
19//!                                          user_tools builtins  .kai scripts
20//!                                                                external cmds
21//!                                                                backend tools
22//! ```
23
24use std::sync::Arc;
25
26use anyhow::Result;
27use async_trait::async_trait;
28
29use crate::ast::{Command, Expr, Value};
30use crate::interpreter::ExecResult;
31use crate::tools::ExecContext;
32
33// The following imports are only used by the test-only `BackendDispatcher`.
34#[cfg(test)]
35use crate::ast::Arg;
36#[cfg(test)]
37use crate::backend::BackendError;
38#[cfg(test)]
39use crate::interpreter::apply_output_format;
40#[cfg(test)]
41use crate::scheduler::build_tool_args;
42#[cfg(test)]
43use crate::tools::{GlobalFlags, ToolRegistry};
44#[cfg(all(test, feature = "subprocess"))]
45use crate::tools::resolve_in_path;
46
47/// Position of a command within a pipeline.
48///
49/// Used by external command execution to decide stdio inheritance:
50/// - `Only` or `Last` in interactive mode → inherit terminal
51/// - `First` or `Middle` → always capture
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53pub enum PipelinePosition {
54    /// Single command, no pipe.
55    #[default]
56    Only,
57    /// First command in a pipeline (no stdin from pipe).
58    First,
59    /// Middle of a pipeline (piped stdin, piped stdout).
60    Middle,
61    /// Last command in a pipeline (piped stdin, final output).
62    Last,
63}
64
65/// Trait for dispatching a single command through the full resolution chain.
66///
67/// Implementations handle argument parsing, tool lookup, and execution.
68/// The pipeline runner handles I/O routing (stdin, redirects, piping).
69#[async_trait]
70pub trait CommandDispatcher: Send + Sync {
71    /// Dispatch a single command for execution.
72    ///
73    /// The `ctx` provides stdin (from pipe or redirect), scope, and backend.
74    /// Implementations should handle schema-aware argument parsing and
75    /// output format extraction internally.
76    async fn dispatch(&self, cmd: &Command, ctx: &mut ExecContext) -> Result<ExecResult>;
77
78    /// Evaluate an expression through the full async chain.
79    ///
80    /// Unlike the runner's sync `eval_simple_expr`, this can run command
81    /// substitution (`$(...)`) because it has access to pipeline execution.
82    /// Used for redirect targets and heredoc bodies so `cat < $(cmd)`,
83    /// `echo x > $(cmd)`, and `$(...)` inside heredoc bodies work. The `ctx`
84    /// carries scope/cwd/backend for dispatchers that evaluate against it;
85    /// stateful dispatchers (Kernel) snapshot their own session state and
86    /// only let command output escape (side effects like `cd` do not).
87    async fn eval_expr(&self, expr: &Expr, ctx: &ExecContext) -> Result<Value>;
88
89    /// Fork the dispatcher for concurrent execution (detached).
90    ///
91    /// Returns a subsidiary dispatcher with independent mutable state, safe
92    /// to run concurrently with the parent and other forks without data
93    /// races on shared scope/cwd/aliases. Used by background `&` jobs,
94    /// where the fork must survive parent cancellation.
95    ///
96    /// For stateful dispatchers (e.g. Kernel) this snapshots per-session
97    /// state into a fresh instance. Stateless dispatchers may clone.
98    async fn fork(&self) -> Arc<dyn CommandDispatcher>;
99
100    /// Fork the dispatcher for concurrent execution (attached to parent cancel).
101    ///
102    /// Like [`Self::fork`] but the fork's cancellation token is a *child* of
103    /// the parent's. Cancelling the parent (timeout, Ctrl-C, embedder
104    /// `Kernel::cancel`) cascades into the fork, which then kills its own
105    /// external children via the usual SIGTERM/SIGKILL discipline.
106    ///
107    /// Used for foreground concurrency: scatter workers, concurrent pipeline
108    /// stages, command substitution. Default implementation delegates to
109    /// [`Self::fork`] for stateless dispatchers that don't track cancellation.
110    async fn fork_attached(&self) -> Arc<dyn CommandDispatcher> {
111        self.fork().await
112    }
113}
114
115/// Minimal stateless dispatcher used by pipeline/runner unit tests.
116///
117/// Production code uses `Kernel` (via `Kernel::fork` for concurrent contexts).
118/// This test-only dispatcher routes directly through `backend.call_tool()` so
119/// the pipeline runner can be exercised without spinning up a full Kernel.
120///
121/// Limitations (intentional — these are test-only constraints):
122/// - No user-defined tools
123/// - No .kai script resolution
124/// - No async argument evaluation (command substitution in args won't work)
125#[cfg(test)]
126pub(crate) struct BackendDispatcher {
127    tools: Arc<ToolRegistry>,
128}
129
130#[cfg(test)]
131impl BackendDispatcher {
132    /// Create a new backend dispatcher with the given tool registry.
133    pub(crate) fn new(tools: Arc<ToolRegistry>) -> Self {
134        Self { tools }
135    }
136
137    /// Try to execute an external command (PATH lookup + process spawn).
138    ///
139    /// Used as fallback when no builtin/backend tool matches. Returns None if
140    /// the command is not found in PATH. Always captures stdout/stderr (never
141    /// inherits terminal — pipeline stages don't need interactive I/O).
142    #[cfg(not(feature = "subprocess"))]
143    async fn try_external(
144        &self,
145        _name: &str,
146        _args: &[Arg],
147        _ctx: &mut ExecContext,
148    ) -> Option<ExecResult> {
149        None
150    }
151
152    /// Try to execute an external command (PATH lookup + process spawn).
153    #[cfg(feature = "subprocess")]
154    async fn try_external(
155        &self,
156        name: &str,
157        args: &[Arg],
158        ctx: &mut ExecContext,
159    ) -> Option<ExecResult> {
160        if !ctx.allow_external_commands {
161            return None;
162        }
163
164        // Get real working directory (needed for relative path resolution and child cwd).
165        // If the CWD is virtual (no real path), skip external execution entirely.
166        let real_cwd = match ctx.backend.resolve_real_path(&ctx.cwd) {
167            Some(p) => p,
168            None => return None,
169        };
170
171        // Resolve command: absolute/relative path or PATH lookup
172        let executable = if name.contains('/') {
173            // Resolve relative paths (./script, ../bin/tool) against the shell's cwd
174            let resolved = if std::path::Path::new(name).is_absolute() {
175                std::path::PathBuf::from(name)
176            } else {
177                real_cwd.join(name)
178            };
179            if resolved.exists() {
180                resolved.to_string_lossy().into_owned()
181            } else {
182                return Some(ExecResult::failure(127, format!("{}: No such file or directory", name)));
183            }
184        } else {
185            // PATH from scope only — never OS env (keeps this test-only spawn
186            // site in sync with kernel.rs::try_execute_external).
187            let path_var = ctx.scope.get("PATH")
188                .map(crate::interpreter::value_to_string)
189                .unwrap_or_default();
190            resolve_in_path(name, &path_var)?
191        };
192
193        // Build flat argv from args
194        let argv: Vec<String> = args.iter().filter_map(|arg| {
195            match arg {
196                Arg::Positional(expr) => match expr {
197                    Expr::Literal(Value::String(s)) => Some(s.clone()),
198                    Expr::Literal(Value::Int(i)) => Some(i.to_string()),
199                    Expr::Literal(Value::Float(f)) => Some(f.to_string()),
200                    Expr::VarRef(path) => ctx.scope.resolve_path(path).map(|v| crate::interpreter::value_to_string(&v)),
201                    _ => None,
202                },
203                Arg::ShortFlag(f) => Some(format!("-{f}")),
204                Arg::LongFlag(f) => Some(format!("--{f}")),
205                Arg::Named { key, value } => match value {
206                    Expr::Literal(Value::String(s)) => Some(format!("--{key}={s}")),
207                    _ => Some(format!("--{key}=")),
208                },
209                Arg::WordAssign { key, value } => match value {
210                    Expr::Literal(Value::String(s)) => Some(format!("{key}={s}")),
211                    _ => Some(format!("{key}=")),
212                },
213                Arg::DoubleDash => Some("--".to_string()),
214            }
215        }).collect();
216
217        // Check for streaming pipes
218        let has_pipe_stdin = ctx.pipe_stdin.is_some();
219        // pipe_stdout checked later when deciding buffered vs streaming output
220        let has_buffered_stdin = ctx.stdin.is_some();
221
222        // Spawn process
223        use tokio::process::Command;
224        use tokio::io::{AsyncReadExt, AsyncWriteExt};
225
226        let mut cmd = Command::new(&executable);
227        cmd.args(&argv);
228        cmd.current_dir(&real_cwd);
229        cmd.kill_on_drop(true);
230
231        // Hermetic env: child sees only kaish's exported vars, not the kaish
232        // process's OS env. Frontends that want OS-env passthrough (REPL, MCP)
233        // populate it via KernelConfig::initial_vars at construction.
234        cmd.env_clear();
235        for (var_name, value) in ctx.scope.exported_vars() {
236            cmd.env(var_name, crate::interpreter::value_to_string(&value));
237        }
238
239        // Stdin: pipe_stdin or buffered string or inherit (interactive) or null
240        cmd.stdin(if has_pipe_stdin || has_buffered_stdin {
241            std::process::Stdio::piped()
242        } else if ctx.interactive && matches!(ctx.pipeline_position, PipelinePosition::First | PipelinePosition::Only) {
243            std::process::Stdio::inherit()
244        } else {
245            std::process::Stdio::null()
246        });
247        cmd.stdout(std::process::Stdio::piped());
248        cmd.stderr(std::process::Stdio::piped());
249
250        let mut child = match cmd.spawn() {
251            Ok(c) => c,
252            Err(e) => return Some(ExecResult::failure(127, format!("{}: {}", name, e))),
253        };
254        // Open a pidfd (Linux) for race-free direct-child kill via wait_or_kill.
255        let kill_target = crate::pidfd::KillTarget::from_child(&child);
256
257        // Stream stdin: copy pipe_stdin → child stdin in chunks (bounded memory)
258        let stdin_task: Option<tokio::task::JoinHandle<()>> = if let Some(mut pipe_in) = ctx.pipe_stdin.take() {
259            child.stdin.take().map(|mut child_stdin| {
260                tokio::spawn(async move {
261                    let mut buf = [0u8; 8192];
262                    loop {
263                        match pipe_in.read(&mut buf).await {
264                            Ok(0) => break, // EOF
265                            Ok(n) => {
266                                if child_stdin.write_all(&buf[..n]).await.is_err() {
267                                    break; // child closed stdin
268                                }
269                            }
270                            Err(_) => break,
271                        }
272                    }
273                    // Drop child_stdin signals EOF to child
274                })
275            })
276        } else if let Some(data) = ctx.stdin.take() {
277            // Buffered string stdin written from a DETACHED task, not inline:
278            // an inline write deadlocks once the stdin pipe fills before the
279            // output drain below has spawned (mirrors the kernel.rs fix; keeps
280            // the two spawn sites in sync). Drop signals EOF; a broken pipe
281            // (child closed stdin early) is fine.
282            child.stdin.take().map(|mut child_stdin| {
283                tokio::spawn(async move {
284                    let _ = child_stdin.write_all(data.as_bytes()).await;
285                })
286            })
287        } else {
288            None
289        };
290
291        // Stream stdout: copy child stdout → pipe_stdout in chunks (bounded memory)
292        if let Some(mut pipe_out) = ctx.pipe_stdout.take() {
293            // Safety: stdout/stderr were set to piped() above, so take() always returns Some
294            let Some(mut child_stdout) = child.stdout.take() else {
295                return Some(ExecResult::failure(1, "internal: stdout not available"));
296            };
297            let Some(mut child_stderr_reader) = child.stderr.take() else {
298                return Some(ExecResult::failure(1, "internal: stderr not available"));
299            };
300            // Stream stderr to the kernel's stderr stream (if available) for
301            // real-time delivery. Otherwise buffer with a cap.
302            let stderr_stream_handle = ctx.stderr.clone();
303            let stderr_task = tokio::spawn(async move {
304                let mut buf = Vec::new();
305                let mut chunk = [0u8; 8192];
306                loop {
307                    match child_stderr_reader.read(&mut chunk).await {
308                        Ok(0) => break,
309                        Ok(n) => {
310                            if let Some(ref stream) = stderr_stream_handle {
311                                // Stream raw bytes — no decode here, lossy decode at drain site
312                                stream.write(&chunk[..n]);
313                            } else {
314                                buf.extend_from_slice(&chunk[..n]);
315                            }
316                        }
317                        Err(_) => break,
318                    }
319                }
320                if stderr_stream_handle.is_some() {
321                    // Already streamed — return empty
322                    String::new()
323                } else {
324                    String::from_utf8_lossy(&buf).into_owned()
325                }
326            });
327
328            // Copy child stdout → pipe_stdout in chunks
329            let mut buf = [0u8; 8192];
330            loop {
331                match child_stdout.read(&mut buf).await {
332                    Ok(0) => break,
333                    Ok(n) => {
334                        if pipe_out.write_all(&buf[..n]).await.is_err() {
335                            break; // next stage dropped its reader (broken pipe)
336                        }
337                    }
338                    Err(_) => break,
339                }
340            }
341            let _ = pipe_out.shutdown().await;
342            drop(pipe_out);
343            let cancel = ctx.cancel.clone();
344            let status = crate::kernel::wait_or_kill(
345                &mut child,
346                kill_target.as_ref(),
347                &cancel,
348                std::time::Duration::from_secs(2),
349            ).await;
350            // Child has exited (naturally or via kill). Abort the stdin writer
351            // (nothing more to feed a dead child). Let the stderr drain FINISH
352            // — the child's stderr pipe EOFs now that it exited, so awaiting it
353            // captures all stderr; aborting first would truncate it. Only abort
354            // the drain if we were cancelled (then we don't care about output).
355            if let Some(task) = stdin_task { task.abort(); }
356            if cancel.is_cancelled() {
357                stderr_task.abort();
358            }
359            let stderr = stderr_task.await.unwrap_or_default();
360            let code = status.map(|s| s.code().unwrap_or(1) as i64).unwrap_or(1);
361            // Output was streamed to pipe, so result.out is empty
362            Some(ExecResult::from_output(code, String::new(), stderr))
363        } else {
364            // No pipe_stdout — last stage or non-pipeline.
365            // Use spill-aware collection if output limits are configured.
366            let Some(child_stdout) = child.stdout.take() else {
367                return Some(ExecResult::failure(1, "internal: stdout not available"));
368            };
369            let Some(child_stderr) = child.stderr.take() else {
370                return Some(ExecResult::failure(1, "internal: stderr not available"));
371            };
372
373            // Always use spill_aware_collect — it handles both limited and
374            // unlimited modes, and correctly streams stderr to ctx.stderr.
375            // (wait_with_output would bypass stderr streaming.)
376            let (stdout, stderr, did_spill) = crate::output_limit::spill_aware_collect(
377                child_stdout,
378                child_stderr,
379                ctx.stderr.clone(),
380                &ctx.output_limit,
381            ).await;
382
383            let cancel = ctx.cancel.clone();
384            let status = crate::kernel::wait_or_kill(
385                &mut child,
386                kill_target.as_ref(),
387                &cancel,
388                std::time::Duration::from_secs(2),
389            ).await;
390            if let Some(task) = stdin_task { task.abort(); }
391            let code = status.map(|s| s.code().unwrap_or(1) as i64).unwrap_or(1);
392            // stdout came back as raw bytes: text if valid UTF-8, else a Bytes
393            // result (so `curl url`, `curl url > file.bin`, etc. keep binary intact).
394            let mut result = ExecResult::success_text_or_bytes(stdout).with_code(code);
395            result.err = stderr;
396            result.did_spill = did_spill;
397            Some(result)
398        }
399    }
400}
401
402#[cfg(test)]
403#[async_trait]
404impl CommandDispatcher for BackendDispatcher {
405    async fn dispatch(&self, cmd: &Command, ctx: &mut ExecContext) -> Result<ExecResult> {
406        // Handle built-in true/false
407        match cmd.name.as_str() {
408            "true" => return Ok(ExecResult::success("")),
409            "false" => return Ok(ExecResult::failure(1, "")),
410            _ => {}
411        }
412
413        // Build tool args with schema-aware parsing (sync — no command substitution)
414        let schema = self.tools.get(&cmd.name).map(|t| t.schema());
415        let tool_args = build_tool_args(&cmd.args, ctx, schema.as_ref());
416
417        // Honor --json before the tool runs so a parse failure inside the
418        // builtin doesn't drop the format on the floor. See kernel.rs for the
419        // matching call in the production path.
420        GlobalFlags::apply_from_args(&tool_args, ctx);
421
422        // Execute via backend
423        let backend = ctx.backend.clone();
424        let result = match backend.call_tool(&cmd.name, tool_args, ctx).await {
425            Ok(tool_result) => {
426                let mut exec = ExecResult::from_output(
427                    tool_result.code as i64,
428                    tool_result.stdout,
429                    tool_result.stderr,
430                );
431                exec.set_output(tool_result.output);
432                exec.content_type = tool_result.content_type;
433                exec.baggage = tool_result.baggage;
434                // Restore structured data from ToolResult (preserved through backend roundtrip)
435                if let Some(json_data) = tool_result.data {
436                    exec.data = Some(Value::Json(json_data));
437                }
438                exec
439            }
440            Err(BackendError::ToolNotFound(_)) => {
441                // Fall back to external command execution
442                match self.try_external(&cmd.name, &cmd.args, ctx).await {
443                    Some(result) => result,
444                    None => ExecResult::failure(127, format!("command not found: {}", cmd.name)),
445                }
446            }
447            Err(e) => ExecResult::failure(127, e.to_string()),
448        };
449
450        // Migrated builtins parse --json via the GlobalFlags flatten and
451        // write ctx.output_format. The kernel just applies it.
452        let result = match ctx.output_format {
453            Some(format) => apply_output_format(result, format),
454            None => result,
455        };
456
457        Ok(result)
458    }
459
460    /// Sync-only evaluation (no command substitution) — matches this
461    /// test dispatcher's documented "no async argument evaluation" limit.
462    async fn eval_expr(&self, expr: &Expr, ctx: &ExecContext) -> Result<Value> {
463        crate::scheduler::pipeline::eval_simple_expr(expr, ctx)
464            .ok_or_else(|| anyhow::anyhow!("cannot evaluate expression in test dispatcher"))
465    }
466
467    /// BackendDispatcher is stateless, so a fork is just a clone.
468    async fn fork(&self) -> Arc<dyn CommandDispatcher> {
469        Arc::new(Self { tools: Arc::clone(&self.tools) })
470    }
471}