2026-04-23 09:22:18 +00:00
|
|
|
/**
|
|
|
|
|
* Tool Capability Requirements
|
|
|
|
|
*
|
|
|
|
|
* Single source of truth for the mapping from agent tool names to the
|
|
|
|
|
* knowledge-base capabilities each tool depends on. Used to:
|
|
|
|
|
* - Gray out tools whose dependencies aren't satisfied by the current scope
|
|
|
|
|
* (see `AgentEditorModal.vue` → `availableTools`).
|
|
|
|
|
* - Derive `kb_filter`-style predicates for agent type presets so the same
|
|
|
|
|
* declarative map drives both the tool allowlist and the KB allowlist
|
|
|
|
|
* (see `deriveKbFilterFromTools`).
|
|
|
|
|
*
|
|
|
|
|
* Capability names mirror the backend's KB capability set:
|
|
|
|
|
* - vector: vector chunk index (embedding-based retrieval)
|
|
|
|
|
* - keyword: keyword/BM25 chunk index
|
|
|
|
|
* - wiki: Wiki page indexing
|
|
|
|
|
* - graph: knowledge graph index
|
|
|
|
|
* - faq: FAQ-type KB (question/answer pairs as chunks)
|
|
|
|
|
*
|
|
|
|
|
* Requirement semantics:
|
|
|
|
|
* - `anyOf`: KB scope must expose at least ONE listed capability.
|
|
|
|
|
* - `allOf`: KB scope must expose ALL listed capabilities.
|
|
|
|
|
* - empty : tool has no KB requirement (always available).
|
|
|
|
|
*
|
|
|
|
|
* IMPORTANT: keep this list aligned with backend tool definitions
|
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
|
|
|
* (`internal/agent/tools/`; this map mirrors
|
2026-09-26 06:57:16 +00:00
|
|
|
* `internal/agent/tools/capabilities.go`). A tool missing from this map
|
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
|
|
|
* defaults to "always available" so new tools don't silently start disabled.
|
2026-04-23 09:22:18 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
export type KBCapability = 'vector' | 'keyword' | 'wiki' | 'graph' | 'faq';
|
|
|
|
|
|
|
|
|
|
export interface ToolRequirement {
|
|
|
|
|
anyOf?: KBCapability[];
|
|
|
|
|
allOf?: KBCapability[];
|
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
|
|
|
/**
|
|
|
|
|
* Auxiliary tools work on the listed KBs but do not by themselves make a KB
|
|
|
|
|
* worth selecting (a document reader can open a wiki-only KB's sources, yet
|
|
|
|
|
* must not pull wiki-only KBs into a RAG agent's scope). They only shape
|
|
|
|
|
* the derived KB filter when no primary tool has a requirement. Mirrors
|
|
|
|
|
* `ToolRequirement.Auxiliary` in `internal/agent/tools/capabilities.go`.
|
|
|
|
|
*/
|
|
|
|
|
auxiliary?: boolean;
|
2026-04-23 09:22:18 +00:00
|
|
|
/**
|
|
|
|
|
* Whether this tool can use user-provided file references (via @ 提及) as
|
|
|
|
|
* an additional retrieval scope. Tools with `consumesFiles: false` ignore
|
|
|
|
|
* `knowledge_ids`; we use this flag in the chat `@` dropdown to decide
|
|
|
|
|
* whether to even offer the "文件" tab to the user.
|
|
|
|
|
*/
|
|
|
|
|
consumesFiles?: boolean;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const TOOL_CAPABILITY_REQUIREMENTS: Record<string, ToolRequirement> = {
|
|
|
|
|
// ---- base / reasoning (no KB dependency) ----
|
|
|
|
|
thinking: {},
|
|
|
|
|
todo_write: {},
|
|
|
|
|
|
|
|
|
|
// ---- RAG / chunk retrieval (need at least one chunk-indexed KB) ----
|
|
|
|
|
// We use vector|keyword as the canonical "has RAG chunks" signal. FAQ KBs
|
|
|
|
|
// also expose chunks, but the current UX message bucket is "RAG KB"; once
|
|
|
|
|
// we add a dedicated `requiresFaqKb` i18n key we can include `faq` here.
|
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: { anyOf: ['vector', 'keyword'], consumesFiles: true },
|
|
|
|
|
// Document readers work on stored chunks, which wiki-only KBs have too.
|
|
|
|
|
read_document: { anyOf: ['vector', 'keyword', 'wiki'], consumesFiles: true, auxiliary: true },
|
|
|
|
|
list_documents: { anyOf: ['vector', 'keyword', 'wiki'], consumesFiles: true, auxiliary: true },
|
|
|
|
|
database_query: { anyOf: ['vector', 'keyword'], consumesFiles: true },
|
|
|
|
|
// Retired names kept so stale agent configs / stored history still resolve.
|
|
|
|
|
// The editor normalizes them to the new names on load (see
|
|
|
|
|
// `@/utils/legacy-tool-names`).
|
2026-04-23 09:22:18 +00:00
|
|
|
knowledge_search: { anyOf: ['vector', 'keyword'], consumesFiles: true },
|
|
|
|
|
grep_chunks: { anyOf: ['vector', 'keyword'], consumesFiles: true },
|
|
|
|
|
list_knowledge_chunks: { anyOf: ['vector', 'keyword'], consumesFiles: true },
|
|
|
|
|
get_document_info: { anyOf: ['vector', 'keyword'], consumesFiles: true },
|
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
|
|
|
wiki_read_source_doc: { anyOf: ['vector', 'keyword', 'wiki'], consumesFiles: true, auxiliary: true },
|
|
|
|
|
|
|
|
|
|
// ---- Knowledge graph (needs a graph-indexed KB) ----
|
|
|
|
|
query_knowledge_graph: { allOf: ['graph'], consumesFiles: true },
|
2026-04-23 09:22:18 +00:00
|
|
|
|
|
|
|
|
// ---- Wiki (operates on wiki pages referenced by the wiki machinery;
|
|
|
|
|
// arbitrary user-picked file IDs aren't meaningful here) ----
|
|
|
|
|
wiki_search: { allOf: ['wiki'] },
|
|
|
|
|
wiki_read_page: { allOf: ['wiki'] },
|
|
|
|
|
wiki_flag_issue: { allOf: ['wiki'] },
|
|
|
|
|
wiki_write_page: { allOf: ['wiki'] },
|
|
|
|
|
wiki_replace_text: { allOf: ['wiki'] },
|
|
|
|
|
wiki_rename_page: { allOf: ['wiki'] },
|
|
|
|
|
wiki_delete_page: { allOf: ['wiki'] },
|
|
|
|
|
wiki_read_issue: { allOf: ['wiki'] },
|
|
|
|
|
wiki_update_issue: { allOf: ['wiki'] },
|
|
|
|
|
|
|
|
|
|
// ---- Data analysis (reads table summary/column chunks produced by RAG ingest) ----
|
|
|
|
|
data_analysis: { anyOf: ['vector', 'keyword'], consumesFiles: true },
|
|
|
|
|
data_schema: { anyOf: ['vector', 'keyword'], consumesFiles: true },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Aggregate KB-capability set available somewhere in the agent's KB scope.
|
|
|
|
|
* All fields default to `false` for unknown capabilities.
|
|
|
|
|
*/
|
|
|
|
|
export interface ScopeCapabilities {
|
|
|
|
|
vector: boolean;
|
|
|
|
|
keyword: boolean;
|
|
|
|
|
wiki: boolean;
|
|
|
|
|
graph: boolean;
|
|
|
|
|
faq: boolean;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Machine-readable reason a tool is unsatisfiable. Map to a user-facing
|
|
|
|
|
* string via i18n on the caller side (see `AgentEditorModal.vue`).
|
|
|
|
|
*/
|
|
|
|
|
export type RequirementMissKind = 'none' | 'needsKb' | 'needsRag' | 'needsWiki' | 'needsGraph' | 'needsFaq';
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Evaluate whether a tool's requirements are satisfied by the scope.
|
|
|
|
|
*
|
|
|
|
|
* @param toolName the tool identifier (see `TOOL_CAPABILITY_REQUIREMENTS`)
|
|
|
|
|
* @param scope aggregate capabilities exposed by KBs currently in scope
|
|
|
|
|
* @param hasAnyKb whether the agent has at least one KB in scope
|
|
|
|
|
* (i.e. `kb_selection_mode !== 'none'`)
|
|
|
|
|
*/
|
|
|
|
|
export function evaluateToolRequirement(
|
|
|
|
|
toolName: string,
|
|
|
|
|
scope: ScopeCapabilities,
|
|
|
|
|
hasAnyKb: boolean,
|
|
|
|
|
): { ok: boolean; missKind: RequirementMissKind } {
|
fix(agent): make agent tool selection match the tools the runtime registers (#4211)
The tools a smart-reasoning agent may use were defined in three places
that never checked each other: the agent editor's checkboxes, the stored
allowed_tools, and what registerTools registers. The editor drew from a
hard-coded list that had drifted (search_conversations, a default tool,
had no checkbox), hid stored entries outside that list, and could not
untick a tool whose knowledge base capability was missing. The save API
stored any name. And an empty list could not mean "no tools": three
places treated it as "use the default tools", so clearing every checkbox
gave an agent without a knowledge base search_conversations, while the
editor's preview said it had none.
One source for the tool list: GET /api/v1/agents/tools serves the tools
of AvailableToolDefinitions with their group, danger flag and knowledge
base requirement, the default tools, and the tools other agent settings
register whatever the list says. The editor renders from it, falling
back to the catalog's label for a tool it has no translation for.
Stored values stay visible: a missing capability only blocks ticking a
tool, and stored names the catalog does not offer are shown ticked in
their own section and can be removed.
An empty list now means no built-in tools; only a list that was never
set selects the defaults. tools.EffectiveAllowedTools makes that
decision for tool registration, the session config and the rerank
requirement. Migration 000116 (SQLite 000035) writes the default tools
into the empty list of every existing smart-reasoning agent, so they
keep the tools they ran with. The knowledge base filter follows the
stored list, so such an agent with an "all" scope now gets the same
scope as one that ticked the defaults: bases search_knowledge cannot use
leave it. The editor writes the defaults into an unset list it loads,
so saving does not silently turn the defaults into no tools.
Saving validates the list: retired names are rewritten, switch-managed
and retired skill tools are dropped, names the request adds that no
tool answers to are rejected with a 400 that lists them, and unknown
names already stored are kept so an existing agent can still be saved.
The response reports what was kept or dropped.
2026-10-13 03:29:24 +00:00
|
|
|
return evaluateRequirement(TOOL_CAPABILITY_REQUIREMENTS[toolName], scope, hasAnyKb);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Evaluate a requirement given directly, such as one served by the backend
|
|
|
|
|
* tool catalog (`GET /api/v1/agents/tools`). An absent or empty requirement
|
|
|
|
|
* is always satisfied.
|
|
|
|
|
*/
|
|
|
|
|
export function evaluateRequirement(
|
|
|
|
|
req: Pick<ToolRequirement, 'anyOf' | 'allOf'> | undefined,
|
|
|
|
|
scope: ScopeCapabilities,
|
|
|
|
|
hasAnyKb: boolean,
|
|
|
|
|
): { ok: boolean; missKind: RequirementMissKind } {
|
|
|
|
|
// No requirements: always available.
|
2026-04-23 09:22:18 +00:00
|
|
|
if (!req || (!req.anyOf?.length && !req.allOf?.length)) {
|
|
|
|
|
return { ok: true, missKind: 'none' };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Any capability requirement implies needing at least one KB in scope.
|
|
|
|
|
if (!hasAnyKb) return { ok: false, missKind: 'needsKb' };
|
|
|
|
|
|
|
|
|
|
const has = (c: KBCapability): boolean => !!scope[c];
|
|
|
|
|
|
|
|
|
|
if (req.allOf && req.allOf.length > 0) {
|
|
|
|
|
for (const c of req.allOf) {
|
|
|
|
|
if (!has(c)) return { ok: false, missKind: primaryMissKind(c) };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (req.anyOf && req.anyOf.length > 0) {
|
|
|
|
|
if (!req.anyOf.some(has)) {
|
|
|
|
|
return { ok: false, missKind: primaryMissKind(req.anyOf[0]) };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return { ok: true, missKind: 'none' };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function primaryMissKind(c: KBCapability): RequirementMissKind {
|
|
|
|
|
switch (c) {
|
|
|
|
|
case 'wiki': return 'needsWiki';
|
|
|
|
|
case 'graph': return 'needsGraph';
|
|
|
|
|
case 'faq': return 'needsFaq';
|
|
|
|
|
case 'vector':
|
|
|
|
|
case 'keyword': return 'needsRag';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Derive a `kb_filter`-style predicate for a list of tools: a KB satisfies
|
|
|
|
|
* the derived filter iff at least ONE of the listed tools would be usable
|
|
|
|
|
* on a scope consisting of just that KB.
|
|
|
|
|
*
|
|
|
|
|
* Used by Step 3 so presets don't have to hand-maintain `kb_filter` next
|
|
|
|
|
* to their `allowed_tools` — the two are always derived from the same map.
|
|
|
|
|
*
|
|
|
|
|
* Returns `null` when none of the input tools have any KB requirement
|
|
|
|
|
* (i.e. any KB is acceptable).
|
|
|
|
|
*/
|
|
|
|
|
export function deriveKbFilterFromTools(
|
|
|
|
|
tools: string[],
|
|
|
|
|
): { any_of: KBCapability[] } | null {
|
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
|
|
|
const primary = new Set<KBCapability>();
|
|
|
|
|
const auxiliary = new Set<KBCapability>();
|
2026-04-23 09:22:18 +00:00
|
|
|
for (const t of tools) {
|
|
|
|
|
const req = TOOL_CAPABILITY_REQUIREMENTS[t];
|
|
|
|
|
if (!req) continue;
|
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
|
|
|
const target = req.auxiliary ? auxiliary : primary;
|
|
|
|
|
req.anyOf?.forEach(c => target.add(c));
|
|
|
|
|
req.allOf?.forEach(c => target.add(c));
|
2026-04-23 09:22:18 +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
|
|
|
const caps = primary.size > 0 ? primary : auxiliary;
|
2026-04-23 09:22:18 +00:00
|
|
|
if (caps.size === 0) return null;
|
|
|
|
|
return { any_of: Array.from(caps) };
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-12 07:41:47 +00:00
|
|
|
/**
|
|
|
|
|
* Implicit KB capability requirement for the "quick-answer" (RAG) agent
|
|
|
|
|
* mode. Quick-answer drives retrieval purely through vector/keyword chunk
|
|
|
|
|
* search and ships with NO `allowed_tools`, so the tool-derived filter
|
|
|
|
|
* alone would let wiki-only KBs through even though they can't contribute
|
|
|
|
|
* anything to a RAG answer. Treat this as a property of the agent MODE.
|
|
|
|
|
*/
|
|
|
|
|
const QUICK_ANSWER_KB_FILTER: { any_of: KBCapability[] } = {
|
|
|
|
|
any_of: ['vector', 'keyword'],
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Agent-mode aware version of `deriveKbFilterFromTools`: unions the
|
|
|
|
|
* tool-derived `any_of` with the implicit requirement of `agentMode`
|
|
|
|
|
* (currently: quick-answer → vector|keyword).
|
|
|
|
|
*
|
|
|
|
|
* Returns `null` when neither the agent mode nor the tools impose any
|
|
|
|
|
* capability constraint (i.e. any KB is acceptable).
|
|
|
|
|
*/
|
|
|
|
|
export function deriveKbFilterForAgent(
|
|
|
|
|
agentMode: string | undefined | null,
|
|
|
|
|
allowedTools: string[] | undefined | null,
|
|
|
|
|
): { any_of: KBCapability[] } | null {
|
|
|
|
|
const caps = new Set<KBCapability>();
|
|
|
|
|
if (agentMode === 'quick-answer') {
|
|
|
|
|
QUICK_ANSWER_KB_FILTER.any_of.forEach(c => caps.add(c));
|
|
|
|
|
}
|
|
|
|
|
const fromTools = deriveKbFilterFromTools(allowedTools || []);
|
|
|
|
|
fromTools?.any_of.forEach(c => caps.add(c));
|
|
|
|
|
if (caps.size === 0) return null;
|
|
|
|
|
return { any_of: Array.from(caps) };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Agent-mode aware version of `kbSatisfiesToolRequirements`: ALSO honours
|
|
|
|
|
* the implicit capability requirement of `agentMode` (quick-answer needs
|
|
|
|
|
* vector or keyword indexing). Use this anywhere the user is choosing a
|
|
|
|
|
* KB for an agent — agent editor "specified KB" dropdown, chat `@`
|
|
|
|
|
* mention list, etc.
|
|
|
|
|
*/
|
|
|
|
|
export function kbSatisfiesAgentRequirements(
|
|
|
|
|
kbCaps: Partial<ScopeCapabilities> | undefined | null,
|
|
|
|
|
agentMode: string | undefined | null,
|
|
|
|
|
allowedTools: string[] | undefined | null,
|
|
|
|
|
): boolean {
|
|
|
|
|
const filter = deriveKbFilterForAgent(agentMode, allowedTools);
|
|
|
|
|
if (!filter) return true;
|
|
|
|
|
if (!kbCaps) return false;
|
|
|
|
|
return filter.any_of.some(c => !!kbCaps[c]);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 09:22:18 +00:00
|
|
|
/**
|
|
|
|
|
* Decide whether a single KB is compatible with an agent's tool set.
|
|
|
|
|
*
|
|
|
|
|
* "Compatible" here means: at least ONE tool in `allowedTools` requires a
|
|
|
|
|
* capability that this KB exposes — i.e. the agent has SOMETHING useful to
|
|
|
|
|
* do against this KB. Tools with no KB requirement don't contribute.
|
|
|
|
|
*
|
|
|
|
|
* If `allowedTools` contains no KB-dependent tool, every KB is considered
|
|
|
|
|
* compatible (the agent won't retrieve anything either way, so filtering
|
|
|
|
|
* is not meaningful).
|
|
|
|
|
*/
|
|
|
|
|
export function kbSatisfiesToolRequirements(
|
|
|
|
|
kbCaps: Partial<ScopeCapabilities> | undefined | null,
|
|
|
|
|
allowedTools: string[] | undefined | null,
|
|
|
|
|
): boolean {
|
|
|
|
|
const filter = deriveKbFilterFromTools(allowedTools || []);
|
|
|
|
|
if (!filter) return true;
|
|
|
|
|
if (!kbCaps) return false;
|
|
|
|
|
return filter.any_of.some(c => !!kbCaps[c]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* True iff any of the agent's allowed tools can consume user-provided file
|
|
|
|
|
* references (`knowledge_ids`). Used by the chat `@` menu to decide whether
|
|
|
|
|
* showing the "文件" list makes sense at all — e.g. a pure Wiki agent has no
|
|
|
|
|
* tool that would read an arbitrary file the user picks, so we don't offer
|
|
|
|
|
* it. `undefined`/`null`/empty → true (permissive fallback: if we don't
|
|
|
|
|
* know, show files).
|
|
|
|
|
*/
|
|
|
|
|
export function toolsConsumeFiles(
|
|
|
|
|
allowedTools: string[] | undefined | null,
|
|
|
|
|
): boolean {
|
|
|
|
|
if (!allowedTools || allowedTools.length === 0) return true;
|
|
|
|
|
for (const t of allowedTools) {
|
|
|
|
|
const req = TOOL_CAPABILITY_REQUIREMENTS[t];
|
|
|
|
|
// Unknown tools (e.g. MCP tools) are treated as potentially file-consuming.
|
|
|
|
|
if (!req) return true;
|
|
|
|
|
if (req.consumesFiles) return true;
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|