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_assert_ne, 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(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> Result<()> {
105 run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
106}
107
108pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
113 run_steps_with_context(fs_root, fs_root, steps)
114}
115
116pub fn run_steps_with_context(
117 fs_root: &GuardedPath,
118 build_context: &GuardedPath,
119 steps: &[Step],
120) -> Result<()> {
121 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
122}
123
124pub fn run_steps_with_context_result(
126 fs_root: &GuardedPath,
127 build_context: &GuardedPath,
128 steps: &[Step],
129 stdin: Option<SharedInput>,
130 stdout: Option<SharedOutput>,
131) -> Result<GuardedPath> {
132 let io = assemble_default_io(stdin, stdout);
133 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
134}
135
136pub fn run_steps_with_context_result_with_io(
137 fs_root: &GuardedPath,
138 build_context: &GuardedPath,
139 steps: &[Step],
140 io: ExecIo,
141) -> Result<GuardedPath> {
142 match run_steps_inner(fs_root, build_context, steps, io) {
143 Ok(final_cwd) => Ok(final_cwd),
144 Err(err) => {
145 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
146 let tree = describe_dir(&fs, fs_root, 2, 24);
147 let snapshot = format!(
148 "filesystem snapshot (root {}):\n{}",
149 fs_root.display(),
150 tree
151 );
152 Err(compose_error_with_snapshot(err, snapshot))
153 }
154 }
155}
156
157fn compose_error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
161 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
163 let mut primary = chain
164 .first()
165 .cloned()
166 .unwrap_or_else(|| "unknown error".into());
167 let rest = if chain.len() > 1 {
168 let first_cause = chain[1].clone();
169 primary = format!("{primary} ({first_cause})");
170 if chain.len() > 2 {
171 let causes = chain
172 .iter()
173 .skip(2)
174 .map(|s| s.as_str())
175 .collect::<Vec<_>>()
176 .join("\n ");
177 format!("\ncauses:\n {}", causes)
178 } else {
179 String::new()
180 }
181 } else {
182 String::new()
183 };
184 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
185 match exit::exit_code_of(&err) {
191 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
192 None => anyhow::anyhow!(msg),
193 }
194}
195
196fn run_steps_inner(
197 fs_root: &GuardedPath,
198 build_context: &GuardedPath,
199 steps: &[Step],
200 io: ExecIo,
201) -> Result<GuardedPath> {
202 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
203 resolver.set_workspace_root(build_context.clone());
204 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
205}
206
207pub struct LazyRunOutput {
212 pub final_cwd: GuardedPath,
213 pub snapshot: Arc<LazyGuardedTempDir>,
214 pub fs: Box<dyn WorkspaceFs>,
215 pub bindings: BTreeMap<String, Value>,
220}
221
222pub fn run_steps_with_lazy_snapshot(
226 build_context: &GuardedPath,
227 steps: &[Step],
228 io: ExecIo,
229) -> Result<LazyRunOutput> {
230 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
231}
232
233pub fn run_steps_with_lazy_snapshot_and_modules(
238 build_context: &GuardedPath,
239 steps: &[Step],
240 io: ExecIo,
241 modules: Vec<HostModule<DefaultProcessManager>>,
242 types: Vec<&'static TypeDescriptor>,
243) -> Result<LazyRunOutput> {
244 run_steps_with_lazy_snapshot_and_modules_and_entry(
245 build_context,
246 steps,
247 io,
248 modules,
249 types,
250 None,
251 )
252}
253
254pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
258 build_context: &GuardedPath,
259 steps: &[Step],
260 io: ExecIo,
261 modules: Vec<HostModule<DefaultProcessManager>>,
262 types: Vec<&'static TypeDescriptor>,
263 entry_file: Option<GuardedPath>,
264) -> Result<LazyRunOutput> {
265 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
266 resolver.set_workspace_root(build_context.clone());
267 let snapshot = resolver.snapshot_handle();
268 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
269 match run_steps_with_manager_with_modules_and_entry(
270 fs,
271 steps,
272 default_process_manager(),
273 io,
274 modules,
275 types,
276 entry_file,
277 ) {
278 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
279 final_cwd,
280 snapshot,
281 fs,
282 bindings,
283 }),
284 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
285 }
286}
287
288pub fn enrich_lazy_error(
293 snapshot: &Arc<LazyGuardedTempDir>,
294 build_context: &GuardedPath,
295 err: anyhow::Error,
296) -> anyhow::Error {
297 match snapshot.get() {
298 Some(concrete) => {
299 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
300 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
301 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
302 };
303 let snapshot_msg = format!(
304 "filesystem snapshot (root {}):\n{}",
305 concrete.display(),
306 tree
307 );
308 compose_error_with_snapshot(err, snapshot_msg)
309 }
310 None => compose_error_with_snapshot(
311 err,
312 String::from(
313 "filesystem snapshot: never materialized (no snapshot directory was created)",
314 ),
315 ),
316 }
317}
318
319pub fn run_steps_with_fs(
320 fs: Box<dyn WorkspaceFs>,
321 steps: &[Step],
322 stdin: Option<SharedInput>,
323 stdout: Option<SharedOutput>,
324) -> Result<GuardedPath> {
325 let io = assemble_default_io(stdin, stdout);
326 run_steps_with_fs_with_io(fs, steps, io)
327}
328
329pub fn run_steps_with_fs_with_io(
330 fs: Box<dyn WorkspaceFs>,
331 steps: &[Step],
332 io: ExecIo,
333) -> Result<GuardedPath> {
334 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
335}
336
337pub(crate) use oxdock_parser::base_name;
342
343#[allow(clippy::type_complexity)]
351pub fn run_steps_with_manager<P: ProcessManager>(
352 fs: Box<dyn WorkspaceFs>,
353 steps: &[Step],
354 process: P,
355 io: ExecIo,
356) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
357 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
358}
359
360#[allow(clippy::type_complexity)]
368pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
369 fs: Box<dyn WorkspaceFs>,
370 steps: &[Step],
371 process: P,
372 io: ExecIo,
373 modules: Vec<HostModule<P>>,
374 types: Vec<&'static self::typing::TypeDescriptor>,
375) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
376 run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
377}
378
379#[allow(clippy::type_complexity)]
383#[allow(clippy::too_many_arguments)]
384pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
385 fs: Box<dyn WorkspaceFs>,
386 steps: &[Step],
387 process: P,
388 io: ExecIo,
389 modules: Vec<HostModule<P>>,
390 types: Vec<&'static self::typing::TypeDescriptor>,
391 entry_file: Option<GuardedPath>,
392) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
393 let mut state = new_state(fs, io)?;
394 state.entry_file = entry_file;
395 state.module_table = build_module_table(&modules);
396 for module in &modules {
397 module.check_pre_run(steps)?;
400 }
401 for module in modules {
402 state.register_module(module);
403 }
404 for descriptor in types {
405 state.register_type(descriptor);
406 }
407 finish_run(state, process, steps)
408}
409
410pub(crate) fn new_state<P: ProcessManager>(
411 fs: Box<dyn WorkspaceFs>,
412 io: ExecIo,
413) -> Result<ExecState<P>> {
414 let cwd = fs.root().clone();
415 let build_context = fs.build_context().clone();
416 let cargo_scratch = reserve_cargo_scratch()?;
417 let seed = Arc::new(oxdock_process::seed_defaults(
422 &cargo_scratch.tmp_seed_display(),
423 &cargo_scratch.target_seed_display(),
424 ));
425 let mut envs = (*seed).clone();
426 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
427 for (key, value) in io.inherit_env_overrides() {
428 envs.insert(key.clone(), value.clone());
429 }
430 let envs = Arc::new(envs);
431 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
432 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
433 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
434 let worker_counter = io.worker_counter();
437 let mut state = ExecState {
438 fs,
439 cargo_scratch,
440 seed,
441 cwd: cwd.clone(),
442 initial_root: cwd,
443 envs,
444 bg_children: Vec::new(),
445 scope_stack: Vec::new(),
446 isolated_stack: Vec::new(),
447 io,
448 assert_windows: assert_windows.clone(),
449 assert_windows_stderr: assert_windows_stderr.clone(),
450 exact_stdout: exact_stdout.clone(),
451 var_scopes: Vec::new(),
452 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
453 cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
454 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
455 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
456 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
457 live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
458 inside_async: false,
459 keeper_expiry: None,
460 cancellable: false,
461 reap_floor: None,
462 functions: self::native::FunctionRegistry::with_builtins(),
463 entry_file: None,
464 import_stack: Vec::new(),
465 import_alias_frame: None,
466 modules: std::collections::HashMap::new(),
467 module_stack: Vec::new(),
468 module_table: self::native::std_module_table(),
469 types: self::typing::startup_type_map(),
470 record_schemas: std::collections::HashMap::new(),
471 module_states: std::collections::HashMap::new(),
472 type_aliases: std::collections::HashMap::new(),
473 call_depth: 0,
474 task_id: 0,
476 push_manifest: Vec::new(),
477 _marker: std::marker::PhantomData,
478 };
479
480 state.push_var_scope();
482
483 Ok(state)
484}
485
486fn build_module_table<P: ProcessManager>(
491 modules: &[self::native::HostModule<P>],
492) -> oxdock_parser::ModuleTable {
493 let mut table = self::native::std_module_table();
494 for module in modules {
495 let mut func_names = std::collections::HashSet::new();
496 for registration in &module.funcs {
497 let name = match registration {
498 self::native::HostRegistration::Stateful { name, .. } => name,
499 self::native::HostRegistration::Pure { name, .. } => name,
500 self::native::HostRegistration::Both { name, .. } => name,
501 };
502 func_names.insert(name.clone());
503 }
504 table.modules.insert(
505 module.name.clone(),
506 Some(oxdock_parser::ModuleFuncs { func_names }),
507 );
508 }
509 table
510}
511
512#[allow(clippy::type_complexity)]
513fn finish_run<P: ProcessManager>(
514 mut state: ExecState<P>,
515 process: P,
516 steps: &[Step],
517) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
518 state.type_aliases = self::typing::collect_type_aliases(steps, &state)?;
522 state.validate_function_type_tags()?;
523 let saved_aliases = state.type_aliases.clone();
530 let closure = self::import::expand_import_closure(&mut state, steps)?;
531 for file in &closure {
532 let aliases = self::typing::collect_type_aliases(&file.steps, &state)?;
533 for (name, target) in &aliases {
538 state.type_aliases.insert(name.clone(), target.clone());
539 }
540 }
541 static_check::validate_script_closure(steps, &closure, &state)?;
542 state.type_aliases = saved_aliases;
543 let assert_windows = Arc::clone(&state.assert_windows);
544 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
545 let exact_stdout = Arc::clone(&state.exact_stdout);
546 let _default_stdout = std::io::stdout();
547 let stdin = state.io.stdin().into();
548 let stdout = Some(StreamHandle::Stream(teed_stdout(
552 state.io.stdout(),
553 assert_windows,
554 exact_stdout,
555 None,
556 )));
557 let stderr = state
558 .io
559 .stderr()
560 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
561 let mut proc_mgr = process;
562 let flow = execute_steps(
563 &mut state,
564 &mut proc_mgr,
565 steps,
566 stdin,
567 false,
568 stdout,
569 stderr,
570 None,
571 None,
572 true,
573 )?;
574 match flow {
575 self::steps::Flow::Done => {
580 let bindings: BTreeMap<String, Value> = state
585 .var_scopes
586 .first()
587 .map(|scope| {
588 scope
589 .iter()
590 .map(|(k, (_, v))| (k.clone(), v.clone()))
591 .collect()
592 })
593 .unwrap_or_default();
594 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
595 }
596 self::steps::Flow::Break { idx } => {
597 anyhow::bail!("step {}: BREAK outside loop", idx + 1)
598 }
599 self::steps::Flow::Continue { idx } => {
600 anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
601 }
602 self::steps::Flow::Return { idx, .. } => {
603 anyhow::bail!(
607 "step {}: RETURN outside function, ASYNC task, or LET block",
608 idx + 1
609 )
610 }
611 }
612}