Ship quantum skill=tools tree with call session and ZH package.

Split ext/quantum into index + modules, add marqdo call --effects/--session/--toget,
narrative-ratio checks, and a same-package 量子/ tree so agents can follow a
decision path for Bell demos without inventing a second API.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-11-08 21:50:01 +08:00
1 parent 492790e985
commit 0e389f34ec
65 files changed
+3714 -1036

No files matched your search

+232 -49
View File
@@ -11,6 +11,7 @@ use anyhow::Result;
use crate::ast::Function;
use crate::bytecode::{compile_for_call, Vm};
use crate::diagnostics::{Diagnostic, Span};
use crate::host::json::json_to_value;
use crate::host::{HostCaps, HostContext};
use crate::interp::Interpreter;
use crate::load::load_module;
@@ -18,40 +19,182 @@ use crate::sema::{compile_file_closure, SemanticArtifact, SemanticProject};
use crate::value::Value;
use crate::Backend;
/// Call `function` in `path` with named arguments.
///
/// Non-pure effects are refused before the function runs. Host write, exec, net,
/// and plugin capabilities stay off for the call.
/// Which host side effects `marqdo call` may perform.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CallEffects {
/// Refuse any non-pure artifact (historical default).
#[default]
None,
/// Allow `plugin.call` (and accompanying `output.write` from load helpers).
Plugin,
}
impl CallEffects {
pub fn parse(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"none" | "" => Ok(Self::None),
"plugin" => Ok(Self::Plugin),
other => Err(call_diag(
None,
0,
"call.bad_effects",
format!("unknown --effects `{other}` (expected none|plugin)"),
)),
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Plugin => "plugin",
}
}
fn host_caps(self) -> HostCaps {
match self {
Self::None => HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: false,
},
Self::Plugin => HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: true,
},
}
}
fn allows(self, effect: &str) -> bool {
match self {
Self::None => effect == "pure",
Self::Plugin => matches!(
effect,
"pure" | "plugin.call" | "output.write" | "time.read" | "random.read"
),
}
}
}
/// Options for one external call.
#[derive(Debug, Clone, Default)]
pub struct CallOptions {
pub effects: CallEffects,
pub session: Option<String>,
pub toget: Option<String>,
}
/// Call `function` in `path` with named arguments (pure-only, no session).
pub fn call_file(
path: &Path,
function: &str,
args: &[(String, Value)],
backend: Backend,
) -> Result<Value> {
call_file_with(path, function, args, backend, CallOptions::default())
}
/// Call with effects / session / toget.
pub fn call_file_with(
path: &Path,
function: &str,
args: &[(String, Value)],
backend: Backend,
opts: CallOptions,
) -> Result<Value> {
let path = path
.canonicalize()
.map_err(|e| call_diag(None, 1, "call.compile", format!("failed to read {}: {e}", path.display())))?;
.map_err(|e| {
call_diag(
None,
1,
"call.compile",
format!("failed to read {}: {e}", path.display()),
)
})?;
let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args)
{
let id = opts
.session
.clone()
.unwrap_or_else(crate::call_session::default_session_id);
Some(crate::call_session::load_session(&id)?)
} else {
None
};
let resolved = if let Some(ref mut sess) = session {
crate::call_session::resolve_args(sess, args, backend)?
} else {
args.to_vec()
};
// Record uses original arg texts (with $refs) so replay can re-resolve.
let record_args = args.to_vec();
let value = call_file_raw(&path, function, &resolved, opts.effects, backend)?;
if let Some(ref mut sess) = session {
crate::call_session::record_step(
sess,
&path,
function,
&record_args,
opts.effects,
opts.toget.as_deref(),
&value,
)?;
crate::call_session::save_session(sess)?;
}
Ok(value)
}
/// Execute without session bookkeeping (used by journal replay).
pub fn call_file_raw(
path: &Path,
function: &str,
args: &[(String, Value)],
effects: CallEffects,
backend: Backend,
) -> Result<Value> {
let path = if path.is_absolute() {
path.to_path_buf()
} else {
path.canonicalize().map_err(|e| {
call_diag(
None,
1,
"call.compile",
format!("failed to read {}: {e}", path.display()),
)
})?
};
let compilation = compile_file_closure(&path).map_err(|e| preserve_diag(&path, e))?;
let artifact = locate_artifact(&compilation.semantics, &path, function)?;
deny_unsafe(&path, artifact)?;
deny_unsafe(&path, artifact, effects)?;
execute_source_function(
&path,
artifact.source.line,
&artifact.display_name,
args,
tight_caps(),
effects.host_caps(),
backend,
true,
)
.map(|(value, _stdout)| value)
}
fn args_need_session(args: &[(String, Value)]) -> bool {
args.iter().any(|(_, v)| {
matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@'))
})
}
/// Run the function declared at `line` in `path`.
///
/// `display_name` is the declaration path (`计算器.加法`). The query the caller
/// typed is not used as a heading search and is not used as the bytecode path,
/// so a unique short name or SymbolId still executes that function.
/// `caps` are the host capabilities for this run. `call` passes them all off.
pub(crate) fn execute_source_function(
path: &Path,
line: u32,
@@ -70,22 +213,20 @@ pub(crate) fn execute_source_function(
format!("无法在 {}:{} 定位函数 {display_name}", path.display(), line),
)
})?;
let expected = display_name
.rsplit('.')
.next()
.unwrap_or(display_name);
let expected = display_name.rsplit('.').next().unwrap_or(display_name);
if fun.name != expected {
return Err(call_diag(
Some(path),
line,
"artifact.unresolved",
format!("源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致", fun.name),
format!(
"源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致",
fun.name
),
));
}
let mut interp = Interpreter::with_capture(Some(path), false)
.with_host(HostContext::for_capture(Some(path), caps));
// `call` checks the signature. `artifact.execute` keeps its previous
// environment injection so an input the body reads is not rejected as unknown.
let bound;
let invoke_args: &[(String, Value)] = if strict_args {
bound = interp.bind_external_args(&module, fun, args)?;
@@ -100,27 +241,53 @@ pub(crate) fn execute_source_function(
}
Backend::Bytecode => {
let program = compile_for_call(Some(path), &module)?;
// Source binding is authoritative even when declaration paths repeat.
let idx = program.functions.iter().position(|chunk|
chunk.module_scope == 0 && chunk.declaration_span == fun.span
&& chunk.name == fun.name && chunk.source.sha256 == module.source.sha256
).ok_or_else(|| {
call_diag(
Some(path),
line,
"artifact.unresolved",
format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"),
)
})?;
let mut vm = Vm::with_capture(Some(path))
.with_host(HostContext::for_capture(Some(path), caps));
let idx = program
.functions
.iter()
.position(|chunk| {
chunk.module_scope == 0
&& chunk.declaration_span == fun.span
&& chunk.name == fun.name
&& chunk.source.sha256 == module.source.sha256
})
.ok_or_else(|| {
call_diag(
Some(path),
line,
"artifact.unresolved",
format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"),
)
})?;
let mut vm =
Vm::with_capture(Some(path)).with_host(HostContext::for_capture(Some(path), caps));
let value = vm.call_function(&program, idx, invoke_args)?;
Ok((value, vm.captured_stdout))
}
}
}
/// Parse `name=value` tokens. Values are integers, decimals, quoted text, or True/False/None.
/// Split trailing `toget <name>` from a clap `args` vector.
pub fn split_toget(tokens: &[String]) -> Result<(Vec<String>, Option<String>)> {
if tokens.len() >= 2 {
let n = tokens.len();
if tokens[n - 2] == "toget" {
let name = tokens[n - 1].clone();
if name.contains('=') {
return Err(call_diag(
None,
0,
"call.bad_toget",
"toget 名字不能含 `=`".into(),
));
}
return Ok((tokens[..n - 2].to_vec(), Some(name)));
}
}
Ok((tokens.to_vec(), None))
}
/// Parse `name=value` tokens. Values are integers, decimals, quoted text, True/False/None,
/// or JSON when the raw value starts with `[` or `{`.
pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> {
let mut out = Vec::new();
for token in tokens {
@@ -148,15 +315,6 @@ pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> {
Ok(out)
}
fn tight_caps() -> HostCaps {
HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: false,
}
}
fn locate_artifact<'a>(
project: &'a SemanticProject,
entry: &Path,
@@ -191,7 +349,17 @@ fn locate_artifact<'a>(
})
.collect()
} else {
Vec::new()
// Nested sub-tools: `outer.helper` matches display path `main.outer.helper`.
let suffix = format!(".{query}");
in_entry
.iter()
.copied()
.filter(|artifact| {
artifact.kind == "function"
&& (artifact.display_name.ends_with(&suffix)
|| artifact.display_name == query)
})
.collect()
};
match hits.len() {
1 => Ok(hits[0]),
@@ -210,7 +378,7 @@ fn locate_artifact<'a>(
}
}
fn deny_unsafe(path: &Path, artifact: &SemanticArtifact) -> Result<()> {
fn deny_unsafe(path: &Path, artifact: &SemanticArtifact, effects: CallEffects) -> Result<()> {
if artifact.kind != "function" || artifact.callable.as_deref() == Some("instance_method") {
return Err(call_diag(
Some(path),
@@ -219,14 +387,21 @@ fn deny_unsafe(path: &Path, artifact: &SemanticArtifact) -> Result<()> {
"只有非实例函数可由 call 直接执行".to_string(),
));
}
if !artifact.effects.is_pure() {
let denied: Vec<String> = artifact
.effects
.values()
.into_iter()
.filter(|e| !effects.allows(e))
.collect();
if !denied.is_empty() {
return Err(call_diag(
Some(path),
artifact.source.line,
"artifact.effect_denied",
format!(
"call 默认只执行纯函数,拒绝效应 {}",
artifact.effects.values().join(", ")
"call --effects {} 拒绝效应 {}",
effects.as_str(),
denied.join(", ")
),
));
}
@@ -260,6 +435,9 @@ fn parse_literal(raw: &str) -> Result<Value, String> {
"None" | "none" => return Ok(Value::None),
_ => {}
}
if raw.starts_with('$') || raw.starts_with('@') {
return Ok(Value::Text(raw.to_string()));
}
if raw.len() >= 2 {
let bytes = raw.as_bytes();
if (bytes[0] == b'"' && bytes[raw.len() - 1] == b'"')
@@ -268,6 +446,11 @@ fn parse_literal(raw: &str) -> Result<Value, String> {
return Ok(Value::Text(raw[1..raw.len() - 1].to_string()));
}
}
if raw.starts_with('[') || raw.starts_with('{') {
let json: serde_json::Value =
serde_json::from_str(raw).map_err(|e| format!("JSON 解析失败: {e}"))?;
return json_to_value(&json);
}
if let Ok(n) = raw.parse::<i64>() {
return Ok(Value::Int(n));
}
@@ -277,7 +460,7 @@ fn parse_literal(raw: &str) -> Result<Value, String> {
}
}
Err(format!(
"无法解析 `{raw}`(整数、小数、引号文本、True/False/None)"
"无法解析 `{raw}`(整数、小数、引号文本、True/False/None、JSON、`$name`)"
))
}