refactor(cli,host): split command entry points and provider/effects modules

This commit is contained in:
Marqdo Agent committed 2026-11-21 08:54:29 +08:00
1 parent 791819a725
commit 550e66b1e2
10 files changed
+708 -671

No files matched your search

+7 -500
View File
@@ -9,8 +9,15 @@ use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
use marqdo_span::Span;
use serde_json::json;
mod check;
mod inspect;
mod run;
mod sandbox;
pub use check::check;
pub use inspect::inspect;
pub use inspect::InspectFlags;
pub use run::execute;
pub use sandbox::SandboxSettings;
use crate::args;
@@ -199,206 +206,6 @@ fn plugin_signature(raw: &str) -> Result<marqdo_ir::callable::CallableSignature,
}
/// `marqdo check`.
pub fn check(
file: Option<&Path>,
json: bool,
refs: bool,
plugins: &[PathBuf],
emit: Option<&Path>,
) -> i32 {
let mut project = match load_project(file, json) {
Ok(project) => project,
Err(code) => return code,
};
if let Err(error) = add_static_plugin_descriptors(&mut project, plugins) {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
if refs {
let ref_diagnostics = validate_refs(&project);
project.diagnostics.extend(ref_diagnostics);
}
let errors = output::error_count(&project.diagnostics);
if let Some(path) = emit {
if errors > 0 {
let _ = std::fs::remove_file(path);
} else if let Err(error) = crate::analysis::write(&project, path) {
eprintln!("error: {error}");
return 2;
}
}
if json {
output::print_json(&json!({
"command": "check",
"success": errors == 0,
"errors": errors,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
let text = output::render_text(&project.diagnostics);
eprint!("{text}");
if errors == 0 {
let checked = project
.program
.modules
.keys()
.filter(|id| !id.instance.starts_with("std:"))
.count();
println!("checked {checked} module(s): ok");
} else {
eprintln!(
"check failed: {} error(s), {} warning(s)",
errors,
project.diagnostics.len() - errors
);
}
}
if errors == 0 {
0
} else {
1
}
}
/// Options for `marqdo inspect`.
#[derive(Debug, Clone, Default)]
pub struct InspectFlags {
/// Show the Markdown AST.
pub ast: bool,
/// Show heading units.
pub units: bool,
/// Show inferred/explicit signatures.
pub signature: bool,
/// Show executable IR.
pub ir: bool,
/// Show link reference edges.
pub refs: bool,
/// Show platform capability report.
pub platform: bool,
}
/// `marqdo inspect`.
pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool) -> i32 {
let project = match load_project(file, json) {
Ok(project) => project,
Err(code) => return code,
};
let entry = project.entry_file();
let module = &entry.analysis.module;
let selected_any =
flags.ast || flags.units || flags.signature || flags.ir || flags.refs || flags.platform;
if json {
let mut object = serde_json::Map::new();
object.insert("command".into(), json!("inspect"));
object.insert("module".into(), json!(entry.module_id.to_string()));
if !selected_any {
object.insert("summary".into(), summary_json(&project));
}
if flags.ast {
object.insert(
"ast".into(),
serde_json::to_value(&entry.analysis.document.root).unwrap_or_default(),
);
}
if flags.units {
object.insert(
"units".into(),
serde_json::to_value(&entry.analysis.units.units).unwrap_or_default(),
);
}
if flags.signature {
object.insert("signatures".into(), signatures_json(module));
}
if flags.ir {
object.insert(
"ir".into(),
serde_json::to_value(&module.functions).unwrap_or_default(),
);
}
if flags.refs {
object.insert("refs".into(), json!(refs_json(&project)));
}
if flags.platform {
object.insert(
"platform".into(),
serde_json::to_value(PlatformCapabilities::detect()).unwrap_or_default(),
);
}
output::print_json(&serde_json::Value::Object(object));
return 0;
}
if !selected_any {
println!("module: {}", entry.module_id);
println!("path: {}", entry.path.display());
println!("project root: {}", project.root.display());
println!("functions:");
for function in &module.functions {
let params = function
.params
.iter()
.map(|param| param.name.as_str())
.collect::<Vec<_>>()
.join(", ");
let kind = match function.signature {
marqdo_ir::SignatureKind::Explicit => "explicit",
marqdo_ir::SignatureKind::Inferred => "inferred",
};
println!(" {} ({params}) [{kind}]", function.id.name);
}
println!(
"resources: {} formula/code block(s)",
module.resources.len()
);
return 0;
}
if flags.ast {
println!(
"{}",
serde_json::to_string_pretty(&entry.analysis.document.root).unwrap_or_default()
);
}
if flags.units {
println!(
"{}",
serde_json::to_string_pretty(&entry.analysis.units.units).unwrap_or_default()
);
}
if flags.signature {
println!(
"{}",
serde_json::to_string_pretty(&signatures_json(module)).unwrap_or_default()
);
}
if flags.ir {
println!(
"{}",
serde_json::to_string_pretty(&module.functions).unwrap_or_default()
);
}
if flags.refs {
println!(
"{}",
serde_json::to_string_pretty(&refs_json(&project)).unwrap_or_default()
);
}
if flags.platform {
println!(
"{}",
serde_json::to_string_pretty(&PlatformCapabilities::detect()).unwrap_or_default()
);
}
0
}
/// Validate Markdown reference edges for every loaded document.
///
/// Links are static references: checking them never executes anything. Broken
/// same-document anchors, missing files and missing target anchors are
/// `ref.unresolved` errors; external HTTP(S) links are accepted as external.
fn validate_refs(project: &LoadedProject) -> Vec<FileDiagnostic> {
let mut diagnostics = Vec::new();
for file in project.files.values() {
@@ -595,306 +402,6 @@ fn launch_strict_process(
}
/// `marqdo run` / `marqdo call`.
pub fn execute(
file: Option<&Path>,
function: Option<&str>,
named_args: &[(String, Value)],
settings: &SandboxSettings,
json: bool,
trace: bool,
) -> i32 {
let command_name = if function.is_some() { "call" } else { "run" };
let mut project = match load_project(file, json) {
Ok(project) => project,
Err(code) => return code,
};
if let Err(error) = add_static_plugin_descriptors(&mut project, &settings.plugins) {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
if project.has_errors() {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
eprint!("{}", output::render_text(&project.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
}
return 1;
}
let warnings: Vec<FileDiagnostic> = project
.diagnostics
.iter()
.filter(|item| !item.diagnostic.is_error())
.cloned()
.collect();
if !json && !warnings.is_empty() {
eprint!("{}", output::render_text(&warnings));
}
let mode = match settings.sandbox_mode() {
Ok(mode) => mode,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
if mode == SandboxMode::Strict {
if let Err(error) = settings.strict_preflight() {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
if marqdo_sandbox::marker_present() {
// We were re-executed by the supervisor: validate the marker set
// before running any project code.
if let Err(reason) = marqdo_sandbox::verify_active() {
if json {
output::print_json(&json!({
"success": false,
"error": format!("strict isolation verification failed: {reason}"),
}));
} else {
eprintln!("error: strict isolation verification failed: {reason}");
}
return 1;
}
} else {
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
if json {
output::print_json(&json!({"success": false, "error": error.to_string()}));
} else {
eprintln!("error: {error}");
}
return 1;
}
return launch_strict_process(&project.root, file, settings);
}
}
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
if json {
output::print_json(&json!({"success": false, "error": error.to_string()}));
} else {
eprintln!("error: {error}");
}
return 1;
}
let capabilities = match settings.capabilities() {
Ok(capabilities) => capabilities,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let stdin = read_stdin();
let mut host = StdHost::new(mode, capabilities, project.root.clone()).with_stdin(stdin);
if trace || json || settings.trace_file.is_some() {
host = host
.with_trace()
.with_trace_budget(marqdo_host::TraceBudget {
max_events: settings
.trace_max_events
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_EVENTS),
max_bytes: settings
.trace_max_bytes
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_BYTES),
});
}
if let Some(fuel) = settings.fuel {
host.budget.fuel = fuel;
}
if let Some(stack) = settings.stack {
host.budget.stack_limit = stack;
}
if let Some(max_output) = settings.max_output {
host.budget.max_output_bytes = max_output;
}
if let Some(timeout) = settings.timeout {
host.budget.deadline = Some(Instant::now() + Duration::from_secs(timeout));
}
for kernel_path in &settings.kernels {
if let Err(error) = load_kernel_descriptor(&mut host, kernel_path) {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
}
for plugin_path in &settings.plugins {
if let Err(message) =
load_plugin_into_host(&mut host, plugin_path, settings.trust_native_plugin)
{
if json {
output::print_json(&json!({"success": false, "error": message}));
} else {
eprintln!("error: {message}");
}
return 1;
}
}
// Expose the complete export names loaded from trusted manifests so the
// runtime resolves exactly those names instead of probing namespaces.
for (name, _signature, digest, package) in host.plugin_exports() {
if project
.program
.external_callables
.iter()
.any(|callable| callable.public_name == name)
{
continue;
}
project
.program
.external_callables
.push(marqdo_ir::callable::CallableDescriptor {
id: marqdo_ir::callable::CallableId(format!("plugin:{package}:{name}")),
public_name: name.clone(),
owner_package: package.clone(),
signature: marqdo_ir::callable::CallableSignature {
params: Vec::new(),
kind: marqdo_ir::SignatureKind::Explicit,
},
effects_requested: vec!["host".to_string()],
origin: marqdo_ir::callable::CallableOrigin::AbiPlugin {
package,
export: name,
},
implementation_digest: Some(digest),
source_span: None,
});
}
let function_name = function.unwrap_or("main").to_string();
let entry_module = &project.program.modules[&project.entry];
if entry_module.function(&function_name).is_none() {
eprintln!(
"error: no function named `{function_name}` in {}",
project.entry_file().path.display()
);
return 1;
}
let runtime_args: Vec<EvaluatedArg> = named_args
.iter()
.map(|(name, value)| EvaluatedArg::named(name.clone(), value.clone(), Span::default()))
.collect();
let memory_limits = MemoryLimits {
max_total_bytes: settings
.max_memory
.unwrap_or(marqdo_runtime::DEFAULT_MAX_TOTAL_BYTES),
max_region_bytes: settings
.max_region_memory
.unwrap_or(marqdo_runtime::DEFAULT_MAX_REGION_BYTES),
};
let result = run_with_limits(
&project.program,
&mut host,
&project.entry,
&function_name,
runtime_args,
memory_limits,
);
if let Some(path) = &settings.trace_file {
let status = match &result {
Ok(_) => "ok",
Err(error) => error.code(),
};
let entry = format!("{}::{}", project.entry, function_name);
if let Err(error) = crate::trace::write(&project, &host, &entry, status, path) {
eprintln!("error: {error}");
return 1;
}
}
let stdout = host.take_output();
let stdout_text = String::from_utf8_lossy(&stdout).to_string();
let stderr = host.take_error();
let stderr_text = String::from_utf8_lossy(&stderr).to_string();
let trace_entries = host.trace().to_vec();
match result {
Ok(outcome) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": true,
"value": marqdo_value::to_wire(&outcome.value),
"stdout": stdout_text,
"stderr": stderr_text,
"diagnostics": output::diagnostics_json(&project.diagnostics),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
if function.is_some() && outcome.value != Value::Unit {
println!("{}", outcome.value.display());
}
if trace {
for entry in &trace_entries {
eprintln!(
"trace: {} {} {}us {}",
entry.op, entry.module, entry.duration_micros, entry.result
);
}
}
}
0
}
Err(error) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"stdout": stdout_text,
"stderr": stderr_text,
"error": runtime_error_json(&error, &project),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
eprint!("{}", render_runtime_error(&error, &project));
}
1
}
}
}
/// Read piped stdin once at the composition boundary.
///
/// A terminal stdin is not read, so `marqdo run` never blocks waiting for an
/// interactive EOF. Non-terminal input is a finite pipe/file and is copied into
/// the run-scoped `stdio/stdin` resource.
fn read_stdin() -> Vec<u8> {
use std::io::{IsTerminal, Read};
let mut stdin = std::io::stdin();
if stdin.is_terminal() {
return Vec::new();
}
let mut bytes = Vec::new();
if let Err(error) = stdin.read_to_end(&mut bytes) {
eprintln!("error: cannot read stdin: {error}");
return Vec::new();
}
bytes
}
fn load_kernel_descriptor(host: &mut StdHost, path: &Path) -> Result<(), String> {
let text = std::fs::read_to_string(path).map_err(|error| {
format!(
+68
View File
@@ -0,0 +1,68 @@
//! `marqdo check` command.
use super::*;
pub fn check(
file: Option<&Path>,
json: bool,
refs: bool,
plugins: &[PathBuf],
emit: Option<&Path>,
) -> i32 {
let mut project = match load_project(file, json) {
Ok(project) => project,
Err(code) => return code,
};
if let Err(error) = add_static_plugin_descriptors(&mut project, plugins) {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
if refs {
let ref_diagnostics = validate_refs(&project);
project.diagnostics.extend(ref_diagnostics);
}
let errors = output::error_count(&project.diagnostics);
if let Some(path) = emit {
if errors > 0 {
let _ = std::fs::remove_file(path);
} else if let Err(error) = crate::analysis::write(&project, path) {
eprintln!("error: {error}");
return 2;
}
}
if json {
output::print_json(&json!({
"command": "check",
"success": errors == 0,
"errors": errors,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
let text = output::render_text(&project.diagnostics);
eprint!("{text}");
if errors == 0 {
let checked = project
.program
.modules
.keys()
.filter(|id| !id.instance.starts_with("std:"))
.count();
println!("checked {checked} module(s): ok");
} else {
eprintln!(
"check failed: {} error(s), {} warning(s)",
errors,
project.diagnostics.len() - errors
);
}
}
if errors == 0 {
0
} else {
1
}
}
+132
View File
@@ -0,0 +1,132 @@
//! `marqdo inspect` command.
use super::*;
/// Options for `marqdo inspect`.
#[derive(Debug, Clone, Default)]
pub struct InspectFlags {
/// Show the Markdown AST.
pub ast: bool,
/// Show heading units.
pub units: bool,
/// Show inferred/explicit signatures.
pub signature: bool,
/// Show executable IR.
pub ir: bool,
/// Show link reference edges.
pub refs: bool,
/// Show platform capability report.
pub platform: bool,
}
pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool) -> i32 {
let project = match load_project(file, json) {
Ok(project) => project,
Err(code) => return code,
};
let entry = project.entry_file();
let module = &entry.analysis.module;
let selected_any =
flags.ast || flags.units || flags.signature || flags.ir || flags.refs || flags.platform;
if json {
let mut object = serde_json::Map::new();
object.insert("command".into(), json!("inspect"));
object.insert("module".into(), json!(entry.module_id.to_string()));
if !selected_any {
object.insert("summary".into(), summary_json(&project));
}
if flags.ast {
object.insert(
"ast".into(),
serde_json::to_value(&entry.analysis.document.root).unwrap_or_default(),
);
}
if flags.units {
object.insert(
"units".into(),
serde_json::to_value(&entry.analysis.units.units).unwrap_or_default(),
);
}
if flags.signature {
object.insert("signatures".into(), signatures_json(module));
}
if flags.ir {
object.insert(
"ir".into(),
serde_json::to_value(&module.functions).unwrap_or_default(),
);
}
if flags.refs {
object.insert("refs".into(), json!(refs_json(&project)));
}
if flags.platform {
object.insert(
"platform".into(),
serde_json::to_value(PlatformCapabilities::detect()).unwrap_or_default(),
);
}
output::print_json(&serde_json::Value::Object(object));
return 0;
}
if !selected_any {
println!("module: {}", entry.module_id);
println!("path: {}", entry.path.display());
println!("project root: {}", project.root.display());
println!("functions:");
for function in &module.functions {
let params = function
.params
.iter()
.map(|param| param.name.as_str())
.collect::<Vec<_>>()
.join(", ");
let kind = match function.signature {
marqdo_ir::SignatureKind::Explicit => "explicit",
marqdo_ir::SignatureKind::Inferred => "inferred",
};
println!(" {} ({params}) [{kind}]", function.id.name);
}
println!(
"resources: {} formula/code block(s)",
module.resources.len()
);
return 0;
}
if flags.ast {
println!(
"{}",
serde_json::to_string_pretty(&entry.analysis.document.root).unwrap_or_default()
);
}
if flags.units {
println!(
"{}",
serde_json::to_string_pretty(&entry.analysis.units.units).unwrap_or_default()
);
}
if flags.signature {
println!(
"{}",
serde_json::to_string_pretty(&signatures_json(module)).unwrap_or_default()
);
}
if flags.ir {
println!(
"{}",
serde_json::to_string_pretty(&module.functions).unwrap_or_default()
);
}
if flags.refs {
println!(
"{}",
serde_json::to_string_pretty(&refs_json(&project)).unwrap_or_default()
);
}
if flags.platform {
println!(
"{}",
serde_json::to_string_pretty(&PlatformCapabilities::detect()).unwrap_or_default()
);
}
0
}
+306
View File
@@ -0,0 +1,306 @@
//! `marqdo run` execution assembly.
//!
//! Child module of `commands`: it may use the parent's project loader and
//! runtime helpers, but keeps the run session out of the command table.
use super::*;
pub fn execute(
file: Option<&Path>,
function: Option<&str>,
named_args: &[(String, Value)],
settings: &SandboxSettings,
json: bool,
trace: bool,
) -> i32 {
let command_name = if function.is_some() { "call" } else { "run" };
let mut project = match load_project(file, json) {
Ok(project) => project,
Err(code) => return code,
};
if let Err(error) = add_static_plugin_descriptors(&mut project, &settings.plugins) {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
if project.has_errors() {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
eprint!("{}", output::render_text(&project.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
}
return 1;
}
let warnings: Vec<FileDiagnostic> = project
.diagnostics
.iter()
.filter(|item| !item.diagnostic.is_error())
.cloned()
.collect();
if !json && !warnings.is_empty() {
eprint!("{}", output::render_text(&warnings));
}
let mode = match settings.sandbox_mode() {
Ok(mode) => mode,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
if mode == SandboxMode::Strict {
if let Err(error) = settings.strict_preflight() {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
if marqdo_sandbox::marker_present() {
// We were re-executed by the supervisor: validate the marker set
// before running any project code.
if let Err(reason) = marqdo_sandbox::verify_active() {
if json {
output::print_json(&json!({
"success": false,
"error": format!("strict isolation verification failed: {reason}"),
}));
} else {
eprintln!("error: strict isolation verification failed: {reason}");
}
return 1;
}
} else {
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
if json {
output::print_json(&json!({"success": false, "error": error.to_string()}));
} else {
eprintln!("error: {error}");
}
return 1;
}
return launch_strict_process(&project.root, file, settings);
}
}
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
if json {
output::print_json(&json!({"success": false, "error": error.to_string()}));
} else {
eprintln!("error: {error}");
}
return 1;
}
let capabilities = match settings.capabilities() {
Ok(capabilities) => capabilities,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let stdin = read_stdin();
let mut host = StdHost::new(mode, capabilities, project.root.clone()).with_stdin(stdin);
if trace || json || settings.trace_file.is_some() {
host = host
.with_trace()
.with_trace_budget(marqdo_host::TraceBudget {
max_events: settings
.trace_max_events
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_EVENTS),
max_bytes: settings
.trace_max_bytes
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_BYTES),
});
}
if let Some(fuel) = settings.fuel {
host.budget.fuel = fuel;
}
if let Some(stack) = settings.stack {
host.budget.stack_limit = stack;
}
if let Some(max_output) = settings.max_output {
host.budget.max_output_bytes = max_output;
}
if let Some(timeout) = settings.timeout {
host.budget.deadline = Some(Instant::now() + Duration::from_secs(timeout));
}
for kernel_path in &settings.kernels {
if let Err(error) = load_kernel_descriptor(&mut host, kernel_path) {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
}
for plugin_path in &settings.plugins {
if let Err(message) =
load_plugin_into_host(&mut host, plugin_path, settings.trust_native_plugin)
{
if json {
output::print_json(&json!({"success": false, "error": message}));
} else {
eprintln!("error: {message}");
}
return 1;
}
}
// Expose the complete export names loaded from trusted manifests so the
// runtime resolves exactly those names instead of probing namespaces.
for (name, _signature, digest, package) in host.plugin_exports() {
if project
.program
.external_callables
.iter()
.any(|callable| callable.public_name == name)
{
continue;
}
project
.program
.external_callables
.push(marqdo_ir::callable::CallableDescriptor {
id: marqdo_ir::callable::CallableId(format!("plugin:{package}:{name}")),
public_name: name.clone(),
owner_package: package.clone(),
signature: marqdo_ir::callable::CallableSignature {
params: Vec::new(),
kind: marqdo_ir::SignatureKind::Explicit,
},
effects_requested: vec!["host".to_string()],
origin: marqdo_ir::callable::CallableOrigin::AbiPlugin {
package,
export: name,
},
implementation_digest: Some(digest),
source_span: None,
});
}
let function_name = function.unwrap_or("main").to_string();
let entry_module = &project.program.modules[&project.entry];
if entry_module.function(&function_name).is_none() {
eprintln!(
"error: no function named `{function_name}` in {}",
project.entry_file().path.display()
);
return 1;
}
let runtime_args: Vec<EvaluatedArg> = named_args
.iter()
.map(|(name, value)| EvaluatedArg::named(name.clone(), value.clone(), Span::default()))
.collect();
let memory_limits = MemoryLimits {
max_total_bytes: settings
.max_memory
.unwrap_or(marqdo_runtime::DEFAULT_MAX_TOTAL_BYTES),
max_region_bytes: settings
.max_region_memory
.unwrap_or(marqdo_runtime::DEFAULT_MAX_REGION_BYTES),
};
let result = run_with_limits(
&project.program,
&mut host,
&project.entry,
&function_name,
runtime_args,
memory_limits,
);
if let Some(path) = &settings.trace_file {
let status = match &result {
Ok(_) => "ok",
Err(error) => error.code(),
};
let entry = format!("{}::{}", project.entry, function_name);
if let Err(error) = crate::trace::write(&project, &host, &entry, status, path) {
eprintln!("error: {error}");
return 1;
}
}
let stdout = host.take_output();
let stdout_text = String::from_utf8_lossy(&stdout).to_string();
let stderr = host.take_error();
let stderr_text = String::from_utf8_lossy(&stderr).to_string();
let trace_entries = host.trace().to_vec();
match result {
Ok(outcome) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": true,
"value": marqdo_value::to_wire(&outcome.value),
"stdout": stdout_text,
"stderr": stderr_text,
"diagnostics": output::diagnostics_json(&project.diagnostics),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
if function.is_some() && outcome.value != Value::Unit {
println!("{}", outcome.value.display());
}
if trace {
for entry in &trace_entries {
eprintln!(
"trace: {} {} {}us {}",
entry.op, entry.module, entry.duration_micros, entry.result
);
}
}
}
0
}
Err(error) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"stdout": stdout_text,
"stderr": stderr_text,
"error": runtime_error_json(&error, &project),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
eprint!("{}", render_runtime_error(&error, &project));
}
1
}
}
}
/// Read piped stdin once at the composition boundary.
///
/// A terminal stdin is not read, so `marqdo run` never blocks waiting for an
/// interactive EOF. Non-terminal input is a finite pipe/file and is copied into
/// the run-scoped `stdio/stdin` resource.
fn read_stdin() -> Vec<u8> {
use std::io::{IsTerminal, Read};
let mut stdin = std::io::stdin();
if stdin.is_terminal() {
return Vec::new();
}
let mut bytes = Vec::new();
if let Err(error) = stdin.read_to_end(&mut bytes) {
eprintln!("error: cannot read stdin: {error}");
return Vec::new();
}
bytes
}