feat(workbench): land M00–M06 runtime contracts and read-only view

Add capabilities/selection/usage/DocumentView/locator/RunContext with
honest probes, LLM messages+cancel, sse-live cancel bridge, and CI
workbench_contracts gate; record design evidence for verified slices.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-25 10:55:08 +08:00
1 parent 663a8ba2c0
commit 03396afd02
41 files changed
+2997 -68

No files matched your search

+9 -3
View File
@@ -193,8 +193,12 @@ fn extract_markdown_or_text(
) -> ExtractedDocument {
let mut segments = Vec::new();
let mut n = 0u32;
let mut byte_off = 0usize;
for (i, line) in text.lines().enumerate() {
let line_no = i + 1;
let line_bytes = line.len();
// M05: stable fragment locator with 1-based line + UTF-8 byte offset.
let loc = |kind: &str| format!("{kind}:L{line_no}:B{byte_off}");
if let Some(rest) = line.trim().strip_prefix('#') {
n += 1;
let heading = rest.trim_start_matches('#').trim();
@@ -202,7 +206,7 @@ fn extract_markdown_or_text(
id: format!("seg-{n}"),
kind: "heading".into(),
text: heading.to_string(),
locator: format!("L{line_no}"),
locator: loc("heading"),
confidence: 1.0,
});
} else if line.trim().starts_with('|') {
@@ -211,7 +215,7 @@ fn extract_markdown_or_text(
id: format!("seg-{n}"),
kind: "table_row".into(),
text: line.to_string(),
locator: format!("L{line_no}"),
locator: loc("table_row"),
confidence: 0.9,
});
} else if !line.trim().is_empty() {
@@ -220,10 +224,12 @@ fn extract_markdown_or_text(
id: format!("seg-{n}"),
kind: "paragraph".into(),
text: line.to_string(),
locator: format!("L{line_no}"),
locator: loc("paragraph"),
confidence: 1.0,
});
}
// +1 for '\n' when present in original (lines() strips it).
byte_off += line_bytes + 1;
}
ExtractedDocument {
source_uri: uri.to_string(),
+16
View File
@@ -331,6 +331,22 @@ fn spawn_file(
));
let _ = std::fs::write(&events_path, "");
cmd.env("MARQDO_EVENT_FORWARD", &events_path);
// Propagate run/selection identity when parent has them (api_key stays via process inheritance).
for key in [
"MARQDO_RUN_ID",
"MARQDO_PARENT_RUN_ID",
"MARQDO_TURN_ID",
"MARQDO_WORKSPACE_SCOPE",
"MARQDO_CANCEL_TOKEN",
"MARQDO_LLM_MODEL",
"MARQDO_LLM_BASE_URL",
"OPENAI_MODEL",
"OPENAI_BASE_URL",
] {
if let Ok(v) = std::env::var(key) {
cmd.env(key, v);
}
}
let mut child = cmd
.spawn()
+1
View File
@@ -37,6 +37,7 @@ pub mod lex;
pub mod linalg_ops;
pub mod load;
pub mod mlsp;
pub mod workbench;
pub mod parse;
pub mod project;
pub mod repair;
+112 -2
View File
@@ -68,17 +68,34 @@ fn dispatch(req: &Value) -> Result<Value, Value> {
Some("document.extract") => document_extract(&params),
Some("artifact.patch") => artifact_patch(&params),
Some("artifact.extract_pure") => artifact_extract_pure(&params),
// Workbench M00–M04: capability probe + read-only view + locator.
Some("capabilities") => Ok(crate::workbench::probe_capabilities(&params)),
#[cfg(feature = "view")]
Some("view.document") => view_document(&params),
#[cfg(not(feature = "view"))]
Some("view.document") => Err(err(
"mlsp.unsupported",
"view.document requires the view feature",
)),
Some("view.reference_resolve") => crate::workbench::resolve_reference(&params),
// `<TAB>` M9: occlusion label search (two-tier vocabulary).
Some("labels.search") => labels_search(&params),
// `<TAB>` M6: one-shot session summary (T1 staleness seen/fixed).
Some("session.summary") => session_summary(),
other => Err(err(
"mlsp.unknown_method",
format!("未知方法 {other:?};可用:locate / syntax / validate / repair_targets / repair_apply / schema / artifact.find / artifact.inspect / link.resolve / artifact.verify / artifact.impact / artifact.bind / artifact.execute / artifact.reuse_execute / artifact.patch / artifact.extract_pure / document.extract"),
format!("未知方法 {other:?};可用:locate / syntax / validate / repair_targets / repair_apply / schema / artifact.find / artifact.inspect / link.resolve / artifact.verify / artifact.impact / artifact.bind / artifact.execute / artifact.reuse_execute / artifact.patch / artifact.extract_pure / document.extract / capabilities / view.document / view.reference_resolve"),
)),
}
}
#[cfg(feature = "view")]
fn view_document(params: &Value) -> Result<Value, Value> {
let req = crate::workbench::DocumentViewRequest::from_params(params)
.map_err(|e| err("mlsp.bad_request", e))?;
crate::workbench::build_document_view(&req)
}
fn artifact_extract_pure(params: &Value) -> Result<Value, Value> {
let name = params
.get("name")
@@ -172,7 +189,100 @@ fn artifact_inspect(params: &Value) -> Result<Value, Value> {
let candidates = artifact_query(&compilation.semantics, query);
if candidates.is_empty() { return Err(err("artifact.unresolved", format!("没有制品 `{query}`"))); }
if candidates.len() != 1 { return Err(json!({"code":"artifact.ambiguous","message":format!("制品 `{query}` 不唯一"),"candidates":candidates.iter().map(|a|&a.artifact_id.0).collect::<Vec<_>>() })); }
Ok(crate::sema::artifact_json(candidates[0]))
let artifact = candidates[0];
// Version contract: expected source/generation mismatch must not silently return current.
check_artifact_version_params(params, &compilation, artifact)?;
Ok(crate::sema::artifact_json(artifact))
}
/// Reject inspect when caller pinned an expected source revision or generation that
/// does not match the current project snapshot (`artifact.version_mismatch`).
fn check_artifact_version_params(
params: &Value,
compilation: &crate::sema::Compilation,
artifact: &crate::sema::SemanticArtifact,
) -> Result<(), Value> {
let expected_rev = params
.get("expected_source_revision")
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
if let Some(expected) = expected_rev {
let project_root = params
.get("project")
.or_else(|| params.get("path"))
.and_then(Value::as_str)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
let root = if project_root.is_file() {
project_root
.parent()
.unwrap_or_else(|| Path::new("."))
.to_path_buf()
} else {
project_root
};
let abs = root.join(&artifact.source.file);
match std::fs::read(&abs) {
Ok(raw) => {
use sha2::{Digest, Sha256};
let actual = format!("sha256:{:x}", Sha256::digest(&raw));
if actual != expected {
return Err(json!({
"code": "artifact.version_mismatch",
"message": format!(
"expected source_revision {expected}, actual {actual}; refusing silent downgrade"
),
"expected_source_revision": expected,
"actual_source_revision": actual,
"artifact_id": artifact.artifact_id.0,
}));
}
}
Err(e) => {
return Err(json!({
"code": "artifact.version_mismatch",
"message": format!(
"cannot verify source_revision for {}: {e}; refusing silent downgrade",
artifact.source.file
),
"expected_source_revision": expected,
"artifact_id": artifact.artifact_id.0,
}));
}
}
}
let expected_gen = params
.get("expected_generation")
.or_else(|| params.get("generation_id"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
if let Some(expected) = expected_gen {
let actual = semantic_generation_id(&compilation.semantics);
if actual != expected {
return Err(json!({
"code": "artifact.version_mismatch",
"message": format!(
"expected generation {expected}, current projection is {actual}; refusing silent downgrade"
),
"expected_generation": expected,
"actual_generation": actual,
"artifact_id": artifact.artifact_id.0,
}));
}
}
Ok(())
}
/// Semantic generation token matching KnowledgePresentation / DocumentView.
fn semantic_generation_id(project: &crate::sema::SemanticProject) -> String {
use sha2::{Digest, Sha256};
let mut gh = Sha256::new();
gh.update(project.project_id.as_bytes());
for a in &project.artifacts {
gh.update(a.hashes.artifact.0.as_bytes());
}
format!("{:x}", gh.finalize())[..16].to_string()
}
fn link_resolve(params: &Value) -> Result<Value, Value> {
+17 -1
View File
@@ -127,7 +127,11 @@ impl KnowledgePresentation {
}
}
/// V2: whether an SSE result packet may update the live document structure.
/// Live View SSE: whether a result packet may update the document structure.
///
/// Legacy packets without a token are accepted so older live-view clients keep
/// working. **Embedded DocumentView clients must use [`sse_accepts_packet_strict`]
/// instead** — missing/empty tokens and mismatches are rejected there.
pub fn sse_accepts_packet(page_token: &str, packet_token: Option<&str>) -> bool {
match packet_token {
None | Some("") => true, // legacy packets without token still apply
@@ -136,6 +140,18 @@ pub fn sse_accepts_packet(page_token: &str, packet_token: Option<&str>) -> bool
}
}
/// Strict SSE / embed gate: reject missing, empty, or mismatched page tokens.
///
/// Use this for DocumentView / qdagent embed hosts. Do not inherit the live-view
/// leniency of [`sse_accepts_packet`].
pub fn sse_accepts_packet_strict(page_token: &str, packet_token: Option<&str>) -> bool {
match packet_token {
None | Some("") => false,
Some(_tok) if page_token.is_empty() => false,
Some(tok) => tok == page_token,
}
}
/// Stable page token from raw source bytes (used by SSE run path).
pub fn page_token_from_source(rel: &str, source: &str) -> String {
let mut h = Sha256::new();
+7 -2
View File
@@ -12,12 +12,17 @@ mod output;
mod render;
pub use knowledge_present::{
page_token_from_source, sse_accepts_packet, title_from_source, KnowledgePresentation,
page_token_from_source, sse_accepts_packet, sse_accepts_packet_strict, title_from_source,
KnowledgePresentation,
};
/// Surface rendering of an expression (labels/diagnostics reuse). `<TAB>` M6
pub use render::expr_display;
/// Read-model HTML helpers for embedded DocumentView (M03) — never execute.
pub use document::render_module_document;
pub use render::render_knowledge_html;
pub use output::{write_capture, write_static, CaptureOptions, OutputOptions};
use std::fs;
@@ -37,7 +42,7 @@ use crate::view::html::{escape, page_file, page_index, LinkMode};
use crate::view::annot::{build_view_annots, view_execution_report_json};
use crate::view::render::{
collect_input_prompts, render_bindings_html, render_module_structure,
render_knowledge_html, render_module_structure_with_annots, render_right_rail, uses_stream_panel, FileViewModel,
render_module_structure_with_annots, render_right_rail, uses_stream_panel, FileViewModel,
};
use crate::{run_file_capture, RunOptions};
+87
View File
@@ -0,0 +1,87 @@
//! Project snapshot analysis cache (M05 / F14): keyed by project_root + source digests.
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use std::time::Instant;
#[derive(Clone)]
struct CacheEntry {
digest_key: String,
#[allow(dead_code)]
compiled_at: Instant,
}
fn cache() -> &'static Mutex<HashMap<String, CacheEntry>> {
static C: OnceLock<Mutex<HashMap<String, CacheEntry>>> = OnceLock::new();
C.get_or_init(|| Mutex::new(HashMap::new()))
}
/// Fingerprint of authorized project sources (shallow: entry + .mq.md under root, capped).
pub fn project_source_digest(project_root: &Path) -> String {
let mut h = Sha256::new();
h.update(project_root.to_string_lossy().as_bytes());
let mut paths: Vec<PathBuf> = Vec::new();
if let Ok(rd) = std::fs::read_dir(project_root) {
for ent in rd.flatten().take(200) {
let p = ent.path();
if p.extension().and_then(|e| e.to_str()) == Some("md")
|| p
.file_name()
.and_then(|n| n.to_str())
.map(|n| n.ends_with(".mq.md"))
.unwrap_or(false)
{
paths.push(p);
}
}
}
paths.sort();
for p in paths {
h.update(p.to_string_lossy().as_bytes());
if let Ok(bytes) = std::fs::read(&p) {
h.update(&bytes);
}
}
format!("{:x}", h.finalize())
}
/// Record/reuse analysis for concurrent same-snapshot reads. Returns true if cache hit.
pub fn note_analysis(project_root: &Path) -> bool {
let key = project_root
.canonicalize()
.unwrap_or_else(|_| project_root.to_path_buf())
.to_string_lossy()
.to_string();
let digest = project_source_digest(project_root);
let mut g = cache().lock().unwrap();
if let Some(e) = g.get(&key) {
if e.digest_key == digest {
return true;
}
}
g.insert(
key,
CacheEntry {
digest_key: digest,
compiled_at: Instant::now(),
},
);
false
}
/// Two project roots must not share cache entries even with identical relative paths.
pub fn cache_keys_isolated(a: &Path, b: &Path) -> bool {
let ka = a
.canonicalize()
.unwrap_or_else(|_| a.to_path_buf())
.to_string_lossy()
.to_string();
let kb = b
.canonicalize()
.unwrap_or_else(|_| b.to_path_buf())
.to_string_lossy()
.to_string();
ka != kb
}
+213
View File
@@ -0,0 +1,213 @@
//! MLSP `capabilities` — probe loaded plugins and declared features (M00 / F16).
//! Feature integers must reflect *implemented and testable* behavior only.
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
/// Host/tests may force stream/cancel off for honesty / F16 mismatch cases.
static FORCE_STREAM_OFF: AtomicBool = AtomicBool::new(false);
static FORCE_CANCEL_OFF: AtomicBool = AtomicBool::new(false);
pub fn set_event_stream_ready(ready: bool) {
FORCE_STREAM_OFF.store(!ready, Ordering::Relaxed);
}
pub fn set_cancel_ready(ready: bool) {
FORCE_CANCEL_OFF.store(!ready, Ordering::Relaxed);
}
/// Build the capabilities document. Does not call providers or execute project code.
pub fn probe_capabilities(params: &Value) -> Value {
let runtime_version = env!("CARGO_PKG_VERSION").to_string();
let mut adapters = vec![json!({
"id": "openai-compatible",
"available": true,
"notes": "HTTP chat completions; messages[] preferred over single prompt"
})];
adapters.push(json!({
"id": "ollama-compatible",
"available": true,
"notes": "OpenAI-compatible path; not a distinct native protocol"
}));
adapters.push(json!({
"id": "anthropic-native",
"available": false,
"notes": "not verified in this release"
}));
adapters.push(json!({
"id": "gemini-native",
"available": false,
"notes": "not verified in this release"
}));
let extract_formats = vec![
json!({"format": "text", "available": true}),
json!({"format": "markdown", "available": true}),
json!({"format": "pdf", "available": false}),
json!({"format": "docx", "available": false}),
json!({"format": "ocr", "available": false}),
];
let loaded_plugins = probe_loaded_plugins(params);
let llm_loaded = loaded_plugins.iter().any(|p| {
p.get("name").and_then(|n| n.as_str()) == Some("llm")
&& p.get("available").and_then(|a| a.as_bool()) == Some(true)
});
let stream_off = FORCE_STREAM_OFF.load(Ordering::Relaxed)
|| params
.get("force_stream_off")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let cancel_off = FORCE_CANCEL_OFF.load(Ordering::Relaxed)
|| params
.get("force_cancel_off")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let mut features = serde_json::Map::new();
features.insert(
"llm.explicit_selection".into(),
json!(if llm_loaded { 1 } else { 0 }),
);
features.insert(
"llm.call_usage".into(),
json!(if llm_loaded { 1 } else { 0 }),
);
features.insert(
"llm.messages".into(),
json!(if llm_loaded { 1 } else { 0 }),
);
// M02 implemented: event_sink + web sse-live + MARQDO_CANCEL in llm plugin.
features.insert(
"runtime.event_stream".into(),
json!(if stream_off { 0 } else { 1 }),
);
features.insert(
"runtime.cancel".into(),
json!(if cancel_off { 0 } else { 1 }),
);
#[cfg(feature = "view")]
{
features.insert("view.document".into(), json!(1));
features.insert("view.reference_resolve".into(), json!(1));
}
#[cfg(not(feature = "view"))]
{
features.insert("view.document".into(), json!(0));
features.insert("view.reference_resolve".into(), json!(0));
}
json!({
"schema_version": 1,
"runtime_version": runtime_version,
"features": features,
"adapters": adapters,
"extract_formats": extract_formats,
"loaded_plugins": loaded_plugins,
"contracts": [
"ModelSelectionV1",
"ModelCallUsageV1",
"RuntimeEventV1",
"DocumentViewV1",
"KnowledgeLocatorV1"
]
})
}
fn probe_loaded_plugins(params: &Value) -> Vec<Value> {
let mut out = Vec::new();
let candidates = [
("llm", "MARQDO_LLM_PLUGIN", plugin_name("llm")),
("agent", "MARQDO_AGENT_PLUGIN", plugin_name("agent")),
("web", "MARQDO_WEB_PLUGIN", plugin_name("web")),
];
let ext_hint = params
.get("ext_root")
.and_then(|v| v.as_str())
.map(PathBuf::from)
.or_else(|| std::env::var_os("MARQDO_EXT").map(PathBuf::from));
let force_unloaded = params
.get("force_unloaded")
.and_then(|v| v.as_bool())
.unwrap_or(false);
for (name, env_key, filename) in candidates {
if force_unloaded {
out.push(json!({
"name": name,
"available": false,
"path": Value::Null,
"capabilities": [],
}));
continue;
}
let mut path: Option<PathBuf> = std::env::var_os(env_key).map(PathBuf::from);
if path.as_ref().map(|p| !p.is_file()).unwrap_or(true) {
let debug = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("debug")
.join(&filename);
if debug.is_file() {
path = Some(debug);
}
}
if path.as_ref().map(|p| !p.is_file()).unwrap_or(true) {
if let Some(ext) = &ext_hint {
let native = ext.join("native").join(&filename);
if native.is_file() {
path = Some(native);
}
}
}
let available = path.as_ref().map(|p| p.is_file()).unwrap_or(false);
let mut caps = Vec::new();
if name == "llm" && available {
caps.push("call_usage_v1");
caps.push("messages_v1");
caps.push("explicit_selection_v1");
caps.push("cancel_v1");
}
if name == "agent" && available {
caps.push("eng_bind_execute");
caps.push("publish_gate");
}
out.push(json!({
"name": name,
"available": available,
"path": path.map(|p| p.to_string_lossy().to_string()),
"capabilities": caps,
}));
}
out
}
fn plugin_name(stem: &str) -> String {
if cfg!(windows) {
format!("{stem}.dll")
} else if cfg!(target_os = "macos") {
format!("lib{stem}.dylib")
} else {
format!("lib{stem}.so")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn force_off_and_unloaded_honest() {
let caps = probe_capabilities(&json!({
"force_unloaded": true,
"force_stream_off": true,
"force_cancel_off": true,
}));
assert_eq!(caps["features"]["runtime.event_stream"], 0);
assert_eq!(caps["features"]["runtime.cancel"], 0);
assert_eq!(caps["features"]["llm.messages"], 0);
}
}
+427
View File
@@ -0,0 +1,427 @@
//! DocumentViewV1 — read-only embedded view (M03). Never executes the document.
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use crate::view::{render_knowledge_html, render_module_document, KnowledgePresentation};
#[derive(Debug, Clone)]
pub struct DocumentViewRequest {
pub project: PathBuf,
pub document: String,
pub revision: Option<String>,
pub generation: Option<String>,
pub node_id: Option<String>,
pub include: Vec<String>,
}
impl DocumentViewRequest {
pub fn from_params(params: &Value) -> Result<Self, String> {
let project = params
.get("project")
.and_then(|v| v.as_str())
.ok_or_else(|| "view.document requires params.project".to_string())?;
let document = params
.get("document")
.and_then(|v| v.as_str())
.ok_or_else(|| "view.document requires params.document".to_string())?;
let mode = params
.get("mode")
.and_then(|v| v.as_str())
.unwrap_or("read");
if mode != "read" {
return Err(format!("view.document unsupported mode={mode}; only read"));
}
let include = match params.get("include") {
Some(Value::Array(a)) => a
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect(),
_ => vec![
"fragment".into(),
"outline".into(),
"nodes".into(),
"refs".into(),
"diagnostics".into(),
],
};
Ok(Self {
project: PathBuf::from(project),
document: document.to_string(),
revision: params
.get("revision")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
generation: params
.get("generation")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
node_id: params
.get("node_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
include,
})
}
}
/// Pure read path: compile_project (no plugin load / no eval) + fragment render.
/// Must never call `build_file_view` with execute=true.
pub fn build_document_view(req: &DocumentViewRequest) -> Result<Value, Value> {
let project_root = canonicalize_project(&req.project)?;
let abs = resolve_under(&project_root, &req.document)?;
let raw = fs::read(&abs).map_err(|e| {
err(
"view.document_read_failed",
format!("cannot read {}: {e}", abs.display()),
)
})?;
let source_revision = format!("sha256:{:x}", Sha256::digest(&raw));
if let Some(expected) = &req.revision {
if expected != &source_revision && !expected.is_empty() {
return Err(err(
"view.revision_mismatch",
format!("requested {expected} but file is {source_revision}; refusing silent downgrade"),
));
}
}
let source = String::from_utf8_lossy(&raw).into_owned();
let title = title_from_source(&source, &req.document);
// Semantic projection — compile_project does not load plugins / evaluate.
// Analysis cache is keyed by project_root + source digests (M05 isolation).
let _cache_hit = crate::workbench::analysis_cache::note_analysis(&project_root);
let options = crate::sema::CompileOptions::for_path(&project_root)
.map_err(|e| err("view.compile_failed", format!("{e:#}")))?;
let compilation = crate::sema::compile_project(&options)
.map_err(|e| err("view.compile_failed", format!("{e:#}")))?;
let rel = req.document.replace('\\', "/");
let mut presentation = KnowledgePresentation::from_project(&compilation.semantics, &rel, &title);
presentation.page_token = {
let mut h = Sha256::new();
h.update(raw.as_slice());
h.update(presentation.semantic_generation.as_bytes());
format!("{:x}", h.finalize())
};
if let Some(gen) = &req.generation {
if !gen.is_empty() && gen != &presentation.semantic_generation {
return Err(err(
"view.generation_mismatch",
format!(
"requested generation {gen} but projection is {}; refusing silent downgrade",
presentation.semantic_generation
),
));
}
}
let wants = |k: &str| req.include.iter().any(|x| x == k);
let heading_outline = outline_from_headings(&source, &presentation);
// Prefer document surface HTML when parseable; fall back to knowledge HTML.
// Never call build_file_view (that path executes).
let fragment = if wants("fragment") {
let raw_html = match crate::load::parse_source_auto(&source) {
Ok(module) => render_module_document(&module, &source, &[]),
Err(_) => render_knowledge_html(&compilation.semantics, &rel),
};
wrap_fragment(&inject_mq_node_attrs(&raw_html, &heading_outline, &presentation))
} else {
String::new()
};
let outline = if wants("outline") {
if heading_outline.is_empty() {
outline_from_presentation(&presentation)
} else {
json!(heading_outline)
}
} else {
json!([])
};
let nodes = if wants("nodes") {
nodes_from_presentation(&presentation, &req.node_id)
} else {
json!([])
};
let refs = if wants("refs") {
refs_from_project(&compilation.semantics, &rel)
} else {
json!([])
};
let mut diag_msgs: Vec<String> = presentation.diagnostics.clone();
for d in &compilation.diagnostics {
diag_msgs.push(d.message.clone());
}
let diagnostics = if wants("diagnostics") {
json!(diag_msgs)
} else {
json!([])
};
let completeness = if diag_msgs.is_empty() {
"complete"
} else {
"partial"
};
Ok(json!({
"schema": "DocumentViewV1",
"schema_version": 1,
"document": {
"id": rel,
"title": title,
"source_revision": source_revision,
"semantic_digest": presentation.source_digest,
"generation_id": if presentation.semantic_generation.is_empty() {
Value::Null
} else {
json!(presentation.semantic_generation)
},
"presentation_token": presentation.page_token,
},
"execution": {"state": "not_run", "run_id": Value::Null},
"render": {
"format": "sanitized_html",
"fragment": fragment,
"renderer_version": "1"
},
"outline": outline,
"nodes": nodes,
"refs": refs,
"diagnostics": diagnostics,
"completeness": completeness,
"capabilities": {"read_only": true, "has_semantics": true, "executed": false}
}))
}
fn wrap_fragment(inner: &str) -> String {
// No html/body, no scripts, namespaced for host theming.
let sanitized = strip_script_tags(inner);
format!("<article class=\"mq-document\">{sanitized}</article>")
}
/// Remove `<script…>` blocks (case-insensitive) so embed fragments stay non-executable.
fn strip_script_tags(html: &str) -> String {
let lower = html.to_ascii_lowercase();
let mut out = String::with_capacity(html.len());
let mut i = 0usize;
while i < html.len() {
if lower[i..].starts_with("<script") {
let after_open = lower[i..]
.find('>')
.map(|p| i + p + 1)
.unwrap_or(html.len());
if let Some(rel) = lower[after_open..].find("</script") {
let close_at = after_open + rel;
let end = lower[close_at..]
.find('>')
.map(|p| close_at + p + 1)
.unwrap_or(html.len());
i = end;
} else {
// Truncate from the dangerous open tag onward.
break;
}
continue;
}
// Advance one UTF-8 char so multi-byte text stays intact.
let ch = html[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
out
}
fn title_from_source(source: &str, fallback: &str) -> String {
for line in source.lines().take(40) {
let t = line.trim();
if let Some(rest) = t.strip_prefix("# ") {
return rest.trim().to_string();
}
if let Some(rest) = t.strip_prefix("title:") {
return rest.trim().trim_matches('"').to_string();
}
}
Path::new(fallback)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or(fallback)
.to_string()
}
/// Outline entries from Markdown / Marqdo `#` headings; prefer matching node ids.
fn outline_from_headings(source: &str, p: &KnowledgePresentation) -> Vec<Value> {
let mut items = Vec::new();
let mut order = 0usize;
for (idx, line) in source.lines().enumerate() {
let line_no = (idx + 1) as u32;
let trimmed = line.trim_start();
if !trimmed.starts_with('#') {
continue;
}
let hashes = trimmed.chars().take_while(|c| *c == '#').count();
if hashes == 0 || hashes > 6 {
continue;
}
// `# Title`, `## Section`, or Marqdo `#main` / `##greet` (no space).
let after = &trimmed[hashes..];
let label = after.trim();
if label.is_empty() {
continue;
}
let matched = p.nodes.iter().find(|n| {
n.source_line == line_no
|| n.display_name == label
|| n.node_id == label
|| n.artifact_id.as_deref() == Some(label)
});
let id = matched
.map(|n| n.node_id.clone())
.unwrap_or_else(|| format!("heading:{line_no}"));
let artifact_id = matched.and_then(|n| n.artifact_id.clone());
items.push(json!({
"id": id,
"parent_id": Value::Null,
"kind": "heading",
"label": label,
"order": order,
"source_span": {"line": line_no},
"artifact_id": artifact_id,
}));
order += 1;
}
items
}
/// Stamp `data-mq-node` onto elements that already carry `data-line` matching a node/outline id.
fn inject_mq_node_attrs(html: &str, outline: &[Value], p: &KnowledgePresentation) -> String {
let mut out = html.to_string();
let mut bindings: Vec<(u32, String)> = Vec::new();
for n in &p.nodes {
bindings.push((n.source_line, n.node_id.clone()));
}
for item in outline {
if let (Some(line), Some(id)) = (
item.pointer("/source_span/line").and_then(|v| v.as_u64()),
item.get("id").and_then(|v| v.as_str()),
) {
bindings.push((line as u32, id.to_string()));
}
}
bindings.sort_by_key(|(line, _)| *line);
bindings.dedup_by_key(|(line, _)| *line);
for (line, id) in bindings {
let needle = format!("data-line=\"{line}\"");
let attr = format!("data-line=\"{line}\" data-mq-node=\"{}\"", html_attr_escape(&id));
if out.contains(&needle) && !out.contains(&format!("data-mq-node=\"{}\"", html_attr_escape(&id))) {
out = out.replacen(&needle, &attr, 1);
}
}
out
}
fn html_attr_escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('"', "&quot;")
.replace('<', "&lt;")
}
fn outline_from_presentation(p: &KnowledgePresentation) -> Value {
json!(p
.nodes
.iter()
.enumerate()
.map(|(i, n)| json!({
"id": n.node_id,
"parent_id": Value::Null,
"kind": "heading",
"label": n.display_name,
"order": i,
"artifact_id": n.artifact_id,
}))
.collect::<Vec<_>>())
}
fn nodes_from_presentation(p: &KnowledgePresentation, filter: &Option<String>) -> Value {
json!(p
.nodes
.iter()
.filter(|n| filter.as_ref().map(|f| &n.node_id == f || n.artifact_id.as_ref() == Some(f)).unwrap_or(true))
.map(|n| json!({
"id": n.node_id,
"parent_id": Value::Null,
"kind": n.kind,
"label": n.display_name,
"order": n.source_line,
"source_span": {"file": n.source_file, "line": n.source_line},
"artifact_id": n.artifact_id,
"ref_ids": [],
"children": [],
"evidence": n.evidence,
"effects": n.effects,
"dependencies": n.dependencies,
"signature": n.signature,
}))
.collect::<Vec<_>>())
}
fn refs_from_project(project: &crate::sema::SemanticProject, rel: &str) -> Value {
let mut refs = Vec::new();
for a in &project.artifacts {
if a.source.file != rel {
continue;
}
for dep in &a.dependencies {
refs.push(json!({
"id": format!("ref:{}:{}", a.artifact_id.0, dep.0),
"from_artifact_id": a.artifact_id.0,
"to": dep.0,
"relation": "depends_on",
}));
}
}
json!(refs)
}
fn canonicalize_project(p: &Path) -> Result<PathBuf, Value> {
let root = if p.is_file() {
p.parent().unwrap_or_else(|| Path::new(".")).to_path_buf()
} else {
p.to_path_buf()
};
root.canonicalize().map_err(|e| {
err(
"view.project_invalid",
format!("project {}: {e}", root.display()),
)
})
}
fn resolve_under(root: &Path, rel: &str) -> Result<PathBuf, Value> {
let joined = root.join(rel);
let canon = joined.canonicalize().map_err(|e| {
err(
"view.document_not_found",
format!("{}: {e}", joined.display()),
)
})?;
if !canon.starts_with(root) {
return Err(err(
"view.path_escape",
"document path escapes project root",
));
}
Ok(canon)
}
fn err(code: &str, message: impl Into<String>) -> Value {
json!({"code": code, "message": message.into()})
}
+59
View File
@@ -0,0 +1,59 @@
//! Request-local RuntimeEventV1 sink (M02). Avoids process-global event mix-up.
use serde_json::{json, Value};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
static SEQ: AtomicU64 = AtomicU64::new(0);
fn sink_path() -> &'static Mutex<Option<PathBuf>> {
static SINK: OnceLock<Mutex<Option<PathBuf>>> = OnceLock::new();
SINK.get_or_init(|| Mutex::new(None))
}
/// Bind this process/request to an NDJSON event file (also used by web sse-live).
pub fn bind_event_sink(path: impl AsRef<Path>) {
if let Ok(mut g) = sink_path().lock() {
*g = Some(path.as_ref().to_path_buf());
}
crate::workbench::capabilities::set_event_stream_ready(true);
}
pub fn clear_event_sink() {
if let Ok(mut g) = sink_path().lock() {
*g = None;
}
}
pub fn emit_event(run_id: &str, event_type: &str, payload: Value) -> Value {
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let event_id = format!("evt-{run_id}-{seq}");
let ev = crate::workbench::usage::runtime_event(&event_id, seq, run_id, event_type, payload);
if let Ok(g) = sink_path().lock() {
if let Some(path) = g.as_ref() {
if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(path) {
let _ = writeln!(f, "{}", ev);
}
}
}
// Also honor MARQDO_EVENT_FORWARD for subtask/web bridge.
if let Ok(fwd) = std::env::var("MARQDO_EVENT_FORWARD") {
if !fwd.is_empty() {
if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&fwd) {
let _ = writeln!(f, "{}", ev);
}
}
}
ev
}
pub fn emit_message_delta(run_id: &str, text: &str) -> Value {
emit_event(
run_id,
"message.delta",
json!({"text": text, "format": "plain"}),
)
}
+312
View File
@@ -0,0 +1,312 @@
//! KnowledgeLocatorV1 + view.reference_resolve (M04).
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
#[derive(Debug, Clone)]
pub struct KnowledgeLocator {
pub project_id: String,
pub document_id: String,
pub source_revision: Option<String>,
pub generation_id: Option<String>,
pub artifact_id: Option<String>,
pub node_id: Option<String>,
pub source_ref_id: Option<String>,
pub span: Option<Value>,
pub relation: String,
}
impl KnowledgeLocator {
pub fn from_params(params: &Value) -> Result<Self, String> {
let loc = params.get("locator").unwrap_or(params);
Ok(Self {
project_id: loc
.get("project_id")
.or_else(|| params.get("project"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
document_id: loc
.get("document_id")
.or_else(|| params.get("document"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
source_revision: loc
.get("source_revision")
.or_else(|| loc.get("revision"))
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
generation_id: loc
.get("generation_id")
.or_else(|| loc.get("generation"))
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
artifact_id: loc
.get("artifact_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
node_id: loc
.get("node_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
source_ref_id: loc
.get("source_ref_id")
.or_else(|| loc.get("ref_id"))
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
span: loc.get("span").cloned(),
relation: loc
.get("relation")
.and_then(|v| v.as_str())
.unwrap_or("cites")
.to_string(),
})
}
pub fn to_json(&self) -> Value {
json!({
"schema": "KnowledgeLocatorV1",
"schema_version": 1,
"project_id": self.project_id,
"document_id": self.document_id,
"source_revision": self.source_revision,
"generation_id": self.generation_id,
"artifact_id": self.artifact_id,
"node_id": self.node_id,
"source_ref_id": self.source_ref_id,
"span": self.span,
"relation": self.relation,
})
}
}
/// Resolve a locator or current-document ref_id against a project snapshot.
/// Never silently falls back to "latest" when expected revision/generation mismatch.
pub fn resolve_reference(params: &Value) -> Result<Value, Value> {
let locator = KnowledgeLocator::from_params(params).map_err(|e| {
json!({"code": "locator.bad_request", "message": e})
})?;
if locator.project_id.is_empty() {
return Err(json!({
"code": "locator.bad_request",
"message": "project_id/project required"
}));
}
let root = PathBuf::from(&locator.project_id);
let root = root.canonicalize().map_err(|e| {
json!({"code": "locator.project_invalid", "message": format!("{e}")})
})?;
let options = crate::sema::CompileOptions::for_path(&root).map_err(|e| {
json!({"code": "locator.compile_failed", "message": format!("{e:#}")})
})?;
let compilation = crate::sema::compile_project(&options).map_err(|e| {
json!({"code": "locator.compile_failed", "message": format!("{e:#}")})
})?;
// Generation mismatch → version_unavailable / stale (no silent current).
if let Some(expected_gen) = &locator.generation_id {
if !expected_gen.is_empty() {
let current_gen = semantic_generation(&compilation.semantics);
if &current_gen != expected_gen {
return Ok(json!({
"schema": "KnowledgeLocatorV1",
"schema_version": 1,
"resolution": "version_unavailable",
"precision": "none",
"locator": locator.to_json(),
"target": Value::Null,
"candidates": [],
"diagnostics": [{
"code": "generation_mismatch",
"message": format!(
"expected generation {expected_gen}, current projection is {current_gen}; refusing silent downgrade"
)
}],
"label": "引用版本不可用"
}));
}
}
}
// Source revision check when document is known.
if let (Some(expected_rev), true) = (
&locator.source_revision,
!locator.document_id.is_empty(),
) {
if !expected_rev.is_empty() {
let abs = resolve_under(&root, &locator.document_id)?;
let raw = std::fs::read(&abs).map_err(|e| {
json!({"code": "locator.source_unreadable", "message": format!("{e}")})
})?;
use sha2::{Digest, Sha256};
let actual = format!("sha256:{:x}", Sha256::digest(&raw));
if &actual != expected_rev {
return Ok(json!({
"schema": "KnowledgeLocatorV1",
"schema_version": 1,
"resolution": "stale",
"precision": "document",
"locator": locator.to_json(),
"target": {
"document_id": locator.document_id,
"source_revision": actual,
"note": "source changed since citation"
},
"candidates": [],
"diagnostics": [{
"code": "source_revision_mismatch",
"message": format!("expected {expected_rev}, actual {actual}")
}],
"label": "该来源已变化"
}));
}
}
}
let query = locator
.artifact_id
.clone()
.or_else(|| locator.node_id.clone())
.or_else(|| locator.source_ref_id.clone());
let Some(q) = query else {
if locator.document_id.is_empty() {
return Ok(json!({
"schema": "KnowledgeLocatorV1",
"schema_version": 1,
"resolution": "unresolved",
"precision": "none",
"locator": locator.to_json(),
"target": Value::Null,
"candidates": [],
"diagnostics": [{"code": "missing_target", "message": "no artifact/node/ref id"}],
"label": "无法定位该知识"
}));
}
return Ok(json!({
"schema": "KnowledgeLocatorV1",
"schema_version": 1,
"resolution": "resolved",
"precision": "document",
"locator": locator.to_json(),
"target": {
"document_id": locator.document_id,
"relation": locator.relation,
},
"candidates": [],
"diagnostics": [],
"label": locator.document_id,
}));
};
let mut matches: Vec<&crate::sema::SemanticArtifact> = compilation
.semantics
.artifacts
.iter()
.filter(|a| {
a.artifact_id.0 == q
|| a.display_name == q
|| a.symbol_id
.as_ref()
.map(|s| s.as_str() == q)
.unwrap_or(false)
})
.collect();
if !locator.document_id.is_empty() {
let scoped: Vec<_> = matches
.iter()
.copied()
.filter(|a| a.source.file == locator.document_id)
.collect();
if !scoped.is_empty() {
matches = scoped;
}
}
match matches.len() {
0 => Ok(json!({
"schema": "KnowledgeLocatorV1",
"schema_version": 1,
"resolution": "unresolved",
"precision": "none",
"locator": locator.to_json(),
"target": Value::Null,
"candidates": [],
"diagnostics": [{"code": "not_found", "message": format!("no artifact matching {q}")}],
"label": "尚未定位到具体知识"
})),
1 => {
let a = matches[0];
Ok(json!({
"schema": "KnowledgeLocatorV1",
"schema_version": 1,
"resolution": "resolved",
"precision": "artifact",
"locator": locator.to_json(),
"target": {
"artifact_id": a.artifact_id.0,
"display_name": a.display_name,
"document_id": a.source.file,
"span": {"line": a.source.line, "end_line": a.source.end_line},
"evidence": a.verification.evidence,
"relation": locator.relation,
},
"candidates": [],
"diagnostics": [],
"label": a.display_name,
}))
}
_ => {
let candidates: Vec<Value> = matches
.iter()
.map(|a| {
json!({
"artifact_id": a.artifact_id.0,
"display_name": a.display_name,
"document_id": a.source.file,
"line": a.source.line,
})
})
.collect();
Ok(json!({
"schema": "KnowledgeLocatorV1",
"schema_version": 1,
"resolution": "ambiguous",
"precision": "none",
"locator": locator.to_json(),
"target": Value::Null,
"candidates": candidates,
"diagnostics": [{"code": "ambiguous", "message": format!("{} candidates for {q}", matches.len())}],
"label": "存在多个候选"
}))
}
}
}
fn semantic_generation(project: &crate::sema::SemanticProject) -> String {
use sha2::{Digest, Sha256};
let mut gh = Sha256::new();
gh.update(project.project_id.as_bytes());
for a in &project.artifacts {
gh.update(a.hashes.artifact.0.as_bytes());
}
format!("{:x}", gh.finalize())[..16].to_string()
}
fn resolve_under(root: &Path, rel: &str) -> Result<PathBuf, Value> {
let joined = root.join(rel);
let canon = joined.canonicalize().map_err(|e| {
json!({"code": "locator.document_not_found", "message": format!("{}: {e}", joined.display())})
})?;
if !canon.starts_with(root) {
return Err(json!({
"code": "locator.path_escape",
"message": "document path escapes project root"
}));
}
Ok(canon)
}
+25
View File
@@ -0,0 +1,25 @@
//! Workbench runtime contracts (M00–M05): schemas, capabilities, DocumentView,
//! KnowledgeLocator, ModelSelection / ModelCallUsage / RuntimeEvent / RunContext.
//!
//! Spec: `doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md`.
//! These are v1 contracts distinct from KnowledgePresentation `schema_version:1`.
pub mod analysis_cache;
pub mod capabilities;
#[cfg(feature = "view")]
pub mod document_view;
pub mod event_sink;
pub mod locator;
pub mod run_context;
pub mod selection;
pub mod usage;
pub use analysis_cache::{cache_keys_isolated, note_analysis, project_source_digest};
pub use capabilities::probe_capabilities;
#[cfg(feature = "view")]
pub use document_view::{build_document_view, DocumentViewRequest};
pub use event_sink::{bind_event_sink, clear_event_sink, emit_event, emit_message_delta};
pub use locator::{resolve_reference, KnowledgeLocator};
pub use run_context::{cancel_requested, RunContext};
pub use selection::{parse_model_selection, ModelSelection};
pub use usage::{model_call_usage_from_provider, runtime_event, token_or_null};
+148
View File
@@ -0,0 +1,148 @@
//! RunContextV1 — request-local run identity for selection / usage / cancel (M01).
use serde_json::{json, Map, Value};
#[derive(Debug, Clone, Default)]
pub struct RunContext {
pub run_id: String,
pub parent_run_id: Option<String>,
pub turn_id: Option<String>,
pub workspace_scope: Option<String>,
pub selection_context: Map<String, Value>,
pub usage_sink: Option<String>,
pub event_sink: Option<String>,
pub cancellation_token: Option<String>,
}
impl RunContext {
pub fn from_value(v: &Value) -> Result<Self, String> {
let run_id = v
.get("run_id")
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
.ok_or_else(|| "run_context.missing:run_id".to_string())?
.to_string();
Ok(Self {
run_id,
parent_run_id: v
.get("parent_run_id")
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string()),
turn_id: v
.get("turn_id")
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string()),
workspace_scope: v
.get("workspace_scope")
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string()),
selection_context: v
.get("selection_context")
.and_then(|x| x.as_object())
.cloned()
.unwrap_or_default(),
usage_sink: v
.get("usage_sink")
.and_then(|x| x.as_str())
.map(|s| s.to_string()),
event_sink: v
.get("event_sink")
.and_then(|x| x.as_str())
.map(|s| s.to_string()),
cancellation_token: v
.get("cancellation_token")
.and_then(|x| x.as_str())
.map(|s| s.to_string()),
})
}
pub fn to_json(&self) -> Value {
json!({
"schema": "RunContextV1",
"schema_version": 1,
"run_id": self.run_id,
"parent_run_id": self.parent_run_id,
"turn_id": self.turn_id,
"workspace_scope": self.workspace_scope,
"selection_context": self.selection_context,
"usage_sink": self.usage_sink,
"event_sink": self.event_sink,
"cancellation_token": self.cancellation_token,
})
}
/// Child inherits selection/event/cancel; new run_id linked to parent.
pub fn spawn_child(&self, child_run_id: &str) -> Self {
Self {
run_id: child_run_id.to_string(),
parent_run_id: Some(self.run_id.clone()),
turn_id: self.turn_id.clone(),
workspace_scope: self.workspace_scope.clone(),
selection_context: self.selection_context.clone(),
usage_sink: self.usage_sink.clone(),
event_sink: self.event_sink.clone(),
cancellation_token: self.cancellation_token.clone(),
}
}
/// Env vars for subtask injection (never includes api_key).
pub fn selection_env(&self) -> Vec<(String, String)> {
let mut out = Vec::new();
out.push(("MARQDO_RUN_ID".into(), self.run_id.clone()));
if let Some(p) = &self.parent_run_id {
out.push(("MARQDO_PARENT_RUN_ID".into(), p.clone()));
}
if let Some(t) = &self.turn_id {
out.push(("MARQDO_TURN_ID".into(), t.clone()));
}
if let Some(w) = &self.workspace_scope {
out.push(("MARQDO_WORKSPACE_SCOPE".into(), w.clone()));
}
if let Some(tok) = &self.cancellation_token {
out.push(("MARQDO_CANCEL_TOKEN".into(), tok.clone()));
}
if let Some(sink) = &self.event_sink {
out.push(("MARQDO_EVENT_FORWARD".into(), sink.clone()));
}
if let Some(model) = self
.selection_context
.get("upstream_model_id")
.or_else(|| self.selection_context.get("model"))
.and_then(|v| v.as_str())
{
out.push(("MARQDO_LLM_MODEL".into(), model.to_string()));
out.push(("OPENAI_MODEL".into(), model.to_string()));
}
if let Some(base) = self
.selection_context
.get("base_url")
.and_then(|v| v.as_str())
{
out.push(("MARQDO_LLM_BASE_URL".into(), base.to_string()));
out.push(("OPENAI_BASE_URL".into(), base.to_string()));
}
out
}
}
/// Check whether a cancel token file/env indicates cancellation.
pub fn cancel_requested(token: Option<&str>) -> bool {
let Some(tok) = token.filter(|s| !s.is_empty()) else {
return false;
};
// Token may be a path: presence of file or contents "1"/"cancelled" means stop.
let path = std::path::Path::new(tok);
if path.is_file() {
if let Ok(body) = std::fs::read_to_string(path) {
let t = body.trim();
return t.is_empty() || t == "1" || t.eq_ignore_ascii_case("cancelled");
}
return true;
}
std::env::var("MARQDO_CANCEL")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false)
}
+147
View File
@@ -0,0 +1,147 @@
//! ModelSelectionV1 — request-level model identity (M01).
use serde_json::{json, Map, Value};
#[derive(Debug, Clone)]
pub struct ModelSelection {
pub schema_version: u64,
pub selection_id: String,
pub provider_id: String,
pub model_id: String,
pub provider_revision: Option<u64>,
pub model_revision: Option<u64>,
pub adapter: String,
pub endpoint_ref: Option<String>,
pub credential_ref: Option<String>,
pub credential_version: Option<u64>,
pub upstream_model_id: String,
pub parameters: Map<String, Value>,
pub fallback_policy: String,
pub auth_mode: String,
/// Resolved call-local endpoint (never serialize API keys into events).
pub base_url: Option<String>,
/// Call-local credential material — must not appear in public snapshots.
pub api_key: Option<String>,
}
impl ModelSelection {
pub fn public_snapshot(&self) -> Value {
json!({
"schema": "ModelSelectionV1",
"schema_version": self.schema_version,
"selection_id": self.selection_id,
"provider_id": self.provider_id,
"model_id": self.model_id,
"provider_revision": self.provider_revision,
"model_revision": self.model_revision,
"adapter": self.adapter,
"endpoint_ref": self.endpoint_ref,
"credential_ref": self.credential_ref,
"credential_version": self.credential_version,
"upstream_model_id": self.upstream_model_id,
"parameters": self.parameters,
"fallback_policy": self.fallback_policy,
"auth_mode": self.auth_mode,
})
}
}
/// Parse selection. In `strict` mode, missing required fields error (no env fallback).
pub fn parse_model_selection(v: &Value, strict: bool) -> Result<ModelSelection, String> {
let schema_version = v
.get("schema_version")
.and_then(|x| x.as_u64())
.unwrap_or(1);
if schema_version != 1 {
return Err(format!("unsupported ModelSelection schema_version={schema_version}"));
}
let require = |key: &str| -> Result<String, String> {
match v.get(key).and_then(|x| x.as_str()).filter(|s| !s.is_empty()) {
Some(s) => Ok(s.to_string()),
None if strict => Err(format!("llm.selection_missing:{key}")),
None => Ok(String::new()),
}
};
let selection_id = require("selection_id")?;
let provider_id = require("provider_id")?;
let model_id = require("model_id")?;
let adapter = v
.get("adapter")
.and_then(|x| x.as_str())
.unwrap_or("openai-compatible")
.to_string();
let upstream = v
.get("upstream_model_id")
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.or_else(|| {
if model_id.is_empty() {
None
} else {
Some(model_id.clone())
}
});
let upstream_model_id = match upstream {
Some(u) => u,
None if strict => return Err("llm.selection_missing:upstream_model_id".into()),
None => String::new(),
};
let auth_mode = v
.get("auth_mode")
.and_then(|x| x.as_str())
.unwrap_or("api_key")
.to_string();
let fallback_policy = v
.get("fallback_policy")
.and_then(|x| x.as_str())
.unwrap_or("disabled")
.to_string();
let parameters = v
.get("parameters")
.and_then(|x| x.as_object())
.cloned()
.unwrap_or_default();
let base_url = v
.get("base_url")
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
let api_key = v
.get("api_key")
.and_then(|x| x.as_str())
.map(|s| s.to_string());
if strict && auth_mode != "none" && api_key.as_ref().map(|s| s.is_empty()).unwrap_or(true) {
// credential_ref may be resolved by host; allow missing api_key if credential_ref present
if v.get("credential_ref").and_then(|x| x.as_str()).is_none() && base_url.is_some() {
return Err("llm.selection_missing:api_key_or_credential_ref".into());
}
}
if strict && selection_id.is_empty() {
return Err("llm.selection_missing:selection_id".into());
}
Ok(ModelSelection {
schema_version,
selection_id,
provider_id,
model_id,
provider_revision: v.get("provider_revision").and_then(|x| x.as_u64()),
model_revision: v.get("model_revision").and_then(|x| x.as_u64()),
adapter,
endpoint_ref: v
.get("endpoint_ref")
.and_then(|x| x.as_str())
.map(|s| s.to_string()),
credential_ref: v
.get("credential_ref")
.and_then(|x| x.as_str())
.map(|s| s.to_string()),
credential_version: v.get("credential_version").and_then(|x| x.as_u64()),
upstream_model_id,
parameters,
fallback_policy,
auth_mode,
base_url,
api_key,
})
}
+144
View File
@@ -0,0 +1,144 @@
//! ModelCallUsageV1 — null ≠ 0; measurement_source honesty (M02 / F04).
use serde_json::{json, Value};
/// Prefer null over zero when the provider omitted a field.
pub fn token_or_null(v: Option<i64>) -> Value {
match v {
Some(n) if n >= 0 => json!(n),
_ => Value::Null,
}
}
/// Build ModelCallUsageV1 from an OpenAI-shaped `usage` object (or Null).
pub fn model_call_usage_from_provider(
call_id: &str,
attempt_id: &str,
run_id: &str,
selection: &Value,
provider_usage: &Value,
status: &str,
) -> Value {
let has_usage = provider_usage.is_object();
let input = provider_usage
.get("prompt_tokens")
.or_else(|| provider_usage.get("input_tokens"))
.and_then(|v| v.as_i64());
let output = provider_usage
.get("completion_tokens")
.or_else(|| provider_usage.get("output_tokens"))
.and_then(|v| v.as_i64());
let total = provider_usage
.get("total_tokens")
.and_then(|v| v.as_i64())
.or_else(|| match (input, output) {
(Some(a), Some(b)) => Some(a + b),
_ => None,
});
let cached = provider_usage
.get("cached_input_tokens")
.or_else(|| {
provider_usage
.get("prompt_tokens_details")
.and_then(|d| d.get("cached_tokens"))
})
.and_then(|v| v.as_i64());
let reasoning = provider_usage
.get("reasoning_output_tokens")
.or_else(|| {
provider_usage
.get("completion_tokens_details")
.and_then(|d| d.get("reasoning_tokens"))
})
.and_then(|v| v.as_i64());
let (usage_state, measurement_source) = if !has_usage {
("unknown", "none")
} else if input.is_none() && output.is_none() && total.is_none() {
("unknown", "none")
} else {
("final", "provider")
};
let mut diagnostics = Vec::new();
if let (Some(t), Some(i), Some(o)) = (total, input, output) {
if t != i + o && cached.is_none() {
diagnostics.push(json!({
"code": "usage.inconsistent",
"message": format!("total_tokens={t} != input+output={}", i + o)
}));
}
}
json!({
"schema": "ModelCallUsageV1",
"schema_version": 1,
"call_id": call_id,
"attempt_id": attempt_id,
"parent_call_id": Value::Null,
"run_id": run_id,
"turn_id": selection.get("turn_id").cloned().unwrap_or(Value::Null),
"workspace_scope": selection.get("workspace_scope").cloned().unwrap_or(Value::Null),
"purpose": selection.get("purpose").cloned().unwrap_or(json!("answer")),
"selection_id": selection.get("selection_id").cloned().unwrap_or(Value::Null),
"provider_id": selection.get("provider_id").cloned().unwrap_or(Value::Null),
"model_id": selection.get("model_id").cloned().unwrap_or(Value::Null),
"requested_model": selection.get("upstream_model_id").cloned()
.or_else(|| selection.get("model").cloned())
.unwrap_or(Value::Null),
"resolved_model": selection.get("resolved_model").cloned()
.or_else(|| selection.get("upstream_model_id").cloned())
.unwrap_or(Value::Null),
"status": status,
"usage_state": usage_state,
"measurement_source": measurement_source,
"input_tokens": token_or_null(input),
"output_tokens": token_or_null(output),
"total_tokens": token_or_null(total),
"cached_input_tokens": token_or_null(cached),
"reasoning_output_tokens": token_or_null(reasoning),
"revision": 1,
"provider_request_id": provider_usage.get("provider_request_id").cloned().unwrap_or(Value::Null),
"diagnostics": diagnostics,
// Legacy fields kept but marked — apps must not treat token_cost as money.
"legacy": {
"tokens": token_or_null(total),
"token_cost": token_or_null(total),
"deprecated": true,
"unit": "tokens"
}
})
}
/// RuntimeEventV1 envelope helper.
pub fn runtime_event(
event_id: &str,
seq: u64,
run_id: &str,
event_type: &str,
payload: Value,
) -> Value {
json!({
"schema": "RuntimeEventV1",
"schema_version": 1,
"event_id": event_id,
"seq": seq,
"run_id": run_id,
"parent_run_id": Value::Null,
"turn_id": Value::Null,
"workspace_scope": Value::Null,
"timestamp": chrono_like_now(),
"type": event_type,
"payload": payload
})
}
fn chrono_like_now() -> String {
// Avoid new chrono dep: RFC3339-ish from system time.
use std::time::{SystemTime, UNIX_EPOCH};
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
format!("{secs}")
}