mod args;
mod capture;
#[cfg(any(test, feature = "test-harness"))]
pub mod conformance;
mod engine;
mod exit;
mod fs_ops;
mod handlers;
mod import;
mod io;
pub mod mcp;
mod native;
pub mod remote;
mod state;
mod static_check;
mod steps;
#[cfg(test)]
mod tests;
mod typing;
pub use self::remote::{
RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
apply_push_symlink,
};
pub use self::args::{
json_to_value, json_to_value_typed, strip_json_comments, value_to_json, value_to_json_typed,
};
#[cfg(any(test, feature = "test-harness"))]
pub use self::conformance::assert_module_returns_conformance;
pub use self::engine::{Engine, EngineOutput};
pub use self::exit::{ExitRequest, exit_code_of};
pub(crate) use self::handlers::{
dispatch_append, dispatch_append_line, dispatch_archive, dispatch_assert_contains,
dispatch_assert_eq, dispatch_assert_ne, dispatch_assign, dispatch_assign_async_step,
dispatch_assign_capture_step, dispatch_async_block, dispatch_await_capture_step,
dispatch_await_step, dispatch_break, dispatch_call, dispatch_cancel_step, dispatch_continue,
dispatch_copy, dispatch_copy_git, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand,
dispatch_for_loop, dispatch_func_def, dispatch_if_then, dispatch_import_file,
dispatch_import_funcs, dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env,
dispatch_isolated_step, dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step,
dispatch_read, dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return,
dispatch_run, dispatch_run_exec, dispatch_set, dispatch_set_executable, dispatch_sleep_step,
dispatch_symlink, dispatch_timeout_step, dispatch_unarchive, dispatch_while_loop,
dispatch_with_io, dispatch_with_io_block, dispatch_workdir, dispatch_workspace, dispatch_write,
};
pub use self::import::{DryRunStep, dry_run_closure};
pub use self::io::ExecIo;
pub use self::io::PipeStream;
pub use self::io::PushManifestSink;
pub use self::io::{StreamChunk, StreamHook, TeeStream};
pub use self::mcp::{McpCallOutput, McpSession};
pub use self::native::{
FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
builtin_function_names, check_script_param_tags, fill_optional_args, optional_zero_value,
placeholder_resolver, required_arity, resolve_script_params, std_module_table,
};
pub use self::state::ExecState;
pub use self::state::MAX_RUNNING_TASKS;
pub use self::steps::StepCtx;
pub use self::typing::{
Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
unshare_shared,
};
use anyhow::Result;
use oxdock_fs::{
GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
};
use oxdock_parser::Step;
use oxdock_process::{
BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
default_process_manager,
};
use std::collections::BTreeMap;
use std::sync::Arc;
use self::fs_ops::describe_dir;
use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
use self::steps::execute_steps;
pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> Result<()> {
run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
}
pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
run_steps_with_context(fs_root, fs_root, steps)
}
pub fn run_steps_with_context(
fs_root: &GuardedPath,
build_context: &GuardedPath,
steps: &[Step],
) -> Result<()> {
run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
}
pub fn run_steps_with_context_result(
fs_root: &GuardedPath,
build_context: &GuardedPath,
steps: &[Step],
stdin: Option<SharedInput>,
stdout: Option<SharedOutput>,
) -> Result<GuardedPath> {
let io = assemble_default_io(stdin, stdout);
run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
}
pub fn run_steps_with_context_result_with_io(
fs_root: &GuardedPath,
build_context: &GuardedPath,
steps: &[Step],
io: ExecIo,
) -> Result<GuardedPath> {
match run_steps_inner(fs_root, build_context, steps, io) {
Ok(final_cwd) => Ok(final_cwd),
Err(err) => {
let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
let tree = describe_dir(&fs, fs_root, 2, 24);
let snapshot = format!(
"filesystem snapshot (root {}):\n{}",
fs_root.display(),
tree
);
Err(error_with_snapshot(err, snapshot))
}
}
}
fn error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
let mut primary = chain
.first()
.cloned()
.unwrap_or_else(|| "unknown error".into());
let rest = if chain.len() > 1 {
let first_cause = chain[1].clone();
primary = format!("{primary} ({first_cause})");
if chain.len() > 2 {
let causes = chain
.iter()
.skip(2)
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join("\n ");
format!("\ncauses:\n {}", causes)
} else {
String::new()
}
} else {
String::new()
};
let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
match exit::exit_code_of(&err) {
Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
None => anyhow::anyhow!(msg),
}
}
fn run_steps_inner(
fs_root: &GuardedPath,
build_context: &GuardedPath,
steps: &[Step],
io: ExecIo,
) -> Result<GuardedPath> {
let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
resolver.set_workspace_root(build_context.clone());
run_steps_with_fs_with_io(Box::new(resolver), steps, io)
}
pub struct LazyRunOutput {
pub final_cwd: GuardedPath,
pub snapshot: Arc<LazyGuardedTempDir>,
pub fs: Box<dyn WorkspaceFs>,
pub bindings: BTreeMap<String, Value>,
}
pub fn run_steps_with_lazy_snapshot(
build_context: &GuardedPath,
steps: &[Step],
io: ExecIo,
) -> Result<LazyRunOutput> {
run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
}
pub fn run_steps_with_lazy_snapshot_and_modules(
build_context: &GuardedPath,
steps: &[Step],
io: ExecIo,
modules: Vec<HostModule<DefaultProcessManager>>,
types: Vec<&'static TypeDescriptor>,
) -> Result<LazyRunOutput> {
run_steps_with_lazy_snapshot_and_modules_and_entry(
build_context,
steps,
io,
modules,
types,
None,
)
}
pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
build_context: &GuardedPath,
steps: &[Step],
io: ExecIo,
modules: Vec<HostModule<DefaultProcessManager>>,
types: Vec<&'static TypeDescriptor>,
entry_file: Option<GuardedPath>,
) -> Result<LazyRunOutput> {
let mut resolver = PathResolver::new_lazy(build_context.clone())?;
resolver.set_workspace_root(build_context.clone());
let snapshot = resolver.snapshot_handle();
let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
match run_steps_with_manager_with_modules_and_entry(
fs,
steps,
default_process_manager(),
io,
modules,
types,
entry_file,
) {
Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
final_cwd,
snapshot,
fs,
bindings,
}),
Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
}
}
pub fn enrich_lazy_error(
snapshot: &Arc<LazyGuardedTempDir>,
build_context: &GuardedPath,
err: anyhow::Error,
) -> anyhow::Error {
match snapshot.get() {
Some(concrete) => {
let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
};
let snapshot_msg = format!(
"filesystem snapshot (root {}):\n{}",
concrete.display(),
tree
);
error_with_snapshot(err, snapshot_msg)
}
None => error_with_snapshot(
err,
String::from(
"filesystem snapshot: never materialized (no snapshot directory was created)",
),
),
}
}
pub fn run_steps_with_fs(
fs: Box<dyn WorkspaceFs>,
steps: &[Step],
stdin: Option<SharedInput>,
stdout: Option<SharedOutput>,
) -> Result<GuardedPath> {
let io = assemble_default_io(stdin, stdout);
run_steps_with_fs_with_io(fs, steps, io)
}
pub fn run_steps_with_fs_with_io(
fs: Box<dyn WorkspaceFs>,
steps: &[Step],
io: ExecIo,
) -> Result<GuardedPath> {
run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
}
pub(crate) use oxdock_parser::base_name;
#[allow(clippy::type_complexity)]
pub fn run_steps_with_manager<P: ProcessManager>(
fs: Box<dyn WorkspaceFs>,
steps: &[Step],
process: P,
io: ExecIo,
) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
}
#[allow(clippy::type_complexity)]
pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
fs: Box<dyn WorkspaceFs>,
steps: &[Step],
process: P,
io: ExecIo,
modules: Vec<HostModule<P>>,
types: Vec<&'static self::typing::TypeDescriptor>,
) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
}
#[allow(clippy::type_complexity)]
#[allow(clippy::too_many_arguments)]
pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
fs: Box<dyn WorkspaceFs>,
steps: &[Step],
process: P,
io: ExecIo,
modules: Vec<HostModule<P>>,
types: Vec<&'static self::typing::TypeDescriptor>,
entry_file: Option<GuardedPath>,
) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
let mut state = new_state(fs, io)?;
state.entry_file = entry_file;
state.module_table = build_module_table(&modules);
for module in &modules {
module.check_pre_run(steps)?;
}
for module in modules {
state.register_module(module);
}
for descriptor in types {
state.register_type(descriptor);
}
finish_run(state, process, steps)
}
pub(crate) fn new_state<P: ProcessManager>(
fs: Box<dyn WorkspaceFs>,
io: ExecIo,
) -> Result<ExecState<P>> {
let cwd = fs.root().clone();
let build_context = fs.build_context().clone();
let cargo_scratch = reserve_cargo_scratch()?;
let seed = Arc::new(oxdock_process::seed_defaults());
let mut envs = (*seed).clone();
envs.extend(BuiltinEnv::collect(&build_context).into_envs());
for (key, value) in io.inherit_env_overrides() {
envs.insert(key.clone(), value.clone());
}
let envs = Arc::new(envs);
let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
let worker_counter = io.worker_counter();
let mut state = ExecState {
fs,
cargo_scratch,
seed,
cwd: cwd.clone(),
envs,
bg_children: Vec::new(),
scope_stack: Vec::new(),
isolated_stack: Vec::new(),
io,
assert_windows: assert_windows.clone(),
assert_windows_stderr: assert_windows_stderr.clone(),
exact_stdout: exact_stdout.clone(),
var_scopes: Vec::new(),
cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
inside_async: false,
keeper_expiry: None,
cancellable: false,
reap_floor: None,
functions: self::native::FunctionRegistry::with_builtins(),
entry_file: None,
import_stack: Vec::new(),
executed_alias_targets: std::collections::HashMap::new(),
call_alias_frames: Vec::new(),
modules: std::collections::HashMap::new(),
validated_modules: std::collections::HashSet::new(),
module_stack: Vec::new(),
module_table: self::native::std_module_table(),
types: self::typing::startup_type_map(),
record_schemas: std::collections::HashMap::new(),
module_states: std::collections::HashMap::new(),
type_aliases: std::collections::HashMap::new(),
call_depth: 0,
task_id: 0,
push_manifest: Vec::new(),
_marker: std::marker::PhantomData,
};
state.push_var_scope();
Ok(state)
}
fn build_module_table<P: ProcessManager>(
modules: &[self::native::HostModule<P>],
) -> oxdock_parser::ModuleTable {
let mut table = self::native::std_module_table();
for module in modules {
let mut func_names = std::collections::HashSet::new();
for registration in &module.funcs {
let name = match registration {
self::native::HostRegistration::Stateful { name, .. } => name,
self::native::HostRegistration::Pure { name, .. } => name,
self::native::HostRegistration::Both { name, .. } => name,
};
func_names.insert(name.clone());
}
table.modules.insert(
module.name.clone(),
Some(oxdock_parser::ModuleFuncs { func_names }),
);
}
table
}
pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
fs: Box<dyn WorkspaceFs>,
steps: &[Step],
modules: Vec<HostModule<P>>,
types: Vec<&'static TypeDescriptor>,
entry_file: Option<GuardedPath>,
) -> Result<()> {
let mut state = new_state(fs, ExecIo::new())?;
state.entry_file = entry_file;
state.module_table = build_module_table(&modules);
for module in modules {
state.register_module(module);
}
for descriptor in types {
state.register_type(descriptor);
}
validate_closure_for_run(&mut state, steps).map(|_| ())
}
pub fn validate_closure_for_run<P: ProcessManager>(
state: &mut ExecState<P>,
steps: &[Step],
) -> Result<Vec<String>> {
state.type_aliases = self::typing::collect_type_aliases(steps, state)?;
state.validate_function_type_tags()?;
let saved_aliases = state.type_aliases.clone();
let closure = self::import::expand_import_closure(state, steps)?;
static_check::validate_script_closure(steps, &closure, state)?;
state.type_aliases = saved_aliases;
let mut exported = Vec::new();
for file in &closure {
exported.extend(file.type_exports.iter().cloned());
}
Ok(exported)
}
#[allow(clippy::type_complexity)]
fn finish_run<P: ProcessManager>(
mut state: ExecState<P>,
process: P,
steps: &[Step],
) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
validate_closure_for_run(&mut state, steps)?;
let assert_windows = Arc::clone(&state.assert_windows);
let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
let exact_stdout = Arc::clone(&state.exact_stdout);
let _default_stdout = std::io::stdout();
let stdin = state.io.stdin().into();
let stdout = Some(StreamHandle::Stream(teed_stdout(
state.io.stdout(),
assert_windows,
exact_stdout,
None,
)));
let stderr = state
.io
.stderr()
.map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
let mut proc_mgr = process;
let flow = execute_steps(
&mut state,
&mut proc_mgr,
steps,
stdin,
false,
stdout,
stderr,
None,
None,
true,
)?;
match flow {
self::steps::Flow::Done => {
let bindings: BTreeMap<String, Value> = state
.var_scopes
.first()
.map(|scope| {
scope
.iter()
.map(|(k, (_, v))| (k.clone(), v.clone()))
.collect()
})
.unwrap_or_default();
Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
}
self::steps::Flow::Break { idx } => {
anyhow::bail!("step {}: BREAK outside loop", idx + 1)
}
self::steps::Flow::Continue { idx } => {
anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
}
self::steps::Flow::Return { idx, .. } => {
anyhow::bail!(
"step {}: RETURN outside function, ASYNC task, or LET block",
idx + 1
)
}
}
}