An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Improve kernel CLI and MCP operation results https://github.com/siyuan-note/siyuan/issues/18824
Danieldfd3c2f491f0
diff --git a/kernel/cli/cmd/block.go b/kernel/cli/cmd/block.goindex 50afb98c42..78dab0893d 100644--- a/kernel/cli/cmd/block.go+++ b/kernel/cli/cmd/block.go@@ -216,21 +216,19 @@ var blockInsertCmd = &cobra.Command{}dom := markdownToBlockDOM(data)- transactions := []*model.Transaction{{- DoOperations: []*model.Operation{{- Action: "insert",- Data: dom,- ParentID: parentID,- PreviousID: previousID,- }},- }}- model.PerformTransactions(&transactions)- model.FlushTxQueue()+ operation := &model.Operation{+ Action: "insert",+ Data: dom,+ ParentID: parentID,+ PreviousID: previousID,+ }+ if err = model.PerformTxSync(&model.Transaction{DoOperations: []*model.Operation{operation}}); err != nil {+ return err+ }if bt := treenode.GetBlockTree(parentID); bt != nil {model.AppendPushReloadProtyleEntry(bt.RootID)}- fmt.Println("ok")- return nil+ return printBlockWriteResult(operation.ID)},}@@ -259,20 +257,18 @@ var blockAppendCmd = &cobra.Command{}dom := markdownToBlockDOM(data)- transactions := []*model.Transaction{{- DoOperations: []*model.Operation{{- Action: "appendInsert",- Data: dom,- ParentID: parentID,- }},- }}- model.PerformTransactions(&transactions)- model.FlushTxQueue()+ operation := &model.Operation{+ Action: "appendInsert",+ Data: dom,+ ParentID: parentID,+ }+ if err = model.PerformTxSync(&model.Transaction{DoOperations: []*model.Operation{operation}}); err != nil {+ return err+ }if bt := treenode.GetBlockTree(parentID); bt != nil {model.AppendPushReloadProtyleEntry(bt.RootID)}- fmt.Println("ok")- return nil+ return printBlockWriteResult(operation.ID)},}@@ -301,23 +297,41 @@ var blockPrependCmd = &cobra.Command{}dom := markdownToBlockDOM(data)- transactions := []*model.Transaction{{- DoOperations: []*model.Operation{{- Action: "prependInsert",- Data: dom,- ParentID: parentID,- }},- }}- model.PerformTransactions(&transactions)- model.FlushTxQueue()+ operation := &model.Operation{+ Action: "prependInsert",+ Data: dom,+ ParentID: parentID,+ }+ if err = model.PerformTxSync(&model.Transaction{DoOperations: []*model.Operation{operation}}); err != nil {+ return err+ }if bt := treenode.GetBlockTree(parentID); bt != nil {model.AppendPushReloadProtyleEntry(bt.RootID)}- fmt.Println("ok")- return nil+ return printBlockWriteResult(operation.ID)},}+func printBlockWriteResult(id string) error {+ return writeBlockWriteResult(os.Stdout, id)+}++func writeBlockWriteResult(output io.Writer, id string) error {+ if id == "" {+ return fmt.Errorf("block write failed: empty block ID")+ }+ if outputFormat == "json" {+ data, err := json.MarshalIndent(map[string]string{"id": id}, "", " ")+ if err != nil {+ return err+ }+ _, err = fmt.Fprintln(output, string(data))+ return err+ }+ _, err := fmt.Fprintln(output, id)+ return err+}+var blockUpdateCmd = &cobra.Command{Use: "update --id <id> [--data <markdown> | --file <path>]",Short: "Update block",diff --git a/kernel/cli/cmd/block_test.go b/kernel/cli/cmd/block_test.gonew file mode 100644index 0000000000..3da8bcf7e2--- /dev/null+++ b/kernel/cli/cmd/block_test.go@@ -0,0 +1,52 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package cmd++import (+ "bytes"+ "encoding/json"+ "strings"+ "testing"+)++func TestWriteBlockWriteResult(t *testing.T) {+ originalOutputFormat := outputFormat+ defer func() {+ outputFormat = originalOutputFormat+ }()++ const id = "20260818000000-abcdefg"+ var output bytes.Buffer+ outputFormat = "table"+ if err := writeBlockWriteResult(&output, id); err != nil {+ t.Fatal(err)+ }+ if got := strings.TrimSpace(output.String()); got != id {+ t.Fatalf("unexpected table output: got %q, want %q", got, id)+ }++ output.Reset()+ outputFormat = "json"+ if err := writeBlockWriteResult(&output, id); err != nil {+ t.Fatal(err)+ }+ result := map[string]string{}+ if err := json.Unmarshal(output.Bytes(), &result); err != nil {+ t.Fatal(err)+ }+ if result["id"] != id {+ t.Fatalf("unexpected JSON output: got %q, want %q", result["id"], id)+ }+}++func TestWriteBlockWriteResultRejectsEmptyID(t *testing.T) {+ if err := writeBlockWriteResult(&bytes.Buffer{}, ""); err == nil {+ t.Fatal("expected empty block ID to fail")+ }+}diff --git a/kernel/cli/cmd/export.go b/kernel/cli/cmd/export.goindex dbc3d3a93a..e2d251aede 100644--- a/kernel/cli/cmd/export.go+++ b/kernel/cli/cmd/export.go@@ -20,6 +20,7 @@ import ("fmt""os"+ "github.com/siyuan-note/filelock""github.com/siyuan-note/siyuan/kernel/model""github.com/spf13/cobra"@@ -130,7 +131,7 @@ var exportDocxCmd = &cobra.Command{}var exportSYCmd = &cobra.Command{- Use: "sy --id <id> [--output <dir>]",+ Use: "sy --id <id> [--output <file>]",Short: "Export as .sy.zip",RunE: func(cmd *cobra.Command, args []string) error {id, _ := cmd.Flags().GetString("id")@@ -149,15 +150,14 @@ var exportSYCmd = &cobra.Command{}_, zipPath := model.ExportPandocConvertZip([]string{id}, "", ".sy")- if output == "" {- fmt.Println(zipPath)- return nil- }- data, err := os.ReadFile(zipPath)+ resultPath, err := materializeExportArtifact(zipPath, output)if err != nil {return err}- return os.WriteFile(output, data, 0644)+ if output == "" {+ fmt.Println(resultPath)+ }+ return nil},}@@ -181,15 +181,14 @@ var exportMdZipCmd = &cobra.Command{}_, zipPath := model.ExportPandocConvertZip([]string{id}, "", ".md")- if output == "" {- fmt.Println(zipPath)- return nil- }- data, err := os.ReadFile(zipPath)+ resultPath, err := materializeExportArtifact(zipPath, output)if err != nil {return err}- return os.WriteFile(output, data, 0644)+ if output == "" {+ fmt.Println(resultPath)+ }+ return nil},}@@ -211,18 +210,36 @@ var exportDataCmd = &cobra.Command{if err != nil {return err}- if output == "" {- fmt.Println(zipPath)- return nil- }- data, err := os.ReadFile(zipPath)+ resultPath, err := materializeExportArtifact(zipPath, output)if err != nil {return err}- return os.WriteFile(output, data, 0644)+ if output == "" {+ fmt.Println(resultPath)+ }+ return nil},}+func materializeExportArtifact(exportPath, output string) (resultPath string, err error) {+ if exportPath == "" {+ return "", fmt.Errorf("export failed: empty artifact path")+ }+ lease, err := model.AcquireExportArtifactLease(exportPath)+ if err != nil {+ return "", err+ }+ defer model.ReleaseExportArtifactLease(lease.ID)++ if output == "" {+ return lease.Path, nil+ }+ if err = filelock.Copy(lease.Path, output); err != nil {+ return "", err+ }+ return output, nil+}+func init() {exportMdCmd.Flags().String("id", "", "block ID")exportMdCmd.Flags().String("output", "", "output file path (default: stdout)")diff --git a/kernel/cli/cmd/export_test.go b/kernel/cli/cmd/export_test.gonew file mode 100644index 0000000000..73554f11aa--- /dev/null+++ b/kernel/cli/cmd/export_test.go@@ -0,0 +1,69 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package cmd++import (+ "net/url"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestMaterializeExportArtifact(t *testing.T) {+ tempDir := t.TempDir()+ originalTempDir := util.TempDir+ util.TempDir = tempDir+ defer func() {+ util.TempDir = originalTempDir+ }()++ exportDir := filepath.Join(tempDir, "export")+ if err := os.MkdirAll(exportDir, 0755); err != nil {+ t.Fatal(err)+ }+ name := "artifact with spaces.zip"+ source := filepath.Join(exportDir, name)+ content := []byte("export content")+ if err := os.WriteFile(source, content, 0644); err != nil {+ t.Fatal(err)+ }+ exportPath := "/export/" + url.PathEscape(name)++ actualPath, err := materializeExportArtifact(exportPath, "")+ if err != nil {+ t.Fatal(err)+ }+ if actualPath != source {+ t.Fatalf("unexpected artifact path: got %q, want %q", actualPath, source)+ }++ target := filepath.Join(tempDir, "target.zip")+ resultPath, err := materializeExportArtifact(exportPath, target)+ if err != nil {+ t.Fatal(err)+ }+ if resultPath != target {+ t.Fatalf("unexpected result path: got %q, want %q", resultPath, target)+ }+ copied, err := os.ReadFile(target)+ if err != nil {+ t.Fatal(err)+ }+ if string(copied) != string(content) {+ t.Fatalf("unexpected copied content: got %q, want %q", copied, content)+ }+}++func TestMaterializeExportArtifactRejectsEmptyPath(t *testing.T) {+ if _, err := materializeExportArtifact("", ""); err == nil {+ t.Fatal("expected empty export path to fail")+ }+}diff --git a/kernel/cli/cmd/template.go b/kernel/cli/cmd/template.goindex 47e5dd9469..2618e49e9e 100644--- a/kernel/cli/cmd/template.go+++ b/kernel/cli/cmd/template.go@@ -19,6 +19,7 @@ package cmdimport ("encoding/json""fmt"+ "io""os""path/filepath""strings"@@ -54,18 +55,29 @@ var templateSearchCmd = &cobra.Command{fmt.Println("No templates found.")return nil}- w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)- fmt.Fprintln(w, "NAME\tPATH")- for _, r := range results {- fmt.Fprintf(w, "%s\t%s\n", r.Content, r.Path)- }- w.Flush()- fmt.Printf("\n%d template(s)\n", len(results))+ return writeTemplateSearchResults(os.Stdout, results)}return nil},}+func writeTemplateSearchResults(output io.Writer, results []*model.TemplateSearchResult) error {+ w := tabwriter.NewWriter(output, 0, 0, 2, ' ', 0)+ if _, err := fmt.Fprintln(w, "NAME\tRELATIVE_PATH\tPATH"); err != nil {+ return err+ }+ for _, result := range results {+ if _, err := fmt.Fprintf(w, "%s\t%s\t%s\n", result.Content, result.RelativePath, result.Path); err != nil {+ return err+ }+ }+ if err := w.Flush(); err != nil {+ return err+ }+ _, err := fmt.Fprintf(output, "\n%d template(s)\n", len(results))+ return err+}+var templateGetCmd = &cobra.Command{Use: "get --path <path>",Short: "Read template content",diff --git a/kernel/cli/cmd/template_test.go b/kernel/cli/cmd/template_test.gonew file mode 100644index 0000000000..474fea71e5--- /dev/null+++ b/kernel/cli/cmd/template_test.go@@ -0,0 +1,36 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package cmd++import (+ "bytes"+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestWriteTemplateSearchResults(t *testing.T) {+ results := []*model.TemplateSearchResult{{+ Content: "Daily report",+ RelativePath: "group/daily.md",+ Path: "/data/templates/group/daily.md",+ }}+ var output bytes.Buffer+ if err := writeTemplateSearchResults(&output, results); err != nil {+ t.Fatal(err)+ }++ text := output.String()+ for _, expected := range []string{"NAME", "RELATIVE_PATH", "PATH", "group/daily.md", results[0].Path, "1 template(s)"} {+ if !strings.Contains(text, expected) {+ t.Fatalf("template search output missing %q: %q", expected, text)+ }+ }+}diff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.goindex fc21882516..6f33a28934 100644--- a/kernel/mcp/tools/block.go+++ b/kernel/mcp/tools/block.go@@ -17,6 +17,7 @@package toolsimport (+ "encoding/json""fmt""strings"@@ -28,7 +29,7 @@ import (var BlockTool = &Tool{Name: "block",- Description: "Block operations. Actions: get(id), get_kramdown(id), get_children(id), tree_stat(id, by document), dom(id), insert(data, dataType, parentID?, nextID?, previousID?), append(data, dataType, parentID) / prepend(...) add a NEW child — use after block.update when both modifying and adding, update(id, data, dataType, lockType?) replaces ONE block only (no append), delete(id), move(id, parentID, previousID?), breadcrumb(id), batch_get(ids) / batch_kramdown(ids) where ids is comma-separated.",+ Description: "Block operations. Actions: get(id), get_kramdown(id), get_children(id), tree_stat(id, by document), dom(id), insert(data, dataType, parentID?, nextID?, previousID?), append(data, dataType, parentID) / prepend(...) add a NEW child and return its ID — use after block.update when both modifying and adding, update(id, data, dataType, lockType?) replaces ONE block only (no append), delete(id), move(id, parentID, previousID?), breadcrumb(id), batch_get(ids) / batch_kramdown(ids) where ids is comma-separated.",InputSchema: ToolSchema{Type: "object",Properties: map[string]Property{@@ -213,15 +214,14 @@ func blockInsert(args map[string]any) (CallToolResult, error) {}}- transaction := &model.Transaction{- DoOperations: []*model.Operation{{- Action: "insert",- Data: data,- ParentID: parentID,- PreviousID: previousID,- NextID: nextID,- }},+ operation := &model.Operation{+ Action: "insert",+ Data: data,+ ParentID: parentID,+ PreviousID: previousID,+ NextID: nextID,}+ transaction := &model.Transaction{DoOperations: []*model.Operation{operation}}if err := model.PerformTxSync(transaction); err != nil {return blockToolError("insert block failed: " + err.Error())@@ -240,7 +240,7 @@ func blockInsert(args map[string]any) (CallToolResult, error) {}}- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block inserted"}}}, nil+ return blockWriteSuccess("insert", operation.ID)}func blockAppend(args map[string]any) (CallToolResult, error) {@@ -270,13 +270,12 @@ func blockAppend(args map[string]any) (CallToolResult, error) {}}- transaction := &model.Transaction{- DoOperations: []*model.Operation{{- Action: "appendInsert",- Data: data,- ParentID: parentID,- }},+ operation := &model.Operation{+ Action: "appendInsert",+ Data: data,+ ParentID: parentID,}+ transaction := &model.Transaction{DoOperations: []*model.Operation{operation}}if err := model.PerformTxSync(transaction); err != nil {return blockToolError("append block failed: " + err.Error())@@ -285,7 +284,7 @@ func blockAppend(args map[string]any) (CallToolResult, error) {if bt := treenode.GetBlockTreeInExactBox(parentID, boxID); bt != nil {util.PushReloadProtyle(bt.RootID)}- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block appended"}}}, nil+ return blockWriteSuccess("append", operation.ID)}func blockPrepend(args map[string]any) (CallToolResult, error) {@@ -315,13 +314,12 @@ func blockPrepend(args map[string]any) (CallToolResult, error) {}}- transaction := &model.Transaction{- DoOperations: []*model.Operation{{- Action: "prependInsert",- Data: data,- ParentID: parentID,- }},+ operation := &model.Operation{+ Action: "prependInsert",+ Data: data,+ ParentID: parentID,}+ transaction := &model.Transaction{DoOperations: []*model.Operation{operation}}if err := model.PerformTxSync(transaction); err != nil {return blockToolError("prepend block failed: " + err.Error())@@ -330,7 +328,28 @@ func blockPrepend(args map[string]any) (CallToolResult, error) {if bt := treenode.GetBlockTreeInExactBox(parentID, boxID); bt != nil {util.PushReloadProtyle(bt.RootID)}- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block prepended"}}}, nil+ return blockWriteSuccess("prepend", operation.ID)+}++type blockWriteOutput struct {+ Action string `json:"action"`+ ID string `json:"id"`+}++func blockWriteSuccess(action, id string) (CallToolResult, error) {+ if id == "" {+ return blockToolError(action + " block failed: empty block ID")+ }+ output := &blockWriteOutput{Action: action, ID: id}+ serialized, err := json.Marshal(output)+ if err != nil {+ return CallToolResult{}, err+ }+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: string(serialized)}},+ StructuredContent: output,+ StructuredContentSet: true,+ }, nil}func blockUpdate(args map[string]any) (CallToolResult, error) {diff --git a/kernel/mcp/tools/block_test.go b/kernel/mcp/tools/block_test.gonew file mode 100644index 0000000000..010a1eec99--- /dev/null+++ b/kernel/mcp/tools/block_test.go@@ -0,0 +1,48 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package tools++import (+ "encoding/json"+ "testing"+)++func TestBlockWriteSuccess(t *testing.T) {+ const id = "20260818000000-abcdefg"+ result, err := blockWriteSuccess("append", id)+ if err != nil {+ t.Fatal(err)+ }+ if result.IsError || !result.HasStructuredContent() || len(result.Content) != 1 {+ t.Fatalf("unexpected block write result: %#v", result)+ }++ textOutput := &blockWriteOutput{}+ if err = json.Unmarshal([]byte(result.Content[0].Text), textOutput); err != nil {+ t.Fatal(err)+ }+ if textOutput.Action != "append" || textOutput.ID != id {+ t.Fatalf("unexpected text output: %#v", textOutput)+ }++ structuredOutput, ok := result.StructuredContent.(*blockWriteOutput)+ if !ok || structuredOutput.Action != "append" || structuredOutput.ID != id {+ t.Fatalf("unexpected structured output: %#v", result.StructuredContent)+ }+}++func TestBlockWriteSuccessRejectsEmptyID(t *testing.T) {+ result, err := blockWriteSuccess("insert", "")+ if err != nil {+ t.Fatal(err)+ }+ if !result.IsError {+ t.Fatalf("expected empty block ID to fail: %#v", result)+ }+}diff --git a/kernel/model/encrypted_export.go b/kernel/model/encrypted_export.goindex dea3ddf5e6..43507f9595 100644--- a/kernel/model/encrypted_export.go+++ b/kernel/model/encrypted_export.go@@ -47,13 +47,15 @@ var managedEncryptedExports = struct {jobs map[string]managedEncryptedExport}{jobs: map[string]managedEncryptedExport{}}-type MobileExportLease struct {+type ExportArtifactLease struct {ID string `json:"leaseID"`Path string `json:"path"`Name string `json:"name"`Size int64 `json:"size"`}+type MobileExportLease = ExportArtifactLease+type mobileExportLeaseState struct {boxID stringcleanupDir string@@ -163,8 +165,8 @@ func IsManagedEncryptedExportPath(relativePath string) bool {return len(parts) >= 1 && ast.IsNodeIDPattern(parts[0])}-// AcquireMobileExportLease 为移动端导出取得覆盖整个原生复制过程的生命周期租约。-func AcquireMobileExportLease(exportPath string) (lease *MobileExportLease, err error) {+// AcquireExportArtifactLease 为导出产物取得覆盖整个复制过程的生命周期租约。+func AcquireExportArtifactLease(exportPath string) (lease *ExportArtifactLease, err error) {if after, ok := strings.CutPrefix(exportPath, "/export/"); ok {fileName, decodeErr := url.PathUnescape(after)if decodeErr != nil {@@ -301,6 +303,11 @@ func AcquireMobileExportLease(exportPath string) (lease *MobileExportLease, errreturn}+// AcquireMobileExportLease 为移动端导出取得覆盖整个原生复制过程的生命周期租约。+func AcquireMobileExportLease(exportPath string) (lease *MobileExportLease, err error) {+ return AcquireExportArtifactLease(exportPath)+}+// GetMobileExportName 返回移动端保存对话框使用的文件名,不生成明文临时文件。func GetMobileExportName(exportPath string) string {if after, ok := strings.CutPrefix(exportPath, "/export/"); ok {@@ -360,9 +367,14 @@ func registerMobileExportLeaseWithID(leaseID, boxID, artifact, name, cleanupDirreturn &MobileExportLease{ID: leaseID, Path: artifact, Name: name, Size: info.Size()}, nil}+// ReleaseExportArtifactLease 释放导出产物租约;重复调用不会产生副作用。+func ReleaseExportArtifactLease(leaseID string) {+ releaseMobileExportLease(leaseID, false)+}+// ReleaseMobileExportLease 释放移动端导出租约;重复调用不会产生副作用。func ReleaseMobileExportLease(leaseID string) {- releaseMobileExportLease(leaseID, false)+ ReleaseExportArtifactLease(leaseID)}func releaseMobileExportLease(leaseID string, expired bool) {