feat(ai): switch page ai to hermes panel

This commit is contained in:
lix-2026
2026-05-14 15:10:33 +08:00
parent e9188716e6
commit 9816035491
48 changed files with 6353 additions and 412 deletions
@@ -0,0 +1,185 @@
use crate::app::AppState;
use crate::context::RequestContext;
use crate::error::WebError;
use crate::hermes_tools::ToolCallInput;
use crate::routes::command_support::execute_runtime_command_via_convex_with_artifacts;
use bridge_runtime::{
RuntimeActorWire, RuntimeCommandEnvelopeWire, RuntimeSourceWire, RuntimeTargetWire,
};
use serde_json::{json, Value};
pub async fn create_summary(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
) -> Result<Value, WebError> {
create_artifact_node(
state,
context,
input,
"summary",
"mnote.artifact.create_summary",
)
.await
}
pub async fn create_ai_note(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
) -> Result<Value, WebError> {
create_artifact_node(
state,
context,
input,
"ai_note",
"mnote.artifact.create_ai_note",
)
.await
}
async fn create_artifact_node(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
node_type: &str,
tool_name: &str,
) -> Result<Value, WebError> {
ensure_write_contract(context, input)?;
let document_id = input.effective_document_id().ok_or_else(|| {
WebError::bad_request_code("mnote_tool_bad_request", "artifact 工具缺少 documentId")
.with_context(context)
})?;
let workspace_id = input.effective_workspace_id();
let content = input
.arg_string("summary")
.or_else(|| input.arg_string("content"))
.ok_or_else(|| {
WebError::bad_request_code("mnote_tool_bad_request", "artifact 工具缺少内容")
.with_context(context)
})?;
let idempotency_key =
input.idempotency_key_or_default(&format!("{tool_name}_{}", context.trace.request_id));
let command_id = format!(
"{}_{}",
tool_name.replace('.', "_"),
context.trace.request_id
);
let artifact_document_id = if node_type == "summary" {
format!("summary_{}", document_id)
} else {
format!("ai_note_{}_{}", document_id, context.trace.request_id)
};
if input.dry_run.unwrap_or(false) {
return Ok(json!({
"dryRun": true,
"commandName": "tree.node.create",
"commandId": command_id,
"artifactType": node_type,
"artifactDocumentId": artifact_document_id,
"documentId": document_id,
"workspaceId": workspace_id,
"diff": [{"op": "create_artifact", "artifactType": node_type}]
}));
}
let command = RuntimeCommandEnvelopeWire {
name: "tree.node.create".into(),
command_id: command_id.clone(),
idempotency_key: Some(idempotency_key),
actor: RuntimeActorWire {
actor_type: context.auth.actor_type.clone(),
actor_id: context.auth.actor_id.clone(),
session_id: input
.session_id
.clone()
.or_else(|| context.auth.session_id.clone()),
},
source: RuntimeSourceWire {
channel: "hermes".into(),
client: "mnote-hermes-plugin".into(),
source_kind: None,
root_uri: None,
workspace_id: workspace_id.clone(),
capabilities: input.capability_scope.clone().unwrap_or_default(),
},
target: Some(RuntimeTargetWire {
workspace_id: workspace_id.clone(),
page_id: Some(document_id.clone()),
block_id: None,
}),
payload: json!({
"workspaceId": workspace_id,
"parentId": document_id,
"documentId": artifact_document_id,
"accessScope": "private",
"nodeType": node_type,
"title": if node_type == "summary" { "AI Summary" } else { "AI Note" },
"content": [
{
"id": format!("{}_body", node_type),
"type": "paragraph",
"content": [{"type": "text", "text": content}]
}
],
"artifact": {
"kind": node_type,
"sourceDocumentId": document_id,
"source": "hermes",
"sessionId": input.session_id,
"runId": input.run_id,
"toolCallId": input.tool_call_id,
"traceId": input.effective_trace_id(&context.trace.trace_id)
},
"referenceEdge": {
"from": document_id,
"kind": "ai_artifact_reference"
}
}),
preflight_data: None,
reason: Some(tool_name.into()),
refs: vec![tool_name.into(), "hermes-tool-call".into()],
dry_run: false,
validate_only: false,
};
let execution = execute_runtime_command_via_convex_with_artifacts(
state.config(),
context,
workspace_id.as_deref(),
command,
)
.await?;
Ok(json!({
"commandName": "tree.node.create",
"commandId": command_id,
"artifactType": node_type,
"artifactDocumentId": artifact_document_id,
"referenceEdge": {
"from": document_id,
"to": artifact_document_id,
"kind": "ai_artifact_reference"
},
"result": execution.result,
"artifacts": execution.artifacts,
"artifactError": execution.artifact_error
}))
}
fn ensure_write_contract(context: &RequestContext, input: &ToolCallInput) -> Result<(), 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.is_none() {
return Err(WebError::bad_request_code(
"mnote_tool_dry_run_required",
"写入型 mnote Hermes tool 必须显式携带 dryRun",
)
.with_context(context));
}
Ok(())
}
@@ -0,0 +1,58 @@
use serde_json::{json, Value};
pub const MANIFEST_SCHEMA_VERSION: &str = "mnote.hermes_tool_manifest.v1";
pub const TOOL_SCHEMA_VERSION: &str = "mnote.hermes_tool.v1";
pub fn manifest() -> Value {
json!({
"schemaVersion": MANIFEST_SCHEMA_VERSION,
"plugin": {
"name": "mnote",
"description": "mnote 页面、树、artifact 与 edge 工具",
"runtimeOwner": "mnote-web",
"writeOwner": "rust-runtime-kernel"
},
"tools": [
page_get_tool(),
planned_tool("mnote.page.save", ["page.write"]),
planned_tool("mnote.page.update_title", ["page.write"]),
planned_tool("mnote.page.update_options", ["page.write"]),
planned_tool("mnote.artifact.create_summary", ["artifact.write"]),
planned_tool("mnote.artifact.create_ai_note", ["artifact.write"])
]
})
}
fn page_get_tool() -> Value {
json!({
"name": "mnote.page.get",
"description": "读取当前页面 Page Aggregate 摘要",
"schemaVersion": TOOL_SCHEMA_VERSION,
"capabilityScope": ["page.read"],
"inputSchema": {
"type": "object",
"required": ["workspaceId", "documentId", "sessionId", "runId", "toolCallId", "traceId"],
"properties": {
"workspaceId": { "type": "string" },
"documentId": { "type": "string" },
"sessionId": { "type": "string" },
"runId": { "type": "string" },
"toolCallId": { "type": "string" },
"traceId": { "type": "string" },
"includeBody": { "type": "boolean", "default": true },
"includeOptions": { "type": "boolean", "default": true },
"includeBlocks": { "type": "boolean", "default": true }
}
}
})
}
fn planned_tool(name: &str, scope: impl IntoIterator<Item = &'static str>) -> Value {
json!({
"name": name,
"description": "已冻结合同,按 7-4 后续 task 接入 Rust runtime / kernel",
"schemaVersion": TOOL_SCHEMA_VERSION,
"capabilityScope": scope.into_iter().collect::<Vec<_>>(),
"status": "planned"
})
}
@@ -0,0 +1,91 @@
pub mod artifact;
pub mod manifest;
pub mod page;
use serde::Deserialize;
use serde_json::Value;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolCallInput {
pub tool_name: String,
pub workspace_id: Option<String>,
pub document_id: Option<String>,
pub actor_id: Option<String>,
pub session_id: Option<String>,
pub run_id: Option<String>,
pub tool_call_id: Option<String>,
pub trace_id: Option<String>,
pub idempotency_key: Option<String>,
pub dry_run: Option<bool>,
pub capability_scope: Option<Vec<String>>,
pub args: Option<Value>,
}
impl ToolCallInput {
pub fn arg_string(&self, key: &str) -> Option<String> {
self.args
.as_ref()
.and_then(|args| args.get(key))
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
}
pub fn arg_value(&self, key: &str) -> Option<Value> {
self.args.as_ref().and_then(|args| args.get(key)).cloned()
}
pub fn effective_workspace_id(&self) -> Option<String> {
self.workspace_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
.or_else(|| self.arg_string("workspaceId"))
}
pub fn effective_document_id(&self) -> Option<String> {
self.document_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
.or_else(|| self.arg_string("documentId"))
}
pub fn effective_tool_call_id(&self) -> String {
self.tool_call_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or("tool_call_missing")
.to_string()
}
pub fn effective_trace_id<'a>(&'a self, fallback: &'a str) -> &'a str {
self.trace_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or(fallback)
}
pub fn idempotency_key_or_default(&self, fallback: &str) -> String {
self.idempotency_key
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or(fallback)
.to_string()
}
pub fn has_idempotency_key(&self) -> bool {
self.idempotency_key
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.is_some()
}
}
@@ -0,0 +1,341 @@
use crate::app::AppState;
use crate::context::RequestContext;
use crate::error::WebError;
use crate::hermes_tools::ToolCallInput;
use crate::routes::command_support::execute_runtime_command_via_convex_with_artifacts;
use crate::routes::web_shell::build_page_aggregate_snapshot;
use bridge_runtime::{
RuntimeActorWire, RuntimeCommandEnvelopeWire, RuntimeSourceWire, RuntimeTargetWire,
};
use serde_json::{json, Value};
pub async fn page_get(
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", "mnote.page.get 缺少 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?;
let aggregate_value =
serde_json::to_value(&aggregate).map_err(|error| WebError::internal(error.to_string()))?;
let title = aggregate_value
.pointer("/head/title")
.and_then(Value::as_str)
.unwrap_or("无标题");
let content = aggregate_value
.pointer("/body/content")
.cloned()
.unwrap_or(Value::Null);
let page_options = aggregate_value
.pointer("/layout/pageOptions")
.or_else(|| aggregate_value.pointer("/layout/page_options"))
.cloned()
.unwrap_or_else(|| json!({}));
let blocks = summarize_blocks(&content);
let body_summary = blocks
.iter()
.filter_map(|block| block.get("text").and_then(Value::as_str))
.filter(|text| !text.trim().is_empty())
.take(8)
.collect::<Vec<_>>()
.join("\n");
Ok(json!({
"documentId": document_id,
"workspaceId": workspace_id,
"title": title,
"bodySummary": body_summary,
"pageOptions": page_options,
"blocks": blocks,
"aggregateSchema": aggregate_value.get("schema").cloned().unwrap_or(Value::Null),
"aggregateSource": aggregate_value.get("source").cloned().unwrap_or(Value::Null)
}))
}
fn ensure_write_contract(context: &RequestContext, input: &ToolCallInput) -> Result<(), 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.is_none() {
return Err(WebError::bad_request_code(
"mnote_tool_dry_run_required",
"写入型 mnote Hermes tool 必须显式携带 dryRun",
)
.with_context(context));
}
Ok(())
}
pub async fn page_save(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
) -> Result<Value, WebError> {
let content = input.arg_value("content").ok_or_else(|| {
WebError::bad_request_code("mnote_tool_bad_request", "mnote.page.save 缺少 content")
.with_context(context)
})?;
page_command(
state,
context,
input,
"page.body.save",
json!({
"content": content,
"mode": input.arg_string("mode").unwrap_or_else(|| "replace".into())
}),
None,
)
.await
}
pub async fn update_title(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
) -> Result<Value, WebError> {
let title = input.arg_string("title").ok_or_else(|| {
WebError::bad_request_code(
"mnote_tool_bad_request",
"mnote.page.update_title 缺少 title",
)
.with_context(context)
})?;
page_command(
state,
context,
input,
"page.head.updateTitle",
json!({ "title": title }),
None,
)
.await
}
pub async fn update_options(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
) -> Result<Value, WebError> {
let options = input.arg_value("options").ok_or_else(|| {
WebError::bad_request_code(
"mnote_tool_bad_request",
"mnote.page.update_options 缺少 options",
)
.with_context(context)
})?;
let (wired_options, ignored_options, warnings) = filter_wired_page_options(options);
page_command(
state,
context,
input,
"page.layout.updateOptions",
json!({ "options": wired_options }),
Some(json!({
"ignoredOptions": ignored_options,
"warnings": warnings
})),
)
.await
}
async fn page_command(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
command_name: &str,
payload_patch: Value,
result_extra: Option<Value>,
) -> Result<Value, WebError> {
ensure_write_contract(context, input)?;
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 command_id = format!(
"{}_{}",
command_name.replace('.', "_"),
context.trace.request_id
);
let idempotency_key = input.idempotency_key_or_default(&command_id);
let payload = merge_page_payload(&document_id, workspace_id.as_deref(), payload_patch);
if input.dry_run.unwrap_or(false) {
let mut result = json!({
"dryRun": true,
"commandName": command_name,
"commandId": command_id,
"documentId": document_id,
"workspaceId": workspace_id,
"diff": [{"op": command_name, "payload": payload}]
});
merge_result_extra(&mut result, result_extra);
return Ok(result);
}
let command = RuntimeCommandEnvelopeWire {
name: command_name.into(),
command_id: command_id.clone(),
idempotency_key: Some(idempotency_key),
actor: RuntimeActorWire {
actor_type: context.auth.actor_type.clone(),
actor_id: context.auth.actor_id.clone(),
session_id: input
.session_id
.clone()
.or_else(|| context.auth.session_id.clone()),
},
source: RuntimeSourceWire {
channel: "hermes".into(),
client: "mnote-hermes-plugin".into(),
source_kind: None,
root_uri: None,
workspace_id: workspace_id.clone(),
capabilities: input.capability_scope.clone().unwrap_or_default(),
},
target: Some(RuntimeTargetWire {
workspace_id: workspace_id.clone(),
page_id: Some(document_id.clone()),
block_id: None,
}),
payload,
preflight_data: None,
reason: Some(format!("Hermes tool {command_name}")),
refs: vec![command_name.into(), "hermes-tool-call".into()],
dry_run: false,
validate_only: false,
};
let execution = execute_runtime_command_via_convex_with_artifacts(
state.config(),
context,
workspace_id.as_deref(),
command,
)
.await?;
let mut result = json!({
"commandName": command_name,
"commandId": command_id,
"result": execution.result,
"artifacts": execution.artifacts,
"artifactError": execution.artifact_error
});
merge_result_extra(&mut result, result_extra);
Ok(result)
}
fn merge_result_extra(result: &mut Value, extra: Option<Value>) {
if let (Value::Object(result_map), Some(Value::Object(extra_map))) = (result, extra) {
for (key, value) in extra_map {
result_map.insert(key, value);
}
}
}
fn merge_page_payload(document_id: &str, workspace_id: Option<&str>, patch: Value) -> Value {
let mut payload = json!({
"documentId": document_id,
"workspaceId": workspace_id
});
if let (Value::Object(base), Value::Object(extra)) = (&mut payload, patch) {
for (key, value) in extra {
base.insert(key, value);
}
}
payload
}
fn filter_wired_page_options(options: Value) -> (Value, Vec<String>, Vec<Value>) {
let allowed = ["wideLayout", "smallText", "showToc", "protectEditing"];
let mut out = serde_json::Map::new();
let mut ignored = Vec::new();
let mut warnings = Vec::new();
if let Value::Object(map) = options {
for (key, value) in map {
if allowed.contains(&key.as_str()) {
out.insert(key, value);
} else {
warnings.push(json!({
"code": "page_option_not_wired",
"field": key.clone(),
"message": "页面设置字段尚未接入 Page Aggregate command,已忽略"
}));
ignored.push(key);
}
}
}
(Value::Object(out), ignored, warnings)
}
fn summarize_blocks(content: &Value) -> Vec<Value> {
let mut out = Vec::new();
collect_blocks(content, &mut out);
out.into_iter().take(40).collect()
}
fn collect_blocks(value: &Value, out: &mut Vec<Value>) {
match value {
Value::Array(items) => {
for item in items {
collect_blocks(item, out);
}
}
Value::Object(map) => {
let block_id = map
.get("id")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
let block_type = map
.get("type")
.and_then(Value::as_str)
.unwrap_or("unknown")
.to_string();
let text = collect_text(value);
if !block_id.is_empty() || !text.is_empty() {
out.push(json!({
"id": block_id,
"type": block_type,
"text": text
}));
}
if let Some(children) = map.get("children") {
collect_blocks(children, out);
}
}
_ => {}
}
}
fn collect_text(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Array(items) => items.iter().map(collect_text).collect::<Vec<_>>().join(""),
Value::Object(map) => {
if let Some(text) = map.get("text").and_then(Value::as_str) {
return text.to_string();
}
if let Some(content) = map.get("content") {
return collect_text(content);
}
String::new()
}
_ => String::new(),
}
}