1mod args;
2mod capture;
3#[cfg(any(test, feature = "test-harness"))]
4pub mod conformance;
5mod engine;
6mod exit;
7mod fs_ops;
8mod handlers;
9mod import;
10mod io;
11pub mod mcp;
12mod native;
13pub mod remote;
14mod state;
15mod static_check;
16mod steps;
17#[cfg(test)]
18mod tests;
19mod typing;
20
21pub use self::remote::{
22 RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
23 apply_push_symlink,
24};
25
26pub use self::args::{json_to_value, json_to_value_typed, value_to_json, value_to_json_typed};
27#[cfg(any(test, feature = "test-harness"))]
28pub use self::conformance::assert_module_returns_conformance;
29pub use self::engine::{Engine, EngineOutput};
30pub use self::exit::{ExitRequest, exit_code_of};
31pub(crate) use self::handlers::{
32 dispatch_append, dispatch_archive, dispatch_assert_contains, dispatch_assert_eq,
33 dispatch_assign, dispatch_assign_async_step, dispatch_assign_capture_step,
34 dispatch_async_block, dispatch_await_capture_step, dispatch_await_step, dispatch_break,
35 dispatch_call, dispatch_cancel_step, dispatch_continue, dispatch_copy, dispatch_copy_git,
36 dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand, dispatch_for_loop,
37 dispatch_func_def, dispatch_if_then, dispatch_import_file, dispatch_import_funcs,
38 dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env, dispatch_isolated_step,
39 dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step, dispatch_read,
40 dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return, dispatch_run,
41 dispatch_run_exec, dispatch_set, dispatch_sleep_step, dispatch_symlink, dispatch_timeout_step,
42 dispatch_unarchive, dispatch_while_loop, dispatch_with_io, dispatch_with_io_block,
43 dispatch_workdir, dispatch_workspace, dispatch_write,
44};
45pub use self::import::{DryRunStep, dry_run_closure};
46pub use self::io::ExecIo;
47pub use self::io::PipeStream;
48pub use self::io::PushManifestSink;
49pub use self::io::{StreamChunk, StreamHook, TeeStream};
50pub use self::mcp::{McpCallOutput, McpSession};
51pub use self::native::{
52 FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
53 OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
54 builtin_function_names, fill_optional_args, required_arity, std_module_table,
55};
56pub use self::state::ExecState;
57pub use self::state::MAX_RUNNING_TASKS;
58pub use self::steps::StepCtx;
59pub use self::typing::{
60 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
61 check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
62 drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
63 load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
64 unshare_shared,
65};
66
67use anyhow::Result;
68use oxdock_fs::{
69 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
70};
71use oxdock_parser::Step;
72use oxdock_process::{
73 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
74 default_process_manager,
75};
76
77use std::collections::BTreeMap;
78use std::sync::Arc;
79
80use self::fs_ops::describe_dir;
81use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
82use self::steps::execute_steps;
83
84pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
89
90pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
94
95pub fn run_steps(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
96 run_steps_with_context(fs_root, fs_root, steps)
97}
98
99pub fn run_steps_with_context(
100 fs_root: &GuardedPath,
101 build_context: &GuardedPath,
102 steps: &[Step],
103) -> Result<()> {
104 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
105}
106
107pub fn run_steps_with_context_result(
109 fs_root: &GuardedPath,
110 build_context: &GuardedPath,
111 steps: &[Step],
112 stdin: Option<SharedInput>,
113 stdout: Option<SharedOutput>,
114) -> Result<GuardedPath> {
115 let io = assemble_default_io(stdin, stdout);
116 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
117}
118
119pub fn run_steps_with_context_result_with_io(
120 fs_root: &GuardedPath,
121 build_context: &GuardedPath,
122 steps: &[Step],
123 io: ExecIo,
124) -> Result<GuardedPath> {
125 match run_steps_inner(fs_root, build_context, steps, io) {
126 Ok(final_cwd) => Ok(final_cwd),
127 Err(err) => {
128 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
129 let tree = describe_dir(&fs, fs_root, 2, 24);
130 let snapshot = format!(
131 "filesystem snapshot (root {}):\n{}",
132 fs_root.display(),
133 tree
134 );
135 Err(compose_error_with_snapshot(err, snapshot))
136 }
137 }
138}
139
140fn compose_error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
144 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
146 let mut primary = chain
147 .first()
148 .cloned()
149 .unwrap_or_else(|| "unknown error".into());
150 let rest = if chain.len() > 1 {
151 let first_cause = chain[1].clone();
152 primary = format!("{primary} ({first_cause})");
153 if chain.len() > 2 {
154 let causes = chain
155 .iter()
156 .skip(2)
157 .map(|s| s.as_str())
158 .collect::<Vec<_>>()
159 .join("\n ");
160 format!("\ncauses:\n {}", causes)
161 } else {
162 String::new()
163 }
164 } else {
165 String::new()
166 };
167 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
168 match exit::exit_code_of(&err) {
174 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
175 None => anyhow::anyhow!(msg),
176 }
177}
178
179fn run_steps_inner(
180 fs_root: &GuardedPath,
181 build_context: &GuardedPath,
182 steps: &[Step],
183 io: ExecIo,
184) -> Result<GuardedPath> {
185 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
186 resolver.set_workspace_root(build_context.clone());
187 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
188}
189
190pub struct LazyRunOutput {
195 pub final_cwd: GuardedPath,
196 pub snapshot: Arc<LazyGuardedTempDir>,
197 pub fs: Box<dyn WorkspaceFs>,
198 pub bindings: BTreeMap<String, Value>,
203}
204
205pub fn run_steps_with_lazy_snapshot(
209 build_context: &GuardedPath,
210 steps: &[Step],
211 io: ExecIo,
212) -> Result<LazyRunOutput> {
213 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
214}
215
216pub fn run_steps_with_lazy_snapshot_and_modules(
221 build_context: &GuardedPath,
222 steps: &[Step],
223 io: ExecIo,
224 modules: Vec<HostModule<DefaultProcessManager>>,
225 types: Vec<&'static TypeDescriptor>,
226) -> Result<LazyRunOutput> {
227 run_steps_with_lazy_snapshot_and_modules_and_entry(
228 build_context,
229 steps,
230 io,
231 modules,
232 types,
233 None,
234 )
235}
236
237pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
241 build_context: &GuardedPath,
242 steps: &[Step],
243 io: ExecIo,
244 modules: Vec<HostModule<DefaultProcessManager>>,
245 types: Vec<&'static TypeDescriptor>,
246 entry_file: Option<GuardedPath>,
247) -> Result<LazyRunOutput> {
248 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
249 resolver.set_workspace_root(build_context.clone());
250 let snapshot = resolver.snapshot_handle();
251 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
252 match run_steps_with_manager_with_modules_and_entry(
253 fs,
254 steps,
255 default_process_manager(),
256 io,
257 modules,
258 types,
259 entry_file,
260 ) {
261 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
262 final_cwd,
263 snapshot,
264 fs,
265 bindings,
266 }),
267 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
268 }
269}
270
271pub fn enrich_lazy_error(
276 snapshot: &Arc<LazyGuardedTempDir>,
277 build_context: &GuardedPath,
278 err: anyhow::Error,
279) -> anyhow::Error {
280 match snapshot.get() {
281 Some(concrete) => {
282 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
283 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
284 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
285 };
286 let snapshot_msg = format!(
287 "filesystem snapshot (root {}):\n{}",
288 concrete.display(),
289 tree
290 );
291 compose_error_with_snapshot(err, snapshot_msg)
292 }
293 None => compose_error_with_snapshot(
294 err,
295 String::from(
296 "filesystem snapshot: never materialized (no snapshot directory was created)",
297 ),
298 ),
299 }
300}
301
302pub fn run_steps_with_fs(
303 fs: Box<dyn WorkspaceFs>,
304 steps: &[Step],
305 stdin: Option<SharedInput>,
306 stdout: Option<SharedOutput>,
307) -> Result<GuardedPath> {
308 let io = assemble_default_io(stdin, stdout);
309 run_steps_with_fs_with_io(fs, steps, io)
310}
311
312pub fn run_steps_with_fs_with_io(
313 fs: Box<dyn WorkspaceFs>,
314 steps: &[Step],
315 io: ExecIo,
316) -> Result<GuardedPath> {
317 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
318}
319
320pub(crate) use oxdock_parser::base_name;
325
326#[allow(clippy::type_complexity)]
334pub fn run_steps_with_manager<P: ProcessManager>(
335 fs: Box<dyn WorkspaceFs>,
336 steps: &[Step],
337 process: P,
338 io: ExecIo,
339) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
340 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
341}
342
343#[allow(clippy::type_complexity)]
351pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
352 fs: Box<dyn WorkspaceFs>,
353 steps: &[Step],
354 process: P,
355 io: ExecIo,
356 modules: Vec<HostModule<P>>,
357 types: Vec<&'static self::typing::TypeDescriptor>,
358) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
359 run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
360}
361
362#[allow(clippy::type_complexity)]
366#[allow(clippy::too_many_arguments)]
367pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
368 fs: Box<dyn WorkspaceFs>,
369 steps: &[Step],
370 process: P,
371 io: ExecIo,
372 modules: Vec<HostModule<P>>,
373 types: Vec<&'static self::typing::TypeDescriptor>,
374 entry_file: Option<GuardedPath>,
375) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
376 let mut state = new_state(fs, io)?;
377 state.entry_file = entry_file;
378 state.module_table = build_module_table(&modules);
379 for module in &modules {
380 module.check_pre_run(steps)?;
383 }
384 for module in modules {
385 state.register_module(module);
386 }
387 for descriptor in types {
388 state.register_type(descriptor);
389 }
390 finish_run(state, process, steps)
391}
392
393pub(crate) fn new_state<P: ProcessManager>(
394 fs: Box<dyn WorkspaceFs>,
395 io: ExecIo,
396) -> Result<ExecState<P>> {
397 let cwd = fs.root().clone();
398 let build_context = fs.build_context().clone();
399 let cargo_scratch = reserve_cargo_scratch()?;
400 let seed = Arc::new(oxdock_process::seed_defaults(
405 &cargo_scratch.tmp_seed_display(),
406 &cargo_scratch.target_seed_display(),
407 ));
408 let mut envs = (*seed).clone();
409 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
410 for (key, value) in io.inherit_env_overrides() {
411 envs.insert(key.clone(), value.clone());
412 }
413 let envs = Arc::new(envs);
414 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
415 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
416 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
417 let worker_counter = io.worker_counter();
420 let mut state = ExecState {
421 fs,
422 cargo_scratch,
423 seed,
424 cwd: cwd.clone(),
425 initial_root: cwd,
426 envs,
427 bg_children: Vec::new(),
428 scope_stack: Vec::new(),
429 isolated_stack: Vec::new(),
430 io,
431 assert_windows: assert_windows.clone(),
432 assert_windows_stderr: assert_windows_stderr.clone(),
433 exact_stdout: exact_stdout.clone(),
434 var_scopes: Vec::new(),
435 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
436 cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
437 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
438 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
439 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
440 live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
441 inside_async: false,
442 keeper_expiry: None,
443 cancellable: false,
444 reap_floor: None,
445 functions: self::native::FunctionRegistry::with_builtins(),
446 entry_file: None,
447 import_stack: Vec::new(),
448 import_alias_frame: None,
449 modules: std::collections::HashMap::new(),
450 module_stack: Vec::new(),
451 module_table: self::native::std_module_table(),
452 types: self::typing::startup_type_map(),
453 record_schemas: std::collections::HashMap::new(),
454 module_states: std::collections::HashMap::new(),
455 type_aliases: std::collections::HashMap::new(),
456 call_depth: 0,
457 task_id: 0,
459 push_manifest: Vec::new(),
460 _marker: std::marker::PhantomData,
461 };
462
463 state.push_var_scope();
465
466 Ok(state)
467}
468
469fn build_module_table<P: ProcessManager>(
474 modules: &[self::native::HostModule<P>],
475) -> oxdock_parser::ModuleTable {
476 let mut table = self::native::std_module_table();
477 for module in modules {
478 let mut func_names = std::collections::HashSet::new();
479 for registration in &module.funcs {
480 let name = match registration {
481 self::native::HostRegistration::Stateful { name, .. } => name,
482 self::native::HostRegistration::Pure { name, .. } => name,
483 self::native::HostRegistration::Both { name, .. } => name,
484 };
485 func_names.insert(name.clone());
486 }
487 table.modules.insert(
488 module.name.clone(),
489 Some(oxdock_parser::ModuleFuncs { func_names }),
490 );
491 }
492 table
493}
494
495#[allow(clippy::type_complexity)]
496fn finish_run<P: ProcessManager>(
497 mut state: ExecState<P>,
498 process: P,
499 steps: &[Step],
500) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
501 state.type_aliases = self::typing::collect_type_aliases(steps, &state)?;
505 state.validate_function_type_tags()?;
506 let saved_aliases = state.type_aliases.clone();
513 let closure = self::import::expand_import_closure(&mut state, steps)?;
514 for file in &closure {
515 let aliases = self::typing::collect_type_aliases(&file.steps, &state)?;
516 for (name, target) in &aliases {
521 state.type_aliases.insert(name.clone(), target.clone());
522 }
523 }
524 static_check::validate_script_closure(steps, &closure, &state)?;
525 state.type_aliases = saved_aliases;
526 let assert_windows = Arc::clone(&state.assert_windows);
527 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
528 let exact_stdout = Arc::clone(&state.exact_stdout);
529 let _default_stdout = std::io::stdout();
530 let stdin = state.io.stdin().into();
531 let stdout = Some(StreamHandle::Stream(teed_stdout(
535 state.io.stdout(),
536 assert_windows,
537 exact_stdout,
538 None,
539 )));
540 let stderr = state
541 .io
542 .stderr()
543 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
544 let mut proc_mgr = process;
545 let flow = execute_steps(
546 &mut state,
547 &mut proc_mgr,
548 steps,
549 stdin,
550 false,
551 stdout,
552 stderr,
553 None,
554 None,
555 true,
556 )?;
557 match flow {
558 self::steps::Flow::Done => {
563 let bindings: BTreeMap<String, Value> = state
568 .var_scopes
569 .first()
570 .map(|scope| {
571 scope
572 .iter()
573 .map(|(k, (_, v))| (k.clone(), v.clone()))
574 .collect()
575 })
576 .unwrap_or_default();
577 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
578 }
579 self::steps::Flow::Break { idx } => {
580 anyhow::bail!("step {}: BREAK outside loop", idx + 1)
581 }
582 self::steps::Flow::Continue { idx } => {
583 anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
584 }
585 self::steps::Flow::Return { idx, .. } => {
586 anyhow::bail!(
590 "step {}: RETURN outside function, ASYNC task, or LET block",
591 idx + 1
592 )
593 }
594 }
595}