feat(ai): switch page ai to hermes panel
This commit is contained in:
@@ -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(),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user