feat(workbench): freeze agent protocols and ship ResourceView v1

Lock M-A0 Error/Tool/Checkpoint/Output/Context fixtures with capability bits off, and land M-A3 static md/txt/code ResourceView (no-exec) behind resource.view.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-27 10:59:59 +08:00
1 parent a1086fd6c3
commit 303c06f773
28 files changed
+1038 -1

No files matched your search

+15 -1
View File
@@ -77,6 +77,13 @@ fn dispatch(req: &Value) -> Result<Value, Value> {
"mlsp.unsupported",
"view.document requires the view feature",
)),
#[cfg(feature = "view")]
Some("resource.view") => resource_view(&params),
#[cfg(not(feature = "view"))]
Some("resource.view") => Err(err(
"mlsp.unsupported",
"resource.view 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),
@@ -84,7 +91,7 @@ fn dispatch(req: &Value) -> Result<Value, Value> {
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 / capabilities / view.document / view.reference_resolve"),
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 / resource.view / view.reference_resolve"),
)),
}
}
@@ -96,6 +103,13 @@ fn view_document(params: &Value) -> Result<Value, Value> {
crate::workbench::build_document_view(&req)
}
#[cfg(feature = "view")]
fn resource_view(params: &Value) -> Result<Value, Value> {
let req = crate::workbench::ResourceViewRequest::from_params(params)
.map_err(|e| err("mlsp.bad_request", e))?;
crate::workbench::build_resource_view(&req)
}
fn artifact_extract_pure(params: &Value) -> Result<Value, Value> {
let name = params
.get("name")
+36
View File
@@ -47,6 +47,14 @@ pub fn probe_capabilities(params: &Value) -> Value {
json!({"format": "pdf", "available": false}),
json!({"format": "docx", "available": false}),
json!({"format": "ocr", "available": false}),
// M-A0 freeze: format matrix rows remain unavailable until M-A3/M-A5.
json!({"format": "json", "available": false}),
json!({"format": "csv", "available": false}),
json!({"format": "image", "available": false}),
json!({"format": "html", "available": false}),
json!({"format": "svg", "available": false}),
json!({"format": "xlsx", "available": false}),
json!({"format": "pptx", "available": false}),
];
let loaded_plugins = probe_loaded_plugins(params);
@@ -109,6 +117,25 @@ pub fn probe_capabilities(params: &Value) -> Value {
features.insert("view.document".into(), json!(0));
features.insert("view.reference_resolve".into(), json!(0));
}
// M-A0/M-A3: freeze protocol names. resource.view_v1 flips on when view feature ships
// the static ResourceView emitter; other agent bits stay 0 until their emitters land.
for (k, v) in [
("agent.error_v1", 0),
("agent.checkpoint_v2", 0),
("agent.tool_schema_v1", 0),
("agent.output_channels_v1", 0),
("agent.context_pack_v2", 0),
] {
features.insert(k.into(), json!(v));
}
#[cfg(feature = "view")]
{
features.insert("resource.view_v1".into(), json!(1));
}
#[cfg(not(feature = "view"))]
{
features.insert("resource.view_v1".into(), json!(0));
}
json!({
"schema_version": 1,
@@ -221,5 +248,14 @@ mod tests {
assert_eq!(caps["features"]["runtime.event_stream"], 0);
assert_eq!(caps["features"]["runtime.cancel"], 0);
assert_eq!(caps["features"]["llm.messages"], 0);
assert_eq!(caps["features"]["agent.error_v1"], 0);
assert_eq!(caps["features"]["agent.checkpoint_v2"], 0);
assert_eq!(caps["features"]["agent.tool_schema_v1"], 0);
assert_eq!(caps["features"]["agent.output_channels_v1"], 0);
assert_eq!(caps["features"]["agent.context_pack_v2"], 0);
#[cfg(feature = "view")]
assert_eq!(caps["features"]["resource.view_v1"], 1);
#[cfg(not(feature = "view"))]
assert_eq!(caps["features"]["resource.view_v1"], 0);
}
}
+4
View File
@@ -10,6 +10,8 @@ pub mod capabilities;
pub mod document_view;
pub mod event_sink;
pub mod locator;
#[cfg(feature = "view")]
pub mod resource_view;
pub mod run_context;
pub mod selection;
pub mod snapshot;
@@ -24,6 +26,8 @@ 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};
#[cfg(feature = "view")]
pub use resource_view::{build_resource_view, ResourceViewRequest};
pub use locator::{resolve_reference, KnowledgeLocator};
pub use run_context::{
cancel_requested, cancel_token_body_means_cancel, RequestContext, RunContext,
+397
View File
@@ -0,0 +1,397 @@
//! ResourceViewV1 — static read-only preview for ordinary resources (M-A3).
//! Never executes Marqdo / never loads plugins. `.mq.md` remains on DocumentView.
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone)]
pub struct ResourceViewRequest {
pub workspace_root: PathBuf,
pub path: String,
pub revision: Option<String>,
pub max_bytes: usize,
}
impl ResourceViewRequest {
pub fn from_params(params: &Value) -> Result<Self, String> {
let root = params
.get("workspace_root")
.or_else(|| params.get("project"))
.and_then(|v| v.as_str())
.ok_or_else(|| "resource.view requires workspace_root or project".to_string())?;
let path = params
.get("path")
.or_else(|| params.get("document"))
.and_then(|v| v.as_str())
.ok_or_else(|| "resource.view requires path or document".to_string())?;
let mode = params
.get("mode")
.and_then(|v| v.as_str())
.unwrap_or("read");
if mode != "read" {
return Err(format!("resource.view unsupported mode={mode}; only read"));
}
let max_bytes = params
.get("max_bytes")
.and_then(|v| v.as_u64())
.unwrap_or(256 * 1024) as usize;
Ok(Self {
workspace_root: PathBuf::from(root),
path: path.to_string(),
revision: params
.get("revision")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
max_bytes,
})
}
}
/// Build a ResourceViewV1 for text / markdown / code. No compile, no eval, no network.
pub fn build_resource_view(req: &ResourceViewRequest) -> Result<Value, Value> {
let root = canonicalize_root(&req.workspace_root)?;
let abs = resolve_under(&root, &req.path)?;
let meta = fs::metadata(&abs).map_err(|e| {
err(
"resource.read_failed",
format!("cannot stat {}: {e}", abs.display()),
)
})?;
if !meta.is_file() {
return Err(err(
"resource.not_file",
format!("{} is not a file", abs.display()),
));
}
let size = meta.len() as usize;
let raw = fs::read(&abs).map_err(|e| {
err(
"resource.read_failed",
format!("cannot read {}: {e}", abs.display()),
)
})?;
let digest = format!("sha256:{:x}", Sha256::digest(&raw));
if let Some(expected) = &req.revision {
if !expected.is_empty() && expected != &digest {
return Err(err(
"resource.revision_mismatch",
format!("requested {expected} but file is {digest}"),
));
}
}
let rel = req.path.replace('\\', "/");
let media = media_type_for(&rel);
let kind = kind_for(&rel, media);
let title = Path::new(&rel)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(&rel)
.to_string();
// `.mq.md` semantic view stays on view.document — refuse silent exec/compile here.
if rel.ends_with(".mq.md") || media == "application/x-marqdo" {
return Ok(json!({
"schema": "ResourceViewV1",
"schema_version": 1,
"resource": {
"resource_id": rel,
"workspace_id": "local",
"kind": "marqdo",
"media_type": "application/x-marqdo",
"revision": digest,
"digest": digest,
"title": title,
"size": size,
"origin": "workspace",
"locator": Value::Null
},
"renderer": {"id": "redirect_document_view", "version": "1", "trust": "none"},
"render": {
"format": "text",
"fragment": Value::Null,
"text": "该资源是 Marqdo 文档;请使用 view.document 获取语义只读视图。"
},
"outline": [],
"locators": [],
"completeness": "partial",
"no_exec": true,
"diagnostics": [{"code": "use_document_view", "message": "use view.document for .mq.md"}],
"next_cursor": Value::Null
}));
}
let truncated = size > req.max_bytes;
let slice = if truncated {
&raw[..req.max_bytes]
} else {
&raw[..]
};
let text = String::from_utf8_lossy(slice).into_owned();
let (renderer_id, format, fragment) = match media {
"text/markdown" => (
"markdown",
"sanitized_html",
wrap_pre(&simple_markdown_to_html(&text)),
),
"text/x-code" | "text/plain" => ("plaintext", "sanitized_html", wrap_pre(&escape_html(&text))),
other => {
return Ok(json!({
"schema": "ResourceViewV1",
"schema_version": 1,
"resource": resource_ref(&rel, other, &digest, &title, size),
"renderer": {"id": "unavailable", "version": "1", "trust": "none"},
"render": {"format": "text", "fragment": Value::Null, "text": format!("unsupported media_type={other}")},
"outline": [],
"locators": [],
"completeness": "partial",
"no_exec": true,
"diagnostics": [{"code": "unsupported_format", "message": other}],
"next_cursor": Value::Null
}));
}
};
let completeness = if truncated { "partial" } else { "complete" };
let mut diagnostics = Vec::new();
if truncated {
diagnostics.push(json!({
"code": "truncated",
"message": format!("preview truncated at {} bytes", req.max_bytes)
}));
}
Ok(json!({
"schema": "ResourceViewV1",
"schema_version": 1,
"resource": resource_ref(&rel, media, &digest, &title, size),
"renderer": {"id": renderer_id, "version": "1", "trust": "sanitized"},
"render": {"format": format, "fragment": fragment},
"outline": [],
"locators": [],
"completeness": completeness,
"no_exec": true,
"diagnostics": diagnostics,
"next_cursor": Value::Null,
"capabilities": {"read_only": true, "executed": false, "kind": kind}
}))
}
fn resource_ref(id: &str, media: &str, digest: &str, title: &str, size: usize) -> Value {
json!({
"resource_id": id,
"workspace_id": "local",
"kind": kind_for(id, media),
"media_type": media,
"revision": digest,
"digest": digest,
"title": title,
"size": size,
"origin": "workspace",
"locator": Value::Null
})
}
fn media_type_for(path: &str) -> &'static str {
let lower = path.to_ascii_lowercase();
if lower.ends_with(".mq.md") {
"application/x-marqdo"
} else if lower.ends_with(".md") || lower.ends_with(".markdown") {
"text/markdown"
} else if lower.ends_with(".rs")
|| lower.ends_with(".ts")
|| lower.ends_with(".tsx")
|| lower.ends_with(".js")
|| lower.ends_with(".jsx")
|| lower.ends_with(".py")
|| lower.ends_with(".go")
|| lower.ends_with(".json")
|| lower.ends_with(".toml")
|| lower.ends_with(".yaml")
|| lower.ends_with(".yml")
|| lower.ends_with(".css")
|| lower.ends_with(".html")
|| lower.ends_with(".sh")
{
"text/x-code"
} else if lower.ends_with(".txt") || lower.ends_with(".log") {
"text/plain"
} else {
"application/octet-stream"
}
}
fn kind_for(path: &str, media: &str) -> &'static str {
if media == "application/x-marqdo" || path.ends_with(".mq.md") {
"marqdo"
} else if media == "text/markdown" {
"markdown"
} else if media == "text/x-code" {
"code"
} else if media.starts_with("text/") {
"text"
} else {
"file"
}
}
fn wrap_pre(inner: &str) -> String {
format!("<article class=\"mq-resource\"><pre class=\"mq-resource-body\">{inner}</pre></article>")
}
fn escape_html(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
c => out.push(c),
}
}
out
}
/// Minimal markdown → HTML (headings/paragraphs/code fences). Not a full parser.
fn simple_markdown_to_html(src: &str) -> String {
let mut out = String::new();
let mut in_fence = false;
for line in src.lines() {
if line.trim_start().starts_with("```") {
if in_fence {
out.push_str("</code></pre>\n");
in_fence = false;
} else {
out.push_str("<pre><code>");
in_fence = true;
}
continue;
}
if in_fence {
out.push_str(&escape_html(line));
out.push('\n');
continue;
}
let t = line.trim_end();
if let Some(rest) = t.strip_prefix("### ") {
out.push_str("<h3>");
out.push_str(&escape_html(rest));
out.push_str("</h3>\n");
} else if let Some(rest) = t.strip_prefix("## ") {
out.push_str("<h2>");
out.push_str(&escape_html(rest));
out.push_str("</h2>\n");
} else if let Some(rest) = t.strip_prefix("# ") {
out.push_str("<h1>");
out.push_str(&escape_html(rest));
out.push_str("</h1>\n");
} else if t.is_empty() {
out.push_str("<br/>\n");
} else {
out.push_str("<p>");
out.push_str(&escape_html(t));
out.push_str("</p>\n");
}
}
if in_fence {
out.push_str("</code></pre>\n");
}
out
}
fn canonicalize_root(project: &Path) -> Result<PathBuf, Value> {
fs::canonicalize(project).map_err(|e| {
err(
"resource.bad_root",
format!("cannot canonicalize {}: {e}", project.display()),
)
})
}
fn resolve_under(root: &Path, rel: &str) -> Result<PathBuf, Value> {
let cleaned = rel.trim_start_matches(['/', '\\']);
if cleaned.is_empty() || cleaned.contains("..") {
return Err(err(
"resource.path_escape",
format!("refusing path {rel:?}"),
));
}
let abs = root.join(cleaned);
let canon = fs::canonicalize(&abs).map_err(|e| {
err(
"resource.not_found",
format!("cannot resolve {}: {e}", abs.display()),
)
})?;
if !canon.starts_with(root) {
return Err(err(
"resource.path_escape",
format!("{} escapes workspace root", canon.display()),
));
}
Ok(canon)
}
fn err(code: &str, message: impl Into<String>) -> Value {
json!({
"ok": false,
"error": {"code": code, "message": message.into()}
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
fn scratch_dir(label: &str) -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!("marqdo-resource-view-{label}-{nanos}"));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn plaintext_no_exec_and_escape() {
let dir = scratch_dir("plain");
let path = dir.join("note.txt");
let mut f = fs::File::create(&path).unwrap();
writeln!(f, "<script>alert(1)</script>").unwrap();
let req = ResourceViewRequest {
workspace_root: dir.clone(),
path: "note.txt".into(),
revision: None,
max_bytes: 10_000,
};
let view = build_resource_view(&req).unwrap();
assert_eq!(view["no_exec"], true);
assert_eq!(view["schema"], "ResourceViewV1");
let frag = view["render"]["fragment"].as_str().unwrap();
assert!(frag.contains("&lt;script&gt;"));
assert!(!frag.contains("<script>"));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn path_escape_rejected() {
let dir = scratch_dir("escape");
let req = ResourceViewRequest {
workspace_root: dir.clone(),
path: "../etc/passwd".into(),
revision: None,
max_bytes: 10_000,
};
let errv = build_resource_view(&req).unwrap_err();
assert_eq!(errv["error"]["code"], "resource.path_escape");
let _ = fs::remove_dir_all(&dir);
}
}
@@ -0,0 +1,14 @@
{
"schema": "AgentErrorV1",
"schema_version": 1,
"code": "tool.timeout",
"category": "transient",
"stage": "tool",
"message": "读取资源超时",
"retryable": true,
"retry_after_ms": 1200,
"effect_state": "none",
"recovery_action": "retry_step",
"call_id": "call_01",
"details_ref": "resource:diagnostic_01"
}
@@ -0,0 +1,15 @@
{
"schema": "AgentErrorV1",
"schema_version": 99,
"code": "tool.timeout",
"category": "transient",
"stage": "tool",
"message": "读取资源超时",
"retryable": true,
"retry_after_ms": 1200,
"effect_state": "none",
"recovery_action": "retry_step",
"call_id": "call_01",
"details_ref": "resource:diagnostic_01",
"future_field": true
}
@@ -0,0 +1,11 @@
{
"schema": "AgentOutputV1",
"schema_version": 1,
"status": "failed",
"answer": {"format": "markdown", "text": "文档门禁未通过,草稿仍可打开。"},
"artifacts": [],
"citations": [],
"validation": {"status": "failed", "report_ref": "resource:verify_fail"},
"finish_reason": "validation_failed",
"recovery_options": [{"action": "repair_once", "label": "修复后重试"}]
}
@@ -0,0 +1,11 @@
{
"schema": "AgentOutputV1",
"schema_version": 1,
"status": "succeeded",
"answer": {"format": "markdown", "text": "已整理为三点,完整笔记见右侧。"},
"artifacts": [{"resource_id": "res_note_01", "revision": "sha256:example"}],
"citations": [],
"validation": {"status": "passed", "report_ref": "resource:verify_01"},
"finish_reason": "completed",
"recovery_options": []
}
@@ -0,0 +1,13 @@
{
"id": "legacy_resume_01",
"updated_at": "2026-10-27T02:49:00Z",
"goal": "回答用户问题",
"task": "你好",
"status": "interrupted",
"workbook": ".marqdo/agent-kb/resources/你好.mq.md",
"events": [],
"route": {},
"result": null,
"round": 1,
"meta": {}
}
@@ -0,0 +1,17 @@
{
"schema": "CheckpointV2",
"schema_version": 2,
"checkpoint_id": "ckpt_01",
"logical_run_id": "run_logic_01",
"task_id": "task_01",
"attempt_id": "attempt_01",
"step_id": "step_01",
"parent_checkpoint_id": null,
"principal_ref": "principal_01",
"workspace_id": "ws_01",
"session_id": "sess_01",
"completed_steps": [],
"pending_operation": null,
"deadline": "2026-10-27T12:00:00Z",
"committed_at": "2026-10-27T02:49:00Z"
}
@@ -0,0 +1,14 @@
{
"schema": "ContextPackV2",
"schema_version": 2,
"items": [
{
"origin": "user",
"trust": "user",
"resource_ref": "res_01",
"revision": "sha256:example",
"token_estimate": 120,
"priority": 1
}
]
}
@@ -0,0 +1,12 @@
{
"schema": "EffectLedgerRecordV1",
"schema_version": 1,
"operation_id": "op_01",
"idempotency_key": "idem_01",
"args_digest": "sha256:args",
"resource_scope": "workspace:ws_01",
"expected_revision": "sha256:example",
"effect_class": "write",
"result_ref": null,
"state": "prepared"
}
@@ -0,0 +1,14 @@
{
"schema": "ResourceRefV1",
"schema_version": 1,
"resource_id": "res_01",
"workspace_id": "ws_01",
"kind": "file",
"media_type": "text/markdown",
"revision": "sha256:example",
"digest": "sha256:example",
"title": "设计说明",
"size": 12,
"origin": "workspace",
"locator": null
}
@@ -0,0 +1,24 @@
{
"schema": "ResourceViewV1",
"schema_version": 1,
"resource": {
"resource_id": "res_01",
"workspace_id": "ws_01",
"kind": "file",
"revision": "sha256:example",
"media_type": "text/markdown",
"title": "设计说明",
"digest": "sha256:example",
"size": 12,
"origin": "workspace",
"locator": null
},
"renderer": {"id": "markdown", "version": "1", "trust": "sanitized"},
"render": {"format": "sanitized_html", "fragment": "<p>正文</p>"},
"outline": [],
"locators": [],
"completeness": "complete",
"no_exec": true,
"diagnostics": [],
"next_cursor": null
}
@@ -0,0 +1,24 @@
{
"schema": "RuntimeEventV2",
"schema_version": 2,
"event_id": "evt_01",
"seq": 7,
"task_id": "task_01",
"run_id": "run_01",
"attempt_id": "attempt_01",
"type": "tool.failed",
"payload": {
"schema": "AgentErrorV1",
"schema_version": 1,
"code": "tool.timeout",
"category": "transient",
"stage": "tool",
"message": "读取资源超时",
"retryable": true,
"retry_after_ms": 1200,
"effect_state": "none",
"recovery_action": "retry_step",
"call_id": "call_01",
"details_ref": "resource:diagnostic_01"
}
}
@@ -0,0 +1,10 @@
{
"schema": "ToolCallV1",
"schema_version": 1,
"call_id": "call_01",
"tool_id": "workspace.read",
"tool_version": "1",
"arguments": {"resource_id": "res_01", "start_line": 1, "max_lines": 40},
"operation_id": "op_01",
"parent_span_id": "span_01"
}
@@ -0,0 +1,15 @@
{
"schema": "ToolResultV1",
"schema_version": 1,
"ok": true,
"status": "succeeded",
"summary": "已读取 12 行",
"structured_content": {"lines": ["a", "b"]},
"resources": [{"resource_id": "res_01", "revision": "sha256:example"}],
"citations": [],
"error": null,
"usage": {"elapsed_ms": 12},
"truncated": false,
"next_cursor": null,
"effect_receipt_ref": null
}
@@ -0,0 +1,26 @@
{
"schema": "ToolSpecV1",
"schema_version": 1,
"id": "workspace.read",
"version": "1",
"description": "读取授权资源的指定行范围",
"input_schema": {
"type": "object",
"properties": {
"resource_id": {"type": "string"},
"revision": {"type": "string"},
"start_line": {"type": "integer", "minimum": 1},
"max_lines": {"type": "integer", "minimum": 1, "maximum": 500}
},
"required": ["resource_id"],
"additionalProperties": false
},
"output_schema_ref": "ResourceReadV1",
"effect": "read",
"scopes": ["workspace:read"],
"timeout_ms": 10000,
"max_result_bytes": 65536,
"idempotency": "safe",
"concurrency_group": "resource-read",
"availability": "ready"
}
@@ -0,0 +1,22 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/AgentErrorV1",
"title": "AgentErrorV1",
"type": "object",
"required": ["schema", "schema_version", "code", "category", "stage", "message", "retryable", "effect_state", "recovery_action"],
"properties": {
"schema": { "const": "AgentErrorV1" },
"schema_version": { "const": 1 },
"code": { "type": "string" },
"category": { "type": "string" },
"stage": { "type": "string" },
"message": { "type": "string" },
"retryable": { "type": "boolean" },
"retry_after_ms": { "type": ["integer", "null"] },
"effect_state": { "type": "string" },
"recovery_action": { "type": "string" },
"call_id": { "type": ["string", "null"] },
"details_ref": { "type": ["string", "null"] }
},
"additionalProperties": true
}
@@ -0,0 +1,19 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/AgentOutputV1",
"title": "AgentOutputV1",
"type": "object",
"required": ["schema", "schema_version", "status", "answer", "finish_reason"],
"properties": {
"schema": { "const": "AgentOutputV1" },
"schema_version": { "const": 1 },
"status": { "enum": ["succeeded", "partial", "failed", "needs_input", "cancelled"] },
"answer": { "type": "object" },
"artifacts": { "type": "array" },
"citations": { "type": "array" },
"validation": { "type": "object" },
"finish_reason": { "type": "string" },
"recovery_options": { "type": "array" }
},
"additionalProperties": true
}
@@ -0,0 +1,25 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/CheckpointV2",
"title": "CheckpointV2",
"type": "object",
"required": ["schema", "schema_version", "checkpoint_id", "logical_run_id", "task_id", "attempt_id", "committed_at"],
"properties": {
"schema": { "const": "CheckpointV2" },
"schema_version": { "const": 2 },
"checkpoint_id": { "type": "string" },
"logical_run_id": { "type": "string" },
"task_id": { "type": "string" },
"attempt_id": { "type": "string" },
"step_id": { "type": ["string", "null"] },
"parent_checkpoint_id": { "type": ["string", "null"] },
"principal_ref": { "type": ["string", "null"] },
"workspace_id": { "type": ["string", "null"] },
"session_id": { "type": ["string", "null"] },
"completed_steps": { "type": "array" },
"pending_operation": {},
"deadline": { "type": ["string", "null"] },
"committed_at": { "type": "string" }
},
"additionalProperties": true
}
@@ -0,0 +1,19 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/ContextPackV2",
"title": "ContextPackV2",
"type": "object",
"required": ["schema", "schema_version", "items"],
"properties": {
"schema": { "const": "ContextPackV2" },
"schema_version": { "const": 2 },
"items": {
"type": "array",
"items": {
"type": "object",
"required": ["origin", "trust", "resource_ref", "revision", "token_estimate", "priority"]
}
}
},
"additionalProperties": true
}
@@ -0,0 +1,22 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/ResourceRefV1",
"title": "ResourceRefV1",
"type": "object",
"required": ["schema", "schema_version", "resource_id", "workspace_id", "kind", "media_type", "revision", "digest", "title", "size", "origin"],
"properties": {
"schema": { "const": "ResourceRefV1" },
"schema_version": { "const": 1 },
"resource_id": { "type": "string" },
"workspace_id": { "type": "string" },
"kind": { "type": "string" },
"media_type": { "type": "string" },
"revision": { "type": "string" },
"digest": { "type": "string" },
"title": { "type": "string" },
"size": { "type": "integer" },
"origin": { "type": "string" },
"locator": {}
},
"additionalProperties": true
}
@@ -0,0 +1,21 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/ResourceViewV1",
"title": "ResourceViewV1",
"type": "object",
"required": ["schema", "schema_version", "resource", "renderer", "completeness", "no_exec"],
"properties": {
"schema": { "const": "ResourceViewV1" },
"schema_version": { "const": 1 },
"resource": { "type": "object" },
"renderer": { "type": "object" },
"render": { "type": "object" },
"outline": { "type": "array" },
"locators": { "type": "array" },
"completeness": { "type": "string" },
"no_exec": { "const": true },
"diagnostics": { "type": "array" },
"next_cursor": { "type": ["string", "null"] }
},
"additionalProperties": true
}
@@ -0,0 +1,18 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/ToolCallV1",
"title": "ToolCallV1",
"type": "object",
"required": ["schema", "schema_version", "call_id", "tool_id", "tool_version", "arguments", "operation_id"],
"properties": {
"schema": { "const": "ToolCallV1" },
"schema_version": { "const": 1 },
"call_id": { "type": "string" },
"tool_id": { "type": "string" },
"tool_version": { "type": "string" },
"arguments": { "type": "object" },
"operation_id": { "type": "string" },
"parent_span_id": { "type": ["string", "null"] }
},
"additionalProperties": true
}
@@ -0,0 +1,23 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/ToolResultV1",
"title": "ToolResultV1",
"type": "object",
"required": ["schema", "schema_version", "ok", "status", "summary"],
"properties": {
"schema": { "const": "ToolResultV1" },
"schema_version": { "const": 1 },
"ok": { "type": "boolean" },
"status": { "type": "string" },
"summary": { "type": "string" },
"structured_content": {},
"resources": { "type": "array" },
"citations": { "type": "array" },
"error": {},
"usage": {},
"truncated": { "type": "boolean" },
"next_cursor": { "type": ["string", "null"] },
"effect_receipt_ref": { "type": ["string", "null"] }
},
"additionalProperties": true
}
@@ -0,0 +1,24 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "marqdo://contracts/ToolSpecV1",
"title": "ToolSpecV1",
"type": "object",
"required": ["schema", "schema_version", "id", "version", "description", "input_schema", "effect", "scopes", "timeout_ms", "availability"],
"properties": {
"schema": { "const": "ToolSpecV1" },
"schema_version": { "const": 1 },
"id": { "type": "string" },
"version": { "type": "string" },
"description": { "type": "string" },
"input_schema": { "type": "object" },
"output_schema_ref": { "type": ["string", "null"] },
"effect": { "type": "string" },
"scopes": { "type": "array" },
"timeout_ms": { "type": "integer" },
"max_result_bytes": { "type": ["integer", "null"] },
"idempotency": { "type": "string" },
"concurrency_group": { "type": ["string", "null"] },
"availability": { "type": "string" }
},
"additionalProperties": true
}
+173
View File
@@ -100,6 +100,179 @@ fn m00_fixtures_consume_and_capabilities() {
assert_eq!(down["result"]["features"]["runtime.cancel"], 0);
}
/// M-A0: freeze Agent reliability protocol fixtures; capability bits stay 0.
#[test]
fn ma0_agent_reliability_protocol_freeze() {
let err = fixture("agent_error_v1.json");
assert_required(&err, &schema("AgentErrorV1.schema.json"), "agent_error");
assert_eq!(err["schema"], "AgentErrorV1");
assert_eq!(err["schema_version"], 1);
let degrade = fixture("agent_error_v1_unknown_version.json");
assert_eq!(degrade["schema"], "AgentErrorV1");
assert_eq!(degrade["schema_version"], 99);
assert_eq!(degrade["future_field"], true);
let tool = fixture("tool_spec_v1.json");
assert_required(&tool, &schema("ToolSpecV1.schema.json"), "tool_spec");
assert_required(
&fixture("tool_call_v1.json"),
&schema("ToolCallV1.schema.json"),
"tool_call",
);
assert_required(
&fixture("tool_result_v1.json"),
&schema("ToolResultV1.schema.json"),
"tool_result",
);
let ckpt = fixture("checkpoint_v2.json");
assert_required(&ckpt, &schema("CheckpointV2.schema.json"), "checkpoint");
assert_eq!(ckpt["schema_version"], 2);
let legacy = fixture("checkpoint_legacy_resume.json");
assert!(legacy.get("schema").is_none());
assert!(legacy.get("effect_class").is_none());
assert_eq!(legacy["id"], "legacy_resume_01");
let ledger = fixture("effect_ledger_v1.json");
assert_eq!(ledger["state"], "prepared");
assert_eq!(ledger["effect_class"], "write");
let out_ok = fixture("agent_output_v1_succeeded.json");
assert_required(&out_ok, &schema("AgentOutputV1.schema.json"), "agent_output_ok");
assert_eq!(out_ok["status"], "succeeded");
let out_fail = fixture("agent_output_v1_failed.json");
assert_required(
&out_fail,
&schema("AgentOutputV1.schema.json"),
"agent_output_fail",
);
assert_eq!(out_fail["status"], "failed");
let pack = fixture("context_pack_v2.json");
assert_required(&pack, &schema("ContextPackV2.schema.json"), "context_pack");
assert_eq!(pack["schema_version"], 2);
let item = &pack["items"][0];
for key in [
"origin",
"trust",
"resource_ref",
"revision",
"token_estimate",
"priority",
] {
assert!(item.get(key).is_some(), "context item missing {key}");
}
assert_required(
&fixture("resource_ref_v1.json"),
&schema("ResourceRefV1.schema.json"),
"resource_ref",
);
let view = fixture("resource_view_v1.json");
assert_required(&view, &schema("ResourceViewV1.schema.json"), "resource_view");
assert_eq!(view["no_exec"], true);
let tev = fixture("runtime_event_tool_failed.json");
assert_eq!(tev["schema"], "RuntimeEventV2");
assert_eq!(tev["type"], "tool.failed");
assert_eq!(tev["payload"]["schema"], "AgentErrorV1");
let caps = mlsp("capabilities", serde_json::json!({}));
assert_eq!(caps["ok"], true, "{caps}");
let features = &caps["result"]["features"];
for bit in [
"agent.error_v1",
"agent.checkpoint_v2",
"agent.tool_schema_v1",
"agent.output_channels_v1",
"agent.context_pack_v2",
] {
assert_eq!(features[bit], 0, "{bit} must stay 0 until emitters land");
}
// M-A3 subset: ResourceView emitter is live under the view feature.
assert_eq!(features["resource.view_v1"], 1);
// Unknown/future schema_version must not flip unimplemented agent bits.
assert_eq!(features["agent.error_v1"], 0);
let formats = caps["result"]["extract_formats"]
.as_array()
.expect("extract_formats");
let pdf = formats
.iter()
.find(|f| f["format"] == "pdf")
.expect("pdf row");
assert_eq!(pdf["available"], false);
let json_fmt = formats
.iter()
.find(|f| f["format"] == "json")
.expect("json row");
assert_eq!(json_fmt["available"], false);
// Live contracts list still excludes unimplemented agent schemas.
let contracts = caps["result"]["contracts"].as_array().unwrap();
assert!(!contracts.iter().any(|c| c.as_str() == Some("AgentErrorV1")));
let down = mlsp(
"capabilities",
serde_json::json!({
"force_unloaded": true,
"force_stream_off": true,
"force_cancel_off": true
}),
);
assert_eq!(down["result"]["features"]["agent.error_v1"], 0);
assert_eq!(down["result"]["features"]["resource.view_v1"], 1);
}
#[test]
fn ma3_resource_view_static_no_exec() {
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!("marqdo-ma3-rv-{nanos}"));
std::fs::create_dir_all(&dir).unwrap();
let md = dir.join("readme.md");
{
let mut f = std::fs::File::create(&md).unwrap();
writeln!(f, "# Hello\n\n<script>x</script>").unwrap();
}
let resp = mlsp(
"resource.view",
serde_json::json!({
"workspace_root": dir.to_string_lossy(),
"path": "readme.md",
"mode": "read"
}),
);
assert_eq!(resp["ok"], true, "{resp}");
let view = &resp["result"];
assert_required(view, &schema("ResourceViewV1.schema.json"), "resource_view_live");
assert_eq!(view["no_exec"], true);
assert_eq!(view["schema"], "ResourceViewV1");
let frag = view["render"]["fragment"].as_str().unwrap();
assert!(frag.contains("Hello"));
assert!(frag.contains("&lt;script&gt;") || !frag.contains("<script>"));
let escape = mlsp(
"resource.view",
serde_json::json!({
"workspace_root": dir.to_string_lossy(),
"path": "../outside.txt",
"mode": "read"
}),
);
assert_eq!(escape["ok"], false, "{escape}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn m00_strict_selection_rejects_missing() {
let bad = serde_json::json!({"schema_version": 1, "model_id": "x"});