Skip to main content

ExecContext

Struct ExecContext 

Source
pub struct ExecContext {
Show 26 fields pub backend: Arc<dyn KernelBackend>, pub scope: Scope, pub cwd: PathBuf, pub prev_cwd: Option<PathBuf>, pub stdin: Option<String>, pub stdin_data: Option<Value>, pub pipe_stdin: Option<PipeReader>, pub pipe_stdout: Option<PipeWriter>, pub tool_schemas: Vec<ToolSchema>, pub tools: Option<Arc<ToolRegistry>>, pub job_manager: Option<Arc<JobManager>>, pub stderr: Option<StderrStream>, pub pipeline_position: PipelinePosition, pub interactive: bool, pub aliases: HashMap<String, String>, pub ignore_config: IgnoreConfig, pub output_limit: OutputLimitConfig, pub allow_external_commands: bool, pub nonce_store: NonceStore, pub trash_backend: Option<Arc<dyn TrashBackend>>, pub dispatcher: Option<Arc<dyn CommandDispatcher>>, pub cancel: CancellationToken, pub output_format: Option<OutputFormat>, pub vfs_budget: Option<Arc<ByteBudget>>, pub watchdog: Option<Arc<Watchdog>>, pub overlay_handle: Option<Arc<OverlayHandle>>,
}
Expand description

Execution context passed to tools.

Provides access to the backend (for file operations and tool dispatch), scope, and other kernel state.

Fields§

§backend: Arc<dyn KernelBackend>

Kernel backend for I/O operations.

This is the preferred way to access filesystem operations. Use backend.read(), backend.write(), etc.

§scope: Scope

Variable scope.

§cwd: PathBuf

Current working directory (VFS path).

§prev_cwd: Option<PathBuf>

Previous working directory (for cd -).

§stdin: Option<String>

Standard input for the tool (from pipeline).

§stdin_data: Option<Value>

Structured data from pipeline (pre-parsed JSON from previous command). Tools can check this before parsing stdin to avoid redundant JSON parsing.

§pipe_stdin: Option<PipeReader>

Streaming pipe input (set when this command is in a concurrent pipeline).

§pipe_stdout: Option<PipeWriter>

Streaming pipe output (set when this command is in a concurrent pipeline).

§tool_schemas: Vec<ToolSchema>

Tool schemas for help command.

§tools: Option<Arc<ToolRegistry>>

Tool registry reference (for tools that need to inspect available tools).

§job_manager: Option<Arc<JobManager>>

Job manager for background jobs (optional).

§stderr: Option<StderrStream>

Kernel stderr stream for real-time error output from pipeline stages.

When set, pipeline stages write stderr here instead of buffering in ExecResult.err. This allows stderr from all stages to stream to the terminal (or other sink) concurrently, matching bash behavior.

§pipeline_position: PipelinePosition

Position of this command within a pipeline (for stdio decisions).

§interactive: bool

Whether we’re running in interactive (REPL) mode.

§aliases: HashMap<String, String>

Command aliases (name → expansion string).

§ignore_config: IgnoreConfig

Ignore file configuration for file-walking tools.

§output_limit: OutputLimitConfig

Output size limit configuration for agent safety.

§allow_external_commands: bool

Whether external command execution is allowed.

When false, external commands (PATH lookup, exec, spawn) are blocked. Only kaish builtins and backend-registered tools (MCP) are available.

§nonce_store: NonceStore

Confirmation nonce store for latch-gated operations.

Arc-shared across pipeline stages so nonces issued in one stage can be validated in another.

§trash_backend: Option<Arc<dyn TrashBackend>>

Trash backend for safe file deletion.

Always present when the kernel creates the context (even if set -o trash is off — the backend exists so kaish-trash list/restore/empty work regardless of the trash flag).

§dispatcher: Option<Arc<dyn CommandDispatcher>>

Command dispatcher for re-dispatching through the full resolution chain.

When set (via Kernel::into_arc()), builtins like timeout can dispatch inner commands through the full chain (user tools → builtins → .kai scripts → external commands) instead of being limited to backend.call_tool().

None when the Kernel was not wrapped via into_arc().

§cancel: CancellationToken

Cancellation token for this execution path.

Populated by the kernel at execute entry, then propagated through pipeline stages, foreground forks (scatter workers, concurrent pipeline stages, $(...) cmdsubs), and into spawned external children. When the token fires, externals receive SIGTERM/SIGKILL via the wait_or_kill helper.

Default for stand-alone ExecContext constructors is a fresh, never-fired token so non-kernel test contexts behave as before.

§output_format: Option<OutputFormat>

Per-execution output format override set by a builtin’s GlobalFlags flatten (e.g. --json). The dispatcher reads this after tool.execute() returns and applies the format via apply_output_format.

Builtins set this via GlobalFlags::apply(ctx); external commands don’t touch it.

§vfs_budget: Option<Arc<ByteBudget>>

Shared VFS memory budget for this kernel’s MemoryFs mounts.

Arc-cloned from the owning Kernel (or its fork parent) so all concurrent execution paths draw from the same pool. None means unbounded. Populated by Kernel::assemble and forwarded through child_for_pipeline / fork_inner so background jobs and scatter workers see the same cap as foreground execution.

§watchdog: Option<Arc<Watchdog>>

The per-execute timeout watchdog, when a script timeout is in effect.

Populated by the kernel at execute entry (alongside cancel) and shared through child_for_pipeline so forks and pipeline stages can acquire patient holds against the same script clock. None when no timeout is configured — ToolCtx::patient then returns an inert guard.

§overlay_handle: Option<Arc<OverlayHandle>>

Active overlay handle when the kernel was constructed with overlay: true.

Arc-cloned so forks and pipeline stages share the same transaction. None when no overlay is active (most kernels).

Implementations§

Source§

impl ExecContext

Source

pub fn new(vfs: Arc<VfsRouter>) -> Self

Create a new execution context with a VFS (uses LocalBackend without tools).

This constructor is for backward compatibility and tests that don’t need tool dispatch. For full tool support, use with_vfs_and_tools.

Source

pub fn with_vfs_and_tools(vfs: Arc<VfsRouter>, tools: Arc<ToolRegistry>) -> Self

Create a new execution context with VFS and tool registry.

This is the preferred constructor for full kaish operation where tools need to be dispatched through the backend.

Source

pub fn with_backend(backend: Arc<dyn KernelBackend>) -> Self

Create a new execution context with a custom backend.

Source

pub fn with_vfs_tools_and_scope( vfs: Arc<VfsRouter>, tools: Arc<ToolRegistry>, scope: Scope, ) -> Self

Create a context with VFS, tools, and a specific scope.

Source

pub fn with_scope(vfs: Arc<VfsRouter>, scope: Scope) -> Self

Create a context with a specific scope (uses LocalBackend without tools).

For tests that don’t need tool dispatch. For full tool support, use with_vfs_tools_and_scope.

Source

pub fn with_backend_and_scope( backend: Arc<dyn KernelBackend>, scope: Scope, ) -> Self

Create a context with a custom backend and scope.

Source

pub fn set_tool_schemas(&mut self, schemas: Vec<ToolSchema>)

Set the available tool schemas (for help command).

Source

pub fn set_tools(&mut self, tools: Arc<ToolRegistry>)

Set the tool registry reference.

Source

pub fn set_job_manager(&mut self, manager: Arc<JobManager>)

Set the job manager for background job tracking.

Source

pub fn set_trash_backend(&mut self, backend: Arc<dyn TrashBackend>)

Set the trash backend.

Source

pub fn set_stdin(&mut self, stdin: String)

Set stdin for this execution.

Source

pub fn take_stdin(&mut self) -> Option<String>

Get stdin, consuming it.

Source

pub fn set_stdin_with_data(&mut self, text: String, data: Option<Value>)

Set both text stdin and structured data.

Use this when passing output through a pipeline where the previous command produced structured data (e.g., JSON from MCP tools).

Source

pub fn take_stdin_data(&mut self) -> Option<Value>

Take structured data if available, consuming it.

Tools can use this to avoid re-parsing JSON that was already parsed by a previous command in the pipeline.

Source

pub fn resolve_path(&self, path: &str) -> PathBuf

Resolve a path relative to cwd, normalizing . and .. components.

Source

pub fn set_cwd(&mut self, path: PathBuf)

Change the current working directory.

Saves the old directory for cd - support.

Source

pub fn get_prev_cwd(&self) -> Option<&PathBuf>

Get the previous working directory (for cd -).

Source

pub async fn read_stdin_to_string(&mut self) -> Option<String>

Read all stdin (pipe or buffered string) into a String.

Prefers pipe_stdin if set (streaming pipeline), otherwise falls back to the buffered stdin string. Consumes the source.

Source

pub fn child_for_pipeline(&self) -> Self

Create a child context for a pipeline stage.

Shares backend, tools, job_manager, aliases, cwd, and scope but has independent stdin/stdout pipes.

Source

pub async fn build_ignore_filter(&self, root: &Path) -> Option<IgnoreFilter>

Build an IgnoreFilter from the current ignore configuration.

Returns None if no filtering is configured.

Source

pub fn verify_nonce( &self, nonce: &str, command: &str, paths: &[&str], ) -> Result<(), String>

Validate a confirmation nonce against a command and paths.

Thin wrapper on NonceStore::validate for ergonomic use from builtins.

Source

pub fn latch_result( &self, command: &str, paths: &[&str], reason: &str, confirm_hint: impl FnOnce(&str) -> String, ) -> ExecResult

Issue a nonce and build the standard exit-2 latch result.

reason explains why confirmation is needed (e.g., "latch enabled", "emptying trash is destructive"). The confirm_hint closure receives the nonce string so each tool can format its own re-run command.

The result includes structured data in .data for programmatic access:

{"nonce": "a3f7b2c1", "command": "rm", "paths": [...], "hint": "rm --confirm=a3f7b2c1 file", "ttl": 60}
Source

pub async fn expand_glob(&self, pattern: &str) -> Result<Vec<PathBuf>, String>

Expand a glob pattern to matching file paths.

Returns the matched paths (absolute). Used by builtins that accept glob patterns in their path arguments (ls, cat, head, tail, wc, etc.).

Source

pub async fn expand_paths( &self, positional: &[Value], ) -> Result<Vec<String>, String>

Expand positional arguments, resolving glob patterns to relative paths.

Used by file-processing builtins (cat, head, tail, wc) that accept glob patterns in their path arguments. Non-string values are converted to strings (matching shell conventions).

Trait Implementations§

Source§

impl ToolCtx for ExecContext

The kernel’s full execution context satisfies the trimmed portable ToolCtx contract that out-of-tree tools see.

Trusted in-tree builtins recover the concrete ExecContext (job control, pipes, dispatcher) through [ToolCtx::as_any_mut].

Source§

fn backend(&self) -> &Arc<dyn KernelBackend>

The backend for file I/O and tool dispatch. Read more
Source§

fn cwd(&self) -> &Path

The current working directory, as a VFS path.
Source§

fn resolve_path(&self, path: &str) -> PathBuf

Resolve a (possibly relative) path against the cwd, normalizing . and .. lexically. Never touches the real filesystem.
Source§

fn var(&self, name: &str) -> Option<Value>

Read a variable from the current scope, cloned. Read more
Source§

fn set_var(&mut self, name: &str, value: Value)

Set a variable in the current scope.
Source§

fn set_output_format(&mut self, format: OutputFormat)

Set the per-execution output format override (e.g. from --json). Read more
Source§

fn patient(&self, budget: Duration) -> PatientGuard

Suspend the script-level timeout watchdog while the returned guard is held, bounding the patient operation by budget instead. Read more
Source§

fn as_any(&self) -> &dyn Any

Escape hatch for trusted in-tree tools: recover the concrete context. Read more
Source§

fn as_any_mut(&mut self) -> &mut dyn Any

Mutable counterpart to ToolCtx::as_any.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<'src, T> IntoMaybe<'src, T> for T
where T: 'src,

Source§

type Proj<U: 'src> = U

Source§

fn map_maybe<R>( self, _f: impl FnOnce(&'src T) -> &'src R, g: impl FnOnce(T) -> R, ) -> <T as IntoMaybe<'src, T>>::Proj<R>
where R: 'src,

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more