feat: EditorRuntimeActor - 三层缓存/delta/事件架构
Phase A — EditorRuntimeActor 内存缓存层 - 新增 editor_actor.rs: EditorBlockDocument 内存态 + apply_command + load_or_init - block.rs 四个写工具(replace/insert/delete/move)接入 actor 路径 - editor_actor feature flag(MNOTE_WEB_ENABLE_EDITOR_ACTOR=true 默认开启) - bridge-runtime 三个核心函数公开化 - rust-toolchain: 1.89 → stable(修复 spike WASM 编译阻塞) Phase B — 编辑器增量 delta channel - BlockDelta/DeltaOperation 类型 + actor.build_block_delta() - leptos-tiptap spike: mnote:editor:block-delta CustomEvent 监听 + JSON patch - DocumentAiAgentPanel: 拦截 blockDelta → window dispatchEvent - 工具响应含 blockDelta 字段供前端消费 Phase C — 事件 stream delta - broadcast channel 在 AppState/actor/SSE 三层贯通 - tree_events SSE 端点发 block.delta 事件 - 旧客户端降级兼容 环境修复 - rustc recursion_limit = 1024(修复 Leptos SSR 类型深度溢出) - run-convex-deploy.js(封装 Convex function 部署到本地后端 3210) ref: design/07-ai/process/7-13-page-block-editor-runtime-actor-v1.md
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,538 @@
|
||||
use crate::app::AppState;
|
||||
use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use crate::hermes_tools::ToolCallInput;
|
||||
use crate::routes::web_shell::build_page_aggregate_snapshot;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub async fn doc_fetch(
|
||||
state: &AppState,
|
||||
context: &RequestContext,
|
||||
input: &ToolCallInput,
|
||||
) -> Result<Value, WebError> {
|
||||
let aggregate = aggregate_value(state, context, input).await?;
|
||||
let document_id = input.effective_document_id().unwrap_or_default();
|
||||
let workspace_id = input.effective_workspace_id();
|
||||
let scope = input
|
||||
.arg_string("scope")
|
||||
.unwrap_or_else(|| "full".into())
|
||||
.to_ascii_lowercase();
|
||||
let detail = input
|
||||
.arg_string("detail")
|
||||
.unwrap_or_else(|| "with_ids".into())
|
||||
.to_ascii_lowercase();
|
||||
let max_blocks = input
|
||||
.arg_value("maxBlocks")
|
||||
.and_then(|value| value.as_u64())
|
||||
.unwrap_or(120)
|
||||
.clamp(1, 240) as usize;
|
||||
let mut blocks = block_projection_blocks(&aggregate);
|
||||
blocks = match scope.as_str() {
|
||||
"outline" => blocks
|
||||
.into_iter()
|
||||
.filter(|block| block.get("type").and_then(Value::as_str) == Some("heading"))
|
||||
.collect(),
|
||||
"block" => {
|
||||
let block_id = input.arg_string("blockId").ok_or_else(|| {
|
||||
WebError::bad_request_code(
|
||||
"mnote_tool_bad_request",
|
||||
"mnote.doc.fetch scope=block 缺少 blockId",
|
||||
)
|
||||
.with_context(context)
|
||||
})?;
|
||||
blocks
|
||||
.into_iter()
|
||||
.filter(|block| block_id_of(block).as_deref() == Some(block_id.as_str()))
|
||||
.collect()
|
||||
}
|
||||
"keyword" => {
|
||||
let query = input.arg_string("query").ok_or_else(|| {
|
||||
WebError::bad_request_code(
|
||||
"mnote_tool_bad_request",
|
||||
"mnote.doc.fetch scope=keyword 缺少 query",
|
||||
)
|
||||
.with_context(context)
|
||||
})?;
|
||||
filter_blocks_by_query(blocks, &query)
|
||||
}
|
||||
"selection" => {
|
||||
let selected_ids = selected_block_ids(input);
|
||||
if selected_ids.is_empty() {
|
||||
return Err(WebError::bad_request_code(
|
||||
"mnote_tool_bad_request",
|
||||
"mnote.doc.fetch scope=selection 缺少 selectedBlockIds",
|
||||
)
|
||||
.with_context(context));
|
||||
}
|
||||
blocks
|
||||
.into_iter()
|
||||
.filter(|block| {
|
||||
block_id_of(block)
|
||||
.map(|block_id| selected_ids.contains(&block_id))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
_ => blocks,
|
||||
};
|
||||
let truncated = blocks.len() > max_blocks;
|
||||
blocks.truncate(max_blocks);
|
||||
let format = input
|
||||
.arg_string("format")
|
||||
.unwrap_or_else(|| "json".into())
|
||||
.to_ascii_lowercase();
|
||||
let include_ids = detail == "with_ids" || detail == "full";
|
||||
let content = blocks_to_content(&format, &blocks, include_ids, &document_id, &aggregate);
|
||||
let warnings = if truncated {
|
||||
json!([{
|
||||
"code": "mnote_doc_fetch_truncated",
|
||||
"message": "结果已按 maxBlocks 裁剪",
|
||||
"maxBlocks": max_blocks
|
||||
}])
|
||||
} else {
|
||||
json!([])
|
||||
};
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"schema": "mnote.page_ai_context.v1",
|
||||
"documentId": document_id,
|
||||
"workspaceId": workspace_id,
|
||||
"revision": aggregate.pointer("/body/revision").cloned().unwrap_or(Value::Null),
|
||||
"conflictDetectionKey": aggregate.pointer("/body/conflictDetectionKey").cloned().unwrap_or(Value::Null),
|
||||
"format": format,
|
||||
"detail": detail,
|
||||
"scope": scope,
|
||||
"content": content,
|
||||
"blocks": blocks,
|
||||
"allowedTargetBlockIds": selected_block_ids(input),
|
||||
"truncated": truncated,
|
||||
"continuation": if truncated { json!({"maxBlocks": max_blocks}) } else { Value::Null },
|
||||
"warnings": warnings
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn doc_find(
|
||||
state: &AppState,
|
||||
context: &RequestContext,
|
||||
input: &ToolCallInput,
|
||||
) -> Result<Value, WebError> {
|
||||
let aggregate = aggregate_value(state, context, input).await?;
|
||||
let query = input.arg_string("query").ok_or_else(|| {
|
||||
WebError::bad_request_code("mnote_tool_bad_request", "mnote.doc.find 缺少 query")
|
||||
.with_context(context)
|
||||
})?;
|
||||
let match_kind = input
|
||||
.arg_string("match")
|
||||
.unwrap_or_else(|| "text".into())
|
||||
.to_ascii_lowercase();
|
||||
let limit = input
|
||||
.arg_value("limit")
|
||||
.and_then(|value| value.as_u64())
|
||||
.unwrap_or(20)
|
||||
.clamp(1, 50) as usize;
|
||||
let mut matches = Vec::new();
|
||||
for block in block_projection_blocks(&aggregate) {
|
||||
let matched = match match_kind.as_str() {
|
||||
"type" => block
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.map(|value| value.eq_ignore_ascii_case(&query))
|
||||
.unwrap_or(false),
|
||||
"block_id" | "blockid" => block_id_of(&block).as_deref() == Some(query.as_str()),
|
||||
_ => block
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.map(|text| text.contains(&query))
|
||||
.unwrap_or(false),
|
||||
};
|
||||
if matched {
|
||||
matches.push(json!({
|
||||
"blockId": block.get("blockId").cloned().unwrap_or(Value::Null),
|
||||
"type": block.get("type").cloned().unwrap_or(Value::Null),
|
||||
"text": block.get("text").cloned().unwrap_or(Value::Null),
|
||||
"path": block.get("path").cloned().unwrap_or(Value::Null),
|
||||
"revisionRef": block.get("revisionRef").cloned().unwrap_or(Value::Null),
|
||||
"score": 1.0
|
||||
}));
|
||||
if matches.len() >= limit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"documentId": input.effective_document_id(),
|
||||
"workspaceId": input.effective_workspace_id(),
|
||||
"revision": aggregate.pointer("/body/revision").cloned().unwrap_or(Value::Null),
|
||||
"conflictDetectionKey": aggregate.pointer("/body/conflictDetectionKey").cloned().unwrap_or(Value::Null),
|
||||
"matches": matches
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn plan_update(
|
||||
state: &AppState,
|
||||
context: &RequestContext,
|
||||
input: &ToolCallInput,
|
||||
) -> Result<Value, WebError> {
|
||||
if !input.has_idempotency_key() {
|
||||
return Err(WebError::bad_request_code(
|
||||
"mnote_tool_idempotency_required",
|
||||
"写入计划型 mnote Hermes tool 必须携带 idempotencyKey",
|
||||
)
|
||||
.with_context(context));
|
||||
}
|
||||
if input.dry_run != Some(true) {
|
||||
return Err(WebError::bad_request_code(
|
||||
"mnote_tool_dry_run_required",
|
||||
"mnote.doc.plan_update 第一阶段只允许 dryRun=true",
|
||||
)
|
||||
.with_context(context));
|
||||
}
|
||||
let aggregate = aggregate_value(state, context, input).await?;
|
||||
let command = input
|
||||
.arg_string("command")
|
||||
.unwrap_or_else(|| "block_replace".into())
|
||||
.to_ascii_lowercase();
|
||||
let blocks = block_projection_blocks(&aggregate);
|
||||
let diff = match command.as_str() {
|
||||
"block_replace" => {
|
||||
let block_id = required_arg(input, context, "blockId")?;
|
||||
let block = find_block(&blocks, &block_id).ok_or_else(|| block_not_found(context))?;
|
||||
vec![json!({
|
||||
"op": "replace",
|
||||
"targetBlockId": block_id,
|
||||
"before": block.get("text").cloned().unwrap_or(Value::Null),
|
||||
"after": input.arg_value("content").unwrap_or(Value::Null)
|
||||
})]
|
||||
}
|
||||
"block_insert_after" => {
|
||||
let anchor = input
|
||||
.arg_string("anchorBlockId")
|
||||
.or_else(|| input.arg_string("afterBlockId"))
|
||||
.ok_or_else(|| {
|
||||
WebError::bad_request_code(
|
||||
"mnote_tool_bad_request",
|
||||
"mnote.doc.plan_update block_insert_after 缺少 anchorBlockId",
|
||||
)
|
||||
.with_context(context)
|
||||
})?;
|
||||
let block = find_block(&blocks, &anchor).ok_or_else(|| block_not_found(context))?;
|
||||
vec![json!({
|
||||
"op": "insert_after",
|
||||
"anchorBlockId": anchor,
|
||||
"after": block.get("text").cloned().unwrap_or(Value::Null),
|
||||
"content": input.arg_value("content").unwrap_or(Value::Null)
|
||||
})]
|
||||
}
|
||||
"block_move_after" => {
|
||||
let block_id = required_arg(input, context, "blockId")?;
|
||||
let anchor = required_arg(input, context, "anchorBlockId")?;
|
||||
let block = find_block(&blocks, &block_id).ok_or_else(|| block_not_found(context))?;
|
||||
let anchor_block =
|
||||
find_block(&blocks, &anchor).ok_or_else(|| block_not_found(context))?;
|
||||
let blocked = block_move_after_blocked(&block, &anchor_block, &block_id, &anchor);
|
||||
vec![json!({
|
||||
"op": "move_after",
|
||||
"blockId": block_id,
|
||||
"anchorBlockId": anchor,
|
||||
"supportedForWrite": !blocked,
|
||||
"blocked": blocked
|
||||
})]
|
||||
}
|
||||
"block_delete" => {
|
||||
let block_id = required_arg(input, context, "blockId")?;
|
||||
let block = find_block(&blocks, &block_id).ok_or_else(|| block_not_found(context))?;
|
||||
let blocked = block
|
||||
.get("children")
|
||||
.and_then(Value::as_array)
|
||||
.map(|children| !children.is_empty())
|
||||
.unwrap_or(false);
|
||||
vec![json!({
|
||||
"op": "delete",
|
||||
"blockId": block_id,
|
||||
"before": block.get("text").cloned().unwrap_or(Value::Null),
|
||||
"supportedForWrite": !blocked,
|
||||
"blocked": blocked
|
||||
})]
|
||||
}
|
||||
"str_replace" => vec![json!({
|
||||
"op": "str_replace",
|
||||
"query": input.arg_value("query").unwrap_or(Value::Null),
|
||||
"replacement": input.arg_value("content").unwrap_or(Value::Null)
|
||||
})],
|
||||
other => {
|
||||
return Err(WebError::bad_request_code(
|
||||
"mnote_tool_bad_request",
|
||||
format!("mnote.doc.plan_update 不支持 command={other}"),
|
||||
)
|
||||
.with_context(context));
|
||||
}
|
||||
};
|
||||
let plan_blocked = matches!(command.as_str(), "block_move_after" | "block_delete")
|
||||
&& diff
|
||||
.first()
|
||||
.and_then(|item| item.get("blocked"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"dryRun": true,
|
||||
"planId": format!("plan_{}", context.trace.request_id),
|
||||
"documentId": input.effective_document_id(),
|
||||
"workspaceId": input.effective_workspace_id(),
|
||||
"revision": aggregate.pointer("/body/revision").cloned().unwrap_or(Value::Null),
|
||||
"conflictDetectionKey": aggregate.pointer("/body/conflictDetectionKey").cloned().unwrap_or(Value::Null),
|
||||
"command": command,
|
||||
"diff": diff,
|
||||
"warnings": if plan_blocked {
|
||||
json!([{
|
||||
"code": "block_move_after_blocked",
|
||||
"message": "第一阶段仅开放同父级普通叶子块移动,且不能移动到自身之后"
|
||||
}])
|
||||
} else {
|
||||
json!([])
|
||||
},
|
||||
"risk": if command == "block_move_after" { "medium" } else { "low" },
|
||||
"blocked": plan_blocked
|
||||
}))
|
||||
}
|
||||
|
||||
fn block_move_after_blocked(
|
||||
block: &Value,
|
||||
anchor: &Value,
|
||||
block_id: &str,
|
||||
anchor_id: &str,
|
||||
) -> bool {
|
||||
let same_parent = block.get("parentBlockId") == anchor.get("parentBlockId");
|
||||
let leaf = block
|
||||
.get("children")
|
||||
.and_then(Value::as_array)
|
||||
.map(|children| children.is_empty())
|
||||
.unwrap_or(true);
|
||||
let movable_type = block
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.map(|block_type| matches!(block_type, "paragraph" | "heading" | "todo" | "task"))
|
||||
.unwrap_or(false);
|
||||
let editable = block
|
||||
.get("editable")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
!same_parent || !leaf || !movable_type || !editable || block_id == anchor_id
|
||||
}
|
||||
|
||||
pub(crate) async fn aggregate_value(
|
||||
state: &AppState,
|
||||
context: &RequestContext,
|
||||
input: &ToolCallInput,
|
||||
) -> Result<Value, WebError> {
|
||||
let document_id = input.effective_document_id().ok_or_else(|| {
|
||||
WebError::bad_request_code("mnote_tool_bad_request", "页面工具缺少 documentId")
|
||||
.with_context(context)
|
||||
})?;
|
||||
let workspace_id = input.effective_workspace_id();
|
||||
let aggregate = build_page_aggregate_snapshot(
|
||||
state,
|
||||
context,
|
||||
&document_id,
|
||||
workspace_id.as_deref(),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
serde_json::to_value(&aggregate).map_err(|error| WebError::internal(error.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) fn block_projection_blocks(aggregate: &Value) -> Vec<Value> {
|
||||
aggregate
|
||||
.pointer("/body/blockDocument/blocks")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn block_id_of(block: &Value) -> Option<String> {
|
||||
block
|
||||
.get("blockId")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub(crate) fn find_block(blocks: &[Value], block_id: &str) -> Option<Value> {
|
||||
blocks
|
||||
.iter()
|
||||
.find(|block| block_id_of(block).as_deref() == Some(block_id))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn required_arg(
|
||||
input: &ToolCallInput,
|
||||
context: &RequestContext,
|
||||
key: &'static str,
|
||||
) -> Result<String, WebError> {
|
||||
input.arg_string(key).ok_or_else(|| {
|
||||
WebError::bad_request_code("mnote_tool_bad_request", format!("工具调用缺少 {key}"))
|
||||
.with_context(context)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn block_not_found(context: &RequestContext) -> WebError {
|
||||
WebError::bad_request_code("mnote_block_not_found", "块不存在").with_context(context)
|
||||
}
|
||||
|
||||
fn filter_blocks_by_query(blocks: Vec<Value>, query: &str) -> Vec<Value> {
|
||||
blocks
|
||||
.into_iter()
|
||||
.filter(|block| {
|
||||
block
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.map(|text| text.contains(query))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn selected_block_ids(input: &ToolCallInput) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut ids = Vec::new();
|
||||
for key in ["selectedBlockIds", "allowedTargetBlockIds"] {
|
||||
if let Some(Value::Array(values)) = input.arg_value(key) {
|
||||
for value in values {
|
||||
if let Some(id) = value.as_str().map(str::trim).filter(|id| !id.is_empty()) {
|
||||
if seen.insert(id.to_string()) {
|
||||
ids.push(id.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for key in ["selectedBlockId", "blockId"] {
|
||||
if let Some(id) = input.arg_string(key) {
|
||||
if seen.insert(id.clone()) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
fn blocks_to_content(
|
||||
format: &str,
|
||||
blocks: &[Value],
|
||||
include_ids: bool,
|
||||
document_id: &str,
|
||||
aggregate: &Value,
|
||||
) -> String {
|
||||
match format {
|
||||
"page_xml" | "xml" => blocks_to_page_xml(blocks, document_id, aggregate),
|
||||
"text" | "plain" => blocks_to_text(blocks, include_ids),
|
||||
"markdown" | "md" => blocks_to_markdown(blocks, include_ids),
|
||||
_ => blocks_to_markdown(blocks, include_ids),
|
||||
}
|
||||
}
|
||||
|
||||
fn blocks_to_text(blocks: &[Value], include_ids: bool) -> String {
|
||||
blocks
|
||||
.iter()
|
||||
.map(|block| {
|
||||
let text = block_text(block);
|
||||
if include_ids {
|
||||
format!("[{}] {text}", block_id_of(block).unwrap_or_default())
|
||||
} else {
|
||||
text
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn blocks_to_markdown(blocks: &[Value], include_ids: bool) -> String {
|
||||
blocks
|
||||
.iter()
|
||||
.map(|block| {
|
||||
let text = block_text(block);
|
||||
let prefix = match block.get("type").and_then(Value::as_str) {
|
||||
Some("heading") => "## ",
|
||||
Some("todo") | Some("task") => "- [ ] ",
|
||||
_ => "",
|
||||
};
|
||||
if include_ids {
|
||||
format!(
|
||||
"{prefix}{text} <!-- block:{} -->",
|
||||
block_id_of(block).unwrap_or_default()
|
||||
)
|
||||
} else {
|
||||
format!("{prefix}{text}")
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn blocks_to_page_xml(blocks: &[Value], document_id: &str, aggregate: &Value) -> String {
|
||||
let revision = aggregate
|
||||
.pointer("/body/revision")
|
||||
.and_then(Value::as_u64)
|
||||
.map(|value| value.to_string())
|
||||
.unwrap_or_else(|| {
|
||||
aggregate
|
||||
.pointer("/body/revision")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
});
|
||||
let mut output = format!(
|
||||
"<page id=\"{}\" revision=\"{}\">",
|
||||
escape_xml(document_id),
|
||||
escape_xml(&revision)
|
||||
);
|
||||
for block in blocks {
|
||||
let block_id = block_id_of(block).unwrap_or_default();
|
||||
let block_type = block
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("paragraph");
|
||||
let revision_ref = block
|
||||
.get("revisionRef")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
output.push_str(&format!(
|
||||
"\n <block id=\"{}\" type=\"{}\" revisionRef=\"{}\"",
|
||||
escape_xml(&block_id),
|
||||
escape_xml(block_type),
|
||||
escape_xml(revision_ref)
|
||||
));
|
||||
if let Some(level) = block
|
||||
.pointer("/attrs/level")
|
||||
.or_else(|| block.pointer("/props/level"))
|
||||
{
|
||||
if let Some(level) = level.as_u64() {
|
||||
output.push_str(&format!(" level=\"{}\"", level));
|
||||
}
|
||||
}
|
||||
output.push_str(&format!(">{}</block>", escape_xml(&block_text(block))));
|
||||
}
|
||||
output.push_str("\n</page>");
|
||||
output
|
||||
}
|
||||
|
||||
fn block_text(block: &Value) -> String {
|
||||
block
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn escape_xml(value: &str) -> String {
|
||||
value
|
||||
.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
@@ -13,6 +13,15 @@ pub fn manifest() -> Value {
|
||||
"writeOwner": "rust-runtime-kernel"
|
||||
},
|
||||
"tools": [
|
||||
doc_fetch_tool(),
|
||||
doc_find_tool(),
|
||||
block_fetch_tool(),
|
||||
doc_plan_update_tool(),
|
||||
block_replace_tool(),
|
||||
block_insert_after_tool(),
|
||||
block_delete_tool(),
|
||||
block_move_after_tool(),
|
||||
doc_apply_block_ops_tool(),
|
||||
page_get_tool(),
|
||||
page_save_tool(),
|
||||
available_tool("mnote.page.update_title", "更新当前页面标题", ["page.write"]),
|
||||
@@ -23,6 +32,306 @@ pub fn manifest() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
fn base_identity_properties() -> Value {
|
||||
json!({
|
||||
"workspaceId": { "type": "string" },
|
||||
"documentId": { "type": "string" },
|
||||
"sessionId": { "type": "string" },
|
||||
"runId": { "type": "string" },
|
||||
"toolCallId": { "type": "string" },
|
||||
"traceId": { "type": "string" },
|
||||
"actorId": { "type": "string" },
|
||||
"actorType": { "type": "string" }
|
||||
})
|
||||
}
|
||||
|
||||
fn doc_fetch_tool() -> Value {
|
||||
let mut properties = base_identity_properties();
|
||||
if let Value::Object(map) = &mut properties {
|
||||
map.insert(
|
||||
"scope".into(),
|
||||
json!({ "type": "string", "default": "full" }),
|
||||
);
|
||||
map.insert(
|
||||
"detail".into(),
|
||||
json!({ "type": "string", "default": "with_ids" }),
|
||||
);
|
||||
map.insert(
|
||||
"format".into(),
|
||||
json!({ "type": "string", "enum": ["json", "markdown", "text", "page_xml"], "default": "json" }),
|
||||
);
|
||||
map.insert("blockId".into(), json!({ "type": "string" }));
|
||||
map.insert(
|
||||
"selectedBlockIds".into(),
|
||||
json!({ "type": "array", "items": { "type": "string" } }),
|
||||
);
|
||||
map.insert(
|
||||
"allowedTargetBlockIds".into(),
|
||||
json!({ "type": "array", "items": { "type": "string" } }),
|
||||
);
|
||||
map.insert("query".into(), json!({ "type": "string" }));
|
||||
map.insert(
|
||||
"maxBlocks".into(),
|
||||
json!({ "type": "integer", "default": 120 }),
|
||||
);
|
||||
}
|
||||
json!({
|
||||
"name": "mnote.doc.fetch",
|
||||
"description": "读取当前页面的 canonical block projection,支持 full/outline/block/keyword 范围",
|
||||
"schemaVersion": TOOL_SCHEMA_VERSION,
|
||||
"capabilityScope": ["page.read"],
|
||||
"status": "available",
|
||||
"annotations": tool_annotations(true, false, true, false),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"required": ["workspaceId", "documentId", "sessionId", "runId", "toolCallId", "traceId", "actorId"],
|
||||
"properties": properties
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn doc_find_tool() -> Value {
|
||||
let mut properties = base_identity_properties();
|
||||
if let Value::Object(map) = &mut properties {
|
||||
map.insert("query".into(), json!({ "type": "string" }));
|
||||
map.insert(
|
||||
"match".into(),
|
||||
json!({ "type": "string", "default": "text" }),
|
||||
);
|
||||
map.insert("limit".into(), json!({ "type": "integer", "default": 20 }));
|
||||
}
|
||||
json!({
|
||||
"name": "mnote.doc.find",
|
||||
"description": "在 Page Aggregate block projection 中按文本、类型或 blockId 查找块",
|
||||
"schemaVersion": TOOL_SCHEMA_VERSION,
|
||||
"capabilityScope": ["page.read"],
|
||||
"status": "available",
|
||||
"annotations": tool_annotations(true, false, true, false),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"required": ["workspaceId", "documentId", "sessionId", "runId", "toolCallId", "traceId", "actorId", "query"],
|
||||
"properties": properties
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn block_fetch_tool() -> Value {
|
||||
let mut properties = base_identity_properties();
|
||||
if let Value::Object(map) = &mut properties {
|
||||
map.insert("blockId".into(), json!({ "type": "string" }));
|
||||
map.insert(
|
||||
"includeChildren".into(),
|
||||
json!({ "type": "boolean", "default": true }),
|
||||
);
|
||||
map.insert(
|
||||
"contextBefore".into(),
|
||||
json!({ "type": "integer", "default": 1 }),
|
||||
);
|
||||
map.insert(
|
||||
"contextAfter".into(),
|
||||
json!({ "type": "integer", "default": 1 }),
|
||||
);
|
||||
map.insert(
|
||||
"format".into(),
|
||||
json!({ "type": "string", "enum": ["json", "markdown", "text", "page_xml"], "default": "json" }),
|
||||
);
|
||||
}
|
||||
json!({
|
||||
"name": "mnote.block.fetch",
|
||||
"description": "读取单个块及同父级上下文",
|
||||
"schemaVersion": TOOL_SCHEMA_VERSION,
|
||||
"capabilityScope": ["block.read", "page.read"],
|
||||
"status": "available",
|
||||
"annotations": tool_annotations(true, false, true, false),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"required": ["workspaceId", "documentId", "sessionId", "runId", "toolCallId", "traceId", "actorId", "blockId"],
|
||||
"properties": properties
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn doc_plan_update_tool() -> Value {
|
||||
write_tool(
|
||||
"mnote.doc.plan_update",
|
||||
"生成页面块更新 dry-run 计划,不直接写入",
|
||||
["page.write", "block.write"],
|
||||
json!({
|
||||
"command": { "type": "string" },
|
||||
"blockId": { "type": "string" },
|
||||
"anchorBlockId": { "type": "string" },
|
||||
"content": { "type": ["string", "object", "array"] },
|
||||
"query": { "type": "string" },
|
||||
"revision": { "type": ["number", "string"] },
|
||||
"conflictDetectionKey": { "type": "string" }
|
||||
}),
|
||||
[],
|
||||
)
|
||||
}
|
||||
|
||||
fn block_replace_tool() -> Value {
|
||||
write_tool(
|
||||
"mnote.block.replace",
|
||||
"替换指定块内容;真实写入走 Rust page.body.save 链路",
|
||||
["block.write", "page.write"],
|
||||
json!({
|
||||
"blockId": { "type": "string" },
|
||||
"content": { "type": ["string", "object", "array"] },
|
||||
"revision": { "type": ["number", "string"] },
|
||||
"conflictDetectionKey": { "type": "string" },
|
||||
"blockRevisionRef": { "type": "string" }
|
||||
}),
|
||||
[
|
||||
"blockId",
|
||||
"content",
|
||||
"revision",
|
||||
"conflictDetectionKey",
|
||||
"blockRevisionRef",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn block_insert_after_tool() -> Value {
|
||||
write_tool(
|
||||
"mnote.block.insert_after",
|
||||
"在指定块后插入新块;真实写入走 Rust page.body.save 链路",
|
||||
["block.write", "page.write"],
|
||||
json!({
|
||||
"anchorBlockId": { "type": "string" },
|
||||
"content": { "type": ["string", "object", "array"] },
|
||||
"block": { "type": "object" },
|
||||
"revision": { "type": ["number", "string"] },
|
||||
"conflictDetectionKey": { "type": "string" },
|
||||
"anchorRevisionRef": { "type": "string" }
|
||||
}),
|
||||
[
|
||||
"anchorBlockId",
|
||||
"content",
|
||||
"revision",
|
||||
"conflictDetectionKey",
|
||||
"anchorRevisionRef",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn block_move_after_tool() -> Value {
|
||||
write_tool(
|
||||
"mnote.block.move_after",
|
||||
"受限同父级普通叶子块移动;真实写入走 Rust page.body.save 链路",
|
||||
["block.write", "page.write"],
|
||||
json!({
|
||||
"blockId": { "type": "string" },
|
||||
"anchorBlockId": { "type": "string" },
|
||||
"revision": { "type": ["number", "string"] },
|
||||
"conflictDetectionKey": { "type": "string" },
|
||||
"blockRevisionRef": { "type": "string" },
|
||||
"anchorRevisionRef": { "type": "string" }
|
||||
}),
|
||||
[
|
||||
"blockId",
|
||||
"anchorBlockId",
|
||||
"revision",
|
||||
"conflictDetectionKey",
|
||||
"blockRevisionRef",
|
||||
"anchorRevisionRef",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn block_delete_tool() -> Value {
|
||||
write_tool(
|
||||
"mnote.block.delete",
|
||||
"删除指定无子块普通块;真实写入走 Rust page.body.save 链路",
|
||||
["block.write", "page.write"],
|
||||
json!({
|
||||
"blockId": { "type": "string" },
|
||||
"revision": { "type": ["number", "string"] },
|
||||
"conflictDetectionKey": { "type": "string" },
|
||||
"blockRevisionRef": { "type": "string" }
|
||||
}),
|
||||
[
|
||||
"blockId",
|
||||
"revision",
|
||||
"conflictDetectionKey",
|
||||
"blockRevisionRef",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn doc_apply_block_ops_tool() -> Value {
|
||||
write_tool(
|
||||
"mnote.doc.apply_block_ops",
|
||||
"一次性应用多个块级操作;Rust 侧统一读取最新 projection、生成 canonical content 并一次保存,适合页面 AI 小段落增删改移动快路径",
|
||||
["block.write", "page.write"],
|
||||
json!({
|
||||
"operations": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"op": { "type": "string" },
|
||||
"blockId": { "type": "string" },
|
||||
"anchorBlockId": { "type": "string" },
|
||||
"matchText": { "type": "string" },
|
||||
"anchorText": { "type": "string" },
|
||||
"afterText": { "type": "string" },
|
||||
"allowedTargetBlockIds": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" }
|
||||
},
|
||||
"content": { "type": ["string", "object", "array"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
["operations"],
|
||||
)
|
||||
}
|
||||
|
||||
fn write_tool(
|
||||
name: &str,
|
||||
description: &str,
|
||||
scope: impl IntoIterator<Item = &'static str>,
|
||||
extra_properties: Value,
|
||||
extra_required: impl IntoIterator<Item = &'static str>,
|
||||
) -> Value {
|
||||
let mut properties = base_identity_properties();
|
||||
if let Value::Object(map) = &mut properties {
|
||||
map.insert("dryRun".into(), json!({ "type": "boolean" }));
|
||||
map.insert("idempotencyKey".into(), json!({ "type": "string" }));
|
||||
if let Value::Object(extra) = extra_properties {
|
||||
for (key, value) in extra {
|
||||
map.insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut required = vec![
|
||||
"workspaceId",
|
||||
"documentId",
|
||||
"sessionId",
|
||||
"runId",
|
||||
"toolCallId",
|
||||
"traceId",
|
||||
"actorId",
|
||||
"dryRun",
|
||||
"idempotencyKey",
|
||||
];
|
||||
required.extend(extra_required);
|
||||
json!({
|
||||
"name": name,
|
||||
"description": description,
|
||||
"schemaVersion": TOOL_SCHEMA_VERSION,
|
||||
"capabilityScope": scope.into_iter().collect::<Vec<_>>(),
|
||||
"status": "available",
|
||||
"annotations": tool_annotations(false, false, false, false),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"required": required,
|
||||
"properties": properties
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn page_get_tool() -> Value {
|
||||
json!({
|
||||
"name": "mnote.page.get",
|
||||
@@ -31,7 +340,7 @@ fn page_get_tool() -> Value {
|
||||
"capabilityScope": ["page.read"],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"required": ["workspaceId", "documentId", "sessionId", "runId", "toolCallId", "traceId"],
|
||||
"required": ["workspaceId", "documentId", "sessionId", "runId", "toolCallId", "traceId", "actorId"],
|
||||
"properties": {
|
||||
"workspaceId": { "type": "string" },
|
||||
"documentId": { "type": "string" },
|
||||
@@ -39,6 +348,8 @@ fn page_get_tool() -> Value {
|
||||
"runId": { "type": "string" },
|
||||
"toolCallId": { "type": "string" },
|
||||
"traceId": { "type": "string" },
|
||||
"actorId": { "type": "string" },
|
||||
"actorType": { "type": "string" },
|
||||
"includeBody": { "type": "boolean", "default": true },
|
||||
"includeOptions": { "type": "boolean", "default": true },
|
||||
"includeBlocks": { "type": "boolean", "default": true }
|
||||
@@ -54,9 +365,10 @@ fn page_save_tool() -> Value {
|
||||
"schemaVersion": TOOL_SCHEMA_VERSION,
|
||||
"capabilityScope": ["page.write"],
|
||||
"status": "available",
|
||||
"annotations": tool_annotations(false, true, false, false),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"required": ["workspaceId", "documentId", "sessionId", "runId", "toolCallId", "traceId", "content", "dryRun", "idempotencyKey"],
|
||||
"required": ["workspaceId", "documentId", "sessionId", "runId", "toolCallId", "traceId", "actorId", "content", "dryRun", "idempotencyKey"],
|
||||
"properties": {
|
||||
"workspaceId": { "type": "string" },
|
||||
"documentId": { "type": "string" },
|
||||
@@ -64,6 +376,8 @@ fn page_save_tool() -> Value {
|
||||
"runId": { "type": "string" },
|
||||
"toolCallId": { "type": "string" },
|
||||
"traceId": { "type": "string" },
|
||||
"actorId": { "type": "string" },
|
||||
"actorType": { "type": "string" },
|
||||
"content": {
|
||||
"description": "要写入的正文块数组、{blocks:[...]}、TipTap content 数组或纯文本",
|
||||
"type": ["array", "object", "string"]
|
||||
@@ -90,6 +404,25 @@ fn available_tool(
|
||||
"description": description,
|
||||
"schemaVersion": TOOL_SCHEMA_VERSION,
|
||||
"capabilityScope": scope.into_iter().collect::<Vec<_>>(),
|
||||
"status": "available"
|
||||
"status": "available",
|
||||
"annotations": tool_annotations(false, false, false, false)
|
||||
})
|
||||
}
|
||||
|
||||
fn tool_annotations(
|
||||
readonly: bool,
|
||||
destructive: bool,
|
||||
idempotent: bool,
|
||||
requires_approval: bool,
|
||||
) -> Value {
|
||||
json!({
|
||||
"readonly": readonly,
|
||||
"destructive": destructive,
|
||||
"idempotent": idempotent,
|
||||
"requiresApproval": requires_approval,
|
||||
"approvalMode": if requires_approval { "review" } else { "yolo" },
|
||||
"runtimeOwner": "mnote-web",
|
||||
"writeOwner": "rust-runtime-kernel",
|
||||
"selectionEffect": if readonly { "preserve" } else { "may_change" }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
pub mod artifact;
|
||||
pub mod block;
|
||||
pub mod doc;
|
||||
pub mod manifest;
|
||||
pub mod page;
|
||||
|
||||
@@ -12,6 +14,7 @@ pub struct ToolCallInput {
|
||||
pub workspace_id: Option<String>,
|
||||
pub document_id: Option<String>,
|
||||
pub actor_id: Option<String>,
|
||||
pub profile: Option<String>,
|
||||
pub session_id: Option<String>,
|
||||
pub run_id: Option<String>,
|
||||
pub tool_call_id: Option<String>,
|
||||
|
||||
@@ -43,7 +43,11 @@ pub async fn page_get(
|
||||
.or_else(|| aggregate_value.pointer("/layout/page_options"))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({}));
|
||||
let blocks = summarize_blocks(&content);
|
||||
let blocks = aggregate_value
|
||||
.pointer("/body/blockDocument/blocks")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| summarize_blocks(&content));
|
||||
let body_summary = blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.get("text").and_then(Value::as_str))
|
||||
|
||||
Reference in New Issue
Block a user