feat(foreign): structured invoke, presets, probe and config
F0/F1: safe execution core (exec gate, bounded IO, process-group timeout), structured invoke records, run options, 15 language presets, register/unset/probe/config, view stderr/exit/ms, and node/bash gold tests.
This commit is contained in:
1 parent
c21a28c3bc
commit
e32ff8f6b3
21 files changed
+2301
-282
No files matched your search
+47
-5
@@ -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(),
|
||||
}
|
||||
|
||||
+42
-23
@@ -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<Vec<String>> {
|
||||
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<String> {
|
||||
#[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<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut quote: Option<char> = 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).
|
||||
|
||||
@@ -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<String>,
|
||||
/// Optional full argv template; supports `{file}`/`{inline}`/… placeholders.
|
||||
pub template: Option<Vec<String>>,
|
||||
pub ext: Option<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
/// Arguments appended to the executable for `probe` (e.g. `--version`).
|
||||
pub version_args: Vec<String>,
|
||||
/// Persistent session bootstrap available.
|
||||
pub session: bool,
|
||||
/// Directory for resolving a relative interpreter path (config file dir).
|
||||
pub base_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
#[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<LangSpec> {
|
||||
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<String> {
|
||||
[
|
||||
"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<Vec<String>> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
+141
-3
@@ -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")]
|
||||
{
|
||||
|
||||
+1468
-224
File diff suppressed because it is too large.
Load diff
+10
-1
@@ -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<PlotArtifact>,
|
||||
/// lang → interpreter argv (from `set_cmd`).
|
||||
pub foreign_cmds: HashMap<String, Vec<String>>,
|
||||
/// Process-local language registrations (`register` / `set_cmd`).
|
||||
pub foreign_specs: HashMap<String, crate::foreign::registry::LangSpec>,
|
||||
/// Project config specs (`.marqdo/foreign.toml`), lower priority than runtime.
|
||||
pub foreign_config_specs: HashMap<String, crate::foreign::registry::LangSpec>,
|
||||
/// 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,
|
||||
|
||||
+13
-7
@@ -120,8 +120,8 @@ fn republish_child_event(line: &str) {
|
||||
pub(crate) struct ForeignTask {
|
||||
child: Child,
|
||||
temp_script: PathBuf,
|
||||
stdout: JoinHandle<String>,
|
||||
stderr: JoinHandle<String>,
|
||||
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<Value, String> {
|
||||
.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<Value, String> {
|
||||
out.pop();
|
||||
}
|
||||
}
|
||||
if out_trunc || err_trunc {
|
||||
out.push_str("\n…(truncated)");
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -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");
|
||||
|
||||
+11
-2
@@ -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");
|
||||
|
||||
+9
-2
@@ -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(),
|
||||
}
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user