Files
mnote/rust/crates/mnote-web/src/hermes_tools/doc.rs
T

539 lines
18 KiB
Rust
Raw Normal View History

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('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&apos;")
}