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_append_line, dispatch_archive, dispatch_assert_contains,
33 dispatch_assert_eq, dispatch_assert_ne, dispatch_assign, dispatch_assign_async_step,
34 dispatch_assign_capture_step, dispatch_async_block, dispatch_await_capture_step,
35 dispatch_await_step, dispatch_break, dispatch_call, dispatch_cancel_step, dispatch_continue,
36 dispatch_copy, dispatch_copy_git, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand,
37 dispatch_for_loop, dispatch_func_def, dispatch_if_then, dispatch_import_file,
38 dispatch_import_funcs, dispatch_inherit_env, dispatch_install, dispatch_isolated_inherit_env,
39 dispatch_isolated_step, dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step,
40 dispatch_read, dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return,
41 dispatch_run, dispatch_run_exec, dispatch_set, dispatch_set_executable, dispatch_sleep_step,
42 dispatch_symlink, dispatch_timeout_step, dispatch_unarchive, dispatch_while_loop,
43 dispatch_with_io, dispatch_with_io_block, 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, placeholder_resolver, required_arity,
55 std_module_table,
56};
57pub use self::state::ExecState;
58pub use self::state::MAX_RUNNING_TASKS;
59pub use self::steps::StepCtx;
60pub use self::typing::{
61 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
62 check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
63 drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
64 load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
65 unshare_shared,
66};
67
68use anyhow::Result;
69use oxdock_fs::{
70 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
71};
72use oxdock_parser::Step;
73use oxdock_process::{
74 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
75 default_process_manager,
76};
77
78use std::collections::BTreeMap;
79use std::sync::Arc;
80
81use self::fs_ops::describe_dir;
82use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
83use self::steps::execute_steps;
84
85pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
90
91pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
95
96pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> Result<()> {
106 run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
107}
108
109pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
114 run_steps_with_context(fs_root, fs_root, steps)
115}
116
117pub fn run_steps_with_context(
118 fs_root: &GuardedPath,
119 build_context: &GuardedPath,
120 steps: &[Step],
121) -> Result<()> {
122 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
123}
124
125pub fn run_steps_with_context_result(
127 fs_root: &GuardedPath,
128 build_context: &GuardedPath,
129 steps: &[Step],
130 stdin: Option<SharedInput>,
131 stdout: Option<SharedOutput>,
132) -> Result<GuardedPath> {
133 let io = assemble_default_io(stdin, stdout);
134 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
135}
136
137pub fn run_steps_with_context_result_with_io(
138 fs_root: &GuardedPath,
139 build_context: &GuardedPath,
140 steps: &[Step],
141 io: ExecIo,
142) -> Result<GuardedPath> {
143 match run_steps_inner(fs_root, build_context, steps, io) {
144 Ok(final_cwd) => Ok(final_cwd),
145 Err(err) => {
146 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
147 let tree = describe_dir(&fs, fs_root, 2, 24);
148 let snapshot = format!(
149 "filesystem snapshot (root {}):\n{}",
150 fs_root.display(),
151 tree
152 );
153 Err(error_with_snapshot(err, snapshot))
154 }
155 }
156}
157
158fn error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
162 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
164 let mut primary = chain
165 .first()
166 .cloned()
167 .unwrap_or_else(|| "unknown error".into());
168 let rest = if chain.len() > 1 {
169 let first_cause = chain[1].clone();
170 primary = format!("{primary} ({first_cause})");
171 if chain.len() > 2 {
172 let causes = chain
173 .iter()
174 .skip(2)
175 .map(|s| s.as_str())
176 .collect::<Vec<_>>()
177 .join("\n ");
178 format!("\ncauses:\n {}", causes)
179 } else {
180 String::new()
181 }
182 } else {
183 String::new()
184 };
185 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
186 match exit::exit_code_of(&err) {
192 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
193 None => anyhow::anyhow!(msg),
194 }
195}
196
197fn run_steps_inner(
198 fs_root: &GuardedPath,
199 build_context: &GuardedPath,
200 steps: &[Step],
201 io: ExecIo,
202) -> Result<GuardedPath> {
203 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
204 resolver.set_workspace_root(build_context.clone());
205 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
206}
207
208pub struct LazyRunOutput {
213 pub final_cwd: GuardedPath,
214 pub snapshot: Arc<LazyGuardedTempDir>,
215 pub fs: Box<dyn WorkspaceFs>,
216 pub bindings: BTreeMap<String, Value>,
221}
222
223pub fn run_steps_with_lazy_snapshot(
227 build_context: &GuardedPath,
228 steps: &[Step],
229 io: ExecIo,
230) -> Result<LazyRunOutput> {
231 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
232}
233
234pub fn run_steps_with_lazy_snapshot_and_modules(
239 build_context: &GuardedPath,
240 steps: &[Step],
241 io: ExecIo,
242 modules: Vec<HostModule<DefaultProcessManager>>,
243 types: Vec<&'static TypeDescriptor>,
244) -> Result<LazyRunOutput> {
245 run_steps_with_lazy_snapshot_and_modules_and_entry(
246 build_context,
247 steps,
248 io,
249 modules,
250 types,
251 None,
252 )
253}
254
255pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
259 build_context: &GuardedPath,
260 steps: &[Step],
261 io: ExecIo,
262 modules: Vec<HostModule<DefaultProcessManager>>,
263 types: Vec<&'static TypeDescriptor>,
264 entry_file: Option<GuardedPath>,
265) -> Result<LazyRunOutput> {
266 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
267 resolver.set_workspace_root(build_context.clone());
268 let snapshot = resolver.snapshot_handle();
269 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
270 match run_steps_with_manager_with_modules_and_entry(
271 fs,
272 steps,
273 default_process_manager(),
274 io,
275 modules,
276 types,
277 entry_file,
278 ) {
279 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
280 final_cwd,
281 snapshot,
282 fs,
283 bindings,
284 }),
285 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
286 }
287}
288
289pub fn enrich_lazy_error(
294 snapshot: &Arc<LazyGuardedTempDir>,
295 build_context: &GuardedPath,
296 err: anyhow::Error,
297) -> anyhow::Error {
298 match snapshot.get() {
299 Some(concrete) => {
300 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
301 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
302 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
303 };
304 let snapshot_msg = format!(
305 "filesystem snapshot (root {}):\n{}",
306 concrete.display(),
307 tree
308 );
309 error_with_snapshot(err, snapshot_msg)
310 }
311 None => error_with_snapshot(
312 err,
313 String::from(
314 "filesystem snapshot: never materialized (no snapshot directory was created)",
315 ),
316 ),
317 }
318}
319
320pub fn run_steps_with_fs(
321 fs: Box<dyn WorkspaceFs>,
322 steps: &[Step],
323 stdin: Option<SharedInput>,
324 stdout: Option<SharedOutput>,
325) -> Result<GuardedPath> {
326 let io = assemble_default_io(stdin, stdout);
327 run_steps_with_fs_with_io(fs, steps, io)
328}
329
330pub fn run_steps_with_fs_with_io(
331 fs: Box<dyn WorkspaceFs>,
332 steps: &[Step],
333 io: ExecIo,
334) -> Result<GuardedPath> {
335 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
336}
337
338pub(crate) use oxdock_parser::base_name;
343
344#[allow(clippy::type_complexity)]
352pub fn run_steps_with_manager<P: ProcessManager>(
353 fs: Box<dyn WorkspaceFs>,
354 steps: &[Step],
355 process: P,
356 io: ExecIo,
357) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
358 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
359}
360
361#[allow(clippy::type_complexity)]
369pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
370 fs: Box<dyn WorkspaceFs>,
371 steps: &[Step],
372 process: P,
373 io: ExecIo,
374 modules: Vec<HostModule<P>>,
375 types: Vec<&'static self::typing::TypeDescriptor>,
376) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
377 run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
378}
379
380#[allow(clippy::type_complexity)]
384#[allow(clippy::too_many_arguments)]
385pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
386 fs: Box<dyn WorkspaceFs>,
387 steps: &[Step],
388 process: P,
389 io: ExecIo,
390 modules: Vec<HostModule<P>>,
391 types: Vec<&'static self::typing::TypeDescriptor>,
392 entry_file: Option<GuardedPath>,
393) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
394 let mut state = new_state(fs, io)?;
395 state.entry_file = entry_file;
396 state.module_table = build_module_table(&modules);
397 for module in &modules {
398 module.check_pre_run(steps)?;
401 }
402 for module in modules {
403 state.register_module(module);
404 }
405 for descriptor in types {
406 state.register_type(descriptor);
407 }
408 finish_run(state, process, steps)
409}
410
411pub(crate) fn new_state<P: ProcessManager>(
412 fs: Box<dyn WorkspaceFs>,
413 io: ExecIo,
414) -> Result<ExecState<P>> {
415 let cwd = fs.root().clone();
416 let build_context = fs.build_context().clone();
417 let cargo_scratch = reserve_cargo_scratch()?;
418 let seed = Arc::new(oxdock_process::seed_defaults());
423 let mut envs = (*seed).clone();
424 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
425 for (key, value) in io.inherit_env_overrides() {
426 envs.insert(key.clone(), value.clone());
427 }
428 let envs = Arc::new(envs);
429 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
430 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
431 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
432 let worker_counter = io.worker_counter();
435 let mut state = ExecState {
436 fs,
437 cargo_scratch,
438 seed,
439 cwd: cwd.clone(),
440 initial_root: cwd,
441 envs,
442 bg_children: Vec::new(),
443 scope_stack: Vec::new(),
444 isolated_stack: Vec::new(),
445 io,
446 assert_windows: assert_windows.clone(),
447 assert_windows_stderr: assert_windows_stderr.clone(),
448 exact_stdout: exact_stdout.clone(),
449 var_scopes: Vec::new(),
450 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
451 cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
452 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
453 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
454 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
455 live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
456 inside_async: false,
457 keeper_expiry: None,
458 cancellable: false,
459 reap_floor: None,
460 functions: self::native::FunctionRegistry::with_builtins(),
461 entry_file: None,
462 import_stack: Vec::new(),
463 import_alias_frame: None,
464 modules: std::collections::HashMap::new(),
465 validated_modules: std::collections::HashSet::new(),
466 module_stack: Vec::new(),
467 module_table: self::native::std_module_table(),
468 types: self::typing::startup_type_map(),
469 record_schemas: std::collections::HashMap::new(),
470 module_states: std::collections::HashMap::new(),
471 type_aliases: std::collections::HashMap::new(),
472 call_depth: 0,
473 task_id: 0,
475 push_manifest: Vec::new(),
476 _marker: std::marker::PhantomData,
477 };
478
479 state.push_var_scope();
481
482 Ok(state)
483}
484
485fn build_module_table<P: ProcessManager>(
490 modules: &[self::native::HostModule<P>],
491) -> oxdock_parser::ModuleTable {
492 let mut table = self::native::std_module_table();
493 for module in modules {
494 let mut func_names = std::collections::HashSet::new();
495 for registration in &module.funcs {
496 let name = match registration {
497 self::native::HostRegistration::Stateful { name, .. } => name,
498 self::native::HostRegistration::Pure { name, .. } => name,
499 self::native::HostRegistration::Both { name, .. } => name,
500 };
501 func_names.insert(name.clone());
502 }
503 table.modules.insert(
504 module.name.clone(),
505 Some(oxdock_parser::ModuleFuncs { func_names }),
506 );
507 }
508 table
509}
510
511pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
518 fs: Box<dyn WorkspaceFs>,
519 steps: &[Step],
520 modules: Vec<HostModule<P>>,
521 types: Vec<&'static TypeDescriptor>,
522 entry_file: Option<GuardedPath>,
523) -> Result<()> {
524 let mut state = new_state(fs, ExecIo::new())?;
525 state.entry_file = entry_file;
526 state.module_table = build_module_table(&modules);
527 for module in modules {
528 state.register_module(module);
529 }
530 for descriptor in types {
531 state.register_type(descriptor);
532 }
533 validate_closure_for_run(&mut state, steps).map(|_| ())
534}
535
536pub fn validate_closure_for_run<P: ProcessManager>(
544 state: &mut ExecState<P>,
545 steps: &[Step],
546) -> Result<Vec<String>> {
547 state.type_aliases = self::typing::collect_type_aliases(steps, state)?;
548 state.validate_function_type_tags()?;
549 let saved_aliases = state.type_aliases.clone();
550 let closure = self::import::expand_import_closure(state, steps)?;
551 static_check::validate_script_closure(steps, &closure, state)?;
552 state.type_aliases = saved_aliases;
553 let mut exported = Vec::new();
554 for file in &closure {
555 exported.extend(file.type_exports.iter().cloned());
556 }
557 Ok(exported)
558}
559
560#[allow(clippy::type_complexity)]
561fn finish_run<P: ProcessManager>(
562 mut state: ExecState<P>,
563 process: P,
564 steps: &[Step],
565) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
566 validate_closure_for_run(&mut state, steps)?;
567 let assert_windows = Arc::clone(&state.assert_windows);
568 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
569 let exact_stdout = Arc::clone(&state.exact_stdout);
570 let _default_stdout = std::io::stdout();
571 let stdin = state.io.stdin().into();
572 let stdout = Some(StreamHandle::Stream(teed_stdout(
576 state.io.stdout(),
577 assert_windows,
578 exact_stdout,
579 None,
580 )));
581 let stderr = state
582 .io
583 .stderr()
584 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
585 let mut proc_mgr = process;
586 let flow = execute_steps(
587 &mut state,
588 &mut proc_mgr,
589 steps,
590 stdin,
591 false,
592 stdout,
593 stderr,
594 None,
595 None,
596 true,
597 )?;
598 match flow {
599 self::steps::Flow::Done => {
604 let bindings: BTreeMap<String, Value> = state
609 .var_scopes
610 .first()
611 .map(|scope| {
612 scope
613 .iter()
614 .map(|(k, (_, v))| (k.clone(), v.clone()))
615 .collect()
616 })
617 .unwrap_or_default();
618 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
619 }
620 self::steps::Flow::Break { idx } => {
621 anyhow::bail!("step {}: BREAK outside loop", idx + 1)
622 }
623 self::steps::Flow::Continue { idx } => {
624 anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
625 }
626 self::steps::Flow::Return { idx, .. } => {
627 anyhow::bail!(
631 "step {}: RETURN outside function, ASYNC task, or LET block",
632 idx + 1
633 )
634 }
635 }
636}