1mod args;
2mod capture;
3#[cfg(any(test, feature = "test-harness"))]
4pub mod conformance;
5mod engine;
6mod exit;
7mod fs_ops;
8mod handlers;
9mod io;
10pub mod mcp;
11mod native;
12pub mod remote;
13mod state;
14mod static_check;
15mod steps;
16#[cfg(test)]
17mod tests;
18mod typing;
19
20pub use self::remote::{
21 RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
22 apply_push_symlink,
23};
24
25pub use self::args::{json_to_value, json_to_value_typed, value_to_json, value_to_json_typed};
26#[cfg(any(test, feature = "test-harness"))]
27pub use self::conformance::assert_module_returns_conformance;
28pub use self::engine::{Engine, EngineOutput};
29pub use self::exit::{ExitRequest, exit_code_of};
30pub(crate) use self::handlers::{
31 dispatch_append, dispatch_archive, dispatch_assert_contains, dispatch_assert_eq,
32 dispatch_assign, dispatch_assign_async_step, dispatch_assign_capture_step,
33 dispatch_async_block, dispatch_await_capture_step, dispatch_await_step, dispatch_break,
34 dispatch_call, dispatch_cancel_step, dispatch_continue, dispatch_copy, dispatch_copy_git,
35 dispatch_cwd, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand, dispatch_for_loop,
36 dispatch_func_def, dispatch_hash_sha256, dispatch_if_then, dispatch_inherit_env,
37 dispatch_install, dispatch_isolated_inherit_env, dispatch_isolated_step, dispatch_ls,
38 dispatch_mkdir, dispatch_prompt, dispatch_push_into_step, dispatch_read, dispatch_read_line,
39 dispatch_remote, dispatch_remove, dispatch_return, dispatch_run, dispatch_run_exec,
40 dispatch_set, dispatch_sleep_step, dispatch_symlink, dispatch_timeout_step, dispatch_unarchive,
41 dispatch_while_loop, dispatch_with_io, dispatch_with_io_block, dispatch_workdir,
42 dispatch_workspace, dispatch_write,
43};
44pub use self::io::ExecIo;
45pub use self::io::PipeStream;
46pub use self::io::PushManifestSink;
47pub use self::io::{StreamChunk, StreamHook, TeeStream};
48pub use self::mcp::{McpCallOutput, McpSession};
49pub use self::native::{
50 FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
51 OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
52 builtin_function_names, fill_optional_args, required_arity, std_module_table,
53};
54pub use self::state::ExecState;
55pub use self::state::MAX_RUNNING_TASKS;
56pub use self::steps::StepCtx;
57pub use self::typing::{
58 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
59 check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
60 drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
61 load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
62 unshare_shared,
63};
64
65use anyhow::Result;
66use oxdock_fs::{
67 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
68};
69use oxdock_parser::Step;
70use oxdock_process::{
71 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
72 default_process_manager,
73};
74
75use std::collections::BTreeMap;
76use std::sync::Arc;
77
78use self::fs_ops::describe_dir;
79use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
80use self::steps::execute_steps;
81
82pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
87
88pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
92
93pub fn run_steps(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
94 run_steps_with_context(fs_root, fs_root, steps)
95}
96
97pub fn run_steps_with_context(
98 fs_root: &GuardedPath,
99 build_context: &GuardedPath,
100 steps: &[Step],
101) -> Result<()> {
102 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
103}
104
105pub fn run_steps_with_context_result(
107 fs_root: &GuardedPath,
108 build_context: &GuardedPath,
109 steps: &[Step],
110 stdin: Option<SharedInput>,
111 stdout: Option<SharedOutput>,
112) -> Result<GuardedPath> {
113 let io = assemble_default_io(stdin, stdout);
114 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
115}
116
117pub fn run_steps_with_context_result_with_io(
118 fs_root: &GuardedPath,
119 build_context: &GuardedPath,
120 steps: &[Step],
121 io: ExecIo,
122) -> Result<GuardedPath> {
123 match run_steps_inner(fs_root, build_context, steps, io) {
124 Ok(final_cwd) => Ok(final_cwd),
125 Err(err) => {
126 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
127 let tree = describe_dir(&fs, fs_root, 2, 24);
128 let snapshot = format!(
129 "filesystem snapshot (root {}):\n{}",
130 fs_root.display(),
131 tree
132 );
133 Err(compose_error_with_snapshot(err, snapshot))
134 }
135 }
136}
137
138fn compose_error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
142 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
144 let mut primary = chain
145 .first()
146 .cloned()
147 .unwrap_or_else(|| "unknown error".into());
148 let rest = if chain.len() > 1 {
149 let first_cause = chain[1].clone();
150 primary = format!("{primary} ({first_cause})");
151 if chain.len() > 2 {
152 let causes = chain
153 .iter()
154 .skip(2)
155 .map(|s| s.as_str())
156 .collect::<Vec<_>>()
157 .join("\n ");
158 format!("\ncauses:\n {}", causes)
159 } else {
160 String::new()
161 }
162 } else {
163 String::new()
164 };
165 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
166 match exit::exit_code_of(&err) {
172 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
173 None => anyhow::anyhow!(msg),
174 }
175}
176
177fn run_steps_inner(
178 fs_root: &GuardedPath,
179 build_context: &GuardedPath,
180 steps: &[Step],
181 io: ExecIo,
182) -> Result<GuardedPath> {
183 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
184 resolver.set_workspace_root(build_context.clone());
185 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
186}
187
188pub struct LazyRunOutput {
193 pub final_cwd: GuardedPath,
194 pub snapshot: Arc<LazyGuardedTempDir>,
195 pub fs: Box<dyn WorkspaceFs>,
196 pub bindings: BTreeMap<String, Value>,
201}
202
203pub fn run_steps_with_lazy_snapshot(
207 build_context: &GuardedPath,
208 steps: &[Step],
209 io: ExecIo,
210) -> Result<LazyRunOutput> {
211 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
212}
213
214pub fn run_steps_with_lazy_snapshot_and_modules(
219 build_context: &GuardedPath,
220 steps: &[Step],
221 io: ExecIo,
222 modules: Vec<HostModule<DefaultProcessManager>>,
223 types: Vec<&'static TypeDescriptor>,
224) -> Result<LazyRunOutput> {
225 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
226 resolver.set_workspace_root(build_context.clone());
227 let snapshot = resolver.snapshot_handle();
228 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
229 match run_steps_with_manager_with_modules(
230 fs,
231 steps,
232 default_process_manager(),
233 io,
234 modules,
235 types,
236 ) {
237 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
238 final_cwd,
239 snapshot,
240 fs,
241 bindings,
242 }),
243 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
244 }
245}
246
247pub fn enrich_lazy_error(
252 snapshot: &Arc<LazyGuardedTempDir>,
253 build_context: &GuardedPath,
254 err: anyhow::Error,
255) -> anyhow::Error {
256 match snapshot.get() {
257 Some(concrete) => {
258 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
259 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
260 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
261 };
262 let snapshot_msg = format!(
263 "filesystem snapshot (root {}):\n{}",
264 concrete.display(),
265 tree
266 );
267 compose_error_with_snapshot(err, snapshot_msg)
268 }
269 None => compose_error_with_snapshot(
270 err,
271 String::from(
272 "filesystem snapshot: never materialized (no snapshot directory was created)",
273 ),
274 ),
275 }
276}
277
278pub fn run_steps_with_fs(
279 fs: Box<dyn WorkspaceFs>,
280 steps: &[Step],
281 stdin: Option<SharedInput>,
282 stdout: Option<SharedOutput>,
283) -> Result<GuardedPath> {
284 let io = assemble_default_io(stdin, stdout);
285 run_steps_with_fs_with_io(fs, steps, io)
286}
287
288pub fn run_steps_with_fs_with_io(
289 fs: Box<dyn WorkspaceFs>,
290 steps: &[Step],
291 io: ExecIo,
292) -> Result<GuardedPath> {
293 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
294}
295
296pub(crate) use oxdock_parser::base_name;
301
302#[allow(clippy::type_complexity)]
310pub fn run_steps_with_manager<P: ProcessManager>(
311 fs: Box<dyn WorkspaceFs>,
312 steps: &[Step],
313 process: P,
314 io: ExecIo,
315) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
316 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
317}
318
319#[allow(clippy::type_complexity)]
327pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
328 fs: Box<dyn WorkspaceFs>,
329 steps: &[Step],
330 process: P,
331 io: ExecIo,
332 modules: Vec<HostModule<P>>,
333 types: Vec<&'static self::typing::TypeDescriptor>,
334) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
335 let mut state = new_state(fs, io)?;
336 for module in &modules {
337 module.check_pre_run(steps)?;
340 }
341 for module in modules {
342 state.register_module(module);
343 }
344 for descriptor in types {
345 state.register_type(descriptor);
346 }
347 finish_run(state, process, steps)
348}
349
350pub(crate) fn new_state<P: ProcessManager>(
351 fs: Box<dyn WorkspaceFs>,
352 io: ExecIo,
353) -> Result<ExecState<P>> {
354 let cwd = fs.root().clone();
355 let build_context = fs.build_context().clone();
356 let cargo_scratch = reserve_cargo_scratch()?;
357 let seed = Arc::new(oxdock_process::seed_defaults(
362 &cargo_scratch.tmp_seed_display(),
363 &cargo_scratch.target_seed_display(),
364 ));
365 let mut envs = (*seed).clone();
366 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
367 for (key, value) in io.inherit_env_overrides() {
368 envs.insert(key.clone(), value.clone());
369 }
370 let envs = Arc::new(envs);
371 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
372 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
373 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
374 let worker_counter = io.worker_counter();
377 let mut state = ExecState {
378 fs,
379 cargo_scratch,
380 seed,
381 cwd,
382 envs,
383 bg_children: Vec::new(),
384 scope_stack: Vec::new(),
385 isolated_stack: Vec::new(),
386 io,
387 assert_windows: assert_windows.clone(),
388 assert_windows_stderr: assert_windows_stderr.clone(),
389 exact_stdout: exact_stdout.clone(),
390 var_scopes: Vec::new(),
391 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
392 cancel_hub: std::sync::Arc::new(oxdock_process::CancelHub::with_counter(worker_counter)),
393 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
394 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
395 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
396 live_tasks: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
397 inside_async: false,
398 keeper_expiry: None,
399 cancellable: false,
400 reap_floor: None,
401 functions: self::native::FunctionRegistry::with_builtins(),
402 types: self::typing::startup_type_map(),
403 record_schemas: std::collections::HashMap::new(),
404 module_states: std::collections::HashMap::new(),
405 type_aliases: std::collections::HashMap::new(),
406 call_depth: 0,
407 task_id: 0,
409 push_manifest: Vec::new(),
410 _marker: std::marker::PhantomData,
411 };
412
413 state.push_var_scope();
415
416 Ok(state)
417}
418
419#[allow(clippy::type_complexity)]
420fn finish_run<P: ProcessManager>(
421 mut state: ExecState<P>,
422 process: P,
423 steps: &[Step],
424) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
425 state.type_aliases = self::typing::collect_type_aliases(steps, &state)?;
429 state.validate_function_type_tags()?;
430 static_check::validate_script_types(steps, &state)?;
434 let assert_windows = Arc::clone(&state.assert_windows);
435 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
436 let exact_stdout = Arc::clone(&state.exact_stdout);
437 let _default_stdout = std::io::stdout();
438 let stdin = state.io.stdin().into();
439 let stdout = Some(StreamHandle::Stream(teed_stdout(
443 state.io.stdout(),
444 assert_windows,
445 exact_stdout,
446 None,
447 )));
448 let stderr = state
449 .io
450 .stderr()
451 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr, None)));
452 let mut proc_mgr = process;
453 let flow = execute_steps(
454 &mut state,
455 &mut proc_mgr,
456 steps,
457 stdin,
458 false,
459 stdout,
460 stderr,
461 None,
462 None,
463 true,
464 )?;
465 match flow {
466 self::steps::Flow::Done => {
471 let bindings: BTreeMap<String, Value> = state
476 .var_scopes
477 .first()
478 .map(|scope| {
479 scope
480 .iter()
481 .map(|(k, (_, v))| (k.clone(), v.clone()))
482 .collect()
483 })
484 .unwrap_or_default();
485 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
486 }
487 self::steps::Flow::Break { idx } => {
488 anyhow::bail!("step {}: BREAK outside loop", idx + 1)
489 }
490 self::steps::Flow::Continue { idx } => {
491 anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
492 }
493 self::steps::Flow::Return { idx, .. } => {
494 anyhow::bail!(
498 "step {}: RETURN outside function, ASYNC task, or LET block",
499 idx + 1
500 )
501 }
502 }
503}