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_fail, 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_switch, dispatch_symlink, dispatch_timeout_step, dispatch_unarchive,
45 dispatch_while_loop, dispatch_with_io, dispatch_with_io_block, dispatch_workdir,
46 dispatch_workspace, dispatch_write,
47};
48pub use self::import::{DryRunStep, dry_run_closure};
49pub use self::io::ExecIo;
50pub use self::io::PipeStream;
51pub use self::io::PushManifestSink;
52pub use self::io::{StreamChunk, StreamHook, TeeStream};
53pub use self::mcp::{McpCallOutput, McpSession};
54pub use self::native::{
55 FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
56 OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
57 builtin_function_names, check_script_param_tags, fill_optional_args, optional_zero_value,
58 placeholder_resolver, required_arity, resolve_script_params, std_module_table,
59};
60pub use self::state::ExecState;
61pub use self::state::MAX_RUNNING_TASKS;
62pub use self::steps::StepCtx;
63pub use self::typing::{
64 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
65 check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
66 drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
67 load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
68 unshare_shared,
69};
70
71use anyhow::Result;
72use oxdock_fs::{
73 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
74};
75use oxdock_parser::Step;
76use oxdock_process::{
77 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
78 default_process_manager,
79};
80
81use std::collections::BTreeMap;
82use std::sync::Arc;
83
84use self::fs_ops::describe_dir;
85use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
86use self::steps::execute_steps;
87
88pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
93
94pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
98
99pub fn run_steps(build_context: &GuardedPath, steps: &[Step], io: ExecIo) -> Result<()> {
109 run_steps_with_lazy_snapshot(build_context, steps, io).map(|_| ())
110}
111
112pub fn run_steps_without_snapshot(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
117 run_steps_with_context(fs_root, fs_root, steps)
118}
119
120pub fn run_steps_with_context(
121 fs_root: &GuardedPath,
122 build_context: &GuardedPath,
123 steps: &[Step],
124) -> Result<()> {
125 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
126}
127
128pub fn run_steps_with_context_result(
130 fs_root: &GuardedPath,
131 build_context: &GuardedPath,
132 steps: &[Step],
133 stdin: Option<SharedInput>,
134 stdout: Option<SharedOutput>,
135) -> Result<GuardedPath> {
136 let io = assemble_default_io(stdin, stdout);
137 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
138}
139
140pub fn run_steps_with_context_result_with_io(
141 fs_root: &GuardedPath,
142 build_context: &GuardedPath,
143 steps: &[Step],
144 io: ExecIo,
145) -> Result<GuardedPath> {
146 match run_steps_inner(fs_root, build_context, steps, io) {
147 Ok(final_cwd) => Ok(final_cwd),
148 Err(err) => {
149 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
150 let tree = describe_dir(&fs, fs_root, 2, 24);
151 let snapshot = format!(
152 "filesystem snapshot (root {}):\n{}",
153 fs_root.display(),
154 tree
155 );
156 Err(error_with_snapshot(err, snapshot))
157 }
158 }
159}
160
161fn error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
165 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
167 let mut primary = chain
168 .first()
169 .cloned()
170 .unwrap_or_else(|| "unknown error".into());
171 let rest = if chain.len() > 1 {
172 let first_cause = chain[1].clone();
173 primary = format!("{primary} ({first_cause})");
174 if chain.len() > 2 {
175 let causes = chain
176 .iter()
177 .skip(2)
178 .map(|s| s.as_str())
179 .collect::<Vec<_>>()
180 .join("\n ");
181 format!("\ncauses:\n {}", causes)
182 } else {
183 String::new()
184 }
185 } else {
186 String::new()
187 };
188 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
189 match exit::exit_code_of(&err) {
195 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
196 None => anyhow::anyhow!(msg),
197 }
198}
199
200fn run_steps_inner(
201 fs_root: &GuardedPath,
202 build_context: &GuardedPath,
203 steps: &[Step],
204 io: ExecIo,
205) -> Result<GuardedPath> {
206 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
207 resolver.set_workspace_root(build_context.clone());
208 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
209}
210
211pub struct LazyRunOutput {
216 pub final_cwd: GuardedPath,
217 pub snapshot: Arc<LazyGuardedTempDir>,
218 pub fs: Box<dyn WorkspaceFs>,
219 pub bindings: BTreeMap<String, Value>,
224}
225
226pub fn run_steps_with_lazy_snapshot(
230 build_context: &GuardedPath,
231 steps: &[Step],
232 io: ExecIo,
233) -> Result<LazyRunOutput> {
234 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
235}
236
237pub fn run_steps_with_lazy_snapshot_and_modules(
242 build_context: &GuardedPath,
243 steps: &[Step],
244 io: ExecIo,
245 modules: Vec<HostModule<DefaultProcessManager>>,
246 types: Vec<&'static TypeDescriptor>,
247) -> Result<LazyRunOutput> {
248 run_steps_with_lazy_snapshot_and_modules_and_entry(
249 build_context,
250 steps,
251 io,
252 modules,
253 types,
254 None,
255 )
256}
257
258pub fn run_steps_with_lazy_snapshot_and_modules_and_entry(
262 build_context: &GuardedPath,
263 steps: &[Step],
264 io: ExecIo,
265 modules: Vec<HostModule<DefaultProcessManager>>,
266 types: Vec<&'static TypeDescriptor>,
267 entry_file: Option<GuardedPath>,
268) -> Result<LazyRunOutput> {
269 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
270 resolver.set_workspace_root(build_context.clone());
271 let snapshot = resolver.snapshot_handle();
272 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
273 match run_steps_with_manager_with_modules_and_entry(
274 fs,
275 steps,
276 default_process_manager(),
277 io,
278 modules,
279 types,
280 entry_file,
281 ) {
282 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
283 final_cwd,
284 snapshot,
285 fs,
286 bindings,
287 }),
288 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
289 }
290}
291
292pub fn enrich_lazy_error(
297 snapshot: &Arc<LazyGuardedTempDir>,
298 build_context: &GuardedPath,
299 err: anyhow::Error,
300) -> anyhow::Error {
301 match snapshot.get() {
302 Some(concrete) => {
303 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
304 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
305 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
306 };
307 let snapshot_msg = format!(
308 "filesystem snapshot (root {}):\n{}",
309 concrete.display(),
310 tree
311 );
312 error_with_snapshot(err, snapshot_msg)
313 }
314 None => error_with_snapshot(
315 err,
316 String::from(
317 "filesystem snapshot: never materialized (no snapshot directory was created)",
318 ),
319 ),
320 }
321}
322
323pub fn run_steps_with_fs(
324 fs: Box<dyn WorkspaceFs>,
325 steps: &[Step],
326 stdin: Option<SharedInput>,
327 stdout: Option<SharedOutput>,
328) -> Result<GuardedPath> {
329 let io = assemble_default_io(stdin, stdout);
330 run_steps_with_fs_with_io(fs, steps, io)
331}
332
333pub fn run_steps_with_fs_with_io(
334 fs: Box<dyn WorkspaceFs>,
335 steps: &[Step],
336 io: ExecIo,
337) -> Result<GuardedPath> {
338 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
339}
340
341pub(crate) use oxdock_parser::base_name;
346
347#[allow(clippy::type_complexity)]
355pub fn run_steps_with_manager<P: ProcessManager>(
356 fs: Box<dyn WorkspaceFs>,
357 steps: &[Step],
358 process: P,
359 io: ExecIo,
360) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
361 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
362}
363
364#[allow(clippy::type_complexity)]
372pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
373 fs: Box<dyn WorkspaceFs>,
374 steps: &[Step],
375 process: P,
376 io: ExecIo,
377 modules: Vec<HostModule<P>>,
378 types: Vec<&'static self::typing::TypeDescriptor>,
379) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
380 run_steps_with_manager_with_modules_and_entry(fs, steps, process, io, modules, types, None)
381}
382
383#[allow(clippy::type_complexity)]
387#[allow(clippy::too_many_arguments)]
388pub fn run_steps_with_manager_with_modules_and_entry<P: ProcessManager>(
389 fs: Box<dyn WorkspaceFs>,
390 steps: &[Step],
391 process: P,
392 io: ExecIo,
393 modules: Vec<HostModule<P>>,
394 types: Vec<&'static self::typing::TypeDescriptor>,
395 entry_file: Option<GuardedPath>,
396) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
397 let mut state = new_state(fs, io)?;
398 state.entry_file = entry_file;
399 state.module_table = build_module_table(&modules);
400 for module in &modules {
401 module.check_pre_run(steps)?;
404 }
405 for module in modules {
406 state.register_module(module);
407 }
408 for descriptor in types {
409 state.register_type(descriptor);
410 }
411 finish_run(state, process, steps)
412}
413
414pub(crate) fn new_state<P: ProcessManager>(
415 fs: Box<dyn WorkspaceFs>,
416 io: ExecIo,
417) -> Result<ExecState<P>> {
418 let cwd = fs.root().clone();
419 let build_context = fs.build_context().clone();
420 let cargo_scratch = reserve_cargo_scratch()?;
421 let seed = Arc::new(oxdock_process::seed_defaults());
426 let mut envs = (*seed).clone();
427 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
428 for (key, value) in io.inherit_env_overrides() {
429 envs.insert(key.clone(), value.clone());
430 }
431 let envs = Arc::new(envs);
432 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
433 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
434 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
435 let worker_counter = io.worker_counter();
438 let mut state = ExecState {
439 fs,
440 cargo_scratch,
441 seed,
442 cwd: cwd.clone(),
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 executed_alias_targets: std::collections::HashMap::new(),
466 call_alias_frames: Vec::new(),
467 modules: std::collections::HashMap::new(),
468 validated_modules: std::collections::HashSet::new(),
469 module_stack: Vec::new(),
470 module_table: self::native::std_module_table(),
471 types: self::typing::startup_type_map(),
472 record_schemas: std::collections::HashMap::new(),
473 module_states: std::collections::HashMap::new(),
474 type_aliases: std::collections::HashMap::new(),
475 type_env_digest: 0,
476 call_depth: 0,
477 task_id: 0,
479 push_manifest: Vec::new(),
480 _marker: std::marker::PhantomData,
481 };
482
483 state.push_var_scope();
485
486 Ok(state)
487}
488
489fn build_module_table<P: ProcessManager>(
494 modules: &[self::native::HostModule<P>],
495) -> oxdock_parser::ModuleTable {
496 let mut table = self::native::std_module_table();
497 for module in modules {
498 let mut func_names = std::collections::HashSet::new();
499 for registration in &module.funcs {
500 let name = match registration {
501 self::native::HostRegistration::Stateful { name, .. } => name,
502 self::native::HostRegistration::Pure { name, .. } => name,
503 self::native::HostRegistration::Both { name, .. } => name,
504 };
505 func_names.insert(name.clone());
506 }
507 table.modules.insert(
508 module.name.clone(),
509 Some(oxdock_parser::ModuleFuncs { func_names }),
510 );
511 }
512 table
513}
514
515pub fn validate_steps_with_fs_modules_and_entry<P: ProcessManager>(
522 fs: Box<dyn WorkspaceFs>,
523 steps: &[Step],
524 modules: Vec<HostModule<P>>,
525 types: Vec<&'static TypeDescriptor>,
526 entry_file: Option<GuardedPath>,
527) -> Result<()> {
528 let mut state = new_state(fs, ExecIo::new())?;
529 state.entry_file = entry_file;
530 state.module_table = build_module_table(&modules);
531 for module in modules {
532 state.register_module(module);
533 }
534 for descriptor in types {
535 state.register_type(descriptor);
536 }
537 validate_closure_for_run(&mut state, steps).map(|_| ())
538}
539
540pub fn validate_closure_for_run<P: ProcessManager>(
548 state: &mut ExecState<P>,
549 steps: &[Step],
550) -> Result<Vec<String>> {
551 state.restore_aliases(self::typing::collect_type_aliases(steps, state)?);
552 state.validate_function_type_tags()?;
553 let saved_aliases = state.type_aliases.clone();
554 let closure = self::import::expand_import_closure(state, steps)?;
555 static_check::validate_script_closure(steps, &closure, state)?;
556 state.restore_aliases(saved_aliases);
557 let mut exported = Vec::new();
558 for file in &closure {
559 exported.extend(file.type_exports.iter().cloned());
560 }
561 Ok(exported)
562}
563
564#[allow(clippy::type_complexity)]
565fn finish_run<P: ProcessManager>(
566 mut state: ExecState<P>,
567 process: P,
568 steps: &[Step],
569) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
570 validate_closure_for_run(&mut state, steps)?;
571 let assert_windows = Arc::clone(&state.assert_windows);
572 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
573 let exact_stdout = Arc::clone(&state.exact_stdout);
574 let _default_stdout = std::io::stdout();
575 let stdin = state.io.stdin().into();
576 let stdout = Some(StreamHandle::Stream(teed_stdout(
580 state.io.stdout(),
581 assert_windows,
582 exact_stdout,
583 None,
584 )));
585 let stderr = state
586 .io
587 .stderr()
588 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
589 let mut proc_mgr = process;
590 let flow = execute_steps(
591 &mut state,
592 &mut proc_mgr,
593 steps,
594 stdin,
595 false,
596 stdout,
597 stderr,
598 None,
599 None,
600 true,
601 )?;
602 match flow {
603 self::steps::Flow::Done => {
608 let bindings: BTreeMap<String, Value> = state
613 .var_scopes
614 .first()
615 .map(|scope| {
616 scope
617 .iter()
618 .map(|(k, (_, v))| (k.clone(), v.clone()))
619 .collect()
620 })
621 .unwrap_or_default();
622 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
623 }
624 self::steps::Flow::Break { idx } => {
625 anyhow::bail!("step {}: BREAK outside loop", idx + 1)
626 }
627 self::steps::Flow::Continue { idx } => {
628 anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
629 }
630 self::steps::Flow::Return { idx, .. } => {
631 anyhow::bail!(
635 "step {}: RETURN outside function, ASYNC task, or LET block",
636 idx + 1
637 )
638 }
639 }
640}