2026-07-26 17:04:19 +00:00
|
|
|
package modelcontext
|
2026-07-16 13:23:20 +00:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
2026-09-07 15:09:27 +00:00
|
|
|
"net/url"
|
2026-07-16 13:23:20 +00:00
|
|
|
"sort"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
)
|
|
|
|
|
|
2026-07-27 07:28:47 +00:00
|
|
|
const (
|
2026-09-07 15:09:27 +00:00
|
|
|
modelWebSearchEvidenceMaxRunes = 1500
|
2026-07-27 07:28:47 +00:00
|
|
|
modelWebFetchSummaryMaxRunes = 4000
|
|
|
|
|
modelWebFetchContentMaxRunes = 8000
|
|
|
|
|
modelWebFetchTotalMaxRunes = 16000
|
|
|
|
|
)
|
|
|
|
|
|
2026-07-16 13:23:20 +00:00
|
|
|
// ModelOutput returns a compact, source-centric representation for the LLM.
|
|
|
|
|
// The canonical ToolResult.Output remains untouched for UI, logs and storage.
|
2026-07-26 17:04:19 +00:00
|
|
|
func (r *sourceRegistry) ModelOutput(result *types.ToolResult) string {
|
2026-07-16 13:23:20 +00:00
|
|
|
if result == nil {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
2026-09-09 16:31:43 +00:00
|
|
|
// Legacy-format output from a current source tool is evidence too. Replay
|
|
|
|
|
// registration alone must never grant this eligibility.
|
|
|
|
|
if result.Success {
|
|
|
|
|
r.registerLegacyToolReferences(result.Output, true)
|
|
|
|
|
copyResult := *result
|
|
|
|
|
copyResult.Output = r.CompactPublicCitations(result.Output, true)
|
|
|
|
|
result = ©Result
|
|
|
|
|
}
|
2026-07-28 14:14:08 +00:00
|
|
|
displayType := stringValue(result.Data, "display_type")
|
|
|
|
|
if displayType == "web_fetch_results" {
|
|
|
|
|
return r.modelWebFetchOutput(mapsValue(result.Data["results"]), result.Output)
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
if !result.Success {
|
2026-08-28 06:27:24 +00:00
|
|
|
return failedToolModelText(result.Output, result.Error)
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
|
|
|
|
switch displayType {
|
|
|
|
|
case "grep_results":
|
|
|
|
|
return r.modelKnowledgeOutput("keyword", mapsValue(result.Data["chunk_results"]), result.Output)
|
|
|
|
|
case "search_results":
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
// search_knowledge reports the mode it actually used; legacy
|
|
|
|
|
// knowledge_search payloads carry none and were always semantic.
|
|
|
|
|
mode := stringValue(result.Data, "mode")
|
|
|
|
|
if mode == "" {
|
|
|
|
|
mode = "semantic"
|
|
|
|
|
}
|
|
|
|
|
output := r.modelKnowledgeOutput(mode, mapsValue(result.Data["results"]), result.Output)
|
|
|
|
|
return r.annotateModeFallbacks(output, result.Data)
|
2026-07-16 13:23:20 +00:00
|
|
|
case "knowledge_chunks_list":
|
|
|
|
|
return r.modelKnowledgeChunksOutput(result.Data, result.Output)
|
|
|
|
|
case "document_info":
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
return r.modelDocumentInfoOutput(result.Data, result.Output)
|
2026-07-16 13:23:20 +00:00
|
|
|
case "graph_query_results":
|
|
|
|
|
return r.modelKnowledgeOutput("graph", mapsValue(result.Data["results"]), result.Output)
|
|
|
|
|
case "web_search_results":
|
|
|
|
|
return r.modelWebSearchOutput(mapsValue(result.Data["results"]), result.Output)
|
2026-07-26 16:59:38 +00:00
|
|
|
case "database_query":
|
|
|
|
|
return r.modelDatabaseQueryOutput(mapsValue(result.Data["rows"]), result.Output)
|
2026-07-16 13:23:20 +00:00
|
|
|
default:
|
|
|
|
|
r.registerLabeledReferences(result.Output)
|
2026-07-26 16:59:38 +00:00
|
|
|
r.registerStructuredReferences(result.Output)
|
2026-07-16 13:23:20 +00:00
|
|
|
return r.CompactKnownText(result.Output)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-26 16:59:38 +00:00
|
|
|
// registerStructuredReferences registers durable IDs found under explicitly
|
|
|
|
|
// labeled keys of a JSON tool result, using the same key dispatch as tool
|
|
|
|
|
// arguments. Non-JSON output is a no-op.
|
2026-07-26 17:04:19 +00:00
|
|
|
func (r *sourceRegistry) registerStructuredReferences(raw string) {
|
2026-07-26 16:59:38 +00:00
|
|
|
var value interface{}
|
|
|
|
|
if json.Unmarshal([]byte(raw), &value) != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
var walk func(string, interface{})
|
|
|
|
|
walk = func(key string, value interface{}) {
|
|
|
|
|
switch typed := value.(type) {
|
|
|
|
|
case string:
|
2026-09-09 16:31:43 +00:00
|
|
|
r.registerSourceIDByKey(key, typed, true)
|
2026-07-26 16:59:38 +00:00
|
|
|
case []interface{}:
|
|
|
|
|
for _, item := range typed {
|
|
|
|
|
walk(key, item)
|
|
|
|
|
}
|
|
|
|
|
case map[string]interface{}:
|
|
|
|
|
for childKey, item := range typed {
|
|
|
|
|
walk(childKey, item)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
walk("", value)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-26 17:04:19 +00:00
|
|
|
func (r *sourceRegistry) modelDatabaseQueryOutput(rows []map[string]interface{}, fallback string) string {
|
2026-07-26 16:59:38 +00:00
|
|
|
for _, row := range rows {
|
|
|
|
|
for key, raw := range row {
|
|
|
|
|
if value, ok := raw.(string); ok {
|
2026-09-09 16:31:43 +00:00
|
|
|
r.registerSourceIDByKey(key, value, true)
|
2026-07-26 16:59:38 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
func (r *sourceRegistry) modelDocumentInfoOutput(data map[string]interface{}, fallback string) string {
|
|
|
|
|
rows := mapsValue(data["documents"])
|
2026-07-16 13:23:20 +00:00
|
|
|
if len(rows) == 0 {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
var b strings.Builder
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
b.WriteString("<documents")
|
|
|
|
|
if kbHandle := r.RegisterKnowledgeBase(stringValue(data, "knowledge_base_id")); kbHandle != "" {
|
|
|
|
|
fmt.Fprintf(&b, " kb=\"%s\"", escapeAttr(kbHandle))
|
|
|
|
|
}
|
|
|
|
|
if total := intValue(data, "total_docs"); total > 0 {
|
|
|
|
|
fmt.Fprintf(&b, " total=\"%d\"", total)
|
|
|
|
|
}
|
|
|
|
|
if page := intValue(data, "page"); page > 0 {
|
|
|
|
|
fmt.Fprintf(&b, " page=\"%d\"", page)
|
|
|
|
|
}
|
|
|
|
|
if next := intValue(data, "next_page"); next > 0 {
|
|
|
|
|
fmt.Fprintf(&b, " next_page=\"%d\"", next)
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(">\n")
|
2026-07-16 13:23:20 +00:00
|
|
|
count := 0
|
|
|
|
|
for _, row := range rows {
|
|
|
|
|
knowledgeID := stringValue(row, "knowledge_id")
|
2026-07-26 17:17:36 +00:00
|
|
|
docHandle := r.RegisterDocument(knowledgeID)
|
2026-07-16 13:23:20 +00:00
|
|
|
if boolValue(row, "is_faq") {
|
|
|
|
|
chunkID := stringValue(row, "faq_id")
|
|
|
|
|
if chunkID == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
title := firstNonEmpty(stringValue(row, "faq_question"), stringValue(row, "title"))
|
2026-07-26 17:17:36 +00:00
|
|
|
chunkHandle := r.RegisterChunk(ChunkReference{
|
2026-07-16 13:23:20 +00:00
|
|
|
ChunkID: chunkID,
|
|
|
|
|
KnowledgeID: knowledgeID,
|
|
|
|
|
DocumentTitle: title,
|
|
|
|
|
ChunkType: "faq",
|
|
|
|
|
})
|
2026-07-26 17:17:36 +00:00
|
|
|
fmt.Fprintf(&b, " <document id=\"%s\" type=\"faq\">\n", escapeAttr(docHandle))
|
|
|
|
|
fmt.Fprintf(&b, " <chunk id=\"%s\" type=\"faq\">\n", escapeAttr(chunkHandle))
|
2026-07-16 13:23:20 +00:00
|
|
|
if title != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <question>%s</question>\n", escapeText(title))
|
|
|
|
|
}
|
|
|
|
|
for _, answer := range stringSliceValue(row["faq_answers"]) {
|
|
|
|
|
fmt.Fprintf(&b, " <answer>%s</answer>\n", escapeText(answer))
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(" </chunk>\n </document>\n")
|
|
|
|
|
count++
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-26 17:17:36 +00:00
|
|
|
if docHandle == "" {
|
2026-07-16 13:23:20 +00:00
|
|
|
continue
|
|
|
|
|
}
|
2026-07-26 17:17:36 +00:00
|
|
|
fmt.Fprintf(&b, " <document id=\"%s\"", escapeAttr(docHandle))
|
2026-07-16 13:23:20 +00:00
|
|
|
if title := stringValue(row, "title"); title != "" {
|
|
|
|
|
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(title))
|
|
|
|
|
}
|
|
|
|
|
if docType := stringValue(row, "type"); docType != "" {
|
|
|
|
|
fmt.Fprintf(&b, " type=\"%s\"", escapeAttr(docType))
|
|
|
|
|
}
|
|
|
|
|
if fileType := stringValue(row, "file_type"); fileType != "" {
|
|
|
|
|
fmt.Fprintf(&b, " file_type=\"%s\"", escapeAttr(fileType))
|
|
|
|
|
}
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
if chunkCount := intValue(row, "chunk_count"); chunkCount > 0 {
|
|
|
|
|
fmt.Fprintf(&b, " chunk_count=\"%d\"", chunkCount)
|
|
|
|
|
}
|
|
|
|
|
if status := stringValue(row, "parse_status"); status != "" {
|
|
|
|
|
fmt.Fprintf(&b, " parse_status=\"%s\"", escapeAttr(status))
|
|
|
|
|
}
|
|
|
|
|
if updated := stringValue(row, "updated_at"); len(updated) >= 10 {
|
|
|
|
|
fmt.Fprintf(&b, " updated_at=\"%s\"", escapeAttr(updated[:10]))
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(">\n")
|
2026-07-16 13:23:20 +00:00
|
|
|
if description := stringValue(row, "description"); description != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <description>%s</description>\n", escapeText(description))
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(" </document>\n")
|
|
|
|
|
count++
|
|
|
|
|
}
|
|
|
|
|
b.WriteString("</documents>")
|
|
|
|
|
if count == 0 {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
return b.String()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type modelChunk struct {
|
2026-07-26 17:17:36 +00:00
|
|
|
handle string
|
|
|
|
|
docHandle string
|
|
|
|
|
kbHandle string
|
2026-07-16 13:23:20 +00:00
|
|
|
title string
|
2026-07-28 07:50:39 +00:00
|
|
|
metadata string
|
2026-07-16 13:23:20 +00:00
|
|
|
chunkType string
|
|
|
|
|
index int
|
|
|
|
|
view string
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
role string
|
2026-07-16 13:23:20 +00:00
|
|
|
match string
|
|
|
|
|
content string
|
|
|
|
|
question string
|
|
|
|
|
answers []string
|
|
|
|
|
images []map[string]interface{}
|
|
|
|
|
docRealID string
|
|
|
|
|
kbRealID string
|
|
|
|
|
chunkReal string
|
|
|
|
|
inputOrder int
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-26 17:04:19 +00:00
|
|
|
func (r *sourceRegistry) modelKnowledgeOutput(mode string, rows []map[string]interface{}, fallback string) string {
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
chunks := r.modelChunksFromRows(mode, rows)
|
|
|
|
|
if len(chunks) == 0 {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
return renderKnowledgeChunks(mode, chunks, nil)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// modelChunksFromRows registers every row's handles and converts it into the
|
|
|
|
|
// renderer's chunk model.
|
|
|
|
|
func (r *sourceRegistry) modelChunksFromRows(mode string, rows []map[string]interface{}) []modelChunk {
|
2026-07-16 13:23:20 +00:00
|
|
|
chunks := make([]modelChunk, 0, len(rows))
|
|
|
|
|
for idx, row := range rows {
|
|
|
|
|
chunkID := firstNonEmpty(stringValue(row, "chunk_id"), stringValue(row, "faq_id"), stringValue(row, "id"))
|
|
|
|
|
knowledgeID := stringValue(row, "knowledge_id")
|
|
|
|
|
kbID := firstNonEmpty(stringValue(row, "knowledge_base_id"), stringValue(row, "knowledge_base"))
|
|
|
|
|
title := firstNonEmpty(stringValue(row, "knowledge_title"), stringValue(row, "title"))
|
|
|
|
|
if chunkID == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
chunkType := stringValue(row, "chunk_type")
|
|
|
|
|
if stringValue(row, "faq_id") != "" && chunkType == "" {
|
|
|
|
|
chunkType = "faq"
|
|
|
|
|
}
|
|
|
|
|
chunkIndex := intValue(row, "chunk_index")
|
|
|
|
|
if chunkIndex == 0 {
|
|
|
|
|
chunkIndex = intValue(row, "index")
|
|
|
|
|
}
|
2026-07-26 17:17:36 +00:00
|
|
|
chunkHandle := r.RegisterChunk(ChunkReference{
|
2026-07-16 13:23:20 +00:00
|
|
|
ChunkID: chunkID,
|
|
|
|
|
KnowledgeID: knowledgeID,
|
|
|
|
|
KnowledgeBaseID: kbID,
|
|
|
|
|
DocumentTitle: title,
|
|
|
|
|
ChunkIndex: chunkIndex,
|
|
|
|
|
ChunkType: chunkType,
|
|
|
|
|
})
|
|
|
|
|
chunks = append(chunks, modelChunk{
|
2026-07-26 17:17:36 +00:00
|
|
|
handle: chunkHandle,
|
|
|
|
|
docHandle: r.RegisterDocument(knowledgeID),
|
|
|
|
|
kbHandle: r.RegisterKnowledgeBase(kbID),
|
2026-07-16 13:23:20 +00:00
|
|
|
title: title,
|
2026-07-28 07:50:39 +00:00
|
|
|
metadata: stringValue(row, "knowledge_metadata"),
|
2026-07-16 13:23:20 +00:00
|
|
|
chunkType: chunkType,
|
|
|
|
|
index: chunkIndex,
|
|
|
|
|
view: viewForRow(row, mode),
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
role: stringValue(row, "role"),
|
2026-07-16 13:23:20 +00:00
|
|
|
match: firstNonEmpty(stringValue(row, "match_snippet"), stringValue(row, "matched_content")),
|
|
|
|
|
content: stringValue(row, "content"),
|
|
|
|
|
question: firstNonEmpty(stringValue(row, "faq_question"), stringValue(row, "faq_standard_question")),
|
|
|
|
|
answers: stringSliceValue(row["faq_answers"]),
|
|
|
|
|
images: mapsValue(row["images"]),
|
|
|
|
|
docRealID: knowledgeID,
|
|
|
|
|
kbRealID: kbID,
|
|
|
|
|
chunkReal: chunkID,
|
|
|
|
|
inputOrder: idx,
|
|
|
|
|
})
|
|
|
|
|
}
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
return chunks
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// annotateModeFallbacks adds the requested mode and one <mode_fallback> per
|
|
|
|
|
// knowledge base that was searched with a different retrieval path.
|
|
|
|
|
func (r *sourceRegistry) annotateModeFallbacks(output string, data map[string]interface{}) string {
|
|
|
|
|
fallbacks := mapsValue(data["mode_fallbacks"])
|
|
|
|
|
requested := stringValue(data, "requested_mode")
|
|
|
|
|
if len(fallbacks) == 0 || !strings.HasSuffix(output, "</retrieval>") {
|
|
|
|
|
return output
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
if requested != "" {
|
|
|
|
|
output = strings.Replace(output, "<retrieval ",
|
|
|
|
|
fmt.Sprintf("<retrieval requested_mode=\"%s\" ", escapeAttr(requested)), 1)
|
|
|
|
|
}
|
|
|
|
|
var b strings.Builder
|
|
|
|
|
for _, fb := range fallbacks {
|
|
|
|
|
fmt.Fprintf(&b, " <mode_fallback kb=\"%s\" mode=\"%s\" reason=\"%s\" />\n",
|
|
|
|
|
escapeAttr(r.RegisterKnowledgeBase(stringValue(fb, "knowledge_base_id"))),
|
|
|
|
|
escapeAttr(stringValue(fb, "mode")), escapeAttr(stringValue(fb, "reason")))
|
|
|
|
|
}
|
|
|
|
|
return strings.TrimSuffix(output, "</retrieval>") + b.String() + "</retrieval>"
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func viewForRow(row map[string]interface{}, mode string) string {
|
|
|
|
|
if stringValue(row, "content") != "" {
|
|
|
|
|
return "full"
|
|
|
|
|
}
|
|
|
|
|
if mode == "deep_read" {
|
|
|
|
|
return "full"
|
|
|
|
|
}
|
|
|
|
|
return "match"
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-26 17:04:19 +00:00
|
|
|
func (r *sourceRegistry) modelKnowledgeChunksOutput(data map[string]interface{}, fallback string) string {
|
2026-07-16 13:23:20 +00:00
|
|
|
rows := mapsValue(data["chunks"])
|
|
|
|
|
title := stringValue(data, "knowledge_title")
|
|
|
|
|
knowledgeID := stringValue(data, "knowledge_id")
|
|
|
|
|
for _, row := range rows {
|
|
|
|
|
if stringValue(row, "knowledge_id") == "" {
|
|
|
|
|
row["knowledge_id"] = knowledgeID
|
|
|
|
|
}
|
|
|
|
|
if stringValue(row, "knowledge_title") == "" {
|
|
|
|
|
row["knowledge_title"] = title
|
|
|
|
|
}
|
|
|
|
|
}
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
var info map[string]interface{}
|
|
|
|
|
if raw, ok := data["document"].(map[string]interface{}); ok {
|
|
|
|
|
info = raw
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
if len(rows) == 0 {
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
// A document that has no chunks (or a query with no matches) still
|
|
|
|
|
// deserves its header so the model learns what it read.
|
|
|
|
|
if info == nil {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
docHandle := r.RegisterDocument(knowledgeID)
|
|
|
|
|
var b strings.Builder
|
|
|
|
|
b.WriteString("<retrieval type=\"knowledge\" mode=\"deep_read\">\n")
|
|
|
|
|
fmt.Fprintf(&b, " <document id=\"%s\" title=\"%s\">\n", escapeAttr(docHandle), escapeAttr(title))
|
|
|
|
|
writeDocumentInfo(&b, info)
|
|
|
|
|
if query := stringValue(data, "query"); query != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <matches query=\"%s\" count=\"0\" />\n", escapeAttr(query))
|
fix(agent): make read_document queries keyword-based and bound its pages
read_document's in-document query was matched as one literal string, so a
keyword query such as "sunflower f(n,k)" found nothing in a 708-chunk
document even when both words were there. The zero-match result gave the
model no next step, and the UI rendered it as "0 / 708 chunks loaded",
which reads like a failed load.
Paging mode also had no size bound: the registry truncates
ToolResult.Output, but the model sees the result rendered from Data, so a
limit=100 page reached ~68k characters in the model context.
- A plain query is split on whitespace; a chunk matches when it contains
every word, in any order. regex=true still matches one expression.
- A zero-match result carries a <hint> suggesting fewer/different words
or reading a chunk from search_knowledge results.
- A page stops adding chunks at 80% of the output budget (counting
per-chunk rendering overhead); next_offset resumes at the first chunk
not returned, and an oversized first chunk is still returned.
- The UI summary shows in-document search results ("no matches" /
"N matches") and, for offset paging, the chunk range instead of a page
number that no longer holds.
2026-09-18 06:53:16 +00:00
|
|
|
b.WriteString(" <hint>No chunk contains every word of the query. Retry with fewer or different " +
|
|
|
|
|
"words (the document's own language and terms), or read a chunk from search_knowledge " +
|
|
|
|
|
"results with id=cN and context.</hint>\n")
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
}
|
|
|
|
|
b.WriteString(" </document>\n</retrieval>")
|
|
|
|
|
return b.String()
|
|
|
|
|
}
|
|
|
|
|
chunks := r.modelChunksFromRows("deep_read", rows)
|
|
|
|
|
if len(chunks) == 0 {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
output := renderKnowledgeChunks("deep_read", chunks, info)
|
|
|
|
|
if info == nil {
|
|
|
|
|
// Legacy list_knowledge_chunks payloads carry no document header.
|
|
|
|
|
remaining := intValue(data, "total_chunks") - intValue(data, "fetched_chunks")
|
|
|
|
|
if remaining > 0 {
|
|
|
|
|
output = strings.TrimSuffix(output, "</retrieval>")
|
|
|
|
|
output += fmt.Sprintf(" <pagination remaining=\"%d\" page=\"%d\" page_size=\"%d\" />\n</retrieval>",
|
|
|
|
|
remaining, intValue(data, "page"), intValue(data, "page_size"))
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
return output
|
|
|
|
|
}
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
var footer strings.Builder
|
|
|
|
|
if query := stringValue(data, "query"); query != "" {
|
|
|
|
|
fmt.Fprintf(&footer, " <matches query=\"%s\" count=\"%d\"", escapeAttr(query), intValue(data, "match_count"))
|
|
|
|
|
if boolValue(data, "truncated") {
|
|
|
|
|
footer.WriteString(" truncated=\"true\"")
|
|
|
|
|
}
|
|
|
|
|
footer.WriteString(" />\n")
|
|
|
|
|
} else if _, ok := data["next_offset"]; ok {
|
|
|
|
|
remaining := intValue(data, "total_chunks") - (intValue(data, "offset") + intValue(data, "fetched_chunks"))
|
|
|
|
|
if remaining < 0 {
|
|
|
|
|
remaining = 0
|
|
|
|
|
}
|
|
|
|
|
fmt.Fprintf(&footer, " <pagination next_offset=\"%d\" remaining=\"%d\" />\n",
|
|
|
|
|
intValue(data, "next_offset"), remaining)
|
|
|
|
|
}
|
|
|
|
|
if footer.Len() > 0 {
|
|
|
|
|
output = strings.TrimSuffix(output, "</retrieval>") + footer.String() + "</retrieval>"
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
|
|
|
|
return output
|
|
|
|
|
}
|
|
|
|
|
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
// writeDocumentInfo renders the read_document metadata header as one
|
|
|
|
|
// <info> element under the document.
|
|
|
|
|
func writeDocumentInfo(b *strings.Builder, info map[string]interface{}) {
|
|
|
|
|
if len(info) == 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(" <info")
|
|
|
|
|
for _, key := range []string{"source", "file_name", "file_type", "file_size", "parse_status"} {
|
|
|
|
|
if value := stringValue(info, key); value != "" {
|
|
|
|
|
fmt.Fprintf(b, " %s=\"%s\"", key, escapeAttr(value))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if count := intValue(info, "chunk_count"); count > 0 {
|
|
|
|
|
fmt.Fprintf(b, " chunk_count=\"%d\"", count)
|
|
|
|
|
}
|
|
|
|
|
description := stringValue(info, "description")
|
|
|
|
|
metadata, _ := info["metadata"].(map[string]interface{})
|
|
|
|
|
if description == "" && len(metadata) == 0 {
|
|
|
|
|
b.WriteString(" />\n")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(">\n")
|
|
|
|
|
if description != "" {
|
|
|
|
|
fmt.Fprintf(b, " <description>%s</description>\n", escapeText(description))
|
|
|
|
|
}
|
|
|
|
|
if len(metadata) > 0 {
|
|
|
|
|
keys := make([]string, 0, len(metadata))
|
|
|
|
|
for key := range metadata {
|
|
|
|
|
keys = append(keys, key)
|
|
|
|
|
}
|
|
|
|
|
sort.Strings(keys)
|
|
|
|
|
b.WriteString(" <metadata>")
|
|
|
|
|
for i, key := range keys {
|
|
|
|
|
if i > 0 {
|
|
|
|
|
b.WriteString("; ")
|
|
|
|
|
}
|
|
|
|
|
fmt.Fprintf(b, "%s: %v", escapeText(key), metadata[key])
|
|
|
|
|
}
|
|
|
|
|
b.WriteString("</metadata>\n")
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(" </info>\n")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func renderKnowledgeChunks(mode string, chunks []modelChunk, info map[string]interface{}) string {
|
2026-07-16 13:23:20 +00:00
|
|
|
type docGroup struct {
|
2026-07-26 17:17:36 +00:00
|
|
|
handle string
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
realID string
|
2026-07-26 17:17:36 +00:00
|
|
|
kbHandle string
|
|
|
|
|
title string
|
2026-07-28 07:50:39 +00:00
|
|
|
metadata string
|
2026-07-26 17:17:36 +00:00
|
|
|
chunks []modelChunk
|
|
|
|
|
order int
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
|
|
|
|
groupsByKey := make(map[string]*docGroup)
|
|
|
|
|
var groups []*docGroup
|
|
|
|
|
for _, chunk := range chunks {
|
2026-07-26 17:17:36 +00:00
|
|
|
key := chunk.docHandle
|
2026-07-16 13:23:20 +00:00
|
|
|
if key == "" {
|
2026-07-26 17:17:36 +00:00
|
|
|
key = "chunk:" + chunk.handle
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
|
|
|
|
group := groupsByKey[key]
|
|
|
|
|
if group == nil {
|
2026-07-28 07:50:39 +00:00
|
|
|
group = &docGroup{
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
handle: chunk.docHandle, realID: chunk.docRealID, kbHandle: chunk.kbHandle, title: chunk.title,
|
2026-07-28 07:50:39 +00:00
|
|
|
metadata: chunk.metadata, order: chunk.inputOrder,
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
groupsByKey[key] = group
|
|
|
|
|
groups = append(groups, group)
|
2026-07-28 07:50:39 +00:00
|
|
|
} else if group.metadata == "" {
|
|
|
|
|
group.metadata = chunk.metadata
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
|
|
|
|
group.chunks = append(group.chunks, chunk)
|
|
|
|
|
}
|
|
|
|
|
sort.SliceStable(groups, func(i, j int) bool { return groups[i].order < groups[j].order })
|
|
|
|
|
|
|
|
|
|
var b strings.Builder
|
|
|
|
|
fmt.Fprintf(&b, "<retrieval type=\"knowledge\" mode=\"%s\">\n", escapeAttr(mode))
|
|
|
|
|
for _, group := range groups {
|
|
|
|
|
b.WriteString(" <document")
|
2026-07-26 17:17:36 +00:00
|
|
|
if group.handle != "" {
|
|
|
|
|
fmt.Fprintf(&b, " id=\"%s\"", escapeAttr(group.handle))
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
2026-07-26 17:17:36 +00:00
|
|
|
if group.kbHandle != "" {
|
|
|
|
|
fmt.Fprintf(&b, " kb=\"%s\"", escapeAttr(group.kbHandle))
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
|
|
|
|
if group.title != "" {
|
|
|
|
|
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(group.title))
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(">\n")
|
2026-07-28 07:50:39 +00:00
|
|
|
if group.metadata != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <metadata>%s</metadata>\n", escapeText(group.metadata))
|
|
|
|
|
}
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
if info != nil && stringValue(info, "knowledge_id") == group.realID {
|
|
|
|
|
writeDocumentInfo(&b, info)
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
for _, chunk := range group.chunks {
|
2026-07-26 17:17:36 +00:00
|
|
|
fmt.Fprintf(&b, " <chunk id=\"%s\" index=\"%d\" view=\"%s\"", chunk.handle, chunk.index, chunk.view)
|
2026-07-16 13:23:20 +00:00
|
|
|
if chunk.chunkType != "" {
|
|
|
|
|
fmt.Fprintf(&b, " type=\"%s\"", escapeAttr(chunk.chunkType))
|
|
|
|
|
}
|
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents
The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.
Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
Keyword mode runs through the retrieval engine's keyword index instead of
the DB regex scan. Modes unavailable for the scope are refused with a
reason. Rerank, MMR and de-duplication are kept; already_seen markers,
retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
wiki_read_source_doc: id accepts a dN or cN handle, always returns the
document header, pages by exact offset (fixing the old floor-to-page
bug), finds passages with query (literal by default, regex opt-in) and
reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
literal queries are escaped so the model never reasons about JSON
escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
scope and its description/tips were trimmed.
Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
their successors by NormalizeAllowedTools at registration time; no data
migration. Stored histories with old names still decode, render and
redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
and document handle tables (decode-only), plus rendering for the
document header, chunk roles, in-document matches and next_offset.
Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
search -> read -> cite order; tool descriptions are short and contain no
workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
becomes keyword search, read_document gains query, wiki_search gains
regex), frontend editor/renderers/i18n, presets, website docs and the
changelog are updated accordingly.
Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.
* fix(agent): address review findings on read_document, list_documents and model rendering
- read_document: fetch the second page whenever the first page did not
reach the end of the document, so an unaligned window near the end no
longer drops the trailing chunks (also fixes context windows around a
chunk near the end); a query passed together with a cN handle now
searches the owning document instead of being ignored; query mode stops
collecting once the output budget is nearly spent and reports truncated;
the document row is authorized in place instead of being fetched twice;
the context read takes the total from the window fetch instead of a
separate count query.
- list_documents: resolve the page's document scope in one batched tag
lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
and budget-bound query results.
* fix(agent): close compatibility gaps in the consolidated retrieval tools
- Wiki-only scopes: read_document and list_documents are registered
whenever a wiki KB is in scope, since every KB stores chunks. Their
capability requirement includes wiki but is marked auxiliary, so they do
not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
of refusing the call: FAQ and vector-only bases answer keyword requests
semantically, keyword-only bases answer semantic requests by keyword.
Results carry requested_mode and mode_fallbacks, the empty-result text
names the fallback, and the call is refused only when no base in scope
has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
pushed into the database filter, pinned documents are loaded by ID, and
total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
sharing the index sequence no longer shift the neighbourhood; offset is
documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
only matches literally when the text is not a valid expression;
regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
fetch candidates from the keyword index (semantic for bases without
one), and every returned chunk is verified against the pattern.
* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics
* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
|
|
|
if chunk.role != "" {
|
|
|
|
|
fmt.Fprintf(&b, " role=\"%s\"", escapeAttr(chunk.role))
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
b.WriteString(">\n")
|
|
|
|
|
if chunk.question != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <question>%s</question>\n", escapeText(chunk.question))
|
|
|
|
|
}
|
|
|
|
|
if chunk.match != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <match>%s</match>\n", escapeText(chunk.match))
|
|
|
|
|
}
|
|
|
|
|
if chunk.content != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <content>%s</content>\n", escapeText(chunk.content))
|
|
|
|
|
}
|
|
|
|
|
for _, answer := range chunk.answers {
|
|
|
|
|
fmt.Fprintf(&b, " <answer>%s</answer>\n", escapeText(answer))
|
|
|
|
|
}
|
|
|
|
|
for _, image := range chunk.images {
|
|
|
|
|
imageURL := stringValue(image, "url")
|
|
|
|
|
if imageURL == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
caption := stringValue(image, "caption")
|
|
|
|
|
fmt.Fprintf(&b, " \n", caption, imageURL)
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(" </chunk>\n")
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(" </document>\n")
|
|
|
|
|
}
|
|
|
|
|
b.WriteString("</retrieval>")
|
|
|
|
|
return b.String()
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-26 17:04:19 +00:00
|
|
|
func (r *sourceRegistry) modelWebSearchOutput(rows []map[string]interface{}, fallback string) string {
|
2026-07-16 13:23:20 +00:00
|
|
|
if len(rows) == 0 {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
var b strings.Builder
|
2026-09-07 15:09:27 +00:00
|
|
|
b.WriteString("<retrieval type=\"web\" mode=\"search\" trust=\"untrusted\">\n")
|
|
|
|
|
evidenceFields := 2
|
|
|
|
|
for _, row := range rows {
|
|
|
|
|
if boolValue(row, "page_verified") {
|
|
|
|
|
evidenceFields = 3
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
perEvidence := min(modelWebSearchEvidenceMaxRunes, 16000/max(1, len(rows)*evidenceFields))
|
2026-07-16 13:23:20 +00:00
|
|
|
count := 0
|
|
|
|
|
for _, row := range rows {
|
|
|
|
|
rawURL := stringValue(row, "url")
|
|
|
|
|
if rawURL == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
2026-07-26 17:17:36 +00:00
|
|
|
handle := r.RegisterWeb(rawURL, stringValue(row, "title"))
|
|
|
|
|
fmt.Fprintf(&b, " <page id=\"%s\" title=\"%s\">\n", handle, escapeAttr(stringValue(row, "title")))
|
2026-07-25 14:14:23 +00:00
|
|
|
b.WriteString(" <evidence type=\"search_summary\" verified=\"false\" />\n")
|
2026-09-07 15:09:27 +00:00
|
|
|
if u, err := url.Parse(rawURL); err == nil {
|
|
|
|
|
fmt.Fprintf(&b, " <domain>%s</domain>\n", escapeText(u.Hostname()))
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
if snippet := stringValue(row, "snippet"); snippet != "" {
|
2026-09-07 15:09:27 +00:00
|
|
|
writeLimitedWebEvidence(&b, "match", snippet, perEvidence, nil)
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
2026-07-25 14:14:23 +00:00
|
|
|
if content := stringValue(row, "content"); content != "" && content != stringValue(row, "snippet") {
|
2026-09-07 15:09:27 +00:00
|
|
|
writeLimitedWebEvidence(&b, "content", content, perEvidence, nil)
|
|
|
|
|
}
|
|
|
|
|
if age := stringValue(row, "age"); age != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <age>%s</age>\n", escapeText(age))
|
|
|
|
|
}
|
|
|
|
|
if boolValue(row, "page_verified") {
|
|
|
|
|
writeLimitedWebEvidence(&b, "fetched_content", stringValue(row, "page_content"), perEvidence, nil)
|
|
|
|
|
b.WriteString(" <page_fetch status=\"success\" verified=\"true\" />\n")
|
|
|
|
|
writeWebPageFileHint(&b, row)
|
|
|
|
|
if stringValue(row, "full_output_path") == "" {
|
|
|
|
|
fmt.Fprintf(&b, " <continue url=\"%s\" next_offset=\"0\">"+
|
|
|
|
|
"Read with web_fetch for more page content.</continue>\n", handle)
|
|
|
|
|
}
|
|
|
|
|
} else if stringValue(row, "page_status") == "failed" {
|
|
|
|
|
fmt.Fprintf(&b, " <page_fetch status=\"failed\">%s</page_fetch>\n",
|
|
|
|
|
escapeText(stringValue(row, "page_error")))
|
2026-07-25 14:14:23 +00:00
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
if published := stringValue(row, "published_at"); published != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <published>%s</published>\n", escapeText(published))
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(" </page>\n")
|
|
|
|
|
count++
|
|
|
|
|
}
|
|
|
|
|
b.WriteString("</retrieval>")
|
|
|
|
|
if count == 0 {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
return b.String()
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-26 17:04:19 +00:00
|
|
|
func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fallback string) string {
|
2026-07-16 13:23:20 +00:00
|
|
|
if len(rows) == 0 {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
|
|
|
|
var b strings.Builder
|
2026-09-07 15:09:27 +00:00
|
|
|
b.WriteString("<retrieval type=\"web\" mode=\"fetch\" trust=\"untrusted\">\n")
|
2026-07-25 14:14:23 +00:00
|
|
|
count, successCount, failedCount := 0, 0, 0
|
2026-09-07 15:09:27 +00:00
|
|
|
// Allocate a share to every successful page, including legacy stored results.
|
|
|
|
|
successPages := 0
|
|
|
|
|
for _, row := range rows {
|
|
|
|
|
if stringValue(row, "status") == "success" || stringValue(row, "status") == "" {
|
|
|
|
|
successPages++
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
perPage := modelWebFetchTotalMaxRunes / max(1, successPages)
|
2026-07-16 13:23:20 +00:00
|
|
|
for _, row := range rows {
|
|
|
|
|
rawURL := stringValue(row, "url")
|
|
|
|
|
if rawURL == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
title := stringValue(row, "title")
|
2026-07-26 17:17:36 +00:00
|
|
|
handle := r.RegisterWeb(rawURL, title)
|
2026-07-25 14:14:23 +00:00
|
|
|
status := stringValue(row, "status")
|
|
|
|
|
if status == "" {
|
|
|
|
|
status = "success"
|
|
|
|
|
}
|
|
|
|
|
fmt.Fprintf(&b, " <page id=\"%s\" status=\"%s\"", handle, escapeAttr(status))
|
2026-07-16 13:23:20 +00:00
|
|
|
if title != "" {
|
|
|
|
|
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(title))
|
|
|
|
|
}
|
2026-07-25 14:14:23 +00:00
|
|
|
if status == "success" {
|
2026-09-07 15:09:27 +00:00
|
|
|
b.WriteString(" view=\"excerpt\">\n")
|
|
|
|
|
writeWebPageFileHint(&b, row)
|
|
|
|
|
remainingEvidence := perPage
|
2026-07-25 14:14:23 +00:00
|
|
|
successCount++
|
|
|
|
|
if summary := stringValue(row, "summary"); summary != "" {
|
2026-07-27 07:28:47 +00:00
|
|
|
writeLimitedWebEvidence(&b, "summary", summary, modelWebFetchSummaryMaxRunes, &remainingEvidence)
|
2026-07-25 14:14:23 +00:00
|
|
|
}
|
|
|
|
|
if summaryStatus := stringValue(row, "summary_status"); summaryStatus == "failed" {
|
|
|
|
|
fmt.Fprintf(&b, " <summary_error code=\"%s\">%s</summary_error>\n",
|
|
|
|
|
escapeAttr(stringValue(row, "summary_error_code")), escapeText(stringValue(row, "summary_error_message")))
|
|
|
|
|
}
|
|
|
|
|
if content := stringValue(row, "raw_content"); content != "" {
|
2026-09-07 15:09:27 +00:00
|
|
|
limit := min(modelWebFetchContentMaxRunes, remainingEvidence)
|
|
|
|
|
writeLimitedWebEvidence(&b, "content", content, limit, &remainingEvidence)
|
|
|
|
|
shown := min(len([]rune(content)), limit)
|
|
|
|
|
offset := intValue(row, "offset")
|
|
|
|
|
total := intValue(row, "content_length")
|
|
|
|
|
if total == 0 {
|
|
|
|
|
total = offset + len([]rune(content))
|
|
|
|
|
}
|
|
|
|
|
fmt.Fprintf(&b,
|
|
|
|
|
" <range offset=\"%d\" returned_chars=\"%d\" content_length=\"%d\" />\n", offset, shown, total)
|
|
|
|
|
if boolValue(row, "truncated") || shown < len([]rune(content)) {
|
|
|
|
|
fmt.Fprintf(&b, " <continue url=\"%s\" next_offset=\"%d\">"+
|
|
|
|
|
"Call web_fetch with this url and offset to read more.</continue>\n", handle, offset+shown)
|
|
|
|
|
}
|
2026-07-25 14:14:23 +00:00
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
fmt.Fprintf(&b, " retryable=\"%t\"", boolValue(row, "retryable"))
|
|
|
|
|
if errorCode := stringValue(row, "error_code"); errorCode != "" {
|
|
|
|
|
fmt.Fprintf(&b, " error_code=\"%s\"", escapeAttr(errorCode))
|
|
|
|
|
}
|
|
|
|
|
b.WriteString(">\n")
|
|
|
|
|
if errorMessage := stringValue(row, "error_message"); errorMessage != "" {
|
|
|
|
|
fmt.Fprintf(&b, " <error>%s</error>\n", escapeText(errorMessage))
|
|
|
|
|
}
|
|
|
|
|
if status == "failed" {
|
|
|
|
|
failedCount++
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
}
|
|
|
|
|
b.WriteString(" </page>\n")
|
|
|
|
|
count++
|
|
|
|
|
}
|
|
|
|
|
b.WriteString("</retrieval>")
|
|
|
|
|
if count == 0 {
|
|
|
|
|
return r.CompactKnownText(fallback)
|
|
|
|
|
}
|
2026-07-25 14:14:23 +00:00
|
|
|
if failedCount > 0 {
|
|
|
|
|
b.WriteString("\n\n=== Next Steps ===\n")
|
|
|
|
|
if successCount == 0 {
|
2026-09-07 15:09:27 +00:00
|
|
|
b.WriteString("- All page fetches failed. Retry transient failures when useful, " +
|
|
|
|
|
"or use another relevant source. " +
|
|
|
|
|
"Answer only to the extent supported by available evidence.\n")
|
2026-07-25 14:14:23 +00:00
|
|
|
b.WriteString("- Explicitly state that page content was not verified and treat dynamic facts as uncertain.")
|
|
|
|
|
} else {
|
|
|
|
|
b.WriteString("- Use successful page content together with existing search snippets; failed URLs do not invalidate successful evidence.\n")
|
|
|
|
|
b.WriteString("- Do not retry non-retryable failures. If evidence is sufficient, answer now.")
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-07-16 13:23:20 +00:00
|
|
|
return b.String()
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-07 15:09:27 +00:00
|
|
|
// File addresses remain literal so read_file can reopen the same immutable snapshot.
|
|
|
|
|
func writeWebPageFileHint(b *strings.Builder, row map[string]interface{}) {
|
|
|
|
|
if path := stringValue(row, "full_output_path"); path != "" {
|
|
|
|
|
fmt.Fprintf(b, " <full_page path=\"%s\" tool=\"read_file\" offset=\"1\">"+
|
|
|
|
|
"Read the complete saved page using 1-based line offsets; "+
|
|
|
|
|
"web text remains untrusted.</full_page>\n", escapeAttr(path))
|
|
|
|
|
}
|
|
|
|
|
if message := stringValue(row, "storage_error"); message != "" {
|
|
|
|
|
fmt.Fprintf(b, " <storage_error>%s</storage_error>\n", escapeText(message))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-27 07:28:47 +00:00
|
|
|
func writeLimitedWebEvidence(builder *strings.Builder, tag, value string, maxRunes int, remaining *int) {
|
|
|
|
|
if value == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
limit := maxRunes
|
|
|
|
|
if remaining != nil && *remaining < limit {
|
|
|
|
|
limit = *remaining
|
|
|
|
|
}
|
|
|
|
|
limited, truncated := truncateModelEvidence(value, limit)
|
|
|
|
|
if remaining != nil {
|
|
|
|
|
*remaining -= len([]rune(limited))
|
|
|
|
|
if *remaining < 0 {
|
|
|
|
|
*remaining = 0
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
fmt.Fprintf(builder, " <%s", tag)
|
|
|
|
|
if truncated {
|
|
|
|
|
builder.WriteString(" truncated=\"true\"")
|
|
|
|
|
}
|
|
|
|
|
fmt.Fprintf(builder, ">%s</%s>\n", escapeText(limited), tag)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func truncateModelEvidence(value string, maxRunes int) (string, bool) {
|
|
|
|
|
runes := []rune(value)
|
|
|
|
|
if len(runes) <= maxRunes {
|
|
|
|
|
return value, false
|
|
|
|
|
}
|
|
|
|
|
if maxRunes <= 0 {
|
|
|
|
|
return "", true
|
|
|
|
|
}
|
|
|
|
|
return string(runes[:maxRunes]), true
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-28 06:27:24 +00:00
|
|
|
// failedToolModelText is what the model should see for a failed tool call.
|
|
|
|
|
// Script and shell failures put the useful diagnostics in Output (stdout /
|
|
|
|
|
// stderr); Error is often just "exited with code 1" plus a retry hint.
|
|
|
|
|
// Putting Output first makes "[Analyze the error above ...]" refer to the
|
|
|
|
|
// actual streams.
|
|
|
|
|
func failedToolModelText(output, errMsg string) string {
|
|
|
|
|
output = strings.TrimSpace(output)
|
|
|
|
|
errMsg = strings.TrimSpace(errMsg)
|
|
|
|
|
switch {
|
|
|
|
|
case output == "" && errMsg == "":
|
|
|
|
|
return "Error: tool call failed"
|
|
|
|
|
case output == "":
|
|
|
|
|
return "Error: " + errMsg
|
|
|
|
|
case errMsg == "" || strings.Contains(output, errMsg):
|
|
|
|
|
return output
|
|
|
|
|
default:
|
|
|
|
|
return output + "\n\nError: " + errMsg
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-16 13:23:20 +00:00
|
|
|
func mapsValue(value interface{}) []map[string]interface{} {
|
|
|
|
|
if value == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
encoded, err := json.Marshal(value)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
var rows []map[string]interface{}
|
|
|
|
|
if err := json.Unmarshal(encoded, &rows); err != nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
return rows
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func stringValue(values map[string]interface{}, key string) string {
|
|
|
|
|
if values == nil {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
switch value := values[key].(type) {
|
|
|
|
|
case string:
|
|
|
|
|
return value
|
|
|
|
|
case fmt.Stringer:
|
|
|
|
|
return value.String()
|
|
|
|
|
case json.Number:
|
|
|
|
|
return value.String()
|
|
|
|
|
default:
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func intValue(values map[string]interface{}, key string) int {
|
|
|
|
|
if values == nil {
|
|
|
|
|
return 0
|
|
|
|
|
}
|
|
|
|
|
switch value := values[key].(type) {
|
|
|
|
|
case int:
|
|
|
|
|
return value
|
|
|
|
|
case int32:
|
|
|
|
|
return int(value)
|
|
|
|
|
case int64:
|
|
|
|
|
return int(value)
|
|
|
|
|
case float64:
|
|
|
|
|
return int(value)
|
|
|
|
|
case json.Number:
|
|
|
|
|
result, _ := value.Int64()
|
|
|
|
|
return int(result)
|
|
|
|
|
default:
|
|
|
|
|
return 0
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func boolValue(values map[string]interface{}, key string) bool {
|
|
|
|
|
if values == nil {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
value, _ := values[key].(bool)
|
|
|
|
|
return value
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func stringSliceValue(value interface{}) []string {
|
|
|
|
|
if value == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
encoded, err := json.Marshal(value)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
var values []string
|
|
|
|
|
if err := json.Unmarshal(encoded, &values); err != nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
return values
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func escapeText(value string) string {
|
|
|
|
|
replacer := strings.NewReplacer("&", "&", "<", "<", ">", ">")
|
|
|
|
|
return replacer.Replace(value)
|
|
|
|
|
}
|