Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Add get asset content api

Daniel4775c7ce7e9a
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 788f6220e6..fc088de9ae 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -201,6 +201,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/search/findReplace", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, findReplace)
ginServer.Handle("POST", "/api/search/fullTextSearchAssetContent", model.CheckAuth, fullTextSearchAssetContent)
ginServer.Handle("POST", "/api/search/getAssetContent", model.CheckAuth, getAssetContent)
+ ginServer.Handle("POST", "/api/search/getAssetContentByPath", model.CheckAuth, getAssetContentByPath)
ginServer.Handle("POST", "/api/search/listInvalidBlockRefs", model.CheckAuth, listInvalidBlockRefs)
ginServer.Handle("POST", "/api/search/semanticSearchBlock", model.CheckAuth, semanticSearchBlock)
diff --git a/kernel/api/search.go b/kernel/api/search.go
index a284cf28f8..8ac2bc7a2f 100644
--- a/kernel/api/search.go
+++ b/kernel/api/search.go
@@ -92,6 +92,32 @@ func getAssetContent(c *gin.Context) {
return
}
+func getAssetContentByPath(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ path := arg["path"].(string)
+ assetContent := model.GetAssetContentByPath(path)
+ if model.IsReadOnlyRoleContext(c) && assetContent != nil {
+ publishAccess := model.GetPublishAccess()
+ filteredAssetContents := model.FilterAssetContentByPublishAccess(c, publishAccess, []*model.AssetContent{assetContent})
+ if len(filteredAssetContents) > 0 {
+ assetContent = filteredAssetContents[0]
+ } else {
+ assetContent = nil
+ }
+ }
+ ret.Data = map[string]any{
+ "assetContent": assetContent,
+ }
+ return
+}
+
func fullTextSearchAssetContent(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/cli/cmd/search.go b/kernel/cli/cmd/search.go
index 26927c1e86..ac3ac46f67 100644
--- a/kernel/cli/cmd/search.go
+++ b/kernel/cli/cmd/search.go
@@ -50,6 +50,11 @@ var searchCmd = &cobra.Command{
return runAssetSearch(cmd, query, method, orderBy, page, pageSize)
}
+ // --get-asset 切换到按路径取单个资源文件全文模式
+ if getAssetMode, _ := cmd.Flags().GetBool("get-asset"); getAssetMode {
+ return runGetAsset(query)
+ }
+
notebooks, _ := cmd.Flags().GetStringArray("notebook")
paths, _ := cmd.Flags().GetStringArray("path")
typeFlags, _ := cmd.Flags().GetStringArray("type")
@@ -109,6 +114,29 @@ func runAssetSearch(cmd *cobra.Command, query string, method, orderBy, page, pag
return nil
}
+func runGetAsset(path string) error {
+ a := model.GetAssetContentByPath(path)
+ if a == nil {
+ fmt.Println("No indexed content found for path:", path)
+ return nil
+ }
+
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(a, "", " ")
+ fmt.Println(string(data))
+ default:
+ fmt.Printf("ID: %s\n", a.ID)
+ fmt.Printf("Name: %s\n", a.Name)
+ fmt.Printf("Ext: %s\n", a.Ext)
+ fmt.Printf("Path: %s\n", a.Path)
+ fmt.Printf("Size: %s\n", a.HSize)
+ fmt.Println("\nContent:")
+ fmt.Println(a.Content)
+ }
+ return nil
+}
+
func printAssetSearchResult(assetContents []*model.AssetContent, matchedAssetCount, pageCount, page, pageSize int) {
if len(assetContents) == 0 {
fmt.Println("No asset content results found.")
@@ -175,6 +203,7 @@ func stringSliceToMap(s []string) map[string]bool {
func init() {
searchCmd.Flags().Bool("asset", false, "search asset file contents (PDF/Word/Excel/txt etc.) instead of blocks")
+ searchCmd.Flags().Bool("get-asset", false, "get the full indexed content of one asset file; the query argument is treated as the asset path, e.g. 'assets/foo.pdf'")
searchCmd.Flags().StringArray("ext", nil, "asset file extension filter, repeatable, e.g. --ext pdf --ext docx (asset mode only)")
searchCmd.Flags().StringArrayP("notebook", "n", nil, "notebook ID filter (repeatable)")
searchCmd.Flags().StringArray("path", nil, "path prefix filter (repeatable)")
diff --git a/kernel/mcp/tools/search.go b/kernel/mcp/tools/search.go
index ffd1935543..4ccd65378f 100644
--- a/kernel/mcp/tools/search.go
+++ b/kernel/mcp/tools/search.go
@@ -25,16 +25,16 @@ import (
var SearchTool = &Tool{
Name: "search",
- Description: "Search. Actions: fulltext(query, page=1, pageSize=20, notebook?, path?, type?, subtype?, method?, orderBy?, groupBy?), semantic(query, page=1, pageSize=20, notebook?, path?, type?, subtype?) — semantic needs AI embedding configured; asset(query, page=1, pageSize=32, ext?, method?, orderBy?) — full-text search inside asset file contents (PDF/Word/Excel/txt etc.), returns matched snippets with <mark> tags.",
+ Description: "Search. Actions: fulltext(query, page=1, pageSize=20, notebook?, path?, type?, subtype?, method?, orderBy?, groupBy?), semantic(query, page=1, pageSize=20, notebook?, path?, type?, subtype?) — semantic needs AI embedding configured; asset(query, page=1, pageSize=32, ext?, method?, orderBy?) — full-text search inside asset file contents (PDF/Word/Excel/txt etc.), returns matched snippets with <mark> tags; getasset(path) — get the full indexed content of one asset file by its path (e.g. 'assets/foo.pdf').",
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
- "action": {Type: "string", Description: "Operation: fulltext, semantic, or asset", Enum: []string{"fulltext", "semantic", "asset"}},
- "query": {Type: "string", Description: "Search keywords"},
+ "action": {Type: "string", Description: "Operation: fulltext, semantic, asset, or getasset", Enum: []string{"fulltext", "semantic", "asset", "getasset"}},
+ "query": {Type: "string", Description: "Search keywords (required for fulltext/semantic/asset)"},
"page": {Type: "number", Description: "Page number (default 1)"},
"pageSize": {Type: "number", Description: "Results per page (default 20 for fulltext/semantic, 32 for asset)"},
"notebook": {Type: "string", Description: "Comma-separated notebook IDs to filter (optional, fulltext/semantic only)"},
- "path": {Type: "string", Description: "Comma-separated path prefixes to filter (optional, fulltext/semantic only)"},
+ "path": {Type: "string", Description: "Comma-separated path prefixes to filter (optional, fulltext/semantic only); for getasset, a single asset file path like 'assets/foo.pdf'"},
"type": {Type: "string", Description: "Comma-separated block types to filter, e.g. 'document,heading,paragraph' (optional, fulltext/semantic only)"},
"subtype": {Type: "string", Description: "Comma-separated block subtypes to filter, e.g. 'o,u,t' (optional, fulltext/semantic only)"},
"ext": {Type: "string", Description: "Comma-separated asset file extensions to filter, e.g. 'pdf,docx,xlsx' (optional, asset only)"},
@@ -42,7 +42,7 @@ var SearchTool = &Tool{
"orderBy": {Type: "number", Description: "Sort order — fulltext: 0=type 1=created-asc 2=created-desc 3=updated-asc 4=updated-desc 5=content 6=relevance-asc 7=relevance-desc; asset: 0=relevance-desc 1=relevance-asc 2=updated-asc 3=updated-desc (default 0)"},
"groupBy": {Type: "number", Description: "Group by (fulltext only): 0=none 1=document (default 0)"},
},
- Required: []string{"action", "query"},
+ Required: []string{"action"},
},
Handler: searchHandler,
}
@@ -60,9 +60,11 @@ func searchHandler(args map[string]interface{}) (CallToolResult, error) {
return semanticSearch(args)
case "asset":
return assetSearch(args)
+ case "getasset":
+ return getAssetHandler(args)
}
return CallToolResult{
- Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [fulltext, semantic, asset]"}},
+ Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [fulltext, semantic, asset, getasset]"}},
IsError: true,
}, nil
}
@@ -236,6 +238,33 @@ func assetSearch(args map[string]interface{}) (CallToolResult, error) {
}, nil
}
+func getAssetHandler(args map[string]interface{}) (CallToolResult, error) {
+ path, _ := args["path"].(string)
+ if path == "" {
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "missing required parameter 'path' (e.g. 'assets/foo.pdf')"}},
+ IsError: true,
+ }, nil
+ }
+
+ a := model.GetAssetContentByPath(path)
+ if a == nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "No indexed content found for path: " + path + " (the file may not be indexed yet)"}}}, nil
+ }
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Asset: %s\n", a.Name))
+ sb.WriteString(fmt.Sprintf("Ext: %s\n", a.Ext))
+ sb.WriteString(fmt.Sprintf("Path: %s\n", a.Path))
+ sb.WriteString(fmt.Sprintf("Size: %s\n", a.HSize))
+ sb.WriteString(fmt.Sprintf("ID: %s\n", a.ID))
+ sb.WriteString("\nContent:\n")
+ sb.WriteString(a.Content)
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: sb.String()}},
+ }, nil
+}
+
func parseStringSlice(v interface{}) []string {
s, ok := v.(string)
if !ok || s == "" {
diff --git a/kernel/model/asset_content.go b/kernel/model/asset_content.go
index 73df47e402..2c4d8058ca 100644
--- a/kernel/model/asset_content.go
+++ b/kernel/model/asset_content.go
@@ -86,6 +86,29 @@ func GetAssetContent(id, query string, queryMethod int) (ret *AssetContent) {
return
}
+// GetAssetContentByPath 按资源文件路径获取已索引的完整内容。
+//
+// path 为工作空间相对路径,形如 "assets/xxx.pdf"。返回 nil 表示该文件尚未被索引。
+// 与 GetAssetContent(按索引记录 id)不同,此处直接返回 content 原文,不做高亮。
+func GetAssetContentByPath(path string) (ret *AssetContent) {
+ path = strings.TrimSpace(path)
+ if "" == path {
+ return
+ }
+
+ table := "asset_contents_fts_case_insensitive"
+ // path 来自用户输入,拼接进 SQL 前需转义单引号,与现有 SQL 拼接风格一致
+ escapedPath := strings.ReplaceAll(path, "'", "''")
+ stmt := "SELECT id, name, ext, path, size, updated, content FROM " + table + " WHERE path = '" + escapedPath + "' LIMIT 1"
+ assetContents := sql.SelectAssetContentsRawStmt(stmt, 1, 1)
+ results := fromSQLAssetContents(&assetContents)
+ if 1 > len(results) {
+ return
+ }
+ ret = results[0]
+ return
+}
+
// FullTextSearchAssetContent 搜索资源文件内容。
//
// method:0:关键字,1:查询语法,2:SQL,3:正则表达式