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::{
27 json_to_value, json_to_value_typed, strip_json_comments, value_to_json, value_to_json_typed,
28};
29#[cfg(any(test, feature = "test-harness"))]
30pub use self::conformance::assert_module_returns_conformance;
31pub use self::engine::{Engine, EngineOutput};
32pub use self::exit::{ExitRequest, exit_code_of};
33pub(crate) use self::handlers::{
34 dispatch_append, dispatch_append_line, dispatch_archive, dispatch_assert_contains,
35 dispatch_assert_eq, dispatch_assert_ne, dispatch_assign, dispatch_assign_async_step,
36 dispatch_assign_capture_step, dispatch_async_block, dispatch_await_capture_step,
37 dispatch_await_step, dispatch_break, dispatch_call, dispatch_cancel_step, dispatch_continue,
38 dispatch_copy, dispatch_copy_git, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand,
39 dispatch_for_loop, dispatch_func_def, dispatch_if_then, dispatch_import_file,
40 dispatch_import_funcs, dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env,
41 dispatch_isolated_step, dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step,
42 dispatch_read, dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return,
43 dispatch_run, dispatch_run_exec, dispatch_set, dispatch_set_executable, dispatch_sleep_step,
44 dispatch_symlink, dispatch_timeout_step, dispatch_unarchive, dispatch_while_loop,
45 dispatch_with_io, dispatch_with_io_block, dispatch_workdir, dispatch_workspace, dispatch_write,
46};
47pub use self::import::{DryRunStep, dry_run_closure};
48pub use self::io::ExecIo;
49pub use self::io::PipeStream;
50pub use self::io::PushManifestSink;
51pub use self::io::{StreamChunk, StreamHook, TeeStream};
52pub use self::mcp::{McpCallOutput, McpSession};
53pub use self::native::{
54 FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
55 OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
56 builtin_function_names, check_script_param_tags, fill_optional_args, optional_zero_value,
57 placeholder_resolver, required_arity, resolve_script_params, std_module_table,
58};
59pub use self::state::ExecState;
60pub use self::state::MAX_RUNNING_TASKS;
61pub use self::steps::StepCtx;
62pub use self::typing::{
63 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
64 check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
65 drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
66 load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
67 unshare_shared,
68};
69
70use anyhow::Result;
71use oxdock_fs::{
72 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
73};
74use oxdock_parser::Step;
75use oxdock_process::{
76 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
77 default_process_manager,
78};
79
80use std::collections::BTreeMap;
81use std::sync::Arc;
82
83use self::fs_ops::describe_dir;
84use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
85use self::steps::execute_steps;
86
87pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
92
93pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
97
98pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> Result<()> {
108 run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
109}
110
111pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
116 run_steps_with_context(fs_root, fs_root, steps)
117}
118
119pub fn run_steps_with_context(
120 fs_root: &GuardedPath,
121 build_context: &GuardedPath,
122 steps: &[Step],
123) -> Result<()> {
124 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
125}
126
127pub fn run_steps_with_context_result(
129 fs_root: &GuardedPath,
130 build_context: &GuardedPath,
131 steps: &[Step],
132 stdin: Option<SharedInput>,
133 stdout: Option<SharedOutput>,
134) -> Result<GuardedPath> {
135 let io = assemble_default_io(stdin, stdout);
136 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
137}
138
139pub fn run_steps_with_context_result_with_io(
140 fs_root: &GuardedPath,
141 build_context: &GuardedPath,
142 steps: &[Step],
143 io: ExecIo,
144) -> Result<GuardedPath> {
145 match run_steps_inner(fs_root, build_context, steps, io) {
146 Ok(final_cwd) => Ok(final_cwd),
147 Err(err) => {
148 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
149 let tree = describe_dir(&fs, fs_root, 2, 24);
150 let snapshot = format!(
151 "filesystem snapshot (root {}):\n{}",
152 fs_root.display(),
153 tree
154 );
155 Err(error_with_snapshot(err, snapshot))
156 }
157 }
158}
159
160fn error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
164 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
166 let mut primary = chain
167 .first()
168 .cloned()
169 .unwrap_or_else(|| "unknown error".into());
170 let rest = if chain.len() > 1 {
171 let first_cause = chain[1].clone();
172 primary = format!("{primary} ({first_cause})");
173 if chain.len() > 2 {
174 let causes = chain
175 .iter()
176 .skip(2)
177 .map(|s| s.as_str())
178 .collect::<Vec<_>>()
179 .join("\n ");
180 format!("\ncauses:\n {}", causes)
181 } else {
182 String::new()
183 }
184 } else {
185 String::new()
186 };
187 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
188 match exit::exit_code_of(&err) {
194 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
195 None => anyhow::anyhow!(msg),
196 }
197}
198
199fn run_steps_inner(
200 fs_root: &GuardedPath,
201 build_context: &GuardedPath,
202 steps: &[Step],
203 io: ExecIo,
204) -> Result<GuardedPath> {
205 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
206 resolver.set_workspace_root(build_context.clone());
207 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
208}
209
210pub struct LazyRunOutput {
215 pub final_cwd: GuardedPath,
216 pub snapshot: Arc<LazyGuardedTempDir>,
217 pub fs: Box<dyn WorkspaceFs>,
218 pub bindings: BTreeMap<String, Value>,
223}
224
225pub fn run_steps_with_lazy_snapshot(
229 build_context: &GuardedPath,
230 steps: &[Step],
231 io: ExecIo,
232) -> Result<LazyRunOutput> {
233 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
234}
235
236pub fn run_steps_with_lazy_snapshot_and_modules(
241 build_context: &GuardedPath,
242 steps: &[Step],
243 io: ExecIo,
244 modules: Vec<HostModule<DefaultProcessManager>>,
245 types: Vec<&'static TypeDescriptor>,
246) -> Result<LazyRunOutput> {
247 run_steps_with_lazy_snapshot_and_modules_and_entry(
248 build_context,
249 steps,
250 io,
251 modules,
252 types,
253 None,
254 )
255}
256
257pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
261 build_context: &GuardedPath,
262 steps: &[Step],
263 io: ExecIo,
264 modules: Vec<HostModule<DefaultProcessManager>>,
265 types: Vec<&'static TypeDescriptor>,
266 entry_file: Option<GuardedPath>,
267) -> Result<LazyRunOutput> {
268 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
269 resolver.set_workspace_root(build_context.clone());
270 let snapshot = resolver.snapshot_handle();
271 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
272 match run_steps_with_manager_with_modules_and_entry(
273 fs,
274 steps,
275 default_process_manager(),
276 io,
277 modules,
278 types,
279 entry_file,
280 ) {
281 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
282 final_cwd,
283 snapshot,
284 fs,
285 bindings,
286 }),
287 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
288 }
289}
290
291pub fn enrich_lazy_error(
296 snapshot: &Arc<LazyGuardedTempDir>,
297 build_context: &GuardedPath,
298 err: anyhow::Error,
299) -> anyhow::Error {
300 match snapshot.get() {
301 Some(concrete) => {
302 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
303 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
304 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
305 };
306 let snapshot_msg = format!(
307 "filesystem snapshot (root {}):\n{}",
308 concrete.display(),
309 tree
310 );
311 error_with_snapshot(err, snapshot_msg)
312 }
313 None => error_with_snapshot(
314 err,
315 String::from(
316 "filesystem snapshot: never materialized (no snapshot directory was created)",
317 ),
318 ),
319 }
320}
321
322pub fn run_steps_with_fs(
323 fs: Box<dyn WorkspaceFs>,
324 steps: &[Step],
325 stdin: Option<SharedInput>,
326 stdout: Option<SharedOutput>,
327) -> Result<GuardedPath> {
328 let io = assemble_default_io(stdin, stdout);
329 run_steps_with_fs_with_io(fs, steps, io)
330}
331
332pub fn run_steps_with_fs_with_io(
333 fs: Box<dyn WorkspaceFs>,
334 steps: &[Step],
335 io: ExecIo,
336) -> Result<GuardedPath> {
337 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
338}
339
340pub(crate) use oxdock_parser::base_name;
345
346#[allow(clippy::type_complexity)]
354pub fn run_steps_with_manager<P: ProcessManager>(
355 fs: Box<dyn WorkspaceFs>,
356 steps: &[Step],
357 process: P,
358 io: ExecIo,
359) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
360 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
361}
362
363#[allow(clippy::type_complexity)]
371pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
372 fs: Box<dyn WorkspaceFs>,
373 steps: &[Step],
374 process: P,
375 io: ExecIo,
376 modules: Vec<HostModule<P>>,
377 types: Vec<&'static self::typing::TypeDescriptor>,
378) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
379 run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
380}
381
382#[allow(clippy::type_complexity)]
386#[allow(clippy::too_many_arguments)]
387pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
388 fs: Box<dyn WorkspaceFs>,
389 steps: &[Step],
390 process: P,
391 io: ExecIo,
392 modules: Vec<HostModule<P>>,
393 types: Vec<&'static self::typing::TypeDescriptor>,
394 entry_file: Option<GuardedPath>,
395) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
396 let mut state = new_state(fs, io)?;
397 state.entry_file = entry_file;
398 state.module_table = build_module_table(&modules);
399 for module in &modules {
400 module.check_pre_run(steps)?;
403 }
404 for module in modules {
405 state.register_module(module);
406 }
407 for descriptor in types {
408 state.register_type(descriptor);
409 }
410 finish_run(state, process, steps)
411}
412
413pub(crate) fn new_state<P: ProcessManager>(
414 fs: Box<dyn WorkspaceFs>,
415 io: ExecIo,
416) -> Result<ExecState<P>> {
417 let cwd = fs.root().clone();
418 let build_context = fs.build_context().clone();
419 let cargo_scratch = reserve_cargo_scratch()?;
420 let seed = Arc::new(oxdock_process::seed_defaults());
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 envs,
443 bg_children: Vec::new(),
444 scope_stack: Vec::new(),
445 isolated_stack: Vec::new(),
446 io,
447 assert_windows: assert_windows.clone(),
448 assert_windows_stderr: assert_windows_stderr.clone(),
449 exact_stdout: exact_stdout.clone(),
450 var_scopes: Vec::new(),
451 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
452 cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
453 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
454 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
455 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
456 live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
457 inside_async: false,
458 keeper_expiry: None,
459 cancellable: false,
460 reap_floor: None,
461 functions: self::native::FunctionRegistry::with_builtins(),
462 entry_file: None,
463 import_stack: Vec::new(),
464 import_alias_frame: None,
465 modules: std::collections::HashMap::new(),
466 validated_modules: std::collections::HashSet::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
512pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
519 fs: Box<dyn WorkspaceFs>,
520 steps: &[Step],
521 modules: Vec<HostModule<P>>,
522 types: Vec<&'static TypeDescriptor>,
523 entry_file: Option<GuardedPath>,
524) -> Result<()> {
525 let mut state = new_state(fs, ExecIo::new())?;
526 state.entry_file = entry_file;
527 state.module_table = build_module_table(&modules);
528 for module in modules {
529 state.register_module(module);
530 }
531 for descriptor in types {
532 state.register_type(descriptor);
533 }
534 validate_closure_for_run(&mut state, steps).map(|_| ())
535}
536
537pub fn validate_closure_for_run<P: ProcessManager>(
545 state: &mut ExecState<P>,
546 steps: &[Step],
547) -> Result<Vec<String>> {
548 state.type_aliases = self::typing::collect_type_aliases(steps, state)?;
549 state.validate_function_type_tags()?;
550 let saved_aliases = state.type_aliases.clone();
551 let closure = self::import::expand_import_closure(state, steps)?;
552 static_check::validate_script_closure(steps, &closure, state)?;
553 state.type_aliases = saved_aliases;
554 let mut exported = Vec::new();
555 for file in &closure {
556 exported.extend(file.type_exports.iter().cloned());
557 }
558 Ok(exported)
559}
560
561#[allow(clippy::type_complexity)]
562fn finish_run<P: ProcessManager>(
563 mut state: ExecState<P>,
564 process: P,
565 steps: &[Step],
566) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
567 validate_closure_for_run(&mut state, steps)?;
568 let assert_windows = Arc::clone(&state.assert_windows);
569 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
570 let exact_stdout = Arc::clone(&state.exact_stdout);
571 let _default_stdout = std::io::stdout();
572 let stdin = state.io.stdin().into();
573 let stdout = Some(StreamHandle::Stream(teed_stdout(
577 state.io.stdout(),
578 assert_windows,
579 exact_stdout,
580 None,
581 )));
582 let stderr = state
583 .io
584 .stderr()
585 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
586 let mut proc_mgr = process;
587 let flow = execute_steps(
588 &mut state,
589 &mut proc_mgr,
590 steps,
591 stdin,
592 false,
593 stdout,
594 stderr,
595 None,
596 None,
597 true,
598 )?;
599 match flow {
600 self::steps::Flow::Done => {
605 let bindings: BTreeMap<String, Value> = state
610 .var_scopes
611 .first()
612 .map(|scope| {
613 scope
614 .iter()
615 .map(|(k, (_, v))| (k.clone(), v.clone()))
616 .collect()
617 })
618 .unwrap_or_default();
619 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
620 }
621 self::steps::Flow::Break { idx } => {
622 anyhow::bail!("step {}: BREAK outside loop", idx + 1)
623 }
624 self::steps::Flow::Continue { idx } => {
625 anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
626 }
627 self::steps::Flow::Return { idx, .. } => {
628 anyhow::bail!(
632 "step {}: RETURN outside function, ASYNC task, or LET block",
633 idx + 1
634 )
635 }
636 }
637}