diff --git a/CHANGELOG.md b/CHANGELOG.md index e1515fc..fe1a935 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,19 @@ ### Added +- **`lib/foreign` F0/F1**:`invoke` 结构化记录(`ok`/`code`/`stdout`/`stderr`/`ms`/`timed_out`/`truncated`/`result`);`run`/`run_lang` 新增 `env`/`cwd`/`timeout`/`args`/`max_output`;15 个语言预设;`probe`/`register`/`unset`/`load_config`;`.marqdo/foreign.toml`。 +- **安全与健壮性**:所有外联入口检查 `exec` 能力;有界 stdout/stderr 读取与截断标记;stdin 写线程;Unix 进程组 / Windows `taskkill /T` 超时清理;shell-like argv 切分。 + ### Fixed +- **外联临时脚本路径**:入口目录为相对路径时,脚本参数现在使用绝对路径,避免 `tests/lib/tests/lib/...` 双拼接。 +- **外联失败可观测**:解释器不存在时进入 `invoke` 记录,`run` 仍报错;view 显示 stderr / exit / ms。 + ### Changed +- **`langs`** 现在返回「预设 ∪ 注册 ∪ 配置」的已知语言(原集合是子集)。 +- 大输出从 `Err` 改为「截断 + `truncated=true`」;`subtask` 外联输出同步采用该语义。 + ## v1.4.6 — 2026-10-16 ### Highlights diff --git a/Cargo.toml b/Cargo.toml index 0c1737d..22b131a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ cli = ["dep:clap"] view = ["dep:tiny_http"] net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize", "dep:zip"] plugin-host = ["dep:libloading"] -exec-host = [] +exec-host = ["dep:libc"] fs-host = [] tty = ["dep:libc"] wasm-core = [] diff --git a/lib/foreign.mq.md b/lib/foreign.mq.md index 37bd2e7..21a76a8 100644 --- a/lib/foreign.mq.md +++ b/lib/foreign.mq.md @@ -8,29 +8,102 @@ Run bound code fences and inline sources via local interpreters. ## set_cmd + `lang` + `cmd` + + `args`=None -Bind interpreter command cmd for language lang. +Bind interpreter command cmd for language lang; optional extra argv. -*> host_foreign_set_cmd lang=`lang` cmd=`cmd`* +*> host_foreign_set_cmd lang=`lang` cmd=`cmd` args=`args`* ## run + `code` + `stdin`=None + + `env`=None + + `cwd`=None + + `timeout`=None + + `args`=None + + `max_output`=None -Run a bound code fence value; optional stdin. +Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds), +extra argv and output cap. Returns stdout text; non-zero exit is an error. Caller: [foreign.run] code=`block` -*> host_foreign_run code=`code` stdin=`stdin`* +*> host_foreign_run code=`code` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`* ## run_lang + `lang` + `source` + `stdin`=None + + `env`=None + + `cwd`=None + + `timeout`=None + + `args`=None + + `max_output`=None -Run source text with language lang; optional stdin. +Run source text with language lang; same options as run. -*> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin`* +*> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`* + +## invoke + + `code`=None + + `lang`=None + + `source`=None + + `stdin`=None + + `input`=None + + `env`=None + + `cwd`=None + + `timeout`=None + + `args`=None + + `output`=auto + + `max_output`=None + + `cmd`=None + + `keep`=False + +Run code or lang+source and return a record map instead of raising on process +failure. Fields: ok, code, stdout, stderr, ms, lang, cmd, timed_out, truncated, +result, result_error, error, script, cached. + +`input` is encoded as JSON on stdin (mutually exclusive with `stdin`). `output` +is auto | text | json | lines. `cmd` overrides the interpreter for this call. + +*> host_foreign_invoke code=`code` lang=`lang` source=`source` stdin=`stdin` input=`input` env=`env` cwd=`cwd` timeout=`timeout` args=`args` output=`output` max_output=`max_output` cmd=`cmd` keep=`keep`* + +## probe + + `lang`=None + +Probe one language, or every known language when lang is omitted. Returns +{lang, cmd, path, ok, version, error} (a list when lang is omitted). + +*> host_foreign_probe lang=`lang`* + +## register + + `lang` + + `cmd`=None + + `args`=None + + `template`=None + + `ext`=None + + `env`=None + + `version_args`=None + +Register a language invocation. Provide cmd (+args) or template (placeholders +{file}, {dir}, {base}, {inline}, {lang}, {cwd}); they are mutually exclusive. + +*> host_foreign_register lang=`lang` cmd=`cmd` args=`args` template=`template` ext=`ext` env=`env` version_args=`version_args`* + +## unset + + `lang` + +Remove a process-local registration. Presets/config/env still apply. + +*> host_foreign_unset lang=`lang`* + +## load_config + + `path`=None + +Load .marqdo/foreign.toml (or an explicit path); returns the number of language +tables read. + +*> host_foreign_load_config path=`path`* ## langs diff --git a/lib/外联.mq.md b/lib/外联.mq.md index 1c96f8a..a57efcb 100644 --- a/lib/外联.mq.md +++ b/lib/外联.mq.md @@ -8,29 +8,101 @@ description: 通过本机解释器运行绑定的代码围栏与内联源码 ## 设置命令 + `语言` + `命令` + + `参数`=None -为语言绑定解释器命令。 +为语言绑定解释器命令;可选附加参数。 -*> host_foreign_set_cmd lang=`语言` cmd=`命令`* +*> host_foreign_set_cmd lang=`语言` cmd=`命令` args=`参数`* ## 运行 + `代码` + `标准输入`=None + + `环境`=None + + `工作目录`=None + + `超时`=None + + `参数`=None + + `最大输出`=None -运行已绑定的代码围栏值;可选标准输入。 +运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、 +附加参数与输出上限。返回 stdout 文本;非 0 退出即报错。 调用例:[外联.运行] 代码=`块` -*> host_foreign_run code=`代码` stdin=`标准输入`* +*> host_foreign_run code=`代码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`* ## 按语言运行 + `语言` + `源码` + `标准输入`=None + + `环境`=None + + `工作目录`=None + + `超时`=None + + `参数`=None + + `最大输出`=None -用语言运行源码文本;可选标准输入。 +用语言运行源码文本;选项同“运行”。 -*> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入`* +*> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`* + +## 执行 + + `代码`=None + + `语言`=None + + `源码`=None + + `标准输入`=None + + `输入`=None + + `环境`=None + + `工作目录`=None + + `超时`=None + + `参数`=None + + `输出`=auto + + `最大输出`=None + + `命令`=None + + `保留`=False + +运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错。 +字段:ok、code、stdout、stderr、ms、lang、cmd、timed_out、truncated、 +result、result_error、error、script、cached。 + +`输入` 会编码为 JSON 写入 stdin(与 `标准输入` 互斥)。`输出` 可取 +auto | text | json | lines。`命令` 仅本次覆盖解释器。 + +*> host_foreign_invoke code=`代码` lang=`语言` source=`源码` stdin=`标准输入` input=`输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` output=`输出` max_output=`最大输出` cmd=`命令` keep=`保留`* + +## 探测 + + `语言`=None + +探测一个语言;省略语言时探测所有已知语言。返回 +{lang, cmd, path, ok, version, error}(省略语言时是列表)。 + +*> host_foreign_probe lang=`语言`* + +## 注册 + + `语言` + + `命令`=None + + `参数`=None + + `模板`=None + + `扩展名`=None + + `环境`=None + + `版本参数`=None + +注册语言调用。提供命令(+参数)或模板(占位符 +{file}、{dir}、{base}、{inline}、{lang}、{cwd});二者互斥。 + +*> host_foreign_register lang=`语言` cmd=`命令` args=`参数` template=`模板` ext=`扩展名` env=`环境` version_args=`版本参数`* + +## 注销 + + `语言` + +移除进程内注册;预设 / 配置 / 环境变量仍然生效。 + +*> host_foreign_unset lang=`语言`* + +## 加载配置 + + `路径`=None + +加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量。 + +*> host_foreign_load_config path=`路径`* ## 语言表 diff --git a/src/aliases.rs b/src/aliases.rs index d34cee3..2f2ff34 100644 --- a/src/aliases.rs +++ b/src/aliases.rs @@ -124,11 +124,53 @@ pub fn canonical_param(builtin: &str, param: &str) -> String { ("host_json_stringify" | "stringify", "indent" | "缩进") => "indent".into(), ("host_plot", "steps" | "步数") => "steps".into(), ("host_plot", "derivative" | "导数") => "derivative".into(), - ("host_foreign_run", "code" | "代码") => "code".into(), - ("host_foreign_run" | "host_foreign_run_lang", "stdin" | "标准输入") => "stdin".into(), - ("host_foreign_set_cmd" | "host_foreign_run_lang", "lang" | "语言") => "lang".into(), - ("host_foreign_set_cmd", "cmd" | "命令") => "cmd".into(), - ("host_foreign_run_lang", "source" | "源码") => "source".into(), + ("host_foreign_run" | "host_foreign_invoke", "code" | "代码") => "code".into(), + ( + "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke", + "stdin" | "标准输入", + ) => "stdin".into(), + ( + "host_foreign_set_cmd" + | "host_foreign_run_lang" + | "host_foreign_invoke" + | "host_foreign_probe" + | "host_foreign_register" + | "host_foreign_unset", + "lang" | "语言", + ) => "lang".into(), + ( + "host_foreign_set_cmd" | "host_foreign_invoke" | "host_foreign_register", + "cmd" | "命令", + ) => "cmd".into(), + ("host_foreign_run_lang" | "host_foreign_invoke", "source" | "源码") => "source".into(), + ( + "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke", + "env" | "环境", + ) => "env".into(), + ( + "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke", + "cwd" | "工作目录", + ) => "cwd".into(), + ( + "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke", + "timeout" | "超时", + ) => "timeout".into(), + ( + "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" + | "host_foreign_register", + "args" | "参数", + ) => "args".into(), + ( + "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke", + "max_output" | "最大输出", + ) => "max_output".into(), + ("host_foreign_invoke", "input" | "输入") => "input".into(), + ("host_foreign_invoke", "output" | "输出") => "output".into(), + ("host_foreign_invoke", "keep" | "保留") => "keep".into(), + ("host_foreign_register", "template" | "模板") => "template".into(), + ("host_foreign_register", "ext" | "扩展名") => "ext".into(), + ("host_foreign_register", "version_args" | "版本参数") => "version_args".into(), + ("host_foreign_load_config", "path" | "路径") => "path".into(), ("host_ext_native_path", "name" | "名") => "name".into(), _ => param.to_string(), } diff --git a/src/foreign/mod.rs b/src/foreign/mod.rs index 51ded0d..e5ab993 100644 --- a/src/foreign/mod.rs +++ b/src/foreign/mod.rs @@ -1,30 +1,49 @@ //! Foreign / code-block helpers (外联). -/// Default interpreter argv for a language tag (before env / set_cmd). -pub fn default_argv(lang: &str) -> Option> { - match lang.to_ascii_lowercase().as_str() { - "python" | "python3" | "py" => Some(default_python_argv()), - "javascript" | "js" | "node" => Some(vec!["node".into()]), - _ => None, - } -} +pub mod registry; -pub fn default_python_argv() -> Vec { - #[cfg(windows)] - { - vec!["python".into()] - } - #[cfg(not(windows))] - { - vec!["python3".into()] - } -} +pub use registry::{default_argv, default_cmd_display, default_python_argv}; -/// Placeholder shown in the view command box. -pub fn default_cmd_display(lang: &str) -> String { - default_argv(lang) - .map(|a| a.join(" ")) - .unwrap_or_else(|| lang.to_string()) +/// Shell-like split: whitespace, single/double quotes, backslash escapes. +pub fn split_cmd_line(s: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut quote: Option = None; + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + match quote { + Some(q) => { + if c == q { + quote = None; + } else if c == '\\' && q == '"' { + if let Some(n) = chars.next() { + cur.push(n); + } + } else { + cur.push(c); + } + } + None => { + if c.is_whitespace() { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + } else if c == '\'' || c == '"' { + quote = Some(c); + } else if c == '\\' { + if let Some(n) = chars.next() { + cur.push(n); + } + } else { + cur.push(c); + } + } + } + } + if !cur.is_empty() { + out.push(cur); + } + out } /// Parse ```lang … opener → language id (first token). diff --git a/src/foreign/registry.rs b/src/foreign/registry.rs new file mode 100644 index 0000000..20c51cd --- /dev/null +++ b/src/foreign/registry.rs @@ -0,0 +1,188 @@ +//! Language presets and specs for `lib/foreign` (pure data; no process spawning). +//! +//! The host runner resolves a `LangSpec`, then builds the command. Keeping this +//! module free of `std::process` lets the browser/wasm build share the syntax and +//! preset tables. + +use std::path::PathBuf; + +/// One language's invocation recipe. +#[derive(Debug, Clone, Default)] +pub struct LangSpec { + pub lang: String, + /// Simple interpreter prefix; the script path is appended. + pub argv: Vec, + /// Optional full argv template; supports `{file}`/`{inline}`/… placeholders. + pub template: Option>, + pub ext: Option, + pub env: Vec<(String, String)>, + /// Arguments appended to the executable for `probe` (e.g. `--version`). + pub version_args: Vec, + /// Persistent session bootstrap available. + pub session: bool, + /// Directory for resolving a relative interpreter path (config file dir). + pub base_dir: Option, +} + +impl LangSpec { + fn simple(lang: &str, argv: &[&str], ext: &str, version: &[&str], session: bool) -> Self { + Self { + lang: lang.to_string(), + argv: argv.iter().map(|s| (*s).to_string()).collect(), + template: None, + ext: Some(ext.to_string()), + env: Vec::new(), + version_args: version.iter().map(|s| (*s).to_string()).collect(), + session, + base_dir: None, + } + } + + fn templated(lang: &str, template: &[&str], ext: &str, version: &[&str]) -> Self { + Self { + lang: lang.to_string(), + argv: vec![template[0].to_string()], + template: Some(template.iter().map(|s| (*s).to_string()).collect()), + ext: Some(ext.to_string()), + env: Vec::new(), + version_args: version.iter().map(|s| (*s).to_string()).collect(), + session: false, + base_dir: None, + } + } +} + +pub fn default_python_argv() -> Vec { + #[cfg(windows)] + { + vec!["python".into()] + } + #[cfg(not(windows))] + { + vec!["python3".into()] + } +} + +/// Canonical preset id for a language or alias. Unknown names pass through lowercased. +pub fn canonical(lang: &str) -> String { + let l = lang.to_ascii_lowercase(); + match l.as_str() { + "python3" | "py" => "python".into(), + "javascript" | "js" => "node".into(), + "shell" | "sh" => "bash".into(), + "rscript" => "r".into(), + "pwsh" | "ps1" => "powershell".into(), + "sqlite3" => "sqlite".into(), + "typescript" => "tsx".into(), + _ => l, + } +} + +/// Built-in preset for a language/alias. +pub fn preset_spec(lang: &str) -> Option { + let id = canonical(lang); + Some(match id.as_str() { + "python" => LangSpec { + argv: default_python_argv(), + ..LangSpec::simple("python", &["python3"], "py", &["--version"], true) + }, + "node" => LangSpec::simple("node", &["node"], "js", &["-v"], true), + "deno" => LangSpec::simple("deno", &["deno", "run"], "ts", &["--version"], false), + "bun" => LangSpec::simple("bun", &["bun"], "js", &["--version"], false), + "ruby" => LangSpec::simple("ruby", &["ruby"], "rb", &["--version"], false), + "perl" => LangSpec::simple("perl", &["perl"], "pl", &["--version"], false), + "php" => LangSpec::templated("php", &["php", "-r", "{inline}"], "php", &["--version"]), + "lua" => LangSpec::simple("lua", &["lua"], "lua", &["-v"], false), + "r" => LangSpec::simple("r", &["Rscript"], "R", &["--version"], false), + "julia" => LangSpec::simple("julia", &["julia"], "jl", &["--version"], false), + "go" => LangSpec::templated("go", &["go", "run", "{file}"], "go", &["version"]), + "bash" => LangSpec::simple("bash", &["bash"], "sh", &["--version"], false), + "powershell" => { + #[cfg(windows)] + { + LangSpec::simple("powershell", &["powershell"], "ps1", &["--version"], false) + } + #[cfg(not(windows))] + { + LangSpec::simple("powershell", &["pwsh"], "ps1", &["--version"], false) + } + } + "sqlite" => LangSpec::simple("sqlite", &["sqlite3"], "sql", &["--version"], false), + "tsx" => LangSpec::simple("tsx", &["tsx"], "ts", &["--version"], false), + _ => return None, + }) +} + +/// Sorted preset ids (for `langs`). +pub fn preset_ids() -> Vec { + [ + "python", "node", "deno", "bun", "ruby", "perl", "php", "lua", "r", "julia", "go", + "bash", "powershell", "sqlite", "tsx", + ] + .iter() + .map(|s| (*s).to_string()) + .collect() +} + +/// Display string for the command box (e.g. `python3`, `go run`, `php -r`). +pub fn default_cmd_display(lang: &str) -> String { + match preset_spec(lang) { + Some(spec) => { + if let Some(t) = &spec.template { + let mut parts = Vec::new(); + for x in t { + if x.contains('{') { + break; + } + parts.push(x.clone()); + } + if parts.is_empty() { + lang.to_string() + } else { + parts.join(" ") + } + } else { + spec.argv.join(" ") + } + } + None => lang.to_string(), + } +} + +/// Default argv for v1 compatibility (simple presets only). +pub fn default_argv(lang: &str) -> Option> { + preset_spec(lang).map(|s| s.argv) +} + +/// Session support for a language (based on preset). +pub fn session_supported(lang: &str) -> bool { + preset_spec(lang).map(|s| s.session).unwrap_or(false) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn aliases_canonicalize() { + assert_eq!(canonical("py"), "python"); + assert_eq!(canonical("javascript"), "node"); + assert_eq!(canonical("sh"), "bash"); + assert_eq!(canonical("unknown"), "unknown"); + } + + #[test] + fn presets_cover_docs() { + assert_eq!(preset_ids().len(), 15); + assert!(preset_spec("python").is_some()); + assert!(preset_spec("node").is_some()); + assert!(preset_spec("go").unwrap().template.is_some()); + assert!(preset_spec("php").unwrap().template.is_some()); + } + + #[test] + fn display_uses_template_prefix() { + assert_eq!(default_cmd_display("go"), "go run"); + assert_eq!(default_cmd_display("php"), "php -r"); + } +} diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs index ec73d1f..27a6207 100644 --- a/src/host/dispatch.rs +++ b/src/host/dispatch.rs @@ -202,6 +202,11 @@ pub enum HostFn { MetaGet = 193, ModuleSource = 194, ArtifactKind = 195, + ForeignInvoke = 196, + ForeignProbe = 197, + ForeignRegister = 198, + ForeignUnset = 199, + ForeignLoadConfig = 200, } @@ -394,6 +399,11 @@ impl HostFn { 193 => Self::MetaGet, 194 => Self::ModuleSource, 195 => Self::ArtifactKind, + 196 => Self::ForeignInvoke, + 197 => Self::ForeignProbe, + 198 => Self::ForeignRegister, + 199 => Self::ForeignUnset, + 200 => Self::ForeignLoadConfig, _ => return None, }) } @@ -470,6 +480,11 @@ impl HostFn { "host_foreign_set_cmd" => Self::ForeignSetCmd, "host_foreign_run" => Self::ForeignRun, "host_foreign_run_lang" => Self::ForeignRunLang, + "host_foreign_invoke" | "foreign_invoke" => Self::ForeignInvoke, + "host_foreign_probe" | "foreign_probe" => Self::ForeignProbe, + "host_foreign_register" | "foreign_register" => Self::ForeignRegister, + "host_foreign_unset" | "foreign_unset" => Self::ForeignUnset, + "host_foreign_load_config" | "foreign_load_config" => Self::ForeignLoadConfig, "host_foreign_langs" => Self::ForeignLangs, "host_dotenv_load" | "load_dotenv" => Self::DotenvLoad, "host_http_request" | "http_request" => Self::HttpRequest, @@ -666,6 +681,11 @@ impl HostFn { Self::ForeignSetCmd => "host_foreign_set_cmd", Self::ForeignRun => "host_foreign_run", Self::ForeignRunLang => "host_foreign_run_lang", + Self::ForeignInvoke => "host_foreign_invoke", + Self::ForeignProbe => "host_foreign_probe", + Self::ForeignRegister => "host_foreign_register", + Self::ForeignUnset => "host_foreign_unset", + Self::ForeignLoadConfig => "host_foreign_load_config", Self::ForeignLangs => "host_foreign_langs", Self::DotenvLoad => "host_dotenv_load", Self::HttpRequest => "host_http_request", @@ -832,6 +852,9 @@ impl HostFn { Self::ForeignSetCmd => &["lang", "cmd"], Self::ForeignRun => &["code"], Self::ForeignRunLang => &["lang", "source"], + Self::ForeignInvoke => &[], + Self::ForeignProbe | Self::ForeignLoadConfig => &[], + Self::ForeignRegister | Self::ForeignUnset => &["lang"], Self::ForeignLangs => &[], Self::PluginLoad => &["path"], Self::PluginUnload | Self::PluginList => &[], @@ -935,7 +958,35 @@ impl HostFn { Self::PlotPoints => &["path", "grid"], Self::PlotConic => &["b", "h", "k", "path", "grid"], Self::ForeignSetCmd => &["args"], - Self::ForeignRun | Self::ForeignRunLang => &["stdin"], + Self::ForeignRun | Self::ForeignRunLang => { + &["stdin", "env", "cwd", "timeout", "args", "max_output"] + } + Self::ForeignInvoke => &[ + "code", + "lang", + "source", + "stdin", + "input", + "env", + "cwd", + "timeout", + "args", + "output", + "max_output", + "cmd", + "keep", + ], + Self::ForeignProbe => &["lang"], + Self::ForeignRegister => &[ + "cmd", + "args", + "template", + "ext", + "env", + "version_args", + ], + Self::ForeignUnset => &[], + Self::ForeignLoadConfig => &["path"], Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => { &["at_end", "key", "line"] } @@ -1184,7 +1235,12 @@ pub fn call_host( HostFn::ForeignRun => { #[cfg(feature = "exec-host")] { - foreign::run(ctx, require(bound, "code")?, bound.get("stdin")) + foreign::run_with_options( + ctx, + require(bound, "code")?, + bound.get("stdin"), + bound, + ) } #[cfg(not(feature = "exec-host"))] { @@ -1195,11 +1251,12 @@ pub fn call_host( HostFn::ForeignRunLang => { #[cfg(feature = "exec-host")] { - foreign::run_lang( + foreign::run_lang_with_options( ctx, require(bound, "lang")?, require(bound, "source")?, bound.get("stdin"), + bound, ) } #[cfg(not(feature = "exec-host"))] @@ -1208,6 +1265,87 @@ pub fn call_host( Err("foreign unavailable in browser wasm".into()) } } + HostFn::ForeignInvoke => { + #[cfg(feature = "exec-host")] + { + foreign::invoke( + ctx, + foreign::InvokeArgs { + code: bound.get("code"), + lang: bound.get("lang"), + source: bound.get("source"), + stdin: bound.get("stdin"), + input: bound.get("input"), + env: bound.get("env"), + cwd: bound.get("cwd"), + timeout: bound.get("timeout"), + args: bound.get("args"), + output: bound.get("output"), + max_output: bound.get("max_output"), + cmd: bound.get("cmd"), + keep: bound.get("keep"), + }, + ) + } + #[cfg(not(feature = "exec-host"))] + { + let _ = (ctx, bound); + Err("foreign unavailable in browser wasm".into()) + } + } + HostFn::ForeignProbe => { + #[cfg(feature = "exec-host")] + { + foreign::probe(ctx, bound.get("lang")) + } + #[cfg(not(feature = "exec-host"))] + { + let _ = (ctx, bound); + Err("foreign unavailable in browser wasm".into()) + } + } + HostFn::ForeignRegister => { + #[cfg(feature = "exec-host")] + { + foreign::register( + ctx, + require(bound, "lang")?, + bound.get("cmd"), + bound.get("args"), + bound.get("template"), + bound.get("ext"), + bound.get("env"), + bound.get("version_args"), + ) + } + #[cfg(not(feature = "exec-host"))] + { + let _ = (ctx, bound); + Err("foreign unavailable in browser wasm".into()) + } + } + HostFn::ForeignUnset => { + #[cfg(feature = "exec-host")] + { + foreign::unset(ctx, require(bound, "lang")?) + } + #[cfg(not(feature = "exec-host"))] + { + let _ = (ctx, bound); + Err("foreign unavailable in browser wasm".into()) + } + } + HostFn::ForeignLoadConfig => { + #[cfg(feature = "exec-host")] + { + foreign::load_config(ctx, bound.get("path")) + } + #[cfg(not(feature = "exec-host"))] + { + let _ = (ctx, bound); + Err("foreign unavailable in browser wasm".into()) + } + } HostFn::ForeignLangs => { #[cfg(feature = "exec-host")] { diff --git a/src/host/foreign.rs b/src/host/foreign.rs index 778bb13..b96a1e5 100644 --- a/src/host/foreign.rs +++ b/src/host/foreign.rs @@ -1,17 +1,28 @@ -//! Foreign language runners (subprocess). Import L1 `lib/foreign` to use. +//! Foreign language runners (subprocess) and persistent kernels. +//! +//! F0: safe one-shot execution + structured `invoke` records. +//! Later phases add language registry, JSON bridge, parallel fan-out and sessions. +use std::collections::HashMap; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::process::{Child, Command, Stdio}; use std::thread; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; -use crate::foreign; +use crate::foreign::registry::{self, LangSpec}; +use crate::foreign::split_cmd_line; +use crate::host::json::{json_to_value, value_to_json}; use crate::host::HostContext; use crate::value::{CodeBlock, Value}; -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); +const DEFAULT_TIMEOUT_SECS: f64 = 10.0; +const MAX_TIMEOUT_SECS: f64 = 3600.0; pub(crate) const MAX_OUTPUT: usize = 1_048_576; +const MIN_OUTPUT: usize = 1024; +const MAX_OUTPUT_LIMIT: usize = 64 * 1024 * 1024; +const INPUT_ENV_CAP: usize = 8 * 1024; +const FAILURE_TAIL: usize = 4096; fn as_text<'a>(v: &'a Value, what: &str) -> Result<&'a str, String> { match v { @@ -20,13 +31,81 @@ fn as_text<'a>(v: &'a Value, what: &str) -> Result<&'a str, String> { } } -fn opt_text(v: Option<&Value>) -> Result, String> { +fn opt_text(v: Option<&Value>) -> Result, String> { match v { None | Some(Value::None) => Ok(None), - Some(v) => Ok(Some(as_text(v, "value")?)), + Some(Value::Text(s)) => Ok(Some(s.clone())), + Some(Value::Secret(s)) => Ok(Some(s.clone())), + Some(_) => Err("value must be text".into()), } } +fn parse_env(v: Option<&Value>) -> Result, String> { + match v { + None | Some(Value::None) => Ok(Vec::new()), + Some(Value::Map(entries)) => Ok(entries + .iter() + .map(|(k, v)| { + let value = match v { + Value::Secret(s) => s.clone(), + other => other.as_display(), + }; + (k.clone(), value) + }) + .collect()), + Some(_) => Err("env must be a map".into()), + } +} + +fn parse_args(v: Option<&Value>) -> Result, String> { + match v { + None | Some(Value::None) => Ok(Vec::new()), + Some(Value::List(xs)) => Ok(xs.iter().map(|x| x.as_display()).collect()), + Some(Value::Text(s)) => Ok(vec![s.clone()]), + Some(_) => Err("args must be list or text".into()), + } +} + +fn parse_bool(v: Option<&Value>, what: &str, default: bool) -> Result { + match v { + None | Some(Value::None) => Ok(default), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(format!("{what} must be bool")), + } +} + +fn parse_timeout(v: Option<&Value>) -> Result { + let secs = match v { + None | Some(Value::None) => DEFAULT_TIMEOUT_SECS, + Some(Value::Int(n)) => *n as f64, + Some(Value::Num(n)) => *n, + Some(_) => return Err("timeout must be a number of seconds".into()), + }; + if !secs.is_finite() || secs <= 0.0 { + return Err("timeout must be > 0 seconds".into()); + } + if secs > MAX_TIMEOUT_SECS { + return Err(format!("timeout must be <= {MAX_TIMEOUT_SECS} seconds")); + } + Ok(Duration::from_secs_f64(secs)) +} + +fn parse_max_output(v: Option<&Value>) -> Result { + let n = match v { + None | Some(Value::None) => MAX_OUTPUT, + Some(Value::Int(n)) if *n > 0 => *n as usize, + Some(Value::Int(_)) => return Err("max_output must be > 0".into()), + Some(_) => return Err("max_output must be an integer byte count".into()), + }; + if n < MIN_OUTPUT { + return Err(format!("max_output must be >= {MIN_OUTPUT} bytes")); + } + if n > MAX_OUTPUT_LIMIT { + return Err(format!("max_output must be <= {MAX_OUTPUT_LIMIT} bytes")); + } + Ok(n) +} + fn as_code(v: &Value) -> Result<&CodeBlock, String> { match v { Value::Code(c) => Ok(c), @@ -34,6 +113,99 @@ fn as_code(v: &Value) -> Result<&CodeBlock, String> { } } +/// One execution request. Owned so it can be sent to worker threads later. +#[derive(Debug, Clone)] +pub(crate) struct Job { + pub lang: String, + pub source: String, + pub stdin: Option, + pub input_json: Option, + pub env: Vec<(String, String)>, + pub cwd: Option, + pub timeout: Duration, + pub extra_args: Vec, + pub max_output: usize, + pub keep: bool, + pub cmd_override: Option, +} + +impl Job { + fn simple(lang: &str, source: &str, stdin: Option<&str>) -> Self { + Self { + lang: lang.to_string(), + source: source.to_string(), + stdin: stdin.map(str::to_string), + input_json: None, + env: Vec::new(), + cwd: None, + timeout: Duration::from_secs_f64(DEFAULT_TIMEOUT_SECS), + extra_args: Vec::new(), + max_output: MAX_OUTPUT, + keep: false, + cmd_override: None, + } + } +} + +/// Result of one subprocess execution. `ok` is the success bit; failures are data. +#[derive(Debug, Clone)] +pub(crate) struct Execution { + pub ok: bool, + pub code: i32, + pub stdout: String, + pub stderr: String, + pub ms: u64, + pub timed_out: bool, + pub truncated: bool, + pub error: String, + pub lang: String, + pub cmd: String, + pub script: String, +} + +impl Execution { + fn failure_ok(&self) -> bool { + self.ok + } + + fn record(&self, result: Value, result_error: String) -> Value { + Value::Map(vec![ + ("ok".into(), Value::Bool(self.failure_ok())), + ("code".into(), Value::Int(self.code as i64)), + ("stdout".into(), Value::Text(self.stdout.clone())), + ("stderr".into(), Value::Text(self.stderr.clone())), + ("ms".into(), Value::Int(self.ms as i64)), + ("lang".into(), Value::Text(self.lang.clone())), + ("cmd".into(), Value::Text(self.cmd.clone())), + ("timed_out".into(), Value::Bool(self.timed_out)), + ("truncated".into(), Value::Bool(self.truncated)), + ("result".into(), result), + ("result_error".into(), Value::Text(result_error)), + ("error".into(), Value::Text(self.error.clone())), + ("script".into(), Value::Text(self.script.clone())), + ("cached".into(), Value::Bool(false)), + ]) + } +} + +/// Arguments for `foreign.invoke`. Kept as a struct so dispatch stays readable. +#[derive(Default)] +pub struct InvokeArgs<'a> { + pub code: Option<&'a Value>, + pub lang: Option<&'a Value>, + pub source: Option<&'a Value>, + pub stdin: Option<&'a Value>, + pub input: Option<&'a Value>, + pub env: Option<&'a Value>, + pub cwd: Option<&'a Value>, + pub timeout: Option<&'a Value>, + pub args: Option<&'a Value>, + pub output: Option<&'a Value>, + pub max_output: Option<&'a Value>, + pub cmd: Option<&'a Value>, + pub keep: Option<&'a Value>, +} + /// Register interpreter argv for `lang` (e.g. venv python). pub fn set_cmd( ctx: &mut HostContext, @@ -41,7 +213,9 @@ pub fn set_cmd( cmd: &Value, args: Option<&Value>, ) -> Result { - let lang = as_text(lang, "lang")?.to_ascii_lowercase(); + ensure_config(ctx); + let requested = as_text(lang, "lang")?.to_ascii_lowercase(); + let canon = registry::canonical(&requested); let cmd = as_text(cmd, "cmd")?; let mut argv = vec![cmd.to_string()]; if let Some(a) = args { @@ -56,18 +230,312 @@ pub fn set_cmd( _ => return Err("set_cmd args must be list or text".into()), } } - ctx.foreign_cmds.insert(lang, argv); + let spec = LangSpec { + lang: canon.clone(), + argv: argv.clone(), + template: None, + ext: None, + env: Vec::new(), + version_args: Vec::new(), + session: registry::session_supported(&canon), + base_dir: None, + }; + ctx.foreign_specs.insert(canon.clone(), spec); + ctx.foreign_cmds.insert(canon, argv); Ok(Value::None) } +fn parse_template(v: Option<&Value>) -> Result>, String> { + match v { + None | Some(Value::None) => Ok(None), + Some(Value::List(xs)) => Ok(Some(xs.iter().map(|x| x.as_display()).collect())), + Some(Value::Text(s)) => Ok(Some(vec![s.clone()])), + Some(_) => Err("template must be a list of text".into()), + } +} + +fn parse_version_args(v: Option<&Value>) -> Result, String> { + match v { + None | Some(Value::None) => Ok(Vec::new()), + Some(Value::List(xs)) => Ok(xs.iter().map(|x| x.as_display()).collect()), + Some(Value::Text(s)) => Ok(vec![s.clone()]), + Some(_) => Err("version_args must be a list of text".into()), + } +} + +/// Register a language invocation (`register`). `cmd` and `template` are exclusive. +pub fn register( + ctx: &mut HostContext, + lang: &Value, + cmd: Option<&Value>, + args: Option<&Value>, + template: Option<&Value>, + ext: Option<&Value>, + env: Option<&Value>, + version_args: Option<&Value>, +) -> Result { + ensure_config(ctx); + let requested = as_text(lang, "lang")?.to_ascii_lowercase(); + let canon = registry::canonical(&requested); + let cmd = opt_text(cmd)?; + let template = parse_template(template)?; + if cmd.is_some() && template.is_some() { + return Err("register: cmd and template are mutually exclusive".into()); + } + if cmd.is_none() && template.is_none() { + return Err("register: provide cmd or template".into()); + } + let mut argv = match &cmd { + Some(c) => { + let mut v = vec![c.clone()]; + v.extend(parse_args(args)?); + v + } + None => vec![template + .as_ref() + .and_then(|t| t.first()) + .cloned() + .ok_or_else(|| "register: template must not be empty".to_string())?], + }; + if let Some(t) = &template { + if t.is_empty() { + return Err("register: template must not be empty".into()); + } + if t.iter().any(|x| x == "{file}") && t.iter().any(|x| x == "{inline}") { + return Err("register: {file} and {inline} cannot be used together".into()); + } + // A template without file/inline gets the script path appended. + if !t.iter().any(|x| x == "{file}" || x == "{inline}") { + // leave as-is; prepare adds the script path + } + } + if cmd.is_none() { + argv = vec![template.as_ref().unwrap()[0].clone()]; + } + let ext = match opt_text(ext)? { + Some(e) => { + let e = e.trim().trim_start_matches('.').to_string(); + if e.is_empty() + || e.len() > 16 + || !e.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-') + { + return Err("register: ext must be 1..16 ASCII alphanumerics".into()); + } + Some(e) + } + None => None, + }; + let env = parse_env(env)?; + let version_args = parse_version_args(version_args)?; + let spec = LangSpec { + lang: canon.clone(), + argv: argv.clone(), + template, + ext, + env, + version_args, + session: registry::session_supported(&canon), + base_dir: None, + }; + ctx.foreign_specs.insert(canon.clone(), spec); + if ctx.foreign_specs.get(&canon).map(|s| s.template.is_none()).unwrap_or(false) { + ctx.foreign_cmds.insert(canon, argv); + } + Ok(Value::None) +} + +/// Remove a process-local registration; presets/config/env still apply. +pub fn unset(ctx: &mut HostContext, lang: &Value) -> Result { + ensure_config(ctx); + let requested = as_text(lang, "lang")?.to_ascii_lowercase(); + let canon = registry::canonical(&requested); + let mut removed = ctx.foreign_specs.remove(&canon).is_some(); + removed |= ctx.foreign_specs.remove(&requested).is_some(); + removed |= ctx.foreign_cmds.remove(&canon).is_some(); + removed |= ctx.foreign_cmds.remove(&requested).is_some(); + Ok(Value::Bool(removed)) +} + +fn discover_config_path(ctx: &HostContext) -> Option { + if let Ok(v) = std::env::var("MARQDO_FOREIGN_CONFIG") { + let v = v.trim(); + if !v.is_empty() { + return Some(PathBuf::from(v)); + } + } + let mut candidates = vec![ctx.cwd.join(".marqdo").join("foreign.toml")]; + if let Some(entry) = &ctx.entry_path { + if let Some(dir) = entry.parent() { + candidates.push(dir.join(".marqdo").join("foreign.toml")); + } + } + if let Ok(home) = std::env::var("HOME") { + if !home.trim().is_empty() { + candidates.push( + PathBuf::from(home) + .join(".config") + .join("marqdo") + .join("foreign.toml"), + ); + } + } + candidates.into_iter().find(|p| p.is_file()) +} + +/// Load project config once; malformed auto-config warns but does not block presets. +pub fn ensure_config(ctx: &mut HostContext) { + if ctx.foreign_config_loaded { + return; + } + ctx.foreign_config_loaded = true; + if let Some(path) = discover_config_path(ctx) { + if let Err(e) = load_config_path(ctx, &path) { + eprintln!( + "marqdo: foreign config {} ignored: {e}", + path.display() + ); + } + } +} + +fn load_config_path(ctx: &mut HostContext, path: &Path) -> Result { + let source = std::fs::read_to_string(path) + .map_err(|e| format!("read {}: {e}", path.display()))?; + let parsed = crate::host::toml_ops::parse(&Value::Text(source)) + .map_err(|e| format!("parse {}: {e}", path.display()))?; + let map = match parsed { + Value::Map(m) => m, + _ => return Err("config must be a TOML table".into()), + }; + let base = path.parent().map(|p| p.to_path_buf()); + let mut count = 0usize; + for (lang, val) in map { + let spec = spec_from_config(&lang, &val, base.as_deref())?; + let canon = registry::canonical(&lang); + // Runtime registrations win; config fills the lower layer. + if !ctx.foreign_config_specs.contains_key(&canon) { + ctx.foreign_config_specs.insert(canon.clone(), spec.clone()); + } + if !ctx.foreign_specs.contains_key(&canon) && !ctx.foreign_cmds.contains_key(&canon) { + if let Some(t) = &spec.template { + if !t.iter().any(|x| x == "{inline}") { + ctx.foreign_cmds.insert(canon, spec.argv.clone()); + } + } else { + ctx.foreign_cmds.insert(canon, spec.argv.clone()); + } + } + count += 1; + } + Ok(count) +} + +fn spec_from_config(lang: &str, v: &Value, base: Option<&Path>) -> Result { + let entries = match v { + Value::Map(m) => m, + _ => return Err(format!("[{lang}] must be a table")), + }; + let mut cmd: Option = None; + let mut args: Vec = Vec::new(); + let mut template: Option> = None; + let mut ext: Option = None; + let mut env: Vec<(String, String)> = Vec::new(); + let mut version_args: Vec = Vec::new(); + let mut session = registry::session_supported(®istry::canonical(lang)); + for (k, val) in entries { + match k.as_str() { + "cmd" => cmd = Some(as_text(val, "cmd")?.to_string()), + "args" => args = parse_args(Some(val))?, + "template" => template = parse_template(Some(val))?, + "ext" => ext = opt_text(Some(val))?, + "env" => env = parse_env(Some(val))?, + "version_args" => version_args = parse_version_args(Some(val))?, + "session" => { + session = parse_bool(Some(val), "session", session)?; + } + _ => {} + } + } + if cmd.is_some() && template.is_some() { + return Err(format!("[{lang}]: cmd and template are mutually exclusive")); + } + if cmd.is_none() && template.is_none() { + return Err(format!("[{lang}]: provide cmd or template")); + } + let canon = registry::canonical(lang); + let mut argv = if let Some(c) = &cmd { + let mut v = vec![resolve_relative_cmd(c, base)]; + v.extend(args); + v + } else { + vec![template.as_ref().unwrap()[0].clone()] + }; + if let Some(t) = &template { + if t.is_empty() { + return Err(format!("[{lang}]: template must not be empty")); + } + argv = vec![t[0].clone()]; + } + Ok(LangSpec { + lang: canon, + argv, + template, + ext, + env, + version_args, + session, + base_dir: base.map(|p| p.to_path_buf()), + }) +} + +fn resolve_relative_cmd(cmd: &str, base: Option<&Path>) -> String { + let p = Path::new(cmd); + if p.is_absolute() || !cmd.contains('/') && !cmd.contains('\\') { + return cmd.to_string(); + } + let base = base.unwrap_or_else(|| Path::new(".")); + std::path::absolute(base.join(p)) + .map(|p| p.display().to_string()) + .unwrap_or_else(|_| cmd.to_string()) +} + +/// Explicit config load; returns the number of language tables read. +pub fn load_config(ctx: &mut HostContext, path: Option<&Value>) -> Result { + let explicit = opt_text(path)?; + if let Some(p) = explicit { + let p = PathBuf::from(p); + if !p.is_file() { + return Err(format!("foreign config not found: {}", p.display())); + } + let n = load_config_path(ctx, &p)?; + ctx.foreign_config_loaded = true; + return Ok(Value::Int(n as i64)); + } + ensure_config(ctx); + Ok(Value::Int(ctx.foreign_config_specs.len() as i64)) +} + pub fn run( ctx: &mut HostContext, code: &Value, stdin: Option<&Value>, ) -> Result { + run_with_options(ctx, code, stdin, &HashMap::new()) +} + +/// `run` with the F0 optional parameters (`stdin` is also accepted in `bound`). +pub fn run_with_options( + ctx: &mut HostContext, + code: &Value, + stdin: Option<&Value>, + bound: &HashMap, +) -> Result { + ensure_config(ctx); let block = as_code(code)?; - let stdin = opt_text(stdin)?; - run_source(ctx, &block.lang, &block.source, stdin) + let mut job = bound_job(ctx, &block.lang, &block.source, stdin, bound)?; + job.lang = block.lang.clone(); + let exec = execute_job(ctx, &job)?; + outcome_text(&exec) } pub fn run_lang( @@ -76,20 +544,363 @@ pub fn run_lang( source: &Value, stdin: Option<&Value>, ) -> Result { - let lang = as_text(lang, "lang")?; - let source = as_text(source, "source")?; - let stdin = opt_text(stdin)?; - run_source(ctx, lang, source, stdin) + run_lang_with_options(ctx, lang, source, stdin, &HashMap::new()) } -pub fn langs(ctx: &HostContext) -> Result { - let mut names: Vec = ctx.foreign_cmds.keys().cloned().collect(); - if !names.iter().any(|n| n == "python" || n == "python3") { - names.push("python".into()); +pub fn run_lang_with_options( + ctx: &mut HostContext, + lang: &Value, + source: &Value, + stdin: Option<&Value>, + bound: &HashMap, +) -> Result { + ensure_config(ctx); + let lang = as_text(lang, "lang")?; + let source = as_text(source, "source")?; + let job = bound_job(ctx, lang, source, stdin, bound)?; + let exec = execute_job(ctx, &job)?; + outcome_text(&exec) +} + +fn bound_job( + ctx: &HostContext, + lang: &str, + source: &str, + stdin: Option<&Value>, + bound: &HashMap, +) -> Result { + let mut job = Job::simple(lang, source, None); + job.stdin = opt_text(stdin)?; + job.env = parse_env(bound.get("env"))?; + job.cwd = opt_text(bound.get("cwd"))?; + job.timeout = parse_timeout(bound.get("timeout"))?; + job.extra_args = parse_args(bound.get("args"))?; + job.max_output = parse_max_output(bound.get("max_output"))?; + let _ = ctx; + Ok(job) +} + +/// Structured one-shot execution. Never errors for process failures; only bad args/policy. +pub fn invoke(ctx: &mut HostContext, args: InvokeArgs<'_>) -> Result { + ensure_config(ctx); + let (lang, source) = resolve_invoke_source(&args)?; + let stdin = opt_text(args.stdin)?; + let input_json = match args.input { + None | Some(Value::None) => None, + Some(v) => Some( + serde_json::to_string(&value_to_json(v)?) + .map_err(|e| format!("input JSON encode: {e}"))?, + ), + }; + if stdin.is_some() && input_json.is_some() { + return Err("stdin and input are mutually exclusive".into()); } + let output = match opt_text(args.output)? { + None => "auto".to_string(), + Some(s) => s.to_ascii_lowercase(), + }; + if !matches!(output.as_str(), "auto" | "text" | "json" | "lines") { + return Err(format!("unknown output mode `{output}` (auto|text|json|lines)")); + } + let mut job = Job::simple(&lang, &source, None); + job.stdin = stdin.or_else(|| input_json.clone()); + job.input_json = input_json; + job.env = parse_env(args.env)?; + job.cwd = opt_text(args.cwd)?; + job.timeout = parse_timeout(args.timeout)?; + job.extra_args = parse_args(args.args)?; + job.max_output = parse_max_output(args.max_output)?; + job.cmd_override = opt_text(args.cmd)?; + job.keep = parse_bool(args.keep, "keep", false)?; + let exec = execute_job(ctx, &job)?; + let (result, result_error) = parse_output(&exec.stdout, &output); + Ok(exec.record(result, result_error)) +} + +fn present(v: Option<&Value>) -> Option<&Value> { + match v { + None | Some(Value::None) => None, + Some(x) => Some(x), + } +} + +fn resolve_invoke_source(args: &InvokeArgs<'_>) -> Result<(String, String), String> { + if let Some(code) = present(args.code) { + if present(args.lang).is_some() || present(args.source).is_some() { + return Err("invoke: pass either code or lang+source, not both".into()); + } + let block = as_code(code)?; + return Ok((block.lang.clone(), block.source.clone())); + } + let lang = present(args.lang).ok_or_else(|| "invoke needs code or lang+source".to_string())?; + let source = + present(args.source).ok_or_else(|| "invoke needs source when lang is given".to_string())?; + Ok(( + as_text(lang, "lang")?.to_string(), + as_text(source, "source")?.to_string(), + )) +} + +fn parse_output(stdout: &str, mode: &str) -> (Value, String) { + match mode { + "text" => (Value::None, String::new()), + "lines" => ( + Value::List(stdout.lines().map(|l| Value::Text(l.to_string())).collect()), + String::new(), + ), + "json" => { + if stdout.trim().is_empty() { + return (Value::None, String::new()); + } + match serde_json::from_str::(stdout) { + Ok(j) => match json_to_value(&j) { + Ok(v) => (v, String::new()), + Err(e) => (Value::None, e), + }, + Err(e) => (Value::None, format!("stdout is not JSON: {e}")), + } + } + _ => { + if stdout.trim().is_empty() { + return (Value::None, String::new()); + } + match serde_json::from_str::(stdout) { + Ok(j) => (json_to_value(&j).unwrap_or(Value::None), String::new()), + Err(_) => (Value::None, String::new()), + } + } + } +} + +fn outcome_text(exec: &Execution) -> Result { + if !exec.ok { + return Err(format_failure(exec)); + } + let mut out = exec.stdout.clone(); + if out.ends_with('\n') { + out.pop(); + if out.ends_with('\r') { + out.pop(); + } + } + Ok(Value::Text(out)) +} + +fn format_failure(exec: &Execution) -> String { + let mut msg = format!( + "foreign run failed (lang={}, cmd={}, exit={})", + exec.lang, exec.cmd, exec.code + ); + if exec.timed_out { + msg.push_str(": timed out"); + } + if !exec.error.is_empty() { + msg.push_str(": "); + msg.push_str(&exec.error); + } + let err = exec.stderr.trim(); + if !err.is_empty() { + msg.push_str(": "); + msg.push_str(&tail(err, FAILURE_TAIL)); + } else { + let out = exec.stdout.trim(); + if !out.is_empty() { + msg.push_str(": stdout: "); + msg.push_str(&tail(out, FAILURE_TAIL)); + } + } + msg +} + +fn tail(s: &str, n: usize) -> String { + if s.len() <= n { + return s.to_string(); + } + let mut start = s.len() - n; + while start < s.len() && !s.is_char_boundary(start) { + start += 1; + } + format!("…{}", &s[start..]) +} + +fn known_langs(ctx: &HostContext) -> Vec { + let mut names: Vec = registry::preset_ids(); + names.extend(ctx.foreign_specs.keys().cloned()); + names.extend(ctx.foreign_config_specs.keys().cloned()); + names.extend(ctx.foreign_cmds.keys().map(|k| registry::canonical(k))); names.sort(); names.dedup(); - Ok(Value::List(names.into_iter().map(Value::Text).collect())) + names +} + +pub fn langs(ctx: &mut HostContext) -> Result { + ensure_config(ctx); + Ok(Value::List( + known_langs(ctx).into_iter().map(Value::Text).collect(), + )) +} + +/// Probe one language: path, version, availability. Never panics on missing tools. +pub fn probe(ctx: &mut HostContext, lang: Option<&Value>) -> Result { + ensure_config(ctx); + if !ctx.allow_exec() { + return Err("foreign probe denied by host policy".into()); + } + match opt_text(lang)? { + Some(l) => Ok(probe_one(ctx, &l)), + None => { + let ids = known_langs(ctx); + Ok(Value::List( + ids.iter().map(|l| probe_one(ctx, l)).collect(), + )) + } + } +} + +fn probe_one(ctx: &HostContext, lang: &str) -> Value { + let spec = match resolve_spec(ctx, lang) { + Ok(s) => s, + Err(e) => { + return Value::Map(vec![ + ("lang".into(), Value::Text(lang.to_string())), + ("cmd".into(), Value::Text(String::new())), + ("path".into(), Value::Text(String::new())), + ("ok".into(), Value::Bool(false)), + ("version".into(), Value::Text(String::new())), + ("error".into(), Value::Text(e)), + ]) + } + }; + let exe = spec + .argv + .first() + .cloned() + .or_else(|| spec.template.as_ref().and_then(|t| t.first()).cloned()) + .unwrap_or_default(); + let path = resolve_executable(&spec, &exe, &ctx.cwd); + let path_text = path + .as_ref() + .map(|p| p.display().to_string()) + .unwrap_or_default(); + let version_args = if spec.version_args.is_empty() { + vec!["--version".to_string()] + } else { + spec.version_args.clone() + }; + let mut display = vec![exe.clone()]; + display.extend(version_args.iter().cloned()); + let cmd_text = display.join(" "); + let Some(exe_path) = path else { + return Value::Map(vec![ + ("lang".into(), Value::Text(lang.to_string())), + ("cmd".into(), Value::Text(cmd_text)), + ("path".into(), Value::Text(String::new())), + ("ok".into(), Value::Bool(false)), + ("version".into(), Value::Text(String::new())), + ("error".into(), Value::Text(format!( + "interpreter `{exe}` not found on PATH — register / set_cmd / MARQDO_FOREIGN_*" + ))), + ]); + }; + let mut command = Command::new(&exe_path); + command.args(&version_args); + command.stdin(Stdio::null()); + command.stdout(Stdio::piped()); + command.stderr(Stdio::piped()); + command.env("MARQDO_FOREIGN_LANG", &spec.lang); + for (k, v) in &spec.env { + command.env(k, v); + } + let mut child = match command.spawn() { + Ok(c) => c, + Err(e) => { + return Value::Map(vec![ + ("lang".into(), Value::Text(lang.to_string())), + ("cmd".into(), Value::Text(cmd_text)), + ("path".into(), Value::Text(path_text)), + ("ok".into(), Value::Bool(false)), + ("version".into(), Value::Text(String::new())), + ("error".into(), Value::Text(format!("spawn {exe}: {e}"))), + ]) + } + }; + let out = child.stdout.take(); + let err = child.stderr.take(); + let out_h = thread::spawn(move || read_capped(out, 64 * 1024)); + let err_h = thread::spawn(move || read_capped(err, 64 * 1024)); + let start = Instant::now(); + let mut ok = false; + let mut error = String::new(); + loop { + match child.try_wait() { + Ok(Some(st)) => { + ok = st.success(); + break; + } + Ok(None) if start.elapsed() > Duration::from_secs(3) => { + let _ = child.kill(); + let _ = child.wait(); + error = "version probe timed out after 3s".into(); + break; + } + Ok(None) => thread::sleep(Duration::from_millis(15)), + Err(e) => { + let _ = child.kill(); + error = format!("version probe failed: {e}"); + break; + } + } + } + let (stdout, _) = out_h.join().unwrap_or_default(); + let (stderr, _) = err_h.join().unwrap_or_default(); + let version = stdout + .lines() + .chain(stderr.lines()) + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or("") + .to_string(); + Value::Map(vec![ + ("lang".into(), Value::Text(lang.to_string())), + ("cmd".into(), Value::Text(cmd_text)), + ("path".into(), Value::Text(path_text)), + ("ok".into(), Value::Bool(ok && error.is_empty())), + ("version".into(), Value::Text(version)), + ("error".into(), Value::Text(error)), + ]) +} + +fn resolve_executable(spec: &LangSpec, exe: &str, cwd: &Path) -> Option { + if exe.is_empty() { + return None; + } + let looks_path = exe.contains('/') || exe.contains('\\'); + if looks_path { + let base = spec.base_dir.as_deref().unwrap_or(cwd); + let p = if Path::new(exe).is_absolute() { + PathBuf::from(exe) + } else { + base.join(exe) + }; + return std::path::absolute(&p).ok().filter(|p| p.is_file()); + } + let path_var = std::env::var_os("PATH")?; + for dir in std::env::split_paths(&path_var) { + let p = dir.join(exe); + if p.is_file() { + return std::path::absolute(&p).ok().or(Some(p)); + } + #[cfg(windows)] + { + for ext in ["exe", "cmd", "bat", "com"] { + let with = dir.join(format!("{exe}.{ext}")); + if with.is_file() { + return Some(with); + } + } + } + } + None } /// Shared entry for CLI host and live view `/api/foreign-run`. @@ -99,12 +910,9 @@ pub fn run_source( source: &str, stdin: Option<&str>, ) -> Result { - let lang_key = lang.to_ascii_lowercase(); - let argv = resolve_argv(ctx, &lang_key)?; - let script_path = write_temp_script(&lang_key, source)?; - let result = run_argv(ctx, &argv, &script_path, stdin, &lang_key); - let _ = std::fs::remove_file(&script_path); - result + let job = Job::simple(lang, source, stdin); + let exec = execute_job(ctx, &job)?; + outcome_text(&exec) } /// Resolve argv with optional one-shot cmd override (view command box). @@ -114,72 +922,201 @@ pub fn resolve_argv_with_override( cmd_override: Option<&str>, ) -> Result, String> { if let Some(cmd) = cmd_override.map(str::trim).filter(|s| !s.is_empty()) { - return Ok(split_cmd_line(cmd)); + let argv = split_cmd_line(cmd); + if argv.is_empty() { + return Err("cmd override is empty".into()); + } + return Ok(argv); } - resolve_argv(ctx, lang) + Ok(resolve_spec(ctx, lang)?.argv) } -fn resolve_argv(ctx: &HostContext, lang: &str) -> Result, String> { - if let Some(argv) = ctx.foreign_cmds.get(lang) { - return Ok(argv.clone()); +fn env_argv_for(lang: &str, canon: &str) -> Result>, String> { + let mut keys = vec![format!("MARQDO_FOREIGN_{}", lang.to_ascii_uppercase())]; + if canon != lang { + keys.push(format!("MARQDO_FOREIGN_{}", canon.to_ascii_uppercase())); } - if lang == "python3" { - if let Some(argv) = ctx.foreign_cmds.get("python") { - return Ok(argv.clone()); - } + if canon == "python" { + keys.push("MARQDO_FOREIGN_PYTHON".to_string()); } - if lang == "python" { - if let Some(argv) = ctx.foreign_cmds.get("python3") { - return Ok(argv.clone()); - } - } - - let env_key = format!("MARQDO_FOREIGN_{}", lang.to_ascii_uppercase()); - if let Ok(v) = std::env::var(&env_key) { - let v = v.trim(); - if !v.is_empty() { - return Ok(split_cmd_line(v)); - } - } - if lang == "python" || lang == "python3" || lang == "py" { - if let Ok(v) = std::env::var("MARQDO_FOREIGN_PYTHON") { + for key in keys { + if let Ok(v) = std::env::var(&key) { let v = v.trim(); if !v.is_empty() { - return Ok(split_cmd_line(v)); + let argv = parse_env_argv(v)?; + if !argv.is_empty() { + return Ok(Some(argv)); + } } } } - if let Some(argv) = foreign::default_argv(lang) { - return Ok(argv); - } + Ok(None) +} +/// Resolve the effective language spec: register > env > config > preset. +fn resolve_spec(ctx: &HostContext, lang: &str) -> Result { + let requested = lang.to_ascii_lowercase(); + let canon = registry::canonical(&requested); + if let Some(s) = ctx + .foreign_specs + .get(&requested) + .or_else(|| ctx.foreign_specs.get(&canon)) + { + return Ok(s.clone()); + } + if let Some(argv) = env_argv_for(&requested, &canon)? { + let mut spec = registry::preset_spec(&canon).unwrap_or_else(|| LangSpec { + lang: canon.clone(), + ..Default::default() + }); + spec.argv = argv; + spec.template = None; + spec.lang = canon.clone(); + return Ok(spec); + } + if let Some(s) = ctx + .foreign_config_specs + .get(&requested) + .or_else(|| ctx.foreign_config_specs.get(&canon)) + { + return Ok(s.clone()); + } + if let Some(s) = registry::preset_spec(&canon) { + return Ok(s); + } Err(format!( - "no interpreter configured for lang=`{lang}` — set_cmd lang={lang} cmd=… \ - or env {env_key} (check your environment)" + "no interpreter configured for lang=`{lang}` — register lang={lang} cmd=… \ + or env MARQDO_FOREIGN_{} (check your environment)", + lang.to_ascii_uppercase() )) } -fn split_cmd_line(s: &str) -> Vec { - s.split_whitespace().map(|p| p.to_string()).collect() +struct Invocation { + argv: Vec, + template: Option>, + ext: String, + env: Vec<(String, String)>, + inline: bool, + #[allow(dead_code)] + session: bool, } -fn write_temp_script(lang: &str, source: &str) -> Result { - let ext = match lang { - "python" | "python3" | "py" => "py", - "javascript" | "js" | "node" => "js", - other => { - if other.len() <= 8 && other.chars().all(|c| c.is_ascii_alphanumeric()) { - other - } else { - "txt" - } +fn default_ext(lang: &str) -> String { + if let Some(s) = registry::preset_spec(lang) { + if let Some(e) = s.ext { + return e; } - }; - let body = if matches!(lang, "python" | "python3" | "py") { + } + let l = lang.to_ascii_lowercase(); + if l.len() <= 8 && l.chars().all(|c| c.is_ascii_alphanumeric()) { + l + } else { + "txt".to_string() + } +} + +fn resolve_invocation(ctx: &HostContext, job: &Job) -> Result { + if let Some(cmd) = job.cmd_override.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + let argv = split_cmd_line(cmd); + if argv.is_empty() { + return Err("cmd override is empty".into()); + } + return Ok(Invocation { + argv, + template: None, + ext: default_ext(&job.lang), + env: Vec::new(), + inline: false, + session: registry::session_supported(&job.lang), + }); + } + let spec = resolve_spec(ctx, &job.lang)?; + let mut template = spec.template.clone(); + if let Some(t) = &mut template { + if t.is_empty() { + return Err(format!("language `{}` has an empty template", spec.lang)); + } + let has_file = t.iter().any(|x| x == "{file}"); + let has_inline = t.iter().any(|x| x == "{inline}"); + if has_file && has_inline { + return Err(format!( + "language `{}` template uses both {{file}} and {{inline}}", + spec.lang + )); + } + if !has_file && !has_inline { + t.push("{file}".into()); + } + } + let inline = template + .as_ref() + .map(|t| t.iter().any(|x| x == "{inline}")) + .unwrap_or(false); + Ok(Invocation { + argv: spec.argv, + template, + ext: spec.ext.unwrap_or_else(|| default_ext(&job.lang)), + env: spec.env, + inline, + session: spec.session, + }) +} + + +/// `MARQDO_FOREIGN_` accepts a shell-like line or a JSON array of strings. +fn parse_env_argv(v: &str) -> Result, String> { + if v.starts_with('[') { + let parsed: serde_json::Value = + serde_json::from_str(v).map_err(|e| format!("invalid JSON argv: {e}"))?; + let arr = parsed + .as_array() + .ok_or_else(|| "argv JSON must be an array".to_string())?; + let mut out = Vec::new(); + for x in arr { + let s = x + .as_str() + .ok_or_else(|| "argv JSON entries must be strings".to_string())?; + out.push(s.to_string()); + } + return Ok(out); + } + Ok(split_cmd_line(v)) +} + +/// Shell-like split: whitespace, single/double quotes, backslash escapes. + +fn is_python(lang: &str) -> bool { + matches!(lang, "python" | "python3" | "py") +} + +fn write_temp_script( + ctx: &HostContext, + lang: &str, + source: &str, + ext: &str, +) -> Result { + let body = if is_python(lang) { format!("# -*- coding: utf-8 -*-\n{source}") } else { source.to_string() }; + let base = { + let preferred = temp_base(ctx); + match std::fs::create_dir_all(&preferred) { + Ok(()) => preferred, + Err(_) => { + let fallback = std::env::temp_dir(); + std::fs::create_dir_all(&fallback).map_err(|e| { + format!( + "failed to create foreign temp dir {} or fallback {}: {e}", + preferred.display(), + fallback.display() + ) + })?; + fallback + } + } + }; let name = format!( "marqdo-foreign-{}-{}.{}", std::process::id(), @@ -189,196 +1126,503 @@ fn write_temp_script(lang: &str, source: &str) -> Result { .unwrap_or(0), ext ); - let path = std::env::temp_dir().join(name); + let path = base.join(name); std::fs::write(&path, body.as_bytes()) .map_err(|e| format!("failed to write temp foreign script: {e}"))?; Ok(path) } +fn temp_base(ctx: &HostContext) -> PathBuf { + let p = if let Ok(v) = std::env::var("MARQDO_FOREIGN_TMPDIR") { + let v = v.trim(); + if !v.is_empty() { + PathBuf::from(v) + } else { + ctx.cwd.join(".marqdo").join("tmp") + } + } else { + ctx.cwd.join(".marqdo").join("tmp") + }; + std::path::absolute(&p).unwrap_or(p) +} + /// Background foreign subprocess (for `lib/subtask`); caller removes `script_path` after join. pub struct SpawnedForeign { - pub child: std::process::Child, + pub child: Child, pub script_path: PathBuf, - pub stdout: thread::JoinHandle, - pub stderr: thread::JoinHandle, + pub stdout: thread::JoinHandle<(String, bool)>, + pub stderr: thread::JoinHandle<(String, bool)>, } pub fn spawn_source( - ctx: &HostContext, + ctx: &mut HostContext, lang: &str, source: &str, stdin: Option<&str>, ) -> Result { - let lang_key = lang.to_ascii_lowercase(); - let argv = resolve_argv(ctx, &lang_key)?; - let script_path = write_temp_script(&lang_key, source)?; - match spawn_argv(ctx, &argv, &script_path, stdin, &lang_key) { - Ok(spawned) => Ok(spawned), - Err(e) => { - let _ = std::fs::remove_file(&script_path); - Err(e) - } - } -} - -fn build_foreign_command( - ctx: &HostContext, - argv: &[String], - script: &Path, -) -> Result { - if argv.is_empty() { - return Err("foreign cmd argv is empty — check set_cmd / env".into()); - } - let mut command = Command::new(&argv[0]); - for a in &argv[1..] { - command.arg(a); - } - command.arg(script); - command.current_dir(&ctx.cwd); - command.stdin(Stdio::piped()); - command.stdout(Stdio::piped()); - command.stderr(Stdio::piped()); - command.env("PYTHONIOENCODING", "utf-8"); - command.env("PYTHONUTF8", "1"); - Ok(command) -} - -fn spawn_argv( - ctx: &HostContext, - argv: &[String], - script: &Path, - stdin: Option<&str>, - lang: &str, -) -> Result { - let mut child = build_foreign_command(ctx, argv, script)? - .spawn() - .map_err(|e| { - format!( - "foreign spawn failed (lang={lang}, cmd={}): {e} — check your interpreter / \ - MARQDO_FOREIGN_* / set_cmd", - argv.join(" ") - ) - })?; - - if let Some(data) = stdin { - if let Some(mut pipe) = child.stdin.take() { - let _ = pipe.write_all(data.as_bytes()); - } - } else { - drop(child.stdin.take()); - } - - let mut stdout_pipe = child.stdout.take(); - let mut stderr_pipe = child.stderr.take(); - let stdout = thread::spawn(move || { - let mut buf = Vec::new(); - if let Some(ref mut r) = stdout_pipe { - let _ = r.read_to_end(&mut buf); - } - String::from_utf8_lossy(&buf).into_owned() - }); - let stderr = thread::spawn(move || { - let mut buf = Vec::new(); - if let Some(ref mut r) = stderr_pipe { - let _ = r.read_to_end(&mut buf); - } - String::from_utf8_lossy(&buf).into_owned() - }); - + ensure_config(ctx); + let job = Job::simple(lang, source, stdin); + let (child, script_path, stdout, stderr) = spawn_job(ctx, &job)?; Ok(SpawnedForeign { child, - script_path: script.to_path_buf(), + script_path, stdout, stderr, }) } -fn run_argv( - ctx: &HostContext, - argv: &[String], - script: &Path, - stdin: Option<&str>, - lang: &str, -) -> Result { - let spawned = spawn_argv(ctx, argv, script, stdin, lang)?; - let SpawnedForeign { - mut child, - stdout: t_out, - stderr: t_err, - .. - } = spawned; +fn job_cwd(ctx: &HostContext, job: &Job) -> Result { + let cwd = match &job.cwd { + Some(c) => ctx.resolve_path(c)?, + None => ctx.cwd.clone(), + }; + if !cwd.is_dir() { + return Err(format!("foreign cwd is not a directory: {}", cwd.display())); + } + Ok(cwd) +} - let start = Instant::now(); - let status = loop { - match child.try_wait() { - Ok(Some(st)) => break st, - Ok(None) if start.elapsed() > DEFAULT_TIMEOUT => { - let _ = child.kill(); - let _ = child.wait(); - return Err(format!( - "foreign run timed out after {}s (lang={lang}, cmd={}) — check your script / environment", - DEFAULT_TIMEOUT.as_secs(), - argv.join(" ") - )); +fn expand_template( + ctx: &HostContext, + job: &Job, + template: &[String], + script: Option<&Path>, + cwd: &Path, +) -> Vec { + let dir = script + .and_then(|p| p.parent()) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| temp_base(ctx)); + let file = script + .map(|p| p.display().to_string()) + .unwrap_or_default(); + let base = script + .and_then(|p| p.file_name()) + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let mut out = Vec::with_capacity(template.len()); + for item in template { + let mut s = item.clone(); + s = s.replace("{file}", &file); + s = s.replace("{dir}", &dir.display().to_string()); + s = s.replace("{base}", &base); + s = s.replace("{inline}", &job.source); + s = s.replace("{lang}", &job.lang); + s = s.replace("{cwd}", &cwd.display().to_string()); + out.push(s); + } + out +} + +fn build_command( + ctx: &HostContext, + job: &Job, + inv: &Invocation, + script: Option<&Path>, +) -> Result<(Command, String), String> { + let cwd = job_cwd(ctx, job)?; + let argv = if let Some(template) = &inv.template { + let mut v = expand_template(ctx, job, template, script, &cwd); + v.extend(job.extra_args.iter().cloned()); + v + } else { + let mut v = inv.argv.clone(); + v.extend(job.extra_args.iter().cloned()); + if let Some(script) = script { + v.push(script.display().to_string()); + } + v + }; + if argv.is_empty() { + return Err("foreign cmd argv is empty — check register / env".into()); + } + let mut command = Command::new(&argv[0]); + for a in &argv[1..] { + command.arg(a); + } + command.current_dir(&cwd); + command.stdin(Stdio::piped()); + command.stdout(Stdio::piped()); + command.stderr(Stdio::piped()); + + command.env("MARQDO_FOREIGN", "1"); + command.env("MARQDO_FOREIGN_LANG", &job.lang); + if let Some(script) = script { + command.env("MARQDO_FOREIGN_SCRIPT", script); + } + command.env( + "MARQDO_FOREIGN_DIR", + script + .and_then(|p| p.parent()) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| temp_base(ctx)), + ); + command.env("MARQDO_FOREIGN_CWD", &cwd); + if let Some(path) = &ctx.entry_path { + command.env("MARQDO_ENTRY", path); + if let Some(dir) = path.parent() { + command.env("MARQDO_ENTRY_DIR", dir); + } + } + if let Some(input) = &job.input_json { + if input.len() <= INPUT_ENV_CAP { + command.env("MARQDO_INPUT", input); + } + } + for (k, v) in &inv.env { + command.env(k, v); + } + for (k, v) in &job.env { + command.env(k, v); + } + if is_python(&job.lang) { + command.env("PYTHONUNBUFFERED", "1"); + command.env("PYTHONIOENCODING", "utf-8"); + command.env("PYTHONUTF8", "1"); + let sep = if cfg!(windows) { ";" } else { ":" }; + let mut paths = vec![cwd.to_string_lossy().into_owned()]; + if let Ok(existing) = std::env::var("PYTHONPATH") { + if !existing.is_empty() { + paths.push(existing); } - Ok(None) => thread::sleep(Duration::from_millis(20)), - Err(e) => { - return Err(format!( - "foreign run failed (lang={lang}, cmd={}): {e}", - argv.join(" ") - )); + } + command.env("PYTHONPATH", paths.join(sep)); + } + + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.process_group(0); + } + + Ok((command, argv.join(" "))) +} + +fn spawn_job( + ctx: &HostContext, + job: &Job, +) -> Result< + ( + Child, + PathBuf, + thread::JoinHandle<(String, bool)>, + thread::JoinHandle<(String, bool)>, + ), + String, +> { + let inv = resolve_invocation(ctx, job)?; + let script = if inv.inline { + None + } else { + Some(write_temp_script(ctx, &job.lang, &job.source, &inv.ext)?) + }; + let (mut command, display) = match build_command(ctx, job, &inv, script.as_deref()) { + Ok(v) => v, + Err(e) => { + if let Some(p) = &script { + let _ = std::fs::remove_file(p); } + return Err(e); + } + }; + let mut child = match command.spawn() { + Ok(c) => c, + Err(e) => { + if let Some(p) = &script { + let _ = std::fs::remove_file(p); + } + return Err(format!( + "foreign spawn failed (lang={}, cmd={}): {e} — check your interpreter / \ + MARQDO_FOREIGN_* / register", + job.lang, display + )); } }; - let stdout = t_out.join().unwrap_or_default(); - let stderr = t_err.join().unwrap_or_default(); - if stdout.len() > MAX_OUTPUT || stderr.len() > MAX_OUTPUT { - return Err(format!( - "foreign output too large (lang={lang}) — truncate script output" - )); + let mut stdin_pipe = child.stdin.take(); + let stdin_data = job.stdin.clone(); + if let Some(data) = stdin_data { + thread::spawn(move || { + if let Some(mut pipe) = stdin_pipe.take() { + let _ = pipe.write_all(data.as_bytes()); + } + }); + } else { + drop(stdin_pipe.take()); } - if !status.success() { - let code = status.code().unwrap_or(1); - let mut msg = format!( - "foreign run failed (lang={lang}, cmd={}, exit={code})", - argv.join(" ") - ); - if !stderr.trim().is_empty() { - msg.push_str(": "); - msg.push_str(stderr.trim()); - } - msg.push_str(" — check your interpreter / MARQDO_FOREIGN_* / set_cmd / script"); - return Err(msg); - } - - let mut out = stdout; - if out.ends_with('\n') { - out.pop(); - if out.ends_with('\r') { - out.pop(); - } - } - Ok(Value::Text(out)) + let stdout = child.stdout.take(); + let stderr = child.stderr.take(); + let max = job.max_output; + let out_h = thread::spawn(move || read_capped(stdout, max)); + let err_h = thread::spawn(move || read_capped(stderr, max)); + Ok((child, script.unwrap_or_default(), out_h, err_h)) } -/// View/API helper: run with optional command override string. -pub fn run_with_cmd_override( - cwd: &Path, +fn display_for_job(ctx: &HostContext, job: &Job, script: Option<&Path>) -> String { + match resolve_invocation(ctx, job) { + Ok(inv) => match build_command(ctx, job, &inv, script) { + Ok((_, d)) => d, + Err(_) => inv.argv.join(" "), + }, + Err(_) => job.lang.clone(), + } +} + +fn read_capped(reader: Option, max: usize) -> (String, bool) { + let mut kept: Vec = Vec::new(); + let mut truncated = false; + if let Some(mut r) = reader { + let mut buf = [0u8; 8192]; + loop { + match r.read(&mut buf) { + Ok(0) => break, + Ok(n) => { + if kept.len() < max { + let take = (max - kept.len()).min(n); + kept.extend_from_slice(&buf[..take]); + if take < n { + truncated = true; + } + } else { + truncated = true; + } + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => break, + } + } + } + (String::from_utf8_lossy(&kept).into_owned(), truncated) +} + +fn kill_tree(child: &mut Child) { + #[cfg(unix)] + unsafe { + libc::kill(-(child.id() as i32), libc::SIGKILL); + } + #[cfg(windows)] + { + let _ = Command::new("taskkill") + .args(["/PID", &child.id().to_string(), "/T", "/F"]) + .output(); + } + let _ = child.kill(); +} + +fn execute_job(ctx: &HostContext, job: &Job) -> Result { + if !ctx.allow_exec() { + if ctx.sandbox_session.is_some() { + return Err("foreign unavailable in sandbox".into()); + } + return Err("foreign denied by host policy".into()); + } + let (mut child, script_path, out_h, err_h) = match spawn_job(ctx, job) { + Ok(v) => v, + Err(error) => { + return Ok(Execution { + ok: false, + code: -1, + stdout: String::new(), + stderr: String::new(), + ms: 0, + timed_out: false, + truncated: false, + error, + lang: job.lang.clone(), + cmd: display_for_job(ctx, job, None), + script: String::new(), + }); + } + }; + let start = Instant::now(); + let mut timed_out = false; + let mut wait_error: Option = None; + let status = loop { + match child.try_wait() { + Ok(Some(st)) => break Some(st), + Ok(None) => { + if start.elapsed() >= job.timeout { + timed_out = true; + kill_tree(&mut child); + let _ = child.wait(); + break None; + } + thread::sleep(Duration::from_millis(10)); + } + Err(e) => { + wait_error = Some(format!("foreign wait failed: {e}")); + kill_tree(&mut child); + let _ = child.wait(); + break None; + } + } + }; + let (stdout, out_trunc) = out_h.join().unwrap_or_default(); + let (stderr, err_trunc) = err_h.join().unwrap_or_default(); + let ms = start.elapsed().as_millis() as u64; + + let script_is_empty = script_path.as_os_str().is_empty(); + let script_keep = if job.keep && !script_is_empty { + script_path.display().to_string() + } else { + if !script_is_empty { + let _ = std::fs::remove_file(&script_path); + } + String::new() + }; + let code = status.and_then(|s| s.code()).unwrap_or(-1); + let ok = status.map(|s| s.success()).unwrap_or(false) && !timed_out && wait_error.is_none(); + let error = if let Some(e) = wait_error { + e + } else if timed_out { + format!("timed out after {:.3}s", job.timeout.as_secs_f64()) + } else { + String::new() + }; + let cmd = display_for_job( + ctx, + job, + if script_is_empty { + None + } else { + Some(script_path.as_path()) + }, + ); + Ok(Execution { + ok, + code, + stdout, + stderr, + ms, + timed_out, + truncated: out_trunc || err_trunc, + error, + lang: job.lang.clone(), + cmd, + script: script_keep, + }) +} + +/// View helper: execute one fence with the command-box override + full record. +pub fn invoke_for_view( + root: &Path, lang: &str, source: &str, cmd_override: Option<&str>, -) -> Result { + stdin: Option<&str>, + timeout_secs: Option, +) -> Result { let mut ctx = HostContext::default(); - ctx.cwd = cwd.to_path_buf(); - let argv = resolve_argv_with_override(&ctx, lang, cmd_override)?; - let script_path = write_temp_script(&lang.to_ascii_lowercase(), source)?; - let result = run_argv(&ctx, &argv, &script_path, None, lang); - let _ = std::fs::remove_file(&script_path); - match result { - Ok(Value::Text(s)) => Ok(s), - Ok(v) => Ok(v.as_display()), - Err(e) => Err(e), + ctx.cwd = root.to_path_buf(); + ctx.fs_root = Some(root.to_path_buf()); + ensure_config(&mut ctx); + let timeout = match timeout_secs { + Some(t) if t > 0.0 => Duration::from_secs_f64(t.min(MAX_TIMEOUT_SECS)), + _ => Duration::from_secs_f64(DEFAULT_TIMEOUT_SECS), + }; + let job = Job { + lang: lang.to_string(), + source: source.to_string(), + stdin: stdin.map(str::to_string), + input_json: None, + env: Vec::new(), + cwd: None, + timeout, + extra_args: Vec::new(), + max_output: MAX_OUTPUT, + keep: false, + cmd_override: cmd_override.map(str::to_string), + }; + let exec = execute_job(&ctx, &job)?; + let (result, result_error) = parse_output(&exec.stdout, "auto"); + Ok(exec.record(result, result_error)) +} + +#[cfg(test)] +mod tests { + use crate::foreign; + use super::*; + + #[test] + fn fence_lang_python() { + assert_eq!(foreign::fence_lang("```python").as_deref(), Some("python")); + assert_eq!( + foreign::fence_lang("```python name=x").as_deref(), + Some("python") + ); + assert!(foreign::fence_lang("```").is_none()); + } + + #[test] + fn split_quotes() { + assert_eq!( + split_cmd_line("python3 -u -c 'a b'"), + vec!["python3", "-u", "-c", "a b"] + ); + assert_eq!( + split_cmd_line(r#"node -e "console.log(\"x\")""#), + vec!["node", "-e", "console.log(\"x\")"] + ); + assert_eq!( + split_cmd_line(r#"/opt/my python/bin/python -u"#), + vec!["/opt/my", "python/bin/python", "-u"] + ); + assert_eq!( + split_cmd_line(r#""/opt/my python/bin/python" -u"#), + vec!["/opt/my python/bin/python", "-u"] + ); + } + + #[test] + fn env_argv_json() { + assert_eq!( + parse_env_argv(r#"["python3","-u"]"#).unwrap(), + vec!["python3", "-u"] + ); + } + + #[test] + fn output_modes() { + let (v, e) = parse_output("42", "auto"); + assert!(e.is_empty()); + assert_eq!(v, Value::Int(42)); + let (v, e) = parse_output("a\nb\n", "lines"); + assert!(e.is_empty()); + assert_eq!(v, Value::List(vec![Value::Text("a".into()), Value::Text("b".into())])); + let (v, e) = parse_output("not json", "json"); + assert!(v == Value::None); + assert!(!e.is_empty()); + } + + #[test] + fn exec_cap_denies() { + let mut ctx = HostContext::default(); + ctx.caps.exec = false; + let job = Job::simple("node", "console.log(1)", None); + let err = execute_job(&ctx, &job).unwrap_err(); + assert!(err.contains("denied"), "{err}"); + } + + #[test] + fn missing_interpreter_is_record() { + let mut ctx = HostContext::default(); + ctx.foreign_cmds.insert( + "nope".into(), + vec!["/definitely/not/a/real/interpreter".into()], + ); + let job = Job::simple("nope", "x", None); + let exec = execute_job(&ctx, &job).unwrap(); + assert!(!exec.ok); + assert_eq!(exec.code, -1); + assert!(!exec.error.is_empty(), "spawn failure should be recorded"); + } + + #[test] + fn read_cap_marks_truncated() { + let data = b"0123456789".to_vec(); + let (text, truncated) = read_capped(Some(std::io::Cursor::new(data)), 4); + assert_eq!(text, "0123"); + assert!(truncated); } } diff --git a/src/host/mod.rs b/src/host/mod.rs index b68dc94..57cd8db 100644 --- a/src/host/mod.rs +++ b/src/host/mod.rs @@ -27,7 +27,7 @@ mod secrets; mod stats; mod text_ops; mod time; -mod toml_ops; +pub(crate) mod toml_ops; mod url_ops; mod uuid_ops; #[cfg(feature = "plugin-host")] @@ -93,6 +93,12 @@ pub struct HostContext { pub plots: Vec, /// lang → interpreter argv (from `set_cmd`). pub foreign_cmds: HashMap>, + /// Process-local language registrations (`register` / `set_cmd`). + pub foreign_specs: HashMap, + /// Project config specs (`.marqdo/foreign.toml`), lower priority than runtime. + pub foreign_config_specs: HashMap, + /// Whether project config has been discovered/loaded. + pub foreign_config_loaded: bool, /// Loaded native plugins (ABI v1/v2). pub plugins: PluginState, /// Entry `.mq.md` source text (for ABI host_query / context injection). @@ -128,6 +134,9 @@ impl Default for HostContext { rng: 0xC0FF_EE42_CAFE_BABE, plots: Vec::new(), foreign_cmds: HashMap::new(), + foreign_specs: HashMap::new(), + foreign_config_specs: HashMap::new(), + foreign_config_loaded: false, plugins: PluginState::default(), entry_source: None, entry_path: None, diff --git a/src/host/subtask.rs b/src/host/subtask.rs index 5452060..f7e850c 100644 --- a/src/host/subtask.rs +++ b/src/host/subtask.rs @@ -120,8 +120,8 @@ fn republish_child_event(line: &str) { pub(crate) struct ForeignTask { child: Child, temp_script: PathBuf, - stdout: JoinHandle, - stderr: JoinHandle, + stdout: JoinHandle<(String, bool)>, + stderr: JoinHandle<(String, bool)>, } enum FnState { @@ -392,6 +392,9 @@ fn spawn_fn( let cwd = ctx.cwd.clone(); let caps = ctx.caps.clone(); let foreign_cmds = ctx.foreign_cmds.clone(); + let foreign_specs = ctx.foreign_specs.clone(); + let foreign_config_specs = ctx.foreign_config_specs.clone(); + let foreign_config_loaded = ctx.foreign_config_loaded; let fs_root = ctx.fs_root.clone(); let argv = ctx.argv.clone(); @@ -407,6 +410,9 @@ fn spawn_fn( host.fs_root = fs_root; host.argv = argv; host.foreign_cmds = foreign_cmds; + host.foreign_specs = foreign_specs; + host.foreign_config_specs = foreign_config_specs; + host.foreign_config_loaded = foreign_config_loaded; host.set_entry_source(Some(&module_path), &source); host.entry_metadata = module.metadata.clone(); let mut interp = Interpreter::with_capture(Some(&module_path), false).with_host(host); @@ -587,12 +593,9 @@ fn join_foreign(mut task: ForeignTask) -> Result { .child .wait() .map_err(|e| format!("subtask foreign join: {e}"))?; - let stdout = task.stdout.join().unwrap_or_default(); - let stderr = task.stderr.join().unwrap_or_default(); + let (stdout, out_trunc) = task.stdout.join().unwrap_or_default(); + let (stderr, err_trunc) = task.stderr.join().unwrap_or_default(); let _ = std::fs::remove_file(&task.temp_script); - if stdout.len() > foreign::MAX_OUTPUT || stderr.len() > foreign::MAX_OUTPUT { - return Err("subtask foreign output too large".into()); - } if !status.success() { let code = status.code().unwrap_or(1); let mut msg = format!("subtask foreign failed (exit={code})"); @@ -609,6 +612,9 @@ fn join_foreign(mut task: ForeignTask) -> Result { out.pop(); } } + if out_trunc || err_trunc { + out.push_str("\n…(truncated)"); + } Ok(Value::Text(out)) } diff --git a/src/view/debug_page.rs b/src/view/debug_page.rs index 5e967c9..695cbba 100644 --- a/src/view/debug_page.rs +++ b/src/view/debug_page.rs @@ -958,13 +958,22 @@ fn debug_js() -> &'static str { }) .then(function (r) { return r.json(); }) .then(function (data) { + var parts = []; + if (data.stdout) parts.push(data.stdout); + if (data.stderr) parts.push("[stderr]\n" + data.stderr); + if (data.error) parts.push(data.error); + var meta = []; + if (typeof data.code === "number") meta.push("exit " + data.code); + if (typeof data.ms === "number") meta.push(data.ms + "ms"); + if (data.timed_out) meta.push("timed out"); + if (data.truncated) meta.push("truncated"); + if (meta.length) parts.push("— " + meta.join(" · ")); if (data.ok) { out.classList.remove("err"); - out.textContent = data.stdout === "" ? "(no stdout)" : data.stdout; } else { out.classList.add("err"); - out.textContent = data.error || "foreign run failed"; } + out.textContent = parts.length ? parts.join("\n\n") : "(no output)"; }) .catch(function (e) { out.classList.add("err"); diff --git a/src/view/html.rs b/src/view/html.rs index 459bdae..8cb4cbe 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -1625,13 +1625,22 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { }}) .then(function (r) {{ return r.json(); }}) .then(function (data) {{ + var parts = []; + if (data.stdout) parts.push(data.stdout); + if (data.stderr) parts.push("[stderr]\n" + data.stderr); + if (data.error) parts.push(data.error); + var meta = []; + if (typeof data.code === "number") meta.push("exit " + data.code); + if (typeof data.ms === "number") meta.push(data.ms + "ms"); + if (data.timed_out) meta.push("timed out"); + if (data.truncated) meta.push("truncated"); + if (meta.length) parts.push("— " + meta.join(" · ")); if (data.ok) {{ out.classList.remove("err"); - out.textContent = data.stdout === "" ? "(no stdout)" : data.stdout; }} else {{ out.classList.add("err"); - out.textContent = data.error || "foreign run failed"; }} + out.textContent = parts.length ? parts.join("\n\n") : "(no output)"; }}) .catch(function (e) {{ out.classList.add("err"); diff --git a/src/view/mod.rs b/src/view/mod.rs index 5e31c2b..eb5530a 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -595,6 +595,8 @@ fn api_foreign_run(root: &ViewRoot, mut request: Request) -> Result<()> { .and_then(|x| x.as_str()) .unwrap_or("python"); let source = v.get("source").and_then(|x| x.as_str()).unwrap_or(""); + let stdin = v.get("stdin").and_then(|x| x.as_str()); + let timeout = v.get("timeout").and_then(|x| x.as_f64()); let cmd = v .get("cmd") .and_then(|x| x.as_str()) @@ -603,13 +605,18 @@ fn api_foreign_run(root: &ViewRoot, mut request: Request) -> Result<()> { let json = if source.is_empty() { serde_json::json!({ "ok": false, "error": "missing source" }).to_string() } else { - match crate::host::foreign::run_with_cmd_override( + match crate::host::foreign::invoke_for_view( &root.root, lang, source, cmd, + stdin, + timeout, ) { - Ok(stdout) => serde_json::json!({ "ok": true, "stdout": stdout }).to_string(), + Ok(value) => match crate::host::json::value_to_json(&value) { + Ok(j) => j.to_string(), + Err(e) => serde_json::json!({ "ok": false, "error": e }).to_string(), + }, Err(error) => serde_json::json!({ "ok": false, "error": error }).to_string(), } }; diff --git a/tests/gold.rs b/tests/gold.rs index db8dd45..c368fd5 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -3317,6 +3317,79 @@ fn lib_foreign_zh() { assert_out("tests/lib/外联-python.mq.md", "中文外联"); } +fn node_available() -> bool { + Command::new("node") + .args(["-e", "process.exit(0)"]) + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +#[test] +fn lib_foreign_invoke() { + if !node_available() { + eprintln!("skip lib_foreign_invoke: no node on PATH"); + return; + } + assert_out("tests/lib/foreign-invoke.mq.md", "False\n3\nboom\nFalse"); +} + +#[test] +fn lib_foreign_json() { + if !node_available() { + eprintln!("skip lib_foreign_json: no node on PATH"); + return; + } + assert_out("tests/lib/foreign-json.mq.md", "True\n4\n10"); +} + +#[test] +fn lib_foreign_env_timeout() { + if !node_available() { + eprintln!("skip lib_foreign_env_timeout: no node on PATH"); + return; + } + assert_out( + "tests/lib/foreign-env-timeout.mq.md", + "fast|node\nFalse\nTrue", + ); +} + +#[test] +fn lib_foreign_probe_register() { + if !node_available() { + eprintln!("skip lib_foreign_probe_register: no node on PATH"); + return; + } + assert_out( + "tests/lib/foreign-probe-register.mq.md", + "True\nnode\ntiny", + ); +} + +#[test] +fn lib_foreign_config() { + if !node_available() { + eprintln!("skip lib_foreign_config: no node on PATH"); + return; + } + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["run", "tests/lib/foreign-config.mq.md"]) + .env( + "MARQDO_FOREIGN_CONFIG", + root.join("tests/lib/fixtures/foreign.toml"), + ) + .current_dir(&root) + .output() + .expect("run foreign-config"); + let code = output.status.code().unwrap_or(1); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(code, 0, "foreign-config stderr={stderr}"); + assert_eq!(stdout.trim_end(), "1\ncfg", "stdout={stdout}"); +} + #[test] fn bytecode_lib_math_formula() { assert_out_backend( diff --git a/tests/lib/fixtures/foreign.toml b/tests/lib/fixtures/foreign.toml new file mode 100644 index 0000000..79bc1b1 --- /dev/null +++ b/tests/lib/fixtures/foreign.toml @@ -0,0 +1,2 @@ +[tinycfg] +template = ["node", "-e", "{inline}"] diff --git a/tests/lib/foreign-config.mq.md b/tests/lib/foreign-config.mq.md new file mode 100644 index 0000000..0183caf --- /dev/null +++ b/tests/lib/foreign-config.mq.md @@ -0,0 +1,12 @@ +--- +title: foreign config load +import foreign:lib/foreign.mq.md +--- + +# main + +**载入 = > foreign.load_config** +> print text=`载入` + +**运行 = > foreign.invoke lang="tinycfg" source="console.log('cfg')"** +> print text=[stdout](`运行`) diff --git a/tests/lib/foreign-env-timeout.mq.md b/tests/lib/foreign-env-timeout.mq.md new file mode 100644 index 0000000..9110142 --- /dev/null +++ b/tests/lib/foreign-env-timeout.mq.md @@ -0,0 +1,32 @@ +--- +title: foreign env cwd timeout +import foreign:lib/foreign.mq.md +--- + +# main + +`环境` = + +| MODE | NOTE | +|------|------| +| fast | test | + +`环境检查` = +```node +console.log(process.env.MODE + "|" + process.env.MARQDO_FOREIGN_LANG); +``` + +**检查 = > foreign.invoke code=`环境检查` env=`环境`** +**检查输出 = > trim [stdout](`检查`)** + +> print text=`检查输出` + +`慢` = +```node +setTimeout(() => console.log("late"), 5000); +``` + +**超时 = > foreign.invoke code=`慢` timeout=0.5** + +> print text=[ok](`超时`) +> print text=[timed_out](`超时`) diff --git a/tests/lib/foreign-invoke.mq.md b/tests/lib/foreign-invoke.mq.md new file mode 100644 index 0000000..1523f2f --- /dev/null +++ b/tests/lib/foreign-invoke.mq.md @@ -0,0 +1,19 @@ +--- +title: foreign invoke record +import foreign:lib/foreign.mq.md +--- + +# main + +`失败` = +```node +process.stderr.write("boom"); +process.exit(3); +``` + +**记录 = > foreign.invoke code=`失败`** + +> print text=[ok](`记录`) +> print text=[code](`记录`) +> print text=[stderr](`记录`) +> print text=[truncated](`记录`) diff --git a/tests/lib/foreign-json.mq.md b/tests/lib/foreign-json.mq.md new file mode 100644 index 0000000..465cb80 --- /dev/null +++ b/tests/lib/foreign-json.mq.md @@ -0,0 +1,32 @@ +--- +title: foreign invoke JSON input +import foreign:lib/foreign.mq.md +--- + +# main + +`数值表` = + +| 数值 | +|------| +| 1 | +| 2 | +| 3 | +| 4 | + +`统计` = +```node +let s = ""; +process.stdin.on("data", d => { s += d; }); +process.stdin.on("end", () => { + const xs = JSON.parse(s); + console.log(JSON.stringify({ n: xs.length, sum: xs.reduce((a, b) => a + b, 0) })); +}); +``` + +**记录 = > foreign.invoke code=`统计` input=`数值表` output="json"** +**统计结果 = [result](`记录`)** + +> print text=[ok](`记录`) +> print text=[n](`统计结果`) +> print text=[sum](`统计结果`) diff --git a/tests/lib/foreign-probe-register.mq.md b/tests/lib/foreign-probe-register.mq.md new file mode 100644 index 0000000..c934779 --- /dev/null +++ b/tests/lib/foreign-probe-register.mq.md @@ -0,0 +1,24 @@ +--- +title: foreign probe and register +import foreign:lib/foreign.mq.md +--- + +# main + +**探测 = > foreign.probe lang="node"** +> print text=[ok](`探测`) +> print text=[lang](`探测`) + +`模板` = + +| 步骤 | +|------| +| node | +| "-e" | +| {inline} | + +**> foreign.register lang="tiny" template=`模板`** +**运行 = > foreign.invoke lang="tiny" source="console.log('tiny')"** +**运行输出 = > trim [stdout](`运行`)** +> print text=`运行输出` +**> foreign.unset lang="tiny"**