chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,165 @@
|
||||
# Model context boundary
|
||||
|
||||
`modelcontext.Registry` is the only application-facing boundary for values
|
||||
that are shortened before an LLM call and restored afterwards. The whole
|
||||
codec lives in this one package:
|
||||
|
||||
| File | Role |
|
||||
| --- | --- |
|
||||
| `registry.go` | `Registry` facade — the only type request lifecycles use |
|
||||
| `handle_table.go` | `handleTable[M]`, the generic bidirectional primitive behind every handle space |
|
||||
| `sources.go` | source handles (`chunk://N`/`doc://N`/`kb://N`/`url://N`) and the tool-argument codec |
|
||||
| `source_text.go` | handle syntax, `academy://` durable URIs, and free-text / streaming handle rewriting |
|
||||
| `citations.go` | protocol prompts, `<ref/>` → `<kb/>`/`<web/>` expansion, citation stream expander |
|
||||
| `model_output.go` | compact source-centric renderings of tool results |
|
||||
| `resources.go` | durable-resource handles (`res://NNNN`) |
|
||||
| `stream.go` | `streamHold` suffix-hold primitive and every streaming decoder |
|
||||
| `tool_policy.go` | the single policy layer: per-tool key contracts + `sourceKeySpaces` dispatch |
|
||||
| `mcp.go` | MCP bridge routing handles (`msN`/`mtN`), definition projection and envelope codec |
|
||||
| `mcp_sources.go` | bounded citation sidecar for HTTP(S) links in successful MCP results |
|
||||
| `handles.go` | exported `HandleTable` for invocation-local spaces (`iN`, `ref-N`, `c000`) |
|
||||
| `leaks.go` | `LeakedIdentifiers` report of raw UUIDs that survive `EncodeMessages`, logged at every model-call site |
|
||||
|
||||
## Identity rules
|
||||
|
||||
- Durable application identities: UUIDs, Wiki slugs, URLs, and
|
||||
`resource://...` references.
|
||||
- Request-local model handles: `chunk://N`, `doc://N`, `kb://N`, `url://N`,
|
||||
`msN`, `mtN`, and `res://NNNN`. The legacy bare `cN`/`dN`/`bN`/`wN` form is
|
||||
still accepted, but only as the whole value of a declared ID field.
|
||||
- Durable text forms of source handles: `academy://kb/<id>`,
|
||||
`academy://doc/<id>`, `academy://chunk/<id>`; a web page becomes its URL.
|
||||
- Tool-private request handles: `iN` for Wiki issues.
|
||||
- Ingest-call handles: `cNNN` and `ref-N`, allocated with `HandleTable`.
|
||||
- Temporary handles are decoded before tool execution, persistence, or UI
|
||||
delivery. They are never accepted as durable authorization or routing data.
|
||||
|
||||
## Request lifecycle
|
||||
|
||||
1. Create one `Registry` for the complete request or Agent execution.
|
||||
2. Register structured source identities as they enter the context.
|
||||
For Agent tools, use `EncodeTools` to project MCP routing enums and source summaries.
|
||||
3. Call `EncodeMessages` immediately before the model call.
|
||||
4. Decode tool calls through `DecodeToolCalls` before parsing or execution.
|
||||
5. Decode complete responses with `DecodeResponse`, or streaming text with one
|
||||
`StreamDecoder` per response channel.
|
||||
|
||||
Unknown handle-shaped values in declared tool fields are rejected before tool
|
||||
execution. The same per-tool policy is applied when historical assistant tool
|
||||
calls and tool results are replayed, so handles neither disappear nor drift to
|
||||
new numbers across Agent rounds.
|
||||
|
||||
The registry owns codec ordering. Resource references are encoded before
|
||||
source IDs so a Wiki slug such as `summary/<knowledge-id>` cannot be corrupted
|
||||
into `summary/doc://1`.
|
||||
|
||||
Source addressability is separate from citation eligibility. Use
|
||||
`RegisterContextChunk` for bound-KB directory entries. Replayed citations,
|
||||
legacy tool history, and tool arguments also register navigation handles only.
|
||||
`ModelToolResultForTool` and explicitly supplied retrieval results authorize
|
||||
citations for the current execution; rereading a historical source promotes the
|
||||
same handle without renumbering it. Both complete and streaming decoders drop
|
||||
references that have not been backed by current evidence.
|
||||
|
||||
## Observability
|
||||
|
||||
Every model-call site runs `LeakedIdentifiers` on the encoded messages and
|
||||
logs a warning naming the role or tool whose text still carries a raw UUID.
|
||||
A *registered* leak means the codec missed a rewrite site; an *unregistered*
|
||||
leak means a producer emitted an identifier that never entered the registry.
|
||||
Text-level compaction (`CompactKnownText`) stays in place as defense in depth
|
||||
until those producers are fixed and the report stays quiet.
|
||||
|
||||
Langfuse generation observations contain the exact encoded payload sent to and
|
||||
returned by the model. Agent tool spans contain both `model_arguments` (the
|
||||
model-emitted handles) and `resolved_arguments` (the durable values actually
|
||||
executed), plus `argument_resolution` and any unresolved handles. Sensitive
|
||||
tools report only argument keys and resolution counts.
|
||||
|
||||
Langfuse is an observer of this boundary; it must not implement another handle
|
||||
mapping.
|
||||
|
||||
## Built-in tool policies
|
||||
|
||||
Canonical ID-bearing arguments for knowledge, graph, data, web, and Wiki tools
|
||||
are decoded centrally through a tool-name plus JSON-field allowlist. The
|
||||
`sourceKeySpaces` table is the single source of truth for which keys are
|
||||
ID-bearing and which handle space they register into; per-tool `sourceIDKeys`
|
||||
contracts gate which of those keys each tool may use.
|
||||
`database_query.sql` has an explicit policy: handles anywhere in the SQL text
|
||||
decode to bare durable IDs so the model can filter the real
|
||||
`knowledges`/`chunks` tables. `data_analysis.sql` carries no handles: the
|
||||
selected document is always exposed as the fixed table `dataset`, so only
|
||||
`knowledge_id` is decoded. Wiki issue IDs use the same lifecycle via an `iN`
|
||||
handle space.
|
||||
|
||||
## Handles in free text
|
||||
|
||||
Models copy handles into prose they write: automation instructions, tasks
|
||||
delegated to other agents, Markdown links, reasoning and final answers. Because
|
||||
the scheme-shaped syntax cannot collide with ordinary words, the registry
|
||||
rewrites handles in every string, not just declared fields:
|
||||
|
||||
- Tool arguments (built-in and MCP): declared ID fields receive bare durable
|
||||
IDs, SQL fields receive bare IDs, and every other string receives the durable
|
||||
text form (`academy://kb/<id>`, `academy://doc/<id>`, `academy://chunk/<id>`,
|
||||
or the page URL). An unknown handle anywhere in the arguments fails closed.
|
||||
- Model output (complete and streaming, content and reasoning): `<ref/>`
|
||||
citations expand as before; bare `kb://N`/`doc://N` become `academy://` URIs,
|
||||
`url://N` becomes the URL, and `chunk://N` becomes a `<kb/>` citation when it
|
||||
is current evidence, otherwise its document URI. Unknown handles are dropped.
|
||||
- Input: `academy://` URIs in any message, reasoning or replayed tool call are
|
||||
registered as navigation-only handles and shown to the model as handles, so
|
||||
a saved instruction round-trips across requests and agents.
|
||||
|
||||
Handles and URIs are never authorization: every tool still authorizes the
|
||||
durable ID it receives.
|
||||
|
||||
Dynamic MCP tools do not get per-field ID contracts. Their schemas and
|
||||
identity semantics are controlled by the MCP server, so the application does
|
||||
not guess that an arbitrary `id`, `knowledge_id`, or `url` field is durable;
|
||||
values that are not scheme-shaped handles pass through untouched. Handles the
|
||||
model copied into MCP arguments get the free-text rewrite above, and durable
|
||||
resource handles still use the normal `res://NNNN` codec. A future MCP ID mapping must be an
|
||||
explicit server/tool annotation and should plug into this registry rather than
|
||||
create a parallel mapper.
|
||||
|
||||
Successful MCP execution results additionally receive an
|
||||
`external_source_candidates` sidecar with up to 50 distinct observed HTTP(S)
|
||||
links mapped to `url://N`. The external payload is not rewritten, discovery schemas
|
||||
are not scanned, and article IDs are never used to guess URLs. A candidate link
|
||||
does not establish that its page was read: the model must select the link whose
|
||||
associated result supports the claim. When no handle is supplied, the citation
|
||||
protocol permits an exact supplied source URL as a Markdown link, never a
|
||||
borrowed knowledge-base citation.
|
||||
|
||||
The application-owned MCP bridge is an explicit exception for routing fields:
|
||||
`discover_mcp_tools.server_id` uses `msN`, and `call_mcp_tool.tool_ref` uses
|
||||
`mtN`. Tool definition enums, service summaries, discovery results and replayed
|
||||
calls share the same request registry. Only directory envelope fields are
|
||||
registered; `input_schema` and external execution results remain opaque, and
|
||||
`call_mcp_tool.arguments` only gets the free-text handle rewrite. Arguments are restored before authorization, validation,
|
||||
execution, persistence and UI events. Unknown routing handles fail closed.
|
||||
|
||||
For model-emitted `call_mcp_tool` calls, one extra JSON-string encoding of the
|
||||
`arguments` envelope is accepted only when it contains a complete JSON object
|
||||
(including `{}`). Normalization runs before resource-handle decoding; original
|
||||
model arguments are retained for tracing. Nested business strings are unchanged,
|
||||
and malformed JSON, arrays, `null`, and further encoding layers remain invalid.
|
||||
The canonical object still passes the existing routing, schema and approval checks.
|
||||
|
||||
## Wiki routing
|
||||
|
||||
`WikiRouteResolver` is intentionally separate. It stores server-side
|
||||
slug-to-knowledge-base provenance gathered during Wiki search/read operations,
|
||||
and can only return knowledge bases already present in the Agent's authorized
|
||||
Wiki scope. It is routing state, not a model handle table. Reads scan every
|
||||
legal Wiki KB so cached provenance cannot hide a duplicate slug; mutations
|
||||
require one unique owner. New pages use link provenance, a single Wiki scope,
|
||||
or a single source-document owner and reject ambiguous routing instead of
|
||||
asking the model for a durable KB ID.
|
||||
|
||||
Document/tag-constrained Wiki and graph requests are filtered by the same
|
||||
server-owned `SearchTargets` provenance. Uncited/global Wiki pages and graph
|
||||
results outside that subset fail closed; only an explicit whole-KB target
|
||||
authorizes whole-KB content.
|
||||
@@ -0,0 +1,322 @@
|
||||
// citations.go owns the public-citation surface of the model context: the
|
||||
// system protocol prompt, expansion of private <ref/> handles into canonical
|
||||
// <kb/> / <web/> tags, re-compaction of canonical tags replayed from history,
|
||||
// and the stream expander that keeps partial tags off the wire.
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const sourceHandleProtocolPrompt = `
|
||||
|
||||
## Source handling protocol (system-owned)
|
||||
Retrieved content uses request-local source handles: chunk://N identifies a knowledge chunk, url://N a web page,
|
||||
doc://N a document, and kb://N a knowledge base.
|
||||
- Copy handles exactly, in this form, wherever you refer to the source: tool arguments, instructions or prompts
|
||||
you write for other agents or automations, Markdown links, and your answer. The system replaces them with the
|
||||
real URL or a stable reference after generation, so a handle in saved text still points to the same source
|
||||
later.
|
||||
- Never invent a handle or change its number, and never write raw chunk IDs, knowledge IDs, or knowledge-base IDs.
|
||||
This does not change separate instructions to preserve retrieved Markdown image URLs.`
|
||||
|
||||
const citationEnabledProtocolPrompt = `
|
||||
- Source citations are enabled for this answer. Cite a knowledge chunk with exactly <ref id="chunk://N"/> and a
|
||||
web page with exactly <ref id="url://N"/>.
|
||||
- Cite only chunk://N and url://N handles backed by tool results for the current task, and only when that source
|
||||
supports the adjacent claim. Never cite doc://N or kb://N.
|
||||
- Each chunk://N covers only its own supplied text or image evidence, not every chunk of the same document.
|
||||
For a direct quotation, verify that the quoted words occur in the cited chunk. Use the later chunk's handle
|
||||
when the words occur there; never reuse a document's first handle for unrelated passages.
|
||||
- OCR watermarks, timestamps and image captions are observations of an image. Do not turn a watermark slogan
|
||||
into a verified service commitment or a caption into a factual document statement without supporting text.
|
||||
- Handles in historical answers, tool arguments, or the bound knowledge-base directory are for navigation, not current
|
||||
evidence. Retrieve the relevant source before citing it.
|
||||
- MCP results are external sources. Use the url://N handle for the matching URL in the system-provided
|
||||
external_source_candidates list; never substitute a knowledge-base chunk handle for MCP content. Candidate URLs
|
||||
are links observed in the result, not proof that every linked page was read.
|
||||
- If a source has no citation handle, use its exact supplied HTTP(S) URL as a Markdown link when available.
|
||||
If neither is available, omit the citation; never invent or borrow a source.
|
||||
- Never output <kb> or <web> tags yourself; the system expands valid <ref/> tags after generation.
|
||||
- Keep each <ref/> inline on the same line as the claim it supports. Do not group citations ` +
|
||||
`at the end. For a requested exact output format, use citations only where the format ` +
|
||||
`permits them; do not break a required schema to add citations.
|
||||
- These rules supersede earlier, saved, or custom prompt instructions about citation syntax.`
|
||||
|
||||
const citationDisabledProtocolPrompt = `
|
||||
- Source citations are disabled for this answer. Do not add <ref>, <kb>, <web>, or source ` +
|
||||
`attribution links to the answer. This does not prohibit a URL explicitly requested by the ` +
|
||||
`user, Wiki navigation links, downloadable deliverables, or relevant image URLs.
|
||||
- These rules supersede earlier, saved, or custom prompt instructions that require source citations.`
|
||||
|
||||
// ProtocolPrompt returns the internal, non-user-editable source protocol for a
|
||||
// model call. Citation formatting stays out of custom and template prompts.
|
||||
func sourceProtocolPrompt(citationsEnabled bool) string {
|
||||
if citationsEnabled {
|
||||
return sourceHandleProtocolPrompt + citationEnabledProtocolPrompt
|
||||
}
|
||||
return sourceHandleProtocolPrompt + citationDisabledProtocolPrompt
|
||||
}
|
||||
|
||||
// ProtocolPrompt returns the source protocol configured for this registry.
|
||||
// Request lifecycle code should normally call this through Registry.
|
||||
func (r *sourceRegistry) ProtocolPrompt() string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
return sourceProtocolPrompt(r.citationsEnabled)
|
||||
}
|
||||
|
||||
var (
|
||||
publicKBTagRE = regexp.MustCompile(`(?is)<kb\b[^>]*>`)
|
||||
publicWebTagRE = regexp.MustCompile(`(?is)<web\b[^>]*>`)
|
||||
docAttrRE = regexp.MustCompile(`(?i)\bdoc\s*=\s*"([^"]*)"`)
|
||||
chunkAttrRE = regexp.MustCompile(`(?i)\bchunk_id\s*=\s*"([^"]+)"`)
|
||||
publicKBAttrRE = regexp.MustCompile(`(?i)\bkb_id\s*=\s*"([^"]*)"`)
|
||||
urlAttrRE = regexp.MustCompile(`(?i)\burl\s*=\s*"([^"]+)"`)
|
||||
titleAttrRE = regexp.MustCompile(`(?i)\btitle\s*=\s*"([^"]*)"`)
|
||||
legacyChunkRE = regexp.MustCompile(`(?is)<(?:chunk|faq)\b[^>]*>`)
|
||||
faqAttrRE = regexp.MustCompile(`(?i)\bfaq_id\s*=\s*"([^"]+)"`)
|
||||
knowledgeTitleAttrRE = regexp.MustCompile(`(?i)\bknowledge_title\s*=\s*"([^"]*)"`)
|
||||
)
|
||||
|
||||
func (r *sourceRegistry) registerLegacyToolReferences(text string, evidence bool) {
|
||||
if r == nil || text == "" {
|
||||
return
|
||||
}
|
||||
r.registerLabeledReferences(text)
|
||||
for _, tag := range legacyChunkRE.FindAllString(text, -1) {
|
||||
chunkID := firstNonEmpty(publicAttr(chunkAttrRE, tag), publicAttr(faqAttrRE, tag))
|
||||
if chunkID == "" {
|
||||
continue
|
||||
}
|
||||
r.registerChunk(ChunkReference{
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: publicAttr(documentAttrRE, tag),
|
||||
KnowledgeBaseID: firstNonEmpty(publicAttr(kbAttrRE, tag), publicAttr(publicKBAttrRE, tag)),
|
||||
DocumentTitle: firstNonEmpty(publicAttr(knowledgeTitleAttrRE, tag), publicAttr(docAttrRE, tag)),
|
||||
}, evidence)
|
||||
}
|
||||
}
|
||||
|
||||
// CompactPublicCitations folds canonical citations into the private protocol.
|
||||
// Historical citations register navigation handles only; citations returned by
|
||||
// a successful current source tool can also authorize evidence.
|
||||
func (r *sourceRegistry) CompactPublicCitations(text string, evidence bool) string {
|
||||
if r == nil || text == "" {
|
||||
return text
|
||||
}
|
||||
text = publicKBTagRE.ReplaceAllStringFunc(text, func(tag string) string {
|
||||
chunkID := publicAttr(chunkAttrRE, tag)
|
||||
if chunkID == "" {
|
||||
return tag
|
||||
}
|
||||
handle := r.registerChunk(ChunkReference{
|
||||
ChunkID: chunkID,
|
||||
KnowledgeBaseID: publicAttr(publicKBAttrRE, tag),
|
||||
DocumentTitle: publicAttr(docAttrRE, tag),
|
||||
}, evidence)
|
||||
return `<ref id="` + handle + `"/>`
|
||||
})
|
||||
return publicWebTagRE.ReplaceAllStringFunc(text, func(tag string) string {
|
||||
rawURL := publicAttr(urlAttrRE, tag)
|
||||
if rawURL == "" {
|
||||
return tag
|
||||
}
|
||||
handle := r.registerWeb(rawURL, publicAttr(titleAttrRE, tag), evidence)
|
||||
return `<ref id="` + handle + `"/>`
|
||||
})
|
||||
}
|
||||
|
||||
func publicAttr(expression *regexp.Regexp, tag string) string {
|
||||
match := expression.FindStringSubmatch(tag)
|
||||
if len(match) != 2 {
|
||||
return ""
|
||||
}
|
||||
return html.UnescapeString(match[1])
|
||||
}
|
||||
|
||||
var (
|
||||
refTagRE = regexp.MustCompile(`(?i)<ref\s+id\s*=\s*"([^"]+)"\s*/?>`)
|
||||
refCandidateRE = regexp.MustCompile(`(?is)<ref(?:\s|$)[^>]*(?:>|$)`)
|
||||
modelKBTagRE = regexp.MustCompile(`(?is)<kb(?:\s|$)[^>]*(?:>|$)`)
|
||||
modelWebTagRE = regexp.MustCompile(`(?is)<web(?:\s|$)[^>]*(?:>|$)`)
|
||||
)
|
||||
|
||||
var (
|
||||
documentAttrRE = regexp.MustCompile(`(?i)\bknowledge_id\s*=\s*"([^"]+)"`)
|
||||
documentElementRE = regexp.MustCompile(`(?is)<knowledge_id>\s*([^<]+?)\s*</knowledge_id>`)
|
||||
kbAttrRE = regexp.MustCompile(`(?i)\b(?:knowledge_base_id|kb_id)\s*=\s*"([^"]+)"`)
|
||||
kbElementRE = regexp.MustCompile(`(?is)<(?:knowledge_base_id|kb_id)>\s*([^<]+?)\s*</(?:knowledge_base_id|kb_id)>`)
|
||||
)
|
||||
|
||||
// registerLabeledReferences covers metadata-oriented tools that do not have a
|
||||
// dedicated compact renderer. Only explicit ID labels are recognized; UUID-like
|
||||
// text in retrieved content is never guessed to be a source identifier.
|
||||
func (r *sourceRegistry) registerLabeledReferences(text string) {
|
||||
if r == nil || text == "" {
|
||||
return
|
||||
}
|
||||
for _, expression := range []*regexp.Regexp{documentAttrRE, documentElementRE} {
|
||||
for _, match := range expression.FindAllStringSubmatch(text, -1) {
|
||||
if len(match) == 2 {
|
||||
r.RegisterDocument(strings.TrimSpace(match[1]))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, expression := range []*regexp.Regexp{kbAttrRE, kbElementRE} {
|
||||
for _, match := range expression.FindAllStringSubmatch(text, -1) {
|
||||
if len(match) == 2 {
|
||||
r.RegisterKnowledgeBase(strings.TrimSpace(match[1]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ExpandText converts the private model protocol into the existing public
|
||||
// <kb/> / <web/> contract. Unknown handles fail closed and disappear.
|
||||
func (r *sourceRegistry) ExpandText(text string) string {
|
||||
if r == nil || text == "" {
|
||||
return text
|
||||
}
|
||||
// Public citation tags are output-only. Drop any instance written directly
|
||||
// by the model, then create canonical tags solely from registered handles.
|
||||
text = modelKBTagRE.ReplaceAllString(text, "")
|
||||
text = modelWebTagRE.ReplaceAllString(text, "")
|
||||
if !r.citationsEnabled {
|
||||
return refCandidateRE.ReplaceAllString(text, "")
|
||||
}
|
||||
return refCandidateRE.ReplaceAllStringFunc(text, func(tag string) string {
|
||||
match := refTagRE.FindStringSubmatch(tag)
|
||||
if len(match) != 2 {
|
||||
return ""
|
||||
}
|
||||
return r.citationTag(match[1])
|
||||
})
|
||||
}
|
||||
|
||||
// citationTag renders the public citation for a handle backed by current
|
||||
// evidence, or "" when the handle may not be cited.
|
||||
func (r *sourceRegistry) citationTag(handle string) string {
|
||||
if r == nil || !r.citationsEnabled {
|
||||
return ""
|
||||
}
|
||||
handle = canonicalSourceHandle(handle)
|
||||
if _, citable := r.citable.Load(handle); !citable {
|
||||
return ""
|
||||
}
|
||||
if chunkID, chunkRef, ok := r.chunks.resolve(handle); ok {
|
||||
attrs := fmt.Sprintf(`doc="%s" chunk_id="%s"`, escapeAttr(chunkRef.DocumentTitle), escapeAttr(chunkID))
|
||||
if chunkRef.KnowledgeBaseID != "" {
|
||||
attrs += fmt.Sprintf(` kb_id="%s"`, escapeAttr(chunkRef.KnowledgeBaseID))
|
||||
}
|
||||
return "<kb " + attrs + " />"
|
||||
}
|
||||
if rawURL, web, ok := r.webs.resolve(handle); ok {
|
||||
return fmt.Sprintf(`<web url="%s" title="%s" />`, escapeAttr(rawURL), escapeAttr(web.title))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func escapeAttr(value string) string { return html.EscapeString(value) }
|
||||
|
||||
// citationStreamExpander prevents partial private <ref/> tags from reaching SSE while
|
||||
// preserving normal streaming for all other content.
|
||||
type citationStreamExpander struct {
|
||||
registry *sourceRegistry
|
||||
pending string
|
||||
}
|
||||
|
||||
func newCitationStreamExpander(registry *sourceRegistry) *citationStreamExpander {
|
||||
return &citationStreamExpander{registry: registry}
|
||||
}
|
||||
|
||||
func (d *citationStreamExpander) Feed(chunk string) string {
|
||||
if d == nil || d.registry == nil {
|
||||
return chunk
|
||||
}
|
||||
data := d.pending + chunk
|
||||
d.pending = ""
|
||||
var out strings.Builder
|
||||
for data != "" {
|
||||
idx := strings.Index(data, "<")
|
||||
if idx < 0 {
|
||||
out.WriteString(data)
|
||||
break
|
||||
}
|
||||
out.WriteString(data[:idx])
|
||||
data = data[idx:]
|
||||
lower := strings.ToLower(data)
|
||||
if isSourceTagPending(lower) && !strings.Contains(data, ">") {
|
||||
d.pending = data
|
||||
break
|
||||
}
|
||||
if isRefTagStart(lower) {
|
||||
end := strings.IndexByte(data, '>')
|
||||
if end < 0 {
|
||||
d.pending = data
|
||||
break
|
||||
}
|
||||
tag := data[:end+1]
|
||||
if refTagRE.MatchString(tag) {
|
||||
out.WriteString(d.registry.ExpandText(tag))
|
||||
}
|
||||
data = data[end+1:]
|
||||
continue
|
||||
}
|
||||
if isNamedTagStart(lower, "kb") || isNamedTagStart(lower, "web") {
|
||||
end := strings.IndexByte(data, '>')
|
||||
if end < 0 {
|
||||
d.pending = data
|
||||
break
|
||||
}
|
||||
data = data[end+1:]
|
||||
continue
|
||||
}
|
||||
out.WriteByte('<')
|
||||
data = data[1:]
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func isRefTagStart(value string) bool {
|
||||
return isNamedTagStart(value, "ref")
|
||||
}
|
||||
|
||||
func isNamedTagStart(value, name string) bool {
|
||||
prefix := "<" + name
|
||||
if !strings.HasPrefix(value, prefix) {
|
||||
return false
|
||||
}
|
||||
if len(value) == len(prefix) {
|
||||
return true
|
||||
}
|
||||
next := value[len(prefix)]
|
||||
return next == ' ' || next == '\t' || next == '\r' || next == '\n' || next == '>'
|
||||
}
|
||||
|
||||
func isSourceTagPending(value string) bool {
|
||||
for _, name := range []string{"ref", "kb", "web"} {
|
||||
prefix := "<" + name
|
||||
if (len(value) <= len(prefix) && strings.HasPrefix(prefix, value)) || isNamedTagStart(value, name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (d *citationStreamExpander) Flush() string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
pending := d.pending
|
||||
d.pending = ""
|
||||
lower := strings.ToLower(pending)
|
||||
if isSourceTagPending(lower) {
|
||||
return ""
|
||||
}
|
||||
return d.registry.ExpandText(pending)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// graphQueryResultData builds the Data of a graph query answer whose relation
|
||||
// list stopped at the tool's cap, as the tool reports it.
|
||||
func graphQueryResultData(relations []map[string]interface{}, totals map[string]interface{}) map[string]interface{} {
|
||||
data := map[string]interface{}{
|
||||
"display_type": "graph_query_results",
|
||||
"results": []map[string]interface{}{{
|
||||
"chunk_id": "graph-chunk-real",
|
||||
"chunk_index": 4,
|
||||
"knowledge_id": "graph-doc-real",
|
||||
"knowledge_base_id": "graph-kb-real",
|
||||
"knowledge_title": "Graph Source",
|
||||
"content": "A relates to B.",
|
||||
}},
|
||||
"relations": relations,
|
||||
}
|
||||
for key, value := range totals {
|
||||
data[key] = value
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// The model reads a view rebuilt from Data, never the tool's Output, so a
|
||||
// capped relation list has to carry its marker into that view: without it the
|
||||
// model treats the returned subgraph as the entity's whole neighbourhood.
|
||||
func TestModelOutputMarksCappedGraphRelations(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
relations := make([]map[string]interface{}, 0, 30)
|
||||
for i := 0; i < 30; i++ {
|
||||
relations = append(relations, map[string]interface{}{
|
||||
"source": "Docker", "type": "depends_on", "target": fmt.Sprintf("Service%02d", i),
|
||||
})
|
||||
}
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Output: "=== Knowledge Graph Query ===\n\n✓ Found 30 of 42 relations and 1 relevant chunks (deduplicated)\n",
|
||||
Data: graphQueryResultData(relations, map[string]interface{}{
|
||||
"relations_total": 42,
|
||||
"relations_omitted": 12,
|
||||
"graph_chunks_total": 14,
|
||||
"graph_chunks_omitted": 4,
|
||||
"query_terms_total": 13,
|
||||
"query_terms_omitted": 5,
|
||||
}),
|
||||
})
|
||||
t.Logf("model view:\n%s", output)
|
||||
|
||||
require.Contains(t, output, `<graph_truncated relations_shown="30" relations_total="42" `+
|
||||
`chunks_fetched="10" chunks_total="14" terms_shown="8" terms_total="13">`)
|
||||
require.Contains(t, output, "not the complete picture")
|
||||
require.Contains(t, output, `<relation source="Docker" type="depends_on" target="Service00" />`)
|
||||
}
|
||||
|
||||
// An answer under every cap must stay clean: the marker only means a subset
|
||||
// when it appears.
|
||||
func TestModelOutputOmitsGraphTruncationMarkerWhenComplete(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: graphQueryResultData([]map[string]interface{}{
|
||||
{"source": "Kubernetes", "type": "orchestrates", "target": "Docker"},
|
||||
}, nil),
|
||||
})
|
||||
|
||||
require.Contains(t, output, `<relation source="Kubernetes" type="orchestrates" target="Docker" />`)
|
||||
require.NotContains(t, output, "graph_truncated")
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// handleTable is the single bidirectional primitive behind every model-handle
|
||||
// space: chunk://N, doc://N, kb://N and url://N source handles, iN issue handles, res://NNNN resource
|
||||
// handles, and the ref-N / c000 ingest handles exposed through HandleTable.
|
||||
//
|
||||
// It maps a durable dedup key to a sequentially allocated handle and stores
|
||||
// the durable value plus optional metadata under one lock, so a resolvable
|
||||
// handle can never be observed without its metadata. The key and the value
|
||||
// may differ (web references dedup on a canonicalized URL but decode back to
|
||||
// the original raw URL). Entries are never removed, which makes the counter
|
||||
// equivalent to the historical len(map)+1 allocation and keeps handle
|
||||
// numbering stable for the lifetime of the table.
|
||||
type handleTable[M any] struct {
|
||||
mu sync.RWMutex
|
||||
prefix string
|
||||
width int
|
||||
next int
|
||||
handleByKey map[string]string
|
||||
entryByHandle map[string]*handleEntry[M]
|
||||
}
|
||||
|
||||
type handleEntry[M any] struct {
|
||||
value string // durable value a handle decodes back to
|
||||
meta M
|
||||
wordBounded *regexp.Regexp
|
||||
}
|
||||
|
||||
// handlePair is a snapshot row for text codecs (compaction/decoding).
|
||||
type handlePair struct {
|
||||
value string
|
||||
handle string
|
||||
// wordBounded matches the handle only on word boundaries. It is compiled
|
||||
// once at registration because DecodeKnownText runs on every streamed
|
||||
// chunk, where recompiling per handle per chunk dominated the cost.
|
||||
wordBounded *regexp.Regexp
|
||||
}
|
||||
|
||||
// newHandleTable creates a handle space such as c1 (prefix="c", width=0,
|
||||
// start=1), c000 (prefix="c", width=3, start=0) or res://0001
|
||||
// (prefix="res://", width=4, start=1).
|
||||
func newHandleTable[M any](prefix string, width, start int) *handleTable[M] {
|
||||
return &handleTable[M]{
|
||||
prefix: prefix,
|
||||
width: width,
|
||||
next: start,
|
||||
handleByKey: make(map[string]string),
|
||||
entryByHandle: make(map[string]*handleEntry[M]),
|
||||
}
|
||||
}
|
||||
|
||||
// register returns the handle assigned to key, allocating the next one on
|
||||
// first use. value is what the handle decodes back to; merge, when non-nil,
|
||||
// folds the metadata of a repeated registration into the existing entry.
|
||||
func (t *handleTable[M]) register(key, value string, meta M, merge func(dst *M, src M)) string {
|
||||
if t == nil || key == "" {
|
||||
return ""
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if handle, ok := t.handleByKey[key]; ok {
|
||||
if merge != nil {
|
||||
merge(&t.entryByHandle[handle].meta, meta)
|
||||
}
|
||||
return handle
|
||||
}
|
||||
number := fmt.Sprintf("%d", t.next)
|
||||
if t.width > 0 {
|
||||
number = fmt.Sprintf("%0*d", t.width, t.next)
|
||||
}
|
||||
t.next++
|
||||
handle := t.prefix + number
|
||||
t.handleByKey[key] = handle
|
||||
t.entryByHandle[handle] = &handleEntry[M]{
|
||||
value: value,
|
||||
meta: meta,
|
||||
wordBounded: regexp.MustCompile(`\b` + regexp.QuoteMeta(handle) + `\b`),
|
||||
}
|
||||
return handle
|
||||
}
|
||||
|
||||
// handleForKey returns an existing handle without allocating one.
|
||||
func (t *handleTable[M]) handleForKey(key string) (string, bool) {
|
||||
if t == nil {
|
||||
return "", false
|
||||
}
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
handle, ok := t.handleByKey[key]
|
||||
return handle, ok
|
||||
}
|
||||
|
||||
// resolve returns the durable value and metadata snapshot for a known handle.
|
||||
func (t *handleTable[M]) resolve(handle string) (string, M, bool) {
|
||||
var zero M
|
||||
if t == nil {
|
||||
return "", zero, false
|
||||
}
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
entry, ok := t.entryByHandle[handle]
|
||||
if !ok {
|
||||
return "", zero, false
|
||||
}
|
||||
return entry.value, entry.meta, true
|
||||
}
|
||||
|
||||
// has reports whether handle exists in this table.
|
||||
func (t *handleTable[M]) has(handle string) bool {
|
||||
if t == nil {
|
||||
return false
|
||||
}
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
_, ok := t.entryByHandle[handle]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t *handleTable[M]) size() int {
|
||||
if t == nil {
|
||||
return 0
|
||||
}
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
return len(t.entryByHandle)
|
||||
}
|
||||
|
||||
// pairs returns a value/handle snapshot for text codecs. Callers own ordering
|
||||
// (e.g. longest-value-first for substring compaction).
|
||||
func (t *handleTable[M]) pairs() []handlePair {
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
out := make([]handlePair, 0, len(t.entryByHandle))
|
||||
for handle, entry := range t.entryByHandle {
|
||||
out = append(out, handlePair{
|
||||
value: entry.value,
|
||||
handle: handle,
|
||||
wordBounded: entry.wordBounded,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// HandleTable is a typed, invocation-local bidirectional mapping used when a
|
||||
// prompt needs compact handles for durable values (wiki issue iN handles,
|
||||
// ingest ref-N slug handles, c000 citation-batch handles). Handles must never
|
||||
// be persisted; Resolve converts model output back to the durable value first.
|
||||
// It is the exported word-boundary-aware wrapper over handleTable.
|
||||
type HandleTable struct {
|
||||
table *handleTable[struct{}]
|
||||
}
|
||||
|
||||
// NewHandleTable creates a handle space such as c000 (prefix=c, width=3,
|
||||
// start=0) or ref-1 (prefix=ref-, width=0, start=1).
|
||||
func NewHandleTable(prefix string, width, start int) *HandleTable {
|
||||
return &HandleTable{table: newHandleTable[struct{}](prefix, width, start)}
|
||||
}
|
||||
|
||||
// Register returns the stable handle assigned to value in this table.
|
||||
func (t *HandleTable) Register(value string) string {
|
||||
if t == nil {
|
||||
return ""
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
return t.table.register(value, value, struct{}{}, nil)
|
||||
}
|
||||
|
||||
// Handle returns an already registered handle without creating one.
|
||||
func (t *HandleTable) Handle(value string) (string, bool) {
|
||||
if t == nil {
|
||||
return "", false
|
||||
}
|
||||
return t.table.handleForKey(value)
|
||||
}
|
||||
|
||||
// Resolve converts a known model handle back to its durable value.
|
||||
func (t *HandleTable) Resolve(handle string) (string, bool) {
|
||||
if t == nil {
|
||||
return "", false
|
||||
}
|
||||
value, _, ok := t.table.resolve(strings.TrimSpace(handle))
|
||||
return value, ok
|
||||
}
|
||||
|
||||
func (t *HandleTable) Empty() bool {
|
||||
return t == nil || t.table.size() == 0
|
||||
}
|
||||
|
||||
func (t *HandleTable) Len() int {
|
||||
if t == nil {
|
||||
return 0
|
||||
}
|
||||
return t.table.size()
|
||||
}
|
||||
|
||||
// EncodeKnownText replaces already-registered durable values with their model
|
||||
// handles. Longer values are processed first to avoid substring shadowing.
|
||||
func (t *HandleTable) EncodeKnownText(value string) string {
|
||||
if t == nil || value == "" {
|
||||
return value
|
||||
}
|
||||
pairs := t.table.pairs()
|
||||
sort.SliceStable(pairs, func(i, j int) bool { return len(pairs[i].value) > len(pairs[j].value) })
|
||||
for _, item := range pairs {
|
||||
value = strings.ReplaceAll(value, item.value, item.handle)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// DecodeKnownText restores registered handles in complete text. Unlike the
|
||||
// resource codec, replacement is word-boundary-aware so short handles such as
|
||||
// i1 cannot fire inside ordinary prose tokens.
|
||||
func (t *HandleTable) DecodeKnownText(value string) string {
|
||||
if t == nil || value == "" {
|
||||
return value
|
||||
}
|
||||
pairs := t.table.pairs()
|
||||
sort.SliceStable(pairs, func(i, j int) bool { return len(pairs[i].handle) > len(pairs[j].handle) })
|
||||
for _, item := range pairs {
|
||||
if item.wordBounded == nil {
|
||||
continue
|
||||
}
|
||||
// A durable value may legally contain '$'. ReplaceAllString would
|
||||
// interpret it as a regexp expansion, so use a literal callback.
|
||||
durable := item.value
|
||||
value = item.wordBounded.ReplaceAllStringFunc(value, func(string) string { return durable })
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// ImageSourcesNote binds images to handles already present in the final model
|
||||
// context. offset counts user images preceding the retrieved ones in this
|
||||
// message. Unknown sources stay explicitly unavailable, never fabricated.
|
||||
func (r *Registry) ImageSourcesNote(chunkIDs []string, offset int) string {
|
||||
if len(chunkIDs) == 0 {
|
||||
return ""
|
||||
}
|
||||
var note strings.Builder
|
||||
note.WriteString("\n\nRetrieved image sources (image numbers are 1-based within this message):")
|
||||
for i, id := range chunkIDs {
|
||||
if handle := r.ChunkHandle(id); handle != "" {
|
||||
fmt.Fprintf(¬e, "\nImage %d: chunk %s.", offset+i+1, handle)
|
||||
} else {
|
||||
fmt.Fprintf(¬e, "\nImage %d: source unavailable; do not invent a citation.", offset+i+1)
|
||||
}
|
||||
}
|
||||
return note.String()
|
||||
}
|
||||
|
||||
// ToolImageSourcesNote is rendered beside the actual images after tool result
|
||||
// rendering has registered its source handles. Stored results have no images
|
||||
// and must not claim to attach them on replay.
|
||||
func (r *Registry) ToolImageSourcesNote(result *types.ToolResult) string {
|
||||
if result == nil || len(result.Images) == 0 {
|
||||
return ""
|
||||
}
|
||||
ids := stringSliceValue(result.Data["context_images"])
|
||||
return r.ImageSourcesNote(ids[:min(len(ids), len(result.Images))], 0)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestImageSourcesUseOnlyKnownHandlesAndAccountForUserImages(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "known-source"})
|
||||
note := registry.ImageSourcesNote([]string{"known-source", "unverified-source"}, 2)
|
||||
require.Contains(t, note, "Image 3: chunk chunk://1.")
|
||||
require.Contains(t, note, "Image 4: source unavailable")
|
||||
require.NotContains(t, note, "unverified-source")
|
||||
require.NotContains(t, note, "known-source")
|
||||
require.Empty(t, registry.ChunkHandle("unverified-source"))
|
||||
stored := &types.ToolResult{Data: map[string]interface{}{"context_images": []string{"known-source"}}}
|
||||
require.Empty(t, registry.ToolImageSourcesNote(stored), "stored history has no image bytes")
|
||||
var missing *Registry
|
||||
require.Contains(t, missing.ImageSourcesNote([]string{"known-source"}, 0), "source unavailable")
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// leaks.go reports durable identifiers that survive encoding. The registry
|
||||
// compacts every identifier it knows about, but a raw UUID can still reach the
|
||||
// model through text it never registered: an error string, a slug, a tool
|
||||
// result of unknown shape. Each such occurrence is a place where the text
|
||||
// codec is doing work that the producer should have done. Reporting them at
|
||||
// the model-call boundary is how those producers are found and fixed, and it
|
||||
// is the precondition for eventually retiring text-level compaction.
|
||||
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
)
|
||||
|
||||
var uuidShapeRE = regexp.MustCompile(
|
||||
`(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b`,
|
||||
)
|
||||
|
||||
// IdentifierLeak is one message field that still carries UUID-shaped values
|
||||
// after EncodeMessages.
|
||||
type IdentifierLeak struct {
|
||||
MessageIndex int
|
||||
Role string
|
||||
// ToolName is the tool that produced a tool message or the tool an
|
||||
// assistant call targets; empty for plain content.
|
||||
ToolName string
|
||||
// Field names the message part: content, reasoning, multi_content, or
|
||||
// tool_call_arguments.
|
||||
Field string
|
||||
// Registered holds leaked values the registry knows a handle for: the
|
||||
// codec missed a rewrite site. Unregistered holds values that never
|
||||
// entered the registry: the producer emitted a raw identifier.
|
||||
Registered []string
|
||||
Unregistered []string
|
||||
}
|
||||
|
||||
// LeakedIdentifiers scans an encoded message list for UUID-shaped values.
|
||||
// User-authored messages are skipped: a user may legitimately paste an ID.
|
||||
// Everything else the application composed, so any UUID there is a leak.
|
||||
func (r *Registry) LeakedIdentifiers(messages []chat.Message) []IdentifierLeak {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
var leaks []IdentifierLeak
|
||||
for i := range messages {
|
||||
msg := &messages[i]
|
||||
if msg.Role == "user" {
|
||||
continue
|
||||
}
|
||||
leaks = r.appendLeak(leaks, i, msg.Role, msg.Name, "content", msg.Content)
|
||||
leaks = r.appendLeak(leaks, i, msg.Role, msg.Name, "reasoning", msg.ReasoningContent)
|
||||
for _, part := range msg.MultiContent {
|
||||
if part.Type == "text" {
|
||||
leaks = r.appendLeak(leaks, i, msg.Role, msg.Name, "multi_content", part.Text)
|
||||
}
|
||||
}
|
||||
for _, call := range msg.ToolCalls {
|
||||
leaks = r.appendLeak(
|
||||
leaks, i, msg.Role, call.Function.Name, "tool_call_arguments", call.Function.Arguments,
|
||||
)
|
||||
}
|
||||
}
|
||||
return leaks
|
||||
}
|
||||
|
||||
func (r *Registry) appendLeak(
|
||||
leaks []IdentifierLeak, index int, role, toolName, field, text string,
|
||||
) []IdentifierLeak {
|
||||
if text == "" {
|
||||
return leaks
|
||||
}
|
||||
matches := uuidShapeRE.FindAllString(text, -1)
|
||||
if len(matches) == 0 {
|
||||
return leaks
|
||||
}
|
||||
seen := make(map[string]struct{}, len(matches))
|
||||
leak := IdentifierLeak{MessageIndex: index, Role: role, ToolName: toolName, Field: field}
|
||||
for _, match := range matches {
|
||||
key := strings.ToLower(match)
|
||||
if _, dup := seen[key]; dup {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
if r.knowsDurable(match) {
|
||||
leak.Registered = append(leak.Registered, match)
|
||||
} else {
|
||||
leak.Unregistered = append(leak.Unregistered, match)
|
||||
}
|
||||
}
|
||||
sort.Strings(leak.Registered)
|
||||
sort.Strings(leak.Unregistered)
|
||||
return append(leaks, leak)
|
||||
}
|
||||
|
||||
// knowsDurable reports whether any handle space has registered the value.
|
||||
func (r *Registry) knowsDurable(value string) bool {
|
||||
if r.sources != nil && r.sources.handleForDurable(value) != "" {
|
||||
return true
|
||||
}
|
||||
if _, ok := r.issues.Handle(value); ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := r.mcpServers.Handle(value); ok {
|
||||
return true
|
||||
}
|
||||
_, ok := r.mcpTools.Handle(value)
|
||||
return ok
|
||||
}
|
||||
|
||||
// maxLeakSamples bounds how many identifiers one summary line quotes.
|
||||
const maxLeakSamples = 3
|
||||
|
||||
// SummarizeLeaks renders leaks as one log line per message field so the
|
||||
// producing tool or role can be identified without dumping the context.
|
||||
func SummarizeLeaks(leaks []IdentifierLeak) string {
|
||||
if len(leaks) == 0 {
|
||||
return ""
|
||||
}
|
||||
lines := make([]string, 0, len(leaks))
|
||||
for _, leak := range leaks {
|
||||
origin := leak.Role
|
||||
if leak.ToolName != "" {
|
||||
origin += "/" + leak.ToolName
|
||||
}
|
||||
lines = append(lines, fmt.Sprintf(
|
||||
"message[%d] %s %s: %d registered %s, %d unregistered %s",
|
||||
leak.MessageIndex, origin, leak.Field,
|
||||
len(leak.Registered), sampleIDs(leak.Registered),
|
||||
len(leak.Unregistered), sampleIDs(leak.Unregistered),
|
||||
))
|
||||
}
|
||||
return strings.Join(lines, "; ")
|
||||
}
|
||||
|
||||
func sampleIDs(ids []string) string {
|
||||
if len(ids) == 0 {
|
||||
return "[]"
|
||||
}
|
||||
if len(ids) > maxLeakSamples {
|
||||
return "[" + strings.Join(ids[:maxLeakSamples], " ") + " ...]"
|
||||
}
|
||||
return "[" + strings.Join(ids, " ") + "]"
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
leakDocID = "3f1c2a8e-0000-4000-8000-000000000001"
|
||||
leakChunkID = "3f1c2a8e-0000-4000-8000-000000000002"
|
||||
leakRawID = "3f1c2a8e-0000-4000-8000-0000000000ff"
|
||||
)
|
||||
|
||||
func TestLeakedIdentifiersIgnoresEncodedHandlesAndUserText(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: leakChunkID, KnowledgeID: leakDocID, KnowledgeBaseID: "kb-1"})
|
||||
messages := registry.EncodeMessages([]chat.Message{
|
||||
{Role: "system", Content: "directory: " + registry.ModelToolResult(searchResultTool(leakChunkID, leakDocID))},
|
||||
{Role: "user", Content: "look at " + leakRawID + " please"},
|
||||
{Role: "assistant", Content: `<kb doc="` + leakDocID + `" chunk_id="` + leakChunkID + `" kb_id="kb-1"/>`},
|
||||
})
|
||||
if leaks := registry.LeakedIdentifiers(messages); len(leaks) != 0 {
|
||||
t.Fatalf("encoded messages must not report leaks, got %s", SummarizeLeaks(leaks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeakedIdentifiersClassifiesRegisteredAndUnregistered(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument(leakDocID)
|
||||
messages := []chat.Message{
|
||||
{Role: "user", Content: leakRawID},
|
||||
{
|
||||
Role: "tool", Name: "shell_exec",
|
||||
Content: "wrote summary/" + leakRawID + " and " + strings.ToUpper(leakRawID),
|
||||
},
|
||||
{Role: "assistant", Content: "Document " + leakDocID + " is relevant.", ToolCalls: []chat.ToolCall{{
|
||||
Function: chat.FunctionCall{Name: "wiki_write_page", Arguments: `{"source_refs":["` + leakDocID + `|T"]}`},
|
||||
}}},
|
||||
{Role: "assistant", MultiContent: []chat.MessageContentPart{{Type: "text", Text: "see " + leakRawID}}},
|
||||
}
|
||||
leaks := registry.LeakedIdentifiers(messages)
|
||||
if len(leaks) != 4 {
|
||||
t.Fatalf("expected 4 leaking fields, got %d: %s", len(leaks), SummarizeLeaks(leaks))
|
||||
}
|
||||
tool := leaks[0]
|
||||
if tool.Role != "tool" || tool.ToolName != "shell_exec" || tool.Field != "content" {
|
||||
t.Fatalf("unexpected first leak origin: %+v", tool)
|
||||
}
|
||||
if len(tool.Registered) != 0 || len(tool.Unregistered) != 1 {
|
||||
t.Fatalf("case-insensitive duplicates must collapse to one unregistered ID: %+v", tool)
|
||||
}
|
||||
content := leaks[1]
|
||||
if content.Field != "content" || len(content.Registered) != 1 || content.Registered[0] != leakDocID {
|
||||
t.Fatalf("registered document in assistant prose must be reported as registered: %+v", content)
|
||||
}
|
||||
args := leaks[2]
|
||||
if args.Field != "tool_call_arguments" || args.ToolName != "wiki_write_page" || len(args.Registered) != 1 {
|
||||
t.Fatalf("tool call arguments must be scanned per call: %+v", args)
|
||||
}
|
||||
if leaks[3].Field != "multi_content" {
|
||||
t.Fatalf("multi-part text must be scanned: %+v", leaks[3])
|
||||
}
|
||||
|
||||
summary := SummarizeLeaks(leaks)
|
||||
for _, want := range []string{
|
||||
"message[1] tool/shell_exec content: 0 registered [], 1 unregistered [" + leakRawID + "]",
|
||||
"message[2] assistant content: 1 registered [" + leakDocID + "], 0 unregistered []",
|
||||
"message[2] assistant/wiki_write_page tool_call_arguments",
|
||||
} {
|
||||
if !strings.Contains(summary, want) {
|
||||
t.Fatalf("summary missing %q:\n%s", want, summary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeakedIdentifiersDoesNotMatchHandlesOrPartialUUIDs(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
messages := []chat.Message{
|
||||
{
|
||||
Role: "assistant",
|
||||
Content: "chunk://1 doc://2 kb://3 url://4 res://0001 i1 and k_3f1c2a8e_0000_4000_8000_000000000001",
|
||||
},
|
||||
{Role: "tool", Name: "x", Content: "3f1c2a8e-0000-4000-8000-00000000000"}, // one hex digit short
|
||||
}
|
||||
if leaks := registry.LeakedIdentifiers(messages); len(leaks) != 0 {
|
||||
t.Fatalf("handles and non-UUID tokens must not be reported: %s", SummarizeLeaks(leaks))
|
||||
}
|
||||
if SummarizeLeaks(nil) != "" {
|
||||
t.Fatal("empty leak list must summarize to an empty string")
|
||||
}
|
||||
if got := sampleIDs([]string{"a", "b", "c", "d"}); got != "[a b c ...]" {
|
||||
t.Fatalf("sample truncation = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func searchResultTool(chunkID, docID string) *types.ToolResult {
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "raw " + chunkID,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "search_results",
|
||||
"results": []map[string]interface{}{{
|
||||
"chunk_id": chunkID,
|
||||
"knowledge_id": docID,
|
||||
"knowledge_base_id": "kb-1",
|
||||
"knowledge_title": "Doc",
|
||||
"chunk_index": 1,
|
||||
"content": "body mentioning " + docID,
|
||||
}},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// normalizeMCPCallArguments tolerates one extra JSON encoding of the bridge's
|
||||
// arguments envelope. Run after preserving ModelArguments and before decoding
|
||||
// resource handles so audit/UI/execution all use the same canonical object.
|
||||
// This is not JSON repair: incomplete JSON, null, arrays and further string
|
||||
// layers remain invalid, and remote business fields are never coerced here.
|
||||
func normalizeMCPCallArguments(calls []types.LLMToolCall) {
|
||||
for i := range calls {
|
||||
if calls[i].Function.Name != "call_mcp_tool" {
|
||||
continue
|
||||
}
|
||||
var envelope map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(calls[i].Function.Arguments), &envelope) != nil {
|
||||
continue
|
||||
}
|
||||
var wrapped string
|
||||
if json.Unmarshal(envelope["arguments"], &wrapped) != nil {
|
||||
continue
|
||||
}
|
||||
var object map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(wrapped), &object) != nil || object == nil {
|
||||
continue
|
||||
}
|
||||
// Retain raw number literals and nested values instead of round-tripping
|
||||
// through float64 or recursively decoding business strings.
|
||||
envelope["arguments"] = json.RawMessage(wrapped)
|
||||
encoded, err := json.Marshal(envelope)
|
||||
if err == nil {
|
||||
calls[i].Function.Arguments = string(encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MCP routing identities belong to our bridge, not to the remote tool schema.
|
||||
// Rewrite only explicit envelope fields; never walk an external input_schema,
|
||||
// call_mcp_tool.arguments, or a dynamic MCP tool's arguments/results.
|
||||
func (r *Registry) mcpArgumentTable(toolName string) (string, *HandleTable) {
|
||||
switch toolHandlePolicies[toolName].mcpRoutingKey {
|
||||
case "server_id":
|
||||
return "server_id", r.mcpServers
|
||||
case "tool_ref":
|
||||
return "tool_ref", r.mcpTools
|
||||
default:
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
|
||||
func rewriteMCPField(raw, key string, rewrite func(string) string) string {
|
||||
var object map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(raw), &object) != nil || object == nil {
|
||||
return raw
|
||||
}
|
||||
var value string
|
||||
if json.Unmarshal(object[key], &value) != nil {
|
||||
return raw
|
||||
}
|
||||
rewritten := rewrite(value)
|
||||
if rewritten == value {
|
||||
return raw
|
||||
}
|
||||
object[key], _ = json.Marshal(rewritten)
|
||||
result, _ := json.Marshal(object)
|
||||
return string(result)
|
||||
}
|
||||
|
||||
func mcpHandleShape(value string, table *HandleTable) bool {
|
||||
return table != nil && strings.HasPrefix(value, table.table.prefix) &&
|
||||
allDigits(strings.TrimPrefix(value, table.table.prefix))
|
||||
}
|
||||
|
||||
func registerMCPIdentity(table *HandleTable, value string) string {
|
||||
// Replayed in-turn results are already encoded. Never allocate aliases for
|
||||
// aliases, including unknown ones from compacted history.
|
||||
if value == "" || mcpHandleShape(value, table) {
|
||||
return value
|
||||
}
|
||||
return table.Register(value)
|
||||
}
|
||||
|
||||
func (r *Registry) encodeMCPArguments(toolName, raw string) string {
|
||||
key, table := r.mcpArgumentTable(toolName)
|
||||
if table == nil {
|
||||
return raw
|
||||
}
|
||||
return rewriteMCPField(raw, key, func(value string) string {
|
||||
if handle, ok := table.Handle(value); ok {
|
||||
return handle
|
||||
}
|
||||
return value
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Registry) decodeMCPArguments(toolName, raw string) (string, []string) {
|
||||
key, table := r.mcpArgumentTable(toolName)
|
||||
if table == nil {
|
||||
return raw, nil
|
||||
}
|
||||
var unresolved []string
|
||||
decoded := rewriteMCPField(raw, key, func(value string) string {
|
||||
if !mcpHandleShape(value, table) {
|
||||
return value
|
||||
}
|
||||
if durable, ok := table.Resolve(value); ok {
|
||||
return durable
|
||||
}
|
||||
unresolved = append(unresolved, value)
|
||||
return value
|
||||
})
|
||||
return decoded, unresolved
|
||||
}
|
||||
|
||||
func (r *Registry) encodeMCPDirectory(output string) string {
|
||||
encodeRow := func(raw string) string {
|
||||
raw = rewriteMCPField(raw, "server_id", func(value string) string {
|
||||
return registerMCPIdentity(r.mcpServers, value)
|
||||
})
|
||||
return rewriteMCPField(raw, "tool_ref", func(value string) string {
|
||||
return registerMCPIdentity(r.mcpTools, value)
|
||||
})
|
||||
}
|
||||
var object map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(output), &object) != nil || object == nil {
|
||||
// Validation failures contain our known durable identifiers in prose.
|
||||
return r.mcpTools.EncodeKnownText(r.mcpServers.EncodeKnownText(output))
|
||||
}
|
||||
for _, key := range []string{"servers", "tools"} {
|
||||
var rows []json.RawMessage
|
||||
if json.Unmarshal(object[key], &rows) != nil {
|
||||
continue
|
||||
}
|
||||
for i := range rows {
|
||||
rows[i] = json.RawMessage(encodeRow(string(rows[i])))
|
||||
}
|
||||
object[key], _ = json.Marshal(rows)
|
||||
}
|
||||
encoded, _ := json.Marshal(object)
|
||||
return encodeRow(string(encoded))
|
||||
}
|
||||
|
||||
// EncodeTools returns a model-facing copy. The registry/executor retains the
|
||||
// original UUID enum and validates only decoded durable identities.
|
||||
func (r *Registry) EncodeTools(tools []chat.Tool) []chat.Tool {
|
||||
if r == nil {
|
||||
return tools
|
||||
}
|
||||
encoded := append([]chat.Tool(nil), tools...)
|
||||
// Register routing enums first, independently of tool description order.
|
||||
for i := range encoded {
|
||||
def := &encoded[i].Function
|
||||
key, table := r.mcpArgumentTable(def.Name)
|
||||
if table == nil {
|
||||
continue
|
||||
}
|
||||
var schema map[string]json.RawMessage
|
||||
if json.Unmarshal(def.Parameters, &schema) != nil {
|
||||
continue
|
||||
}
|
||||
var properties map[string]json.RawMessage
|
||||
if json.Unmarshal(schema["properties"], &properties) != nil {
|
||||
continue
|
||||
}
|
||||
var field map[string]json.RawMessage
|
||||
if json.Unmarshal(properties[key], &field) != nil {
|
||||
continue
|
||||
}
|
||||
var ids []string
|
||||
if json.Unmarshal(field["enum"], &ids) != nil {
|
||||
continue
|
||||
}
|
||||
for j := range ids {
|
||||
ids[j] = registerMCPIdentity(table, ids[j])
|
||||
}
|
||||
field["enum"], _ = json.Marshal(ids)
|
||||
properties[key], _ = json.Marshal(field)
|
||||
schema["properties"], _ = json.Marshal(properties)
|
||||
def.Parameters, _ = json.Marshal(schema)
|
||||
}
|
||||
for i := range encoded {
|
||||
def := &encoded[i].Function
|
||||
if def.Name == "discover_mcp_tools" {
|
||||
lines := strings.Split(def.Description, "\n")
|
||||
for j := range lines {
|
||||
lines[j] = rewriteMCPField(lines[j], "server_id", func(value string) string {
|
||||
return registerMCPIdentity(r.mcpServers, value)
|
||||
})
|
||||
}
|
||||
def.Description = strings.Join(lines, "\n")
|
||||
} else if strings.HasPrefix(def.Name, "mcp_") && strings.HasPrefix(def.Description, "[MCP service ") {
|
||||
prefix, body, ok := strings.Cut(def.Description, " (external)] ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
def.Description = r.encodeMCPRoutingText(prefix) + " (external)] " + body
|
||||
}
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
|
||||
// Only system-owned routing syntax is compacted in runtime-context text. Do
|
||||
// not replace arbitrary matching UUIDs in user prose or external tool payloads.
|
||||
func (r *Registry) encodeMCPRoutingText(text string) string {
|
||||
for _, pair := range r.mcpServers.table.pairs() {
|
||||
text = strings.ReplaceAll(text, "server_id="+strconv.Quote(pair.value), "server_id="+strconv.Quote(pair.handle))
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MCP schemas and payloads remain opaque. This sidecar only indexes literal
|
||||
// HTTP(S) links observed in a successful result; it never interprets external
|
||||
// IDs as knowledge chunks or synthesizes URLs from article IDs.
|
||||
const maxMCPSourceCandidates = 50
|
||||
|
||||
var (
|
||||
mcpJSONStringRE = regexp.MustCompile(`"(?:[^"\\]|\\.)*"`)
|
||||
mcpURLRE = regexp.MustCompile("https?://[^\\s<>\"'`\\\\,。;!?、()【】]+")
|
||||
)
|
||||
|
||||
func (r *Registry) mcpSourceCandidates(output string) string {
|
||||
if !r.sources.citationsEnabled {
|
||||
return ""
|
||||
}
|
||||
// Decode JSON string escaping only in a scratch copy used to find links.
|
||||
// Both the external body and the durable ToolResult stay unchanged.
|
||||
scan := mcpJSONStringRE.ReplaceAllStringFunc(output, func(token string) string {
|
||||
var value string
|
||||
if json.Unmarshal([]byte(token), &value) == nil {
|
||||
return `"` + value + `"`
|
||||
}
|
||||
return token
|
||||
})
|
||||
seen := make(map[string]bool)
|
||||
var rows strings.Builder
|
||||
for _, match := range mcpURLRE.FindAllString(scan, -1) {
|
||||
rawURL := strings.TrimRight(html.UnescapeString(match), ".,;!?")
|
||||
// Strip Markdown/prose closing delimiters, retaining balanced URL
|
||||
// parentheses such as /wiki/Function_(mathematics).
|
||||
for _, pair := range [][2]string{{"(", ")"}, {"[", "]"}, {"{", "}"}} {
|
||||
for strings.HasSuffix(rawURL, pair[1]) && strings.Count(rawURL, pair[1]) > strings.Count(rawURL, pair[0]) {
|
||||
rawURL = strings.TrimSuffix(rawURL, pair[1])
|
||||
}
|
||||
}
|
||||
parsed, err := url.Parse(rawURL)
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User != nil ||
|
||||
(parsed.Scheme != "https" && parsed.Scheme != "http") {
|
||||
continue
|
||||
}
|
||||
key := canonicalWebURL(rawURL)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
handle := r.sources.RegisterWeb(rawURL, "")
|
||||
fmt.Fprintf(&rows, "<source id=\"%s\" url=\"%s\"/>\n", handle, escapeAttr(rawURL))
|
||||
if len(seen) >= maxMCPSourceCandidates {
|
||||
break
|
||||
}
|
||||
}
|
||||
if rows.Len() == 0 {
|
||||
return ""
|
||||
}
|
||||
return "\n\n<external_source_candidates>\n" +
|
||||
"System-indexed links from this MCP result. Cite the matching url://N " +
|
||||
"only when the result supports the claim; " +
|
||||
"a link alone does not mean the linked page was read. Do not use KB " +
|
||||
"chunk handles for this external content.\n" +
|
||||
rows.String() + "</external_source_candidates>"
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMCPAnswerCannotBorrowDirectoryOrHistoricalKnowledgeCitations(t *testing.T) {
|
||||
r := NewRegistry(true)
|
||||
r.RegisterContextChunk(ChunkReference{ChunkID: "faq-1", DocumentTitle: "什么是 Academy?"})
|
||||
r.RegisterContextChunk(ChunkReference{ChunkID: "faq-2", DocumentTitle: "如何创建知识库?"})
|
||||
history := []chat.Message{{Role: "assistant", Content: `物业工作 <kb doc="9月13日周报.docx" chunk_id="weekly-report" />`}}
|
||||
r.EncodeMessages(history)
|
||||
const article = "https://km.woa.com/articles/show/669504?jumpfrom=kmmcp"
|
||||
result := &types.ToolResult{Success: true, Output: "标题: AI 玩法\nAI摘要: Computer Use 案例\n链接: " + article}
|
||||
modelOutput := r.ModelToolResultForTool("call_mcp_tool", result)
|
||||
require.True(t, strings.HasPrefix(modelOutput, result.Output), "external payload is preserved")
|
||||
require.Contains(t, modelOutput, `<source id="url://1" url="`+article+`"/>`)
|
||||
require.Equal(t, modelOutput, r.ModelToolResultForTool("call_mcp_tool", result),
|
||||
"rebuilding context keeps stable handles")
|
||||
r.EncodeMessages(history) // Replaying history must not promote its citations.
|
||||
raw := `玩法<ref id="chunk://3"/> 动画<ref id="chunk://1"/> 对话<ref id="chunk://2"/> 来源<ref id="url://1"/>`
|
||||
want := `玩法 动画 对话 来源<web url="` + article + `" title="" />`
|
||||
require.Equal(t, want, r.DecodeOutputText(raw))
|
||||
decoder := r.StreamDecoder()
|
||||
var streamed strings.Builder
|
||||
for _, char := range raw {
|
||||
streamed.WriteString(decoder.Feed(string(char)))
|
||||
}
|
||||
streamed.WriteString(decoder.Flush())
|
||||
require.Equal(t, want, streamed.String(), "SSE and final text apply identical evidence checks")
|
||||
|
||||
// Directory handles remain usable to retrieve the actual FAQ.
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "list_knowledge_chunks", Arguments: `{"faq_id":"chunk://1"}`,
|
||||
}}}
|
||||
r.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"faq_id":"faq-1"}`, calls[0].Function.Arguments)
|
||||
r.ModelToolResultForTool("knowledge_search", &types.ToolResult{Success: true, Data: map[string]interface{}{
|
||||
"display_type": "search_results",
|
||||
"results": []map[string]interface{}{{
|
||||
"chunk_id": "faq-1", "knowledge_title": "什么是 Academy?", "content": "知识库管理系统",
|
||||
}},
|
||||
}})
|
||||
r.RegisterContextChunk(ChunkReference{ChunkID: "faq-1"})
|
||||
r.EncodeMessages(history)
|
||||
require.Contains(t, r.DecodeOutputText(`<ref id="chunk://1"/>`), `chunk_id="faq-1"`,
|
||||
"fresh KB evidence is still citable in a mixed-source answer")
|
||||
require.Empty(t, r.DecodeOutputText(`<ref id="chunk://2"/><ref id="chunk://3"/>`))
|
||||
}
|
||||
|
||||
func TestToolArgumentsAloneDoNotAuthorizeCitations(t *testing.T) {
|
||||
r := NewRegistry(true)
|
||||
r.EncodeMessages([]chat.Message{{Role: "assistant", ToolCalls: []chat.ToolCall{
|
||||
{Function: chat.FunctionCall{Name: "list_knowledge_chunks", Arguments: `{"faq_id":"faq-real"}`}},
|
||||
{Function: chat.FunctionCall{Name: "web_fetch", Arguments: `{"items":[{"url":"https://example.com/unread"}]}`}},
|
||||
}}})
|
||||
require.Empty(t, r.DecodeOutputText(`<ref id="chunk://1"/><ref id="url://1"/>`))
|
||||
r.ModelToolResultForTool("call_mcp_tool", &types.ToolResult{Success: false, Error: "https://example.com/error"})
|
||||
require.Empty(t, r.DecodeOutputText(`<ref id="url://2"/>`))
|
||||
}
|
||||
|
||||
func TestCurrentLegacySourceResultsRemainCitableButHistoryDoesNot(t *testing.T) {
|
||||
for _, output := range []string{
|
||||
`<chunk chunk_id="chunk-real" knowledge_title="Guide">Evidence</chunk>`,
|
||||
`Evidence <kb doc="Guide" chunk_id="chunk-real" />`,
|
||||
} {
|
||||
r := NewRegistry(true)
|
||||
r.EncodeMessages([]chat.Message{{Role: "tool", Name: "wiki_read_page", Content: output}})
|
||||
require.Empty(t, r.DecodeOutputText(`<ref id="chunk://1"/>`))
|
||||
result := &types.ToolResult{Success: true, Output: output}
|
||||
modelOutput := r.ModelToolResultForTool("wiki_read_page", result)
|
||||
require.Contains(t, modelOutput, "chunk://1")
|
||||
require.Equal(t, output, result.Output)
|
||||
require.Contains(t, r.DecodeOutputText(`<ref id="chunk://1"/>`), `chunk_id="chunk-real"`)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPSourceCandidatesPreserveExternalLinksAndPayload(t *testing.T) {
|
||||
for _, tool := range []string{"call_mcp_tool", "mcp_external_search"} {
|
||||
t.Run(tool, func(t *testing.T) {
|
||||
r := NewRegistry(true)
|
||||
body := "[MCP result]\n" + `{"url":"https:\/\/example.com\/article?a=1\u0026b=2","chunk_id":"foreign-id"}` +
|
||||
"\n[Article](https://example.com/article?a=1&b=2)\n[Wiki](https://example.com/Function_(math))。\n" +
|
||||
"[HTML](https://example.com/page?x=1&y=2)\n" +
|
||||
"https://user:pass@example.com/private javascript:alert(1) https://"
|
||||
result := &types.ToolResult{Success: true, Output: body}
|
||||
got := r.ModelToolResultForTool(tool, result)
|
||||
require.Equal(t, body, result.Output)
|
||||
require.True(t, strings.HasPrefix(got, body))
|
||||
sidecar := strings.TrimPrefix(got, body)
|
||||
require.Equal(t, 3, strings.Count(sidecar, "<source "))
|
||||
require.Contains(t, sidecar, `url="https://example.com/article?a=1&b=2"`)
|
||||
require.Contains(t, sidecar, `url="https://example.com/Function_(math)"`)
|
||||
require.Contains(t, sidecar, `url="https://example.com/page?x=1&y=2"`)
|
||||
require.NotContains(t, sidecar, "user:pass")
|
||||
require.Empty(t, r.ChunkHandle("foreign-id"), "external IDs never become KB references")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPSourceCandidatesAreBoundedAndOnlyForSuccessfulExternalResults(t *testing.T) {
|
||||
var body strings.Builder
|
||||
for i := 0; i < maxMCPSourceCandidates+10; i++ {
|
||||
fmt.Fprintf(&body, "https://example.com/%d\n", i)
|
||||
}
|
||||
r := NewRegistry(true)
|
||||
got := r.ModelToolResultForTool("call_mcp_tool", &types.ToolResult{Success: true, Output: body.String()})
|
||||
require.Equal(t, maxMCPSourceCandidates, strings.Count(got, "<source "))
|
||||
for _, tc := range []struct {
|
||||
tool string
|
||||
enabled, success bool
|
||||
}{
|
||||
{"discover_mcp_tools", true, true},
|
||||
{"read_file", true, true},
|
||||
{"call_mcp_tool", false, true},
|
||||
{"call_mcp_tool", true, false},
|
||||
} {
|
||||
r := NewRegistry(tc.enabled)
|
||||
output := r.ModelToolResultForTool(tc.tool, &types.ToolResult{
|
||||
Success: tc.success, Output: "https://example.com/page",
|
||||
})
|
||||
require.NotContains(t, output, "<external_source_candidates>")
|
||||
require.Empty(t, r.DecodeOutputText(`<ref id="url://1"/>`))
|
||||
}
|
||||
r = NewRegistry(true)
|
||||
require.Equal(t, "No links", r.ModelToolResultForTool("call_mcp_tool", &types.ToolResult{
|
||||
Success: true, Output: "No links",
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
mcpTestServer = "8f7a5b68-a7ab-4565-b6f3-1cae2578f040"
|
||||
mcpTestRef = "mcpt_123456789abcdef"
|
||||
)
|
||||
|
||||
func mcpTestDefinitions() []chat.Tool {
|
||||
return []chat.Tool{{Type: "function", Function: chat.FunctionDef{
|
||||
Name: "discover_mcp_tools",
|
||||
Description: `Sources:` + "\n" + `{"server_id":"` + mcpTestServer + `","name":"amap-maps"}`,
|
||||
Parameters: json.RawMessage(`{"type":"object","properties":{"server_id":` +
|
||||
`{"type":"string","enum":["` + mcpTestServer + `"]}}}`),
|
||||
}}}
|
||||
}
|
||||
|
||||
func TestMCPRoutingHandlesRoundTripWithoutTouchingExternalPayloads(t *testing.T) {
|
||||
r := NewRegistry(false)
|
||||
definitions := mcpTestDefinitions()
|
||||
encoded := r.EncodeTools(definitions)
|
||||
require.Contains(t, encoded[0].Function.Description, `"server_id":"ms1"`)
|
||||
require.Contains(t, string(encoded[0].Function.Parameters), `"enum":["ms1"]`)
|
||||
require.Contains(t, string(definitions[0].Function.Parameters), mcpTestServer, "executor schema stays durable")
|
||||
external := `{"type":"object","properties":{"server_id":{"const":"` + mcpTestServer +
|
||||
`"},"tool_ref":{"const":"` + mcpTestRef + `"}}}`
|
||||
output := `{"server_id":"` + mcpTestServer + `","tool_ref":"` + mcpTestRef + `","input_schema":` + external + `}`
|
||||
result := &types.ToolResult{Success: true, Output: output}
|
||||
modelOutput := r.ModelToolResultForTool("discover_mcp_tools", result)
|
||||
var description map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal([]byte(modelOutput), &description))
|
||||
require.JSONEq(t, `"ms1"`, string(description["server_id"]))
|
||||
require.JSONEq(t, `"mt1"`, string(description["tool_ref"]))
|
||||
require.JSONEq(t, external, string(description["input_schema"]))
|
||||
require.Equal(t, output, result.Output, "durable result for UI and storage must not change")
|
||||
replayed := r.ModelToolResultForTool("discover_mcp_tools", &types.ToolResult{Success: true, Output: modelOutput})
|
||||
require.Equal(t, modelOutput, replayed)
|
||||
calls := []types.LLMToolCall{
|
||||
{Function: types.FunctionCall{
|
||||
Name: "discover_mcp_tools", Arguments: `{"mode":"list_tools","server_id":"ms1"}`,
|
||||
}},
|
||||
{Function: types.FunctionCall{
|
||||
Name: "call_mcp_tool",
|
||||
Arguments: `{"tool_ref":"mt1","arguments":{"server_id":"ms1","tool_ref":"mt1","url":"w1"}}`,
|
||||
}},
|
||||
}
|
||||
r.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"mode":"list_tools","server_id":"`+mcpTestServer+`"}`, calls[0].Function.Arguments)
|
||||
require.JSONEq(t, `{"tool_ref":"`+mcpTestRef+`","arguments":{"server_id":"ms1","tool_ref":"mt1","url":"w1"}}`,
|
||||
calls[1].Function.Arguments)
|
||||
for _, call := range calls {
|
||||
require.Equal(t, ArgumentResolutionResolved, call.ArgumentResolution)
|
||||
require.Empty(t, call.UnresolvedHandles)
|
||||
}
|
||||
require.Contains(t, calls[0].ModelArguments, `"ms1"`)
|
||||
require.Contains(t, calls[1].ModelArguments, `"mt1"`)
|
||||
require.Equal(t, output, r.ModelToolResultForTool("call_mcp_tool", result), "external call results are opaque")
|
||||
require.Equal(t, output, r.ModelToolResultForTool("mcp_external_tool", result))
|
||||
}
|
||||
|
||||
func TestMCPRoutingReplayAndStreamUseTheSameRegistry(t *testing.T) {
|
||||
r := NewRegistry(false)
|
||||
r.EncodeTools(mcpTestDefinitions())
|
||||
output := `{"server_id":"` + mcpTestServer + `","tool_ref":"` + mcpTestRef + `"}`
|
||||
raw := `{"tool_ref":"` + mcpTestRef + `","arguments":{"id":"42"}}`
|
||||
history := []chat.Message{
|
||||
{Role: "user", Content: `Use server_id="` + mcpTestServer + `"`},
|
||||
{Role: "assistant", ToolCalls: []chat.ToolCall{
|
||||
{Function: chat.FunctionCall{Name: "call_mcp_tool", Arguments: raw}},
|
||||
}},
|
||||
{Role: "tool", Name: "discover_mcp_tools", Content: output},
|
||||
}
|
||||
encoded := r.EncodeMessages(history)
|
||||
require.Equal(t, `Use server_id="ms1"`, encoded[0].Content)
|
||||
require.JSONEq(t, `{"tool_ref":"mt1","arguments":{"id":"42"}}`, encoded[1].ToolCalls[0].Function.Arguments)
|
||||
require.JSONEq(t, `{"server_id":"ms1","tool_ref":"mt1"}`, encoded[2].Content)
|
||||
require.Equal(t, raw, history[1].ToolCalls[0].Function.Arguments)
|
||||
require.Equal(t, output, history[2].Content)
|
||||
require.Equal(t, encoded, r.EncodeMessages(encoded), "replay must not renumber handles")
|
||||
durable := "Use " + mcpTestServer + " with " + mcpTestRef + "."
|
||||
require.Equal(t, durable, r.DecodeOutputText("Use ms1 with mt1."))
|
||||
decoder := r.StreamDecoder()
|
||||
var streamed string
|
||||
for _, char := range "Use ms1 with mt1." {
|
||||
streamed += decoder.Feed(string(char))
|
||||
}
|
||||
streamed += decoder.Flush()
|
||||
require.Equal(t, durable, streamed)
|
||||
// A fresh execution remaps durable history; handles themselves never carry authority.
|
||||
fresh := NewRegistry(false)
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "call_mcp_tool", Arguments: `{"tool_ref":"mt1","arguments":{}}`,
|
||||
}}}
|
||||
fresh.DecodeToolCalls(calls)
|
||||
require.Equal(t, []string{"mt1"}, calls[0].UnresolvedHandles)
|
||||
fresh.EncodeTools(mcpTestDefinitions())
|
||||
require.Equal(t, encoded, fresh.EncodeMessages(history))
|
||||
}
|
||||
|
||||
func TestMCPUnknownRoutingHandlesFailClosedOnlyAtTheEnvelope(t *testing.T) {
|
||||
r := NewRegistry(false)
|
||||
r.EncodeTools(mcpTestDefinitions())
|
||||
calls := []types.LLMToolCall{
|
||||
{Function: types.FunctionCall{Name: "discover_mcp_tools", Arguments: `{"server_id":"ms99","query":"ms98"}`}},
|
||||
{Function: types.FunctionCall{
|
||||
Name: "call_mcp_tool", Arguments: `{"tool_ref":"mt99","arguments":{"tool_ref":"mt98"}}`,
|
||||
}},
|
||||
{Function: types.FunctionCall{Name: "mcp_external", Arguments: `{"server_id":"ms99","tool_ref":"mt99"}`}},
|
||||
}
|
||||
r.DecodeToolCalls(calls)
|
||||
require.Equal(t, []string{"ms99"}, calls[0].UnresolvedHandles)
|
||||
require.Equal(t, []string{"mt99"}, calls[1].UnresolvedHandles)
|
||||
require.Empty(t, calls[2].UnresolvedHandles)
|
||||
for _, call := range calls {
|
||||
require.JSONEq(t, call.ModelArguments, call.Function.Arguments)
|
||||
}
|
||||
require.Equal(t, ArgumentResolutionUnresolved, calls[0].ArgumentResolution)
|
||||
require.Equal(t, ArgumentResolutionUnresolved, calls[1].ArgumentResolution)
|
||||
}
|
||||
|
||||
func TestMCPStringArgumentsNormalizeOnlyOneCompleteObject(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
arguments any
|
||||
normalized bool
|
||||
}{
|
||||
{"empty object", "{}", true},
|
||||
{"whitespace", " \n { } \t", true},
|
||||
{"nested business string", `{"query":"{\"id\":1}","items":[{"enabled":true}]}`, true},
|
||||
{"already an object", map[string]any{"query": "{}"}, false},
|
||||
{"null", nil, false},
|
||||
{"encoded null", "null", false},
|
||||
{"array", "[]", false},
|
||||
{"scalar", "123", false},
|
||||
{"empty string", "", false},
|
||||
{"malformed", `{"id":`, false},
|
||||
{"trailing content", `{} {}`, false},
|
||||
{"another encoding layer", `"{}"`, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := NewRegistry(false)
|
||||
raw, err := json.Marshal(map[string]any{"tool_ref": mcpTestRef, "arguments": tc.arguments})
|
||||
require.NoError(t, err)
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Name: "call_mcp_tool", Arguments: string(raw)}}}
|
||||
r.DecodeToolCalls(calls)
|
||||
require.Equal(t, string(raw), calls[0].ModelArguments)
|
||||
if tc.normalized {
|
||||
require.Equal(t, ArgumentResolutionResolved, calls[0].ArgumentResolution)
|
||||
var envelope map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal([]byte(calls[0].Function.Arguments), &envelope))
|
||||
require.JSONEq(t, tc.arguments.(string), string(envelope["arguments"]))
|
||||
} else {
|
||||
require.JSONEq(t, string(raw), calls[0].Function.Arguments)
|
||||
require.Equal(t, ArgumentResolutionUnchanged, calls[0].ArgumentResolution)
|
||||
}
|
||||
first := calls[0]
|
||||
r.DecodeToolCalls(calls)
|
||||
require.Equal(t, first, calls[0], "stream completion may decode the same call again")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPStringArgumentsDecodeResourcesAndKeepOtherToolsOpaque(t *testing.T) {
|
||||
r := NewRegistry(false)
|
||||
const resource = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
require.Equal(t, "res://0001", r.CompactKnownText(resource))
|
||||
r.ModelToolResultForTool("discover_mcp_tools", &types.ToolResult{
|
||||
Success: true, Output: `{"tool_ref":"` + mcpTestRef + `"}`,
|
||||
})
|
||||
r.RegisterWeb("https://example.com/page", "")
|
||||
raw := `{"tool_ref":"mt1","arguments":"{\"file\":\"res://0001\",\"knowledge_id\":\"d1\",\"link\":\"url://1\"}"}`
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Name: "call_mcp_tool", Arguments: raw}}}
|
||||
r.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"tool_ref":"`+mcpTestRef+`","arguments":{"file":"`+resource+`","knowledge_id":"d1",`+
|
||||
`"link":"https://example.com/page"}}`,
|
||||
calls[0].Function.Arguments)
|
||||
require.Equal(t, raw, calls[0].ModelArguments)
|
||||
require.Empty(t, calls[0].UnresolvedHandles)
|
||||
for _, name := range []string{"mcp_external_tool", "discover_mcp_tools", "read_file"} {
|
||||
original := `{"arguments":"{\"id\":1}"}`
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Name: name, Arguments: original}}}
|
||||
r.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, original, calls[0].Function.Arguments)
|
||||
}
|
||||
unknown := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "call_mcp_tool", Arguments: `{"tool_ref":"mt1","arguments":"{\"file\":\"res://9999\"}"}`,
|
||||
}}}
|
||||
r.DecodeToolCalls(unknown)
|
||||
require.Equal(t, []string{"res://9999"}, unknown[0].UnresolvedHandles)
|
||||
require.Equal(t, ArgumentResolutionPartiallyResolved, unknown[0].ArgumentResolution)
|
||||
}
|
||||
@@ -0,0 +1,963 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
modelWebSearchEvidenceMaxRunes = 1500
|
||||
modelWebFetchSummaryMaxRunes = 4000
|
||||
modelWebFetchContentMaxRunes = 8000
|
||||
modelWebFetchTotalMaxRunes = 16000
|
||||
)
|
||||
|
||||
// ModelOutput returns a compact, source-centric representation for the LLM.
|
||||
// The canonical ToolResult.Output remains untouched for UI, logs and storage.
|
||||
func (r *sourceRegistry) ModelOutput(result *types.ToolResult) string {
|
||||
if result == nil {
|
||||
return ""
|
||||
}
|
||||
// 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
|
||||
}
|
||||
displayType := stringValue(result.Data, "display_type")
|
||||
if displayType == "web_fetch_results" {
|
||||
return r.modelWebFetchOutput(mapsValue(result.Data["results"]), result.Output)
|
||||
}
|
||||
if !result.Success {
|
||||
return failedToolModelText(result.Output, result.Error)
|
||||
}
|
||||
switch displayType {
|
||||
case "grep_results":
|
||||
return r.modelKnowledgeOutput("keyword", mapsValue(result.Data["chunk_results"]), result.Output)
|
||||
case "search_results":
|
||||
// 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 annotateSearchNotes(r.annotateModeFallbacks(output, result.Data), result.Data)
|
||||
case "knowledge_chunks_list":
|
||||
return r.modelKnowledgeChunksOutput(result.Data, result.Output)
|
||||
case "document_info":
|
||||
return r.modelDocumentInfoOutput(result.Data, result.Output)
|
||||
case "graph_query_results":
|
||||
return annotateGraphResult(
|
||||
r.modelKnowledgeOutput("graph", mapsValue(result.Data["results"]), result.Output), result.Data)
|
||||
case "web_search_results":
|
||||
return annotateWebSearchNotes(
|
||||
r.modelWebSearchOutput(mapsValue(result.Data["results"]), result.Output), result.Data)
|
||||
case "database_query":
|
||||
return r.modelDatabaseQueryOutput(mapsValue(result.Data["rows"]), result.Output)
|
||||
default:
|
||||
r.registerLabeledReferences(result.Output)
|
||||
r.registerStructuredReferences(result.Output)
|
||||
return r.CompactKnownText(result.Output)
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (r *sourceRegistry) registerStructuredReferences(raw string) {
|
||||
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:
|
||||
r.registerSourceIDByKey(key, typed, true)
|
||||
case []interface{}:
|
||||
for _, item := range typed {
|
||||
walk(key, item)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
for childKey, item := range typed {
|
||||
walk(childKey, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk("", value)
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) modelDatabaseQueryOutput(rows []map[string]interface{}, fallback string) string {
|
||||
for _, row := range rows {
|
||||
for key, raw := range row {
|
||||
if value, ok := raw.(string); ok {
|
||||
r.registerSourceIDByKey(key, value, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) modelDocumentInfoOutput(data map[string]interface{}, fallback string) string {
|
||||
rows := mapsValue(data["documents"])
|
||||
if len(rows) == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
var b strings.Builder
|
||||
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")
|
||||
count := 0
|
||||
for _, row := range rows {
|
||||
knowledgeID := stringValue(row, "knowledge_id")
|
||||
docHandle := r.RegisterDocument(knowledgeID)
|
||||
if boolValue(row, "is_faq") {
|
||||
chunkID := stringValue(row, "faq_id")
|
||||
if chunkID == "" {
|
||||
continue
|
||||
}
|
||||
title := firstNonEmpty(stringValue(row, "faq_question"), stringValue(row, "title"))
|
||||
chunkHandle := r.RegisterChunk(ChunkReference{
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: knowledgeID,
|
||||
DocumentTitle: title,
|
||||
ChunkType: "faq",
|
||||
})
|
||||
fmt.Fprintf(&b, " <document id=\"%s\" type=\"faq\">\n", escapeAttr(docHandle))
|
||||
fmt.Fprintf(&b, " <chunk id=\"%s\" type=\"faq\">\n", escapeAttr(chunkHandle))
|
||||
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
|
||||
}
|
||||
|
||||
if docHandle == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, " <document id=\"%s\"", escapeAttr(docHandle))
|
||||
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))
|
||||
}
|
||||
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")
|
||||
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 {
|
||||
handle string
|
||||
docHandle string
|
||||
kbHandle string
|
||||
title string
|
||||
metadata string
|
||||
chunkType string
|
||||
index int
|
||||
view string
|
||||
role string
|
||||
match string
|
||||
content string
|
||||
question string
|
||||
answers []string
|
||||
images []map[string]interface{}
|
||||
docRealID string
|
||||
kbRealID string
|
||||
chunkReal string
|
||||
inputOrder int
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) modelKnowledgeOutput(mode string, rows []map[string]interface{}, fallback string) string {
|
||||
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 {
|
||||
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")
|
||||
}
|
||||
chunkHandle := r.RegisterChunk(ChunkReference{
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: knowledgeID,
|
||||
KnowledgeBaseID: kbID,
|
||||
DocumentTitle: title,
|
||||
ChunkIndex: chunkIndex,
|
||||
ChunkType: chunkType,
|
||||
})
|
||||
chunks = append(chunks, modelChunk{
|
||||
handle: chunkHandle,
|
||||
docHandle: r.RegisterDocument(knowledgeID),
|
||||
kbHandle: r.RegisterKnowledgeBase(kbID),
|
||||
title: title,
|
||||
metadata: stringValue(row, "knowledge_metadata"),
|
||||
chunkType: chunkType,
|
||||
index: chunkIndex,
|
||||
view: viewForRow(row, mode),
|
||||
role: stringValue(row, "role"),
|
||||
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,
|
||||
})
|
||||
}
|
||||
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
|
||||
}
|
||||
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>"
|
||||
}
|
||||
|
||||
// matchAddsToContent reports whether a match snippet tells the model
|
||||
// anything the chunk's content does not: it does when there is no content
|
||||
// (a snippet-only view), or when the snippet is not an excerpt of it.
|
||||
// Rendering an excerpt next to the full content repeated up to 800
|
||||
// characters per row.
|
||||
func matchAddsToContent(match, content string) bool {
|
||||
if content == "" {
|
||||
return true
|
||||
}
|
||||
excerpt := strings.TrimSpace(match)
|
||||
for _, marker := range []string{"...", "…"} {
|
||||
excerpt = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(excerpt, marker), marker))
|
||||
}
|
||||
return excerpt != "" && !strings.Contains(content, excerpt)
|
||||
}
|
||||
|
||||
// annotateGraphResult adds the graph relations, any per-knowledge-base
|
||||
// failures, and any cap the graph tool hit to a graph query's chunk view. The
|
||||
// first two lived only in Output, which the model never sees once there are
|
||||
// chunk rows to render; the same goes for a truncated relation list, which
|
||||
// without a marker reads as the entity's whole neighbourhood.
|
||||
func annotateGraphResult(output string, data map[string]interface{}) string {
|
||||
relations := mapsValue(data["relations"])
|
||||
failures := stringSliceValue(data["errors"])
|
||||
truncation := graphTruncationNote(data, len(relations))
|
||||
if (len(relations) == 0 && len(failures) == 0 && truncation == "") ||
|
||||
!strings.HasSuffix(output, "</retrieval>") {
|
||||
return output
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, rel := range relations {
|
||||
fmt.Fprintf(&b, " <relation source=\"%s\" type=\"%s\" target=\"%s\" />\n",
|
||||
escapeAttr(stringValue(rel, "source")), escapeAttr(stringValue(rel, "type")),
|
||||
escapeAttr(stringValue(rel, "target")))
|
||||
}
|
||||
for _, failure := range failures {
|
||||
fmt.Fprintf(&b, " <error>%s</error>\n", escapeText(failure))
|
||||
}
|
||||
b.WriteString(truncation)
|
||||
return strings.TrimSuffix(output, "</retrieval>") + b.String() + "</retrieval>"
|
||||
}
|
||||
|
||||
// graphTruncationNote states inside the model's view the caps the graph query
|
||||
// tool hit. shownRelations is how many relations that view carries; the tool
|
||||
// reports the totals under relations_total / graph_chunks_total /
|
||||
// query_terms_total. It returns "" when nothing was dropped, so a complete
|
||||
// result stays clean.
|
||||
func graphTruncationNote(data map[string]interface{}, shownRelations int) string {
|
||||
totalRelations := intValue(data, "relations_total")
|
||||
totalChunks := intValue(data, "graph_chunks_total")
|
||||
fetchedChunks := totalChunks - intValue(data, "graph_chunks_omitted")
|
||||
totalTerms := intValue(data, "query_terms_total")
|
||||
if totalRelations <= shownRelations && totalChunks <= fetchedChunks && totalTerms <= 0 {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString(" <graph_truncated")
|
||||
if totalRelations > shownRelations {
|
||||
fmt.Fprintf(&b, " relations_shown=\"%d\" relations_total=\"%d\"", shownRelations, totalRelations)
|
||||
}
|
||||
if totalChunks > fetchedChunks {
|
||||
fmt.Fprintf(&b, " chunks_fetched=\"%d\" chunks_total=\"%d\"", fetchedChunks, totalChunks)
|
||||
}
|
||||
if totalTerms > 0 {
|
||||
fmt.Fprintf(&b, " terms_shown=\"%d\" terms_total=\"%d\"",
|
||||
totalTerms-intValue(data, "query_terms_omitted"), totalTerms)
|
||||
}
|
||||
b.WriteString(">This graph query stopped at a result cap, so it is not the complete picture: ")
|
||||
if totalRelations > shownRelations {
|
||||
b.WriteString("the relations listed are a subset of these entities' relations, ")
|
||||
}
|
||||
if totalChunks > fetchedChunks {
|
||||
b.WriteString("some of their source chunks are missing, ")
|
||||
}
|
||||
if totalTerms > 0 {
|
||||
b.WriteString("and some words of the query were never matched against entity names, ")
|
||||
}
|
||||
b.WriteString("so a relation may be absent only because it was dropped. Narrow the query to a single entity " +
|
||||
"name before concluding that a relation does not exist.</graph_truncated>\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// annotateSearchNotes tells the model what a search result does not show:
|
||||
// how many lower-ranked results were left out to fit the tool output budget
|
||||
// (so it narrows the query or lowers the limit instead of concluding nothing
|
||||
// else matched), how much of the ranked candidate pool the rendered passages
|
||||
// stand for, and which knowledge bases could not be searched (so a failure is
|
||||
// not read as an absence of evidence).
|
||||
func annotateSearchNotes(output string, data map[string]interface{}) string {
|
||||
omitted := intValue(data, "omitted_for_budget")
|
||||
failures := stringSliceValue(data["partial_failures"])
|
||||
// retrieval_candidates is the candidate pool of the first ranked-filter
|
||||
// stage that dropped anything (rerank, merge or FILTER_TOP_K), not the
|
||||
// number of matches in the knowledge base, which retrieval never computes
|
||||
// at that depth; retrieval_shown is how many knowledge passages this view
|
||||
// renders out of that pool. Both count passages.
|
||||
shown := intValue(data, "retrieval_shown")
|
||||
candidates := intValue(data, "retrieval_candidates")
|
||||
truncated := shown > 0 && candidates > shown
|
||||
if (omitted <= 0 && len(failures) == 0 && !truncated) || !strings.HasSuffix(output, "</retrieval>") {
|
||||
return output
|
||||
}
|
||||
var b strings.Builder
|
||||
if omitted > 0 {
|
||||
fmt.Fprintf(&b, " <omitted count=\"%d\" reason=\"output_budget\">Lower-ranked results were left out to "+
|
||||
"fit the output size. Narrow the query or lower limit to see them.</omitted>\n", omitted)
|
||||
}
|
||||
if truncated {
|
||||
// The caveat is conditional on purpose: a truncated view is the norm
|
||||
// for a ranked retrieval, so an unconditional "the answer may be
|
||||
// incomplete" would add a disclaimer to ordinary factual answers that
|
||||
// the subset does not affect. Only counting and exhaustive-list
|
||||
// questions have to report the scope of what was read.
|
||||
fmt.Fprintf(&b, " <subset shown=\"%d\" candidates=\"%d\">If the question asks for a count or an "+
|
||||
"exhaustive list, state that the provided context contains only the top %d of %d candidate "+
|
||||
"passages at this filtering stage, and do not treat these passage counts as the requested "+
|
||||
"total; otherwise answer normally without adding a disclaimer solely because of this "+
|
||||
"truncation.</subset>\n", shown, candidates, shown, candidates)
|
||||
}
|
||||
for _, failure := range failures {
|
||||
fmt.Fprintf(&b, " <partial_failure>%s — these knowledge bases were not searched.</partial_failure>\n",
|
||||
escapeText(failure))
|
||||
}
|
||||
return strings.TrimSuffix(output, "</retrieval>") + b.String() + "</retrieval>"
|
||||
}
|
||||
|
||||
// annotateWebSearchNotes restates a clamped count inside the retrieval block.
|
||||
// web_search also writes the note into ToolResult.Output, but once there is at
|
||||
// least one row the model only sees this rendered view, so the note has to
|
||||
// travel in Data — the same reason annotateSearchNotes reads Data, not Output.
|
||||
func annotateWebSearchNotes(output string, data map[string]interface{}) string {
|
||||
if !boolValue(data, "count_clamped") || !strings.HasSuffix(output, "</retrieval>") {
|
||||
return output
|
||||
}
|
||||
requested := intValue(data, "count_requested")
|
||||
maximum := intValue(data, "count_maximum")
|
||||
if requested < 1 || maximum < 1 {
|
||||
return output
|
||||
}
|
||||
note := fmt.Sprintf(" <count_clamped requested=\"%d\" maximum=\"%d\">The requested count is "+
|
||||
"outside 1-%d and was clamped to %d. Ask for a value in range, or omit count to use the "+
|
||||
"maximum.</count_clamped>\n", requested, maximum, maximum, maximum)
|
||||
return strings.TrimSuffix(output, "</retrieval>") + note + "</retrieval>"
|
||||
}
|
||||
|
||||
func viewForRow(row map[string]interface{}, mode string) string {
|
||||
if stringValue(row, "content") != "" {
|
||||
return "full"
|
||||
}
|
||||
if mode == "deep_read" {
|
||||
return "full"
|
||||
}
|
||||
return "match"
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) modelKnowledgeChunksOutput(data map[string]interface{}, fallback string) string {
|
||||
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
|
||||
}
|
||||
}
|
||||
var info map[string]interface{}
|
||||
if raw, ok := data["document"].(map[string]interface{}); ok {
|
||||
info = raw
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
// 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))
|
||||
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=chunk://N and context.</hint>\n")
|
||||
}
|
||||
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"))
|
||||
}
|
||||
return output
|
||||
}
|
||||
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\"")
|
||||
if _, ok := data["next_offset"]; ok {
|
||||
fmt.Fprintf(&footer, " next_offset=\"%d\"", intValue(data, "next_offset"))
|
||||
}
|
||||
}
|
||||
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>"
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
// 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 {
|
||||
type docGroup struct {
|
||||
handle string
|
||||
realID string
|
||||
kbHandle string
|
||||
title string
|
||||
metadata string
|
||||
chunks []modelChunk
|
||||
order int
|
||||
}
|
||||
groupsByKey := make(map[string]*docGroup)
|
||||
var groups []*docGroup
|
||||
for _, chunk := range chunks {
|
||||
key := chunk.docHandle
|
||||
if key == "" {
|
||||
key = "chunk:" + chunk.handle
|
||||
}
|
||||
group := groupsByKey[key]
|
||||
if group == nil {
|
||||
group = &docGroup{
|
||||
handle: chunk.docHandle, realID: chunk.docRealID, kbHandle: chunk.kbHandle, title: chunk.title,
|
||||
metadata: chunk.metadata, order: chunk.inputOrder,
|
||||
}
|
||||
groupsByKey[key] = group
|
||||
groups = append(groups, group)
|
||||
} else if group.metadata == "" {
|
||||
group.metadata = chunk.metadata
|
||||
}
|
||||
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")
|
||||
if group.handle != "" {
|
||||
fmt.Fprintf(&b, " id=\"%s\"", escapeAttr(group.handle))
|
||||
}
|
||||
if group.kbHandle != "" {
|
||||
fmt.Fprintf(&b, " kb=\"%s\"", escapeAttr(group.kbHandle))
|
||||
}
|
||||
if group.title != "" {
|
||||
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(group.title))
|
||||
}
|
||||
b.WriteString(">\n")
|
||||
if group.metadata != "" {
|
||||
fmt.Fprintf(&b, " <metadata>%s</metadata>\n", escapeText(group.metadata))
|
||||
}
|
||||
if info != nil && stringValue(info, "knowledge_id") == group.realID {
|
||||
writeDocumentInfo(&b, info)
|
||||
}
|
||||
for _, chunk := range group.chunks {
|
||||
fmt.Fprintf(&b, " <chunk id=\"%s\" index=\"%d\" view=\"%s\"", chunk.handle, chunk.index, chunk.view)
|
||||
if chunk.chunkType != "" {
|
||||
fmt.Fprintf(&b, " type=\"%s\"", escapeAttr(chunk.chunkType))
|
||||
}
|
||||
if chunk.role != "" {
|
||||
fmt.Fprintf(&b, " role=\"%s\"", escapeAttr(chunk.role))
|
||||
}
|
||||
b.WriteString(">\n")
|
||||
if chunk.question != "" {
|
||||
fmt.Fprintf(&b, " <question>%s</question>\n", escapeText(chunk.question))
|
||||
}
|
||||
// Deep reads keep the snippet: it locates the hit inside a long
|
||||
// chunk. Search rows are chunk-sized, so an excerpt of the content
|
||||
// shown beside it only repeats it.
|
||||
if chunk.match != "" && (mode == "deep_read" || matchAddsToContent(chunk.match, chunk.content)) {
|
||||
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()
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) modelWebSearchOutput(rows []map[string]interface{}, fallback string) string {
|
||||
if len(rows) == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
var b strings.Builder
|
||||
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))
|
||||
count := 0
|
||||
for _, row := range rows {
|
||||
rawURL := stringValue(row, "url")
|
||||
if rawURL == "" {
|
||||
continue
|
||||
}
|
||||
handle := r.RegisterWeb(rawURL, stringValue(row, "title"))
|
||||
fmt.Fprintf(&b, " <page id=\"%s\" title=\"%s\">\n", handle, escapeAttr(stringValue(row, "title")))
|
||||
b.WriteString(" <evidence type=\"search_summary\" verified=\"false\" />\n")
|
||||
if u, err := url.Parse(rawURL); err == nil {
|
||||
fmt.Fprintf(&b, " <domain>%s</domain>\n", escapeText(u.Hostname()))
|
||||
}
|
||||
if snippet := stringValue(row, "snippet"); snippet != "" {
|
||||
writeLimitedWebEvidence(&b, "match", snippet, perEvidence, nil)
|
||||
}
|
||||
if content := stringValue(row, "content"); content != "" && content != stringValue(row, "snippet") {
|
||||
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")))
|
||||
}
|
||||
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()
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fallback string) string {
|
||||
if len(rows) == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("<retrieval type=\"web\" mode=\"fetch\" trust=\"untrusted\">\n")
|
||||
count, successCount, failedCount := 0, 0, 0
|
||||
// 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)
|
||||
for _, row := range rows {
|
||||
rawURL := stringValue(row, "url")
|
||||
if rawURL == "" {
|
||||
continue
|
||||
}
|
||||
title := stringValue(row, "title")
|
||||
handle := r.RegisterWeb(rawURL, title)
|
||||
status := stringValue(row, "status")
|
||||
if status == "" {
|
||||
status = "success"
|
||||
}
|
||||
if handle == "" {
|
||||
// Unknown references must not become page IDs: a later real page may
|
||||
// legitimately receive that ID in this registry.
|
||||
fmt.Fprintf(&b, " <page requested_reference=\"%s\" status=\"%s\"", escapeAttr(rawURL), escapeAttr(status))
|
||||
} else {
|
||||
fmt.Fprintf(&b, " <page id=\"%s\" status=\"%s\"", escapeAttr(handle), escapeAttr(status))
|
||||
}
|
||||
if title != "" {
|
||||
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(title))
|
||||
}
|
||||
if status == "success" {
|
||||
b.WriteString(" view=\"excerpt\">\n")
|
||||
writeWebPageFileHint(&b, row)
|
||||
remainingEvidence := perPage
|
||||
successCount++
|
||||
if summary := stringValue(row, "summary"); summary != "" {
|
||||
writeLimitedWebEvidence(&b, "summary", summary, modelWebFetchSummaryMaxRunes, &remainingEvidence)
|
||||
}
|
||||
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 != "" {
|
||||
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)
|
||||
}
|
||||
}
|
||||
} 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++
|
||||
}
|
||||
}
|
||||
b.WriteString(" </page>\n")
|
||||
count++
|
||||
}
|
||||
b.WriteString("</retrieval>")
|
||||
if count == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
if failedCount > 0 {
|
||||
b.WriteString("\n\n=== Next Steps ===\n")
|
||||
if successCount == 0 {
|
||||
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")
|
||||
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.")
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAnnotateSearchNotes(t *testing.T) {
|
||||
t.Parallel()
|
||||
base := "<retrieval mode=\"hybrid\">\n</retrieval>"
|
||||
got := annotateSearchNotes(base, map[string]interface{}{
|
||||
"omitted_for_budget": 4,
|
||||
"partial_failures": []string{"[kb-2]: vector store unavailable"},
|
||||
})
|
||||
if !strings.Contains(got, `<omitted count="4" reason="output_budget">`) ||
|
||||
!strings.Contains(got, "<partial_failure>[kb-2]: vector store unavailable") ||
|
||||
!strings.HasSuffix(got, "</retrieval>") {
|
||||
t.Fatalf("annotated = %q", got)
|
||||
}
|
||||
if annotateSearchNotes(base, map[string]interface{}{}) != base {
|
||||
t.Fatal("nothing to add must leave the output unchanged")
|
||||
}
|
||||
}
|
||||
|
||||
// The subset note is conditional: only a counting or exhaustive-list question
|
||||
// has to report the scope of the view. It must also carry the counts it was
|
||||
// given, so the model reads the real shown / candidate numbers rather than a
|
||||
// placeholder or a knowledge-base total.
|
||||
func TestAnnotateSearchNotesReportsTruncatedRetrieval(t *testing.T) {
|
||||
t.Parallel()
|
||||
base := "<retrieval mode=\"hybrid\">\n</retrieval>"
|
||||
got := annotateSearchNotes(base, map[string]interface{}{
|
||||
"retrieval_shown": 5,
|
||||
"retrieval_candidates": 146,
|
||||
})
|
||||
want := ` <subset shown="5" candidates="146">If the question asks for a count or an exhaustive list, ` +
|
||||
`state that the provided context contains only the top 5 of 146 candidate passages at this ` +
|
||||
`filtering stage, and do not treat these passage counts as the requested total; otherwise ` +
|
||||
`answer normally without adding a disclaimer solely because of this truncation.</subset>`
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("annotated = %q\nwant subset %q", got, want)
|
||||
}
|
||||
if strings.Contains(got, "say the answer may be incomplete") {
|
||||
t.Fatalf("the unconditional disclaimer must be gone: %q", got)
|
||||
}
|
||||
if !strings.HasSuffix(got, "</retrieval>") {
|
||||
t.Fatalf("subset note must stay inside the retrieval block: %q", got)
|
||||
}
|
||||
// A prompt that saw every candidate, or was given no usable counts,
|
||||
// carries no caveat at all.
|
||||
for name, data := range map[string]map[string]interface{}{
|
||||
"complete": {"retrieval_shown": 5, "retrieval_candidates": 5},
|
||||
"no counts": {},
|
||||
"shown only": {"retrieval_shown": 5},
|
||||
"candidates only": {"retrieval_candidates": 146},
|
||||
"more than pool": {"retrieval_shown": 7, "retrieval_candidates": 5},
|
||||
"no shown passage": {"retrieval_shown": 0, "retrieval_candidates": 146},
|
||||
} {
|
||||
if annotateSearchNotes(base, data) != base {
|
||||
t.Fatalf("%s: a non-truncated retrieval must leave the output unchanged", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnotateGraphResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
base := "<retrieval mode=\"graph\">\n</retrieval>"
|
||||
got := annotateGraphResult(base, map[string]interface{}{
|
||||
"relations": []map[string]interface{}{{"source": "Kubernetes", "type": "orchestrates", "target": "Docker"}},
|
||||
"errors": []string{"KB kb://2: graph extraction not configured"},
|
||||
})
|
||||
for _, want := range []string{
|
||||
`<relation source="Kubernetes" type="orchestrates" target="Docker" />`,
|
||||
"<error>KB kb://2: graph extraction not configured</error>",
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("missing %q in %q", want, got)
|
||||
}
|
||||
}
|
||||
if annotateGraphResult(base, map[string]interface{}{}) != base {
|
||||
t.Fatal("nothing to add must leave the output unchanged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchAddsToContent(t *testing.T) {
|
||||
t.Parallel()
|
||||
content := "Install the engine, then configure psionic drive parameters."
|
||||
if matchAddsToContent("... configure psionic drive ...", content) {
|
||||
t.Fatal("an excerpt of the content adds nothing")
|
||||
}
|
||||
if !matchAddsToContent("How do I tune the drive?", content) {
|
||||
t.Fatal("a matched question absent from the content adds information")
|
||||
}
|
||||
if !matchAddsToContent("anything", "") {
|
||||
t.Fatal("a snippet-only row keeps its snippet")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
// Package modelcontext owns every request-local handle exposed to a language
|
||||
// model. Application code should use Registry instead of coordinating source
|
||||
// references and durable-resource codecs independently.
|
||||
//
|
||||
// Its boundaries are deliberate:
|
||||
// - UUIDs, wiki slugs, URLs, and resource:// handles are durable identities.
|
||||
// - kb://N, doc://N, chunk://N, url://N, iN, res://NNNN and ref-N values are
|
||||
// temporary model handles; academy:// URIs are their durable text form.
|
||||
// - temporary handles are never persisted or accepted outside their registry.
|
||||
// - every model response is decoded before tools, storage, or UI consume it.
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
ArgumentResolutionUnchanged = "unchanged"
|
||||
ArgumentResolutionResolved = "resolved"
|
||||
ArgumentResolutionPartiallyResolved = "partially_resolved"
|
||||
ArgumentResolutionUnresolved = "unresolved"
|
||||
)
|
||||
|
||||
const resourceHandleProtocolPrompt = `
|
||||
|
||||
## Resource handle protocol (system-owned)
|
||||
Some durable resources and high-entropy Wiki slugs are represented by request-local res://NNNN handles. Wiki issues may use iN handles.
|
||||
- Copy supplied handles exactly in links, images, and tool arguments; they refer only to the supplied resource versions.
|
||||
- For downloadable deliverables generated in the session workspace, use sandbox:<file name>; ` +
|
||||
`never reuse or invent a resource handle. This download convention does not apply to ` +
|
||||
`editing installed skill files.`
|
||||
|
||||
// Registry is the single request-scoped boundary between durable application
|
||||
// identities and temporary model handles.
|
||||
//
|
||||
// Durable resource references are encoded before source identifiers. This
|
||||
// ordering is intentionally private: summary/<knowledge-id> wiki slugs must be
|
||||
// protected as one resource-like handle before the embedded document ID can be
|
||||
// compacted to doc://N. Callers therefore cannot accidentally reverse the codecs.
|
||||
type Registry struct {
|
||||
sources *sourceRegistry
|
||||
resources *resourceRegistry
|
||||
issues *HandleTable
|
||||
mcpServers *HandleTable
|
||||
mcpTools *HandleTable
|
||||
}
|
||||
|
||||
// NewRegistry creates a registry for one model request/Agent execution.
|
||||
func NewRegistry(citationsEnabled bool) *Registry {
|
||||
return &Registry{
|
||||
sources: newSourceRegistry(citationsEnabled),
|
||||
resources: newResourceRegistry(),
|
||||
issues: NewHandleTable("i", 0, 1),
|
||||
mcpServers: NewHandleTable("ms", 0, 1),
|
||||
mcpTools: NewHandleTable("mt", 0, 1),
|
||||
}
|
||||
}
|
||||
|
||||
// ProtocolPrompt returns the system-owned model handle and citation protocol.
|
||||
func (r *Registry) ProtocolPrompt() string {
|
||||
if r == nil || r.sources == nil {
|
||||
return ""
|
||||
}
|
||||
return r.sources.ProtocolPrompt() + resourceHandleProtocolPrompt +
|
||||
"\nMCP routing uses request-local msN server IDs and mtN tool references. " +
|
||||
"Copy them exactly from the directory or describe result; never invent them.\n"
|
||||
}
|
||||
|
||||
// EncodeMessages returns a model-facing copy with every temporary handle
|
||||
// encoded in the only safe order.
|
||||
func (r *Registry) EncodeMessages(messages []chat.Message) []chat.Message {
|
||||
if r == nil {
|
||||
return messages
|
||||
}
|
||||
messages = r.resources.EncodeMessages(messages)
|
||||
// Register tool-private IDs from all replayed results before encoding any
|
||||
// assistant call. The scan is intentionally order-independent, matching the
|
||||
// source codec's two-pass replay behavior.
|
||||
for i := range messages {
|
||||
if messages[i].Role == "system" || messages[i].Role == "user" {
|
||||
messages[i].Content = r.encodeMCPRoutingText(messages[i].Content)
|
||||
}
|
||||
if messages[i].Role == "tool" {
|
||||
messages[i].Content = r.encodeToolPrivateResult(messages[i].Name, messages[i].Content)
|
||||
}
|
||||
}
|
||||
messages = r.sources.EncodeMessagesWithPolicies(messages, sourceArgumentAllowed, sourceOutputAllowed)
|
||||
for i := range messages {
|
||||
if len(messages[i].ToolCalls) == 0 {
|
||||
continue
|
||||
}
|
||||
messages[i].ToolCalls = append([]chat.ToolCall(nil), messages[i].ToolCalls...)
|
||||
for j := range messages[i].ToolCalls {
|
||||
r.encodeReplayedToolPolicies(&messages[i].ToolCalls[j])
|
||||
}
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
// DecodeToolCalls restores all temporary handles in tool-call arguments.
|
||||
func (r *Registry) DecodeToolCalls(toolCalls []types.LLMToolCall) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
for i := range toolCalls {
|
||||
if toolCalls[i].ModelArguments == "" {
|
||||
toolCalls[i].ModelArguments = toolCalls[i].Function.Arguments
|
||||
}
|
||||
}
|
||||
normalizeWebFetchItems(toolCalls)
|
||||
normalizeMCPCallArguments(toolCalls)
|
||||
r.resources.DecodeToolCalls(toolCalls)
|
||||
r.sources.DecodeToolCallsWithPolicy(toolCalls, sourceArgumentAllowed, sourceBareTextAllowed)
|
||||
for i := range toolCalls {
|
||||
r.decodeToolPolicies(&toolCalls[i])
|
||||
decodedMCP, unresolvedMCP := r.decodeMCPArguments(toolCalls[i].Function.Name, toolCalls[i].Function.Arguments)
|
||||
toolCalls[i].Function.Arguments = decodedMCP
|
||||
resolved := toolCalls[i].Function.Arguments
|
||||
unresolved := append(
|
||||
r.resources.OrphanHandles(resolved),
|
||||
r.sources.UnresolvedToolHandlesWithPolicy(
|
||||
toolCalls[i].Function.Name, resolved, sourceArgumentAllowed,
|
||||
)...,
|
||||
)
|
||||
unresolved = append(unresolved, r.unresolvedPrivateToolHandles(toolCalls[i].Function.Name, resolved)...)
|
||||
unresolved = append(unresolved, unresolvedMCP...)
|
||||
toolCalls[i].UnresolvedHandles = uniqueSorted(unresolved)
|
||||
changed := !jsonEquivalent(toolCalls[i].ModelArguments, resolved)
|
||||
switch {
|
||||
case changed && len(toolCalls[i].UnresolvedHandles) > 0:
|
||||
toolCalls[i].ArgumentResolution = ArgumentResolutionPartiallyResolved
|
||||
case len(toolCalls[i].UnresolvedHandles) > 0:
|
||||
toolCalls[i].ArgumentResolution = ArgumentResolutionUnresolved
|
||||
case changed:
|
||||
toolCalls[i].ArgumentResolution = ArgumentResolutionResolved
|
||||
default:
|
||||
toolCalls[i].ArgumentResolution = ArgumentResolutionUnchanged
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func jsonEquivalent(left, right string) bool {
|
||||
var leftValue interface{}
|
||||
var rightValue interface{}
|
||||
if json.Unmarshal([]byte(left), &leftValue) != nil || json.Unmarshal([]byte(right), &rightValue) != nil {
|
||||
return left == right
|
||||
}
|
||||
return reflect.DeepEqual(leftValue, rightValue)
|
||||
}
|
||||
|
||||
func uniqueSorted(values []string) []string {
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
if value != "" {
|
||||
seen[value] = struct{}{}
|
||||
}
|
||||
}
|
||||
result := make([]string, 0, len(seen))
|
||||
for value := range seen {
|
||||
result = append(result, value)
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result
|
||||
}
|
||||
|
||||
// DecodeResponse restores resources, expands citations, and decodes tool
|
||||
// arguments in a non-streaming response.
|
||||
func (r *Registry) DecodeResponse(response *types.ChatResponse) {
|
||||
if r == nil || response == nil {
|
||||
return
|
||||
}
|
||||
response.Content = r.DecodeOutputText(response.Content)
|
||||
reasoningBefore := response.ReasoningContent
|
||||
response.ReasoningContent = r.DecodeOutputText(response.ReasoningContent)
|
||||
if response.ReasoningContent != reasoningBefore &&
|
||||
api.SignatureFor(api.APIAnthropicMessages, response.ReasoningSignature) != "" {
|
||||
// Same reason and same protocol limit as dropStaleReasoningSignature:
|
||||
// the decoded text is no longer what Claude signed, and this response
|
||||
// is what lands on the agent step. Anthropic turns replay from
|
||||
// ReasoningMetadata, which decoding never touches, so this only
|
||||
// affects turns stored before that metadata existed.
|
||||
response.ReasoningSignature = ""
|
||||
}
|
||||
r.DecodeToolCalls(response.ToolCalls)
|
||||
}
|
||||
|
||||
// StreamDecoder creates one ordered decoder for a response text channel.
|
||||
func (r *Registry) StreamDecoder() *StreamDecoder {
|
||||
if r == nil {
|
||||
return &StreamDecoder{}
|
||||
}
|
||||
return &StreamDecoder{
|
||||
resources: newResourceStreamDecoder(r.resources),
|
||||
sources: newCitationStreamExpander(r.sources),
|
||||
handles: newSourceHandleStreamDecoder(r.sources),
|
||||
issues: NewHandleStreamDecoder(r.issues),
|
||||
mcpServers: NewHandleStreamDecoder(r.mcpServers),
|
||||
mcpTools: NewHandleStreamDecoder(r.mcpTools),
|
||||
orphans: newOrphanResourceStreamFilter(),
|
||||
}
|
||||
}
|
||||
|
||||
// OrphanResourceHandles reports model-generated resource handles with no
|
||||
// backing durable reference.
|
||||
func (r *Registry) OrphanResourceHandles(decoded string) []string {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
return r.resources.OrphanHandles(decoded)
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterChunk(ref ChunkReference) string {
|
||||
if r == nil || r.sources == nil {
|
||||
return ""
|
||||
}
|
||||
return r.sources.RegisterChunk(ref)
|
||||
}
|
||||
|
||||
// RegisterContextChunk makes a directory entry addressable by tools without
|
||||
// allowing it to substantiate an answer before retrieval.
|
||||
func (r *Registry) RegisterContextChunk(ref ChunkReference) string {
|
||||
if r == nil || r.sources == nil {
|
||||
return ""
|
||||
}
|
||||
return r.sources.registerChunk(ref, false)
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterDocument(id string) string {
|
||||
if r == nil || r.sources == nil {
|
||||
return ""
|
||||
}
|
||||
return r.sources.RegisterDocument(id)
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterKnowledgeBase(id string) string {
|
||||
if r == nil || r.sources == nil {
|
||||
return ""
|
||||
}
|
||||
return r.sources.RegisterKnowledgeBase(id)
|
||||
}
|
||||
|
||||
// RegisterIssue allocates the iN handle the Wiki issue tools accept for id.
|
||||
func (r *Registry) RegisterIssue(id string) string {
|
||||
if r == nil || r.issues == nil || strings.TrimSpace(id) == "" {
|
||||
return ""
|
||||
}
|
||||
return r.issues.Register(id)
|
||||
}
|
||||
|
||||
// EncodeKnownIssues replaces registered Wiki issue IDs with their handles.
|
||||
// CompactKnownText leaves them alone because tools opt into issue encoding
|
||||
// per policy; runtime context the engine renders opts in explicitly.
|
||||
func (r *Registry) EncodeKnownIssues(text string) string {
|
||||
if r == nil || r.issues == nil {
|
||||
return text
|
||||
}
|
||||
return r.issues.EncodeKnownText(text)
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterWeb(rawURL, title string) string {
|
||||
if r == nil || r.sources == nil {
|
||||
return ""
|
||||
}
|
||||
return r.sources.RegisterWeb(rawURL, title)
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterSearchResults(results []*types.SearchResult) {
|
||||
if r == nil || r.sources == nil {
|
||||
return
|
||||
}
|
||||
r.sources.RegisterSearchResults(results)
|
||||
}
|
||||
|
||||
func (r *Registry) ChunkHandle(id string) string {
|
||||
if r == nil || r.sources == nil {
|
||||
return ""
|
||||
}
|
||||
return r.sources.ChunkHandle(id)
|
||||
}
|
||||
|
||||
// CompactKnownText replaces only previously registered durable source IDs.
|
||||
func (r *Registry) CompactKnownText(text string) string {
|
||||
if r == nil || r.sources == nil {
|
||||
return text
|
||||
}
|
||||
text = r.resources.EncodeText(text)
|
||||
return r.sources.CompactKnownText(text)
|
||||
}
|
||||
|
||||
// ModelToolResult renders a tool result using registered model handles.
|
||||
func (r *Registry) ModelToolResult(result *types.ToolResult) string {
|
||||
return r.ModelToolResultForTool("", result)
|
||||
}
|
||||
|
||||
// ModelToolResultForTool renders a result and applies any explicit private-ID
|
||||
// policy owned by that built-in tool family.
|
||||
func (r *Registry) ModelToolResultForTool(toolName string, result *types.ToolResult) string {
|
||||
if result == nil {
|
||||
return ""
|
||||
}
|
||||
if r == nil || r.sources == nil {
|
||||
if result.Success {
|
||||
return result.Output + outputFilesPrompt(result)
|
||||
}
|
||||
return failedToolModelText(result.Output, result.Error) + outputFilesPrompt(result)
|
||||
}
|
||||
// Protect durable resources and UUID-bearing summary slugs before the
|
||||
// source codec sees any embedded document IDs. Encode once more afterwards
|
||||
// for resource references rendered from structured ToolResult.Data.
|
||||
copyResult := *result
|
||||
// Error text is encoded on the same path as Output: a failed tool call
|
||||
// routinely echoes the offending argument, so a raw durable ID would leak
|
||||
// through the error branch of an otherwise handle-only tool.
|
||||
copyResult.Output = r.resources.EncodeText(r.encodeToolPrivateResult(toolName, result.Output))
|
||||
copyResult.Error = r.resources.EncodeText(r.encodeToolPrivateResult(toolName, result.Error))
|
||||
var modelOutput string
|
||||
if sourceOutputAllowed(toolName) {
|
||||
modelOutput = r.sources.ModelOutput(©Result)
|
||||
} else if copyResult.Success {
|
||||
modelOutput = copyResult.Output
|
||||
} else {
|
||||
modelOutput = failedToolModelText(copyResult.Output, copyResult.Error)
|
||||
}
|
||||
// Even tools without structured source results can surface a known durable
|
||||
// ID in validation errors or status text. Compact only explicitly declared
|
||||
// built-ins; dynamic MCP output remains fully opaque.
|
||||
if sourceCompactionAllowed(toolName) {
|
||||
modelOutput = r.sources.CompactKnownText(modelOutput)
|
||||
}
|
||||
if result.Success && (toolName == "call_mcp_tool" || strings.HasPrefix(toolName, "mcp_")) {
|
||||
modelOutput += r.mcpSourceCandidates(result.Output)
|
||||
}
|
||||
return r.resources.EncodeText(modelOutput) + outputFilesPrompt(result)
|
||||
}
|
||||
|
||||
func outputFilesPrompt(result *types.ToolResult) string {
|
||||
if result == nil || result.OutputFiles == nil {
|
||||
return ""
|
||||
}
|
||||
if len(result.OutputFiles) == 0 {
|
||||
return "\nOutput files: none identified by this call."
|
||||
}
|
||||
return "\nOutput files: `" + strings.Join(result.OutputFiles, "`, `") + "`"
|
||||
}
|
||||
|
||||
// DecodeOutputText applies the public citation policy to complete text. It is
|
||||
// primarily used by non-streaming cleanup/fallback paths.
|
||||
func (r *Registry) DecodeOutputText(text string) string {
|
||||
if r == nil {
|
||||
return text
|
||||
}
|
||||
text = r.resources.DecodeText(text)
|
||||
text = r.resources.StripOrphanHandles(text)
|
||||
text = r.sources.ExpandText(text)
|
||||
text = r.sources.ExpandHandleText(text)
|
||||
return r.mcpTools.DecodeKnownText(r.mcpServers.DecodeKnownText(r.issues.DecodeKnownText(text)))
|
||||
}
|
||||
@@ -0,0 +1,783 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestRegistryOwnsEncodingOrderForSummarySlugs(t *testing.T) {
|
||||
const knowledgeID = "36283d3d-a495-40d2-a13f-e925fc322996"
|
||||
registry := NewRegistry(true)
|
||||
require.Equal(t, "doc://1", registry.RegisterDocument(knowledgeID))
|
||||
|
||||
messages := registry.EncodeMessages([]chat.Message{{
|
||||
Role: "tool",
|
||||
Content: "[[summary/" + knowledgeID + "|Summary]] document=" + knowledgeID,
|
||||
}})
|
||||
require.Contains(t, messages[0].Content, "[[res://0001|Summary]]")
|
||||
require.Contains(t, messages[0].Content, "document=doc://1")
|
||||
require.NotContains(t, messages[0].Content, "summary/d1")
|
||||
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "wiki_read_source_doc",
|
||||
Arguments: `{"slugs":["res://0001"],"knowledge_id":"doc://1"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"slugs":["summary/`+knowledgeID+`"],"knowledge_id":"`+knowledgeID+`"}`, calls[0].Function.Arguments)
|
||||
require.JSONEq(t, `{"slugs":["res://0001"],"knowledge_id":"doc://1"}`, calls[0].ModelArguments)
|
||||
require.Equal(t, ArgumentResolutionResolved, calls[0].ArgumentResolution)
|
||||
require.Empty(t, calls[0].UnresolvedHandles)
|
||||
persisted, err := json.Marshal(calls[0])
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(persisted), `"res://0001"`)
|
||||
require.NotContains(t, string(persisted), `"doc://1"`)
|
||||
require.NotContains(t, string(persisted), ArgumentResolutionResolved)
|
||||
}
|
||||
|
||||
func TestRegistryProtocolOwnsResourceHandleRules(t *testing.T) {
|
||||
prompt := NewRegistry(true).ProtocolPrompt()
|
||||
require.Contains(t, prompt, "Source handling protocol")
|
||||
require.Contains(t, prompt, "Resource handle protocol")
|
||||
require.Contains(t, prompt, "res://NNNN")
|
||||
}
|
||||
|
||||
func TestOutputFilesAreRenderedOnlyForLiveModelResults(t *testing.T) {
|
||||
result := &types.ToolResult{Success: true, Output: "generated", OutputFiles: []string{"sandbox:比赛信息.pptx"}}
|
||||
registry := NewRegistry(true)
|
||||
require.Equal(t, "generated\nOutput files: `sandbox:比赛信息.pptx`", registry.ModelToolResultForTool("shell_exec", result))
|
||||
require.Equal(t, "generated", result.Output)
|
||||
encoded, err := json.Marshal(result)
|
||||
require.NoError(t, err)
|
||||
var restored types.ToolResult
|
||||
require.NoError(t, json.Unmarshal(encoded, &restored))
|
||||
require.Equal(t, "generated", registry.ModelToolResultForTool("shell_exec", &restored))
|
||||
result.Success = false
|
||||
result.Error = "timeout"
|
||||
require.Contains(t, registry.ModelToolResultForTool("shell_exec", result), "sandbox:比赛信息.pptx")
|
||||
}
|
||||
|
||||
func TestEmptyOutputInspectionIsExplicitOnlyInLiveModelResults(t *testing.T) {
|
||||
for _, registry := range []*Registry{NewRegistry(true), nil} {
|
||||
result := &types.ToolResult{Success: true, Output: "page-1.png", OutputFiles: []string{}}
|
||||
modelOutput := registry.ModelToolResultForTool("shell_exec", result)
|
||||
require.Equal(t, "page-1.png\nOutput files: none identified by this call.", modelOutput)
|
||||
require.NotContains(t, modelOutput, "sandbox:page-1.png")
|
||||
encoded, err := json.Marshal(result)
|
||||
require.NoError(t, err)
|
||||
var restored types.ToolResult
|
||||
require.NoError(t, json.Unmarshal(encoded, &restored))
|
||||
require.Equal(t, "page-1.png", registry.ModelToolResultForTool("shell_exec", &restored))
|
||||
result.Success = false
|
||||
result.Error = "command timed out"
|
||||
modelOutput = registry.ModelToolResultForTool("shell_exec", result)
|
||||
require.Contains(t, modelOutput, "command timed out")
|
||||
require.Contains(t, modelOutput, "Output files: none identified by this call.")
|
||||
result.OutputFiles = nil
|
||||
require.NotContains(t, registry.ModelToolResultForTool("shell_exec", result), "Output files:")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryAuditsUnresolvedAndPartiallyResolvedToolHandles(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterKnowledgeBase("kb-real")
|
||||
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "knowledge_search",
|
||||
Arguments: `{"knowledge_base_ids":["kb://1","kb://99"],"query":"b98 kb://97","asset":"res://0099"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
|
||||
require.JSONEq(t,
|
||||
`{"knowledge_base_ids":["kb-real","kb://99"],"query":"b98 kb://97","asset":"res://0099"}`,
|
||||
calls[0].Function.Arguments,
|
||||
)
|
||||
require.Equal(t, ArgumentResolutionPartiallyResolved, calls[0].ArgumentResolution)
|
||||
// Scheme-shaped handles are reserved in any text, so an unknown one fails
|
||||
// closed; legacy-shaped prose such as "b98" is not an ID.
|
||||
require.Equal(t, []string{"kb://97", "kb://99", "res://0099"}, calls[0].UnresolvedHandles)
|
||||
}
|
||||
|
||||
func TestRegistryAuditsUnchangedJSONFormattingAsUnchanged(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Arguments: `{ "query": "hello" }`}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.Equal(t, ArgumentResolutionUnchanged, calls[0].ArgumentResolution)
|
||||
}
|
||||
|
||||
func TestRegistryDecodesKnownHandlesEmbeddedInBuiltInSQL(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument("doc-real")
|
||||
registry.RegisterKnowledgeBase("kb-real")
|
||||
calls := []types.LLMToolCall{{
|
||||
Function: types.FunctionCall{
|
||||
Name: "database_query",
|
||||
Arguments: `{"sql":"SELECT * FROM knowledges WHERE id = 'doc://1' AND knowledge_base_id = 'kb://1'"}`,
|
||||
},
|
||||
}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t,
|
||||
`{"sql":"SELECT * FROM knowledges WHERE id = 'doc-real' AND knowledge_base_id = 'kb-real'"}`,
|
||||
calls[0].Function.Arguments,
|
||||
)
|
||||
require.Equal(t, ArgumentResolutionResolved, calls[0].ArgumentResolution)
|
||||
}
|
||||
|
||||
func TestRegistryDecodesSQLHandlesWithoutTouchingAliasesAndRejectsUnknownOnes(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument("doc-real")
|
||||
|
||||
calls := []types.LLMToolCall{{
|
||||
Function: types.FunctionCall{
|
||||
Name: "database_query",
|
||||
Arguments: `{"sql":"SELECT d1.id FROM documents d1 WHERE d1.id = 'doc://1' AND d1.parent_id = 'doc://99'"}`,
|
||||
},
|
||||
}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t,
|
||||
`{"sql":"SELECT d1.id FROM documents d1 WHERE d1.id = 'doc-real' AND d1.parent_id = 'doc://99'"}`,
|
||||
calls[0].Function.Arguments,
|
||||
)
|
||||
require.Equal(t, []string{"doc://99"}, calls[0].UnresolvedHandles)
|
||||
require.Equal(t, ArgumentResolutionPartiallyResolved, calls[0].ArgumentResolution)
|
||||
}
|
||||
|
||||
func TestRegistryReplaysStructuredAndPrivateHandlesWithoutAliasDrift(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument("doc-real")
|
||||
registry.RegisterKnowledgeBase("kb-real")
|
||||
registry.ModelToolResultForTool("wiki_read_issue", &types.ToolResult{
|
||||
Success: true,
|
||||
Output: `{"id":"issue-real","knowledge_base_id":"kb-real","suspected_knowledge_ids":["doc-real"]}`,
|
||||
})
|
||||
|
||||
messages := []chat.Message{
|
||||
{
|
||||
Role: "assistant",
|
||||
ToolCalls: []chat.ToolCall{{Function: chat.FunctionCall{
|
||||
Name: "database_query",
|
||||
Arguments: `{"sql":"SELECT * FROM knowledges WHERE id = 'doc-real' AND knowledge_base_id = 'kb-real'"}`,
|
||||
}}},
|
||||
},
|
||||
{
|
||||
Role: "tool",
|
||||
Name: "wiki_read_issue",
|
||||
Content: `{"id":"issue-real","knowledge_base_id":"kb-real","suspected_knowledge_ids":["doc-real"]}`,
|
||||
},
|
||||
{
|
||||
Role: "assistant",
|
||||
ToolCalls: []chat.ToolCall{{Function: chat.FunctionCall{
|
||||
Name: "wiki_update_issue",
|
||||
Arguments: `{"issue_id":"issue-real","status":"resolved"}`,
|
||||
}}},
|
||||
},
|
||||
}
|
||||
|
||||
first := registry.EncodeMessages(messages)
|
||||
require.JSONEq(t,
|
||||
`{"sql":"SELECT * FROM knowledges WHERE id = 'doc://1' AND knowledge_base_id = 'kb://1'"}`,
|
||||
first[0].ToolCalls[0].Function.Arguments,
|
||||
)
|
||||
require.JSONEq(t,
|
||||
`{"id":"i1","knowledge_base_id":"kb://1","suspected_knowledge_ids":["doc://1"]}`,
|
||||
first[1].Content,
|
||||
)
|
||||
require.JSONEq(t, `{"issue_id":"i1","status":"resolved"}`, first[2].ToolCalls[0].Function.Arguments)
|
||||
|
||||
second := registry.EncodeMessages(first)
|
||||
require.JSONEq(t, first[0].ToolCalls[0].Function.Arguments, second[0].ToolCalls[0].Function.Arguments)
|
||||
require.JSONEq(t, first[1].Content, second[1].Content)
|
||||
require.JSONEq(t, first[2].ToolCalls[0].Function.Arguments, second[2].ToolCalls[0].Function.Arguments)
|
||||
}
|
||||
|
||||
func TestRegistryOwnsWikiIssueHandles(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
modelResult := registry.ModelToolResultForTool("wiki_read_issue", &types.ToolResult{
|
||||
Success: true,
|
||||
Output: `[{"id":"issue-uuid","knowledge_base_id":"kb-real","suspected_knowledge_ids":["doc-real"],"slug":"concept/a","status":"pending"}]`,
|
||||
})
|
||||
require.JSONEq(t,
|
||||
`[{"id":"i1","knowledge_base_id":"kb://1","suspected_knowledge_ids":["doc://1"],`+
|
||||
`"slug":"concept/a","status":"pending"}]`, modelResult)
|
||||
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "wiki_update_issue",
|
||||
Arguments: `{"issue_id":"i1","status":"resolved"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"issue_id":"issue-uuid","status":"resolved"}`, calls[0].Function.Arguments)
|
||||
require.Equal(t, ArgumentResolutionResolved, calls[0].ArgumentResolution)
|
||||
|
||||
decoder := registry.StreamDecoder()
|
||||
got := decoder.Feed("updated i") + decoder.Feed("1 successfully") + decoder.Flush()
|
||||
require.Equal(t, "updated issue-uuid successfully", got)
|
||||
}
|
||||
|
||||
func TestRegistryDecodesWikiReadIssueHandleArgument(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.ModelToolResultForTool("wiki_read_issue", &types.ToolResult{
|
||||
Success: true,
|
||||
Output: `[{"id":"issue-uuid","slug":"concept/a","status":"pending"}]`,
|
||||
})
|
||||
|
||||
// The wiki_read_issue schema instructs the model to pass the short iN
|
||||
// handle back as issue_id; it must resolve to the durable issue ID before
|
||||
// the tool executes.
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "wiki_read_issue",
|
||||
Arguments: `{"issue_id":"i1"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"issue_id":"issue-uuid"}`, calls[0].Function.Arguments)
|
||||
require.Equal(t, ArgumentResolutionResolved, calls[0].ArgumentResolution)
|
||||
require.Empty(t, calls[0].UnresolvedHandles)
|
||||
|
||||
unknown := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "wiki_read_issue",
|
||||
Arguments: `{"issue_id":"i9"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(unknown)
|
||||
require.Equal(t, ArgumentResolutionUnresolved, unknown[0].ArgumentResolution)
|
||||
require.Equal(t, []string{"i9"}, unknown[0].UnresolvedHandles)
|
||||
}
|
||||
|
||||
func TestRegistryReportsUnknownWikiIssueHandle(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "wiki_update_issue",
|
||||
Arguments: `{"issue_id":"i9","status":"resolved"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.Equal(t, ArgumentResolutionUnresolved, calls[0].ArgumentResolution)
|
||||
require.Equal(t, []string{"i9"}, calls[0].UnresolvedHandles)
|
||||
}
|
||||
|
||||
func TestRegistryDoesNotApplyBuiltInFieldPoliciesToDynamicTools(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument("doc-real")
|
||||
registry.RegisterWeb("https://example.com", "Example")
|
||||
registry.ModelToolResultForTool("wiki_read_issue", &types.ToolResult{
|
||||
Success: true,
|
||||
Output: `{"id":"issue-real"}`,
|
||||
})
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "dynamic_mcp_tool",
|
||||
Arguments: `{"issue_id":"i1","knowledge_id":"doc://1","url":"url://1","sql":"SELECT 'doc://1'"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
// Dynamic tools own no ID fields: every handle becomes its durable text
|
||||
// form, and tool-private iN handles stay opaque.
|
||||
require.JSONEq(t,
|
||||
`{"issue_id":"i1","knowledge_id":"academy://doc/doc-real","url":"https://example.com",`+
|
||||
`"sql":"SELECT 'academy://doc/doc-real'"}`,
|
||||
calls[0].Function.Arguments)
|
||||
require.Equal(t, ArgumentResolutionResolved, calls[0].ArgumentResolution)
|
||||
require.Empty(t, calls[0].UnresolvedHandles)
|
||||
|
||||
messages := registry.EncodeMessages([]chat.Message{
|
||||
{
|
||||
Role: "assistant",
|
||||
ToolCalls: []chat.ToolCall{{Function: chat.FunctionCall{
|
||||
Name: "dynamic_mcp_tool",
|
||||
Arguments: `{"knowledge_id":"doc-real"}`,
|
||||
}}},
|
||||
},
|
||||
{
|
||||
Role: "tool",
|
||||
Name: "dynamic_mcp_tool",
|
||||
Content: `<knowledge_id>mcp-owned-id</knowledge_id> doc-real`,
|
||||
},
|
||||
})
|
||||
require.JSONEq(t, `{"knowledge_id":"doc-real"}`, messages[0].ToolCalls[0].Function.Arguments)
|
||||
require.Equal(t, `<knowledge_id>mcp-owned-id</knowledge_id> doc-real`, messages[1].Content)
|
||||
|
||||
modelOutput := registry.ModelToolResultForTool("dynamic_mcp_tool", &types.ToolResult{
|
||||
Success: true,
|
||||
Output: `<knowledge_id>mcp-owned-id</knowledge_id> doc-real`,
|
||||
})
|
||||
require.Equal(t, `<knowledge_id>mcp-owned-id</knowledge_id> doc-real`, modelOutput)
|
||||
}
|
||||
|
||||
func TestRegistryCompactsKnownIDsInBuiltInValidationErrors(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument("doc-real")
|
||||
registry.RegisterKnowledgeBase("kb-real")
|
||||
|
||||
got := registry.ModelToolResultForTool("wiki_write_page", &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "document doc-real belongs to knowledge base kb-real",
|
||||
})
|
||||
require.Equal(t, "Error: document doc://1 belongs to knowledge base kb://1", got)
|
||||
}
|
||||
|
||||
func TestModelToolResultForTool_failedSkillScriptKeepsStdout(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
stdout := `{"chart":{"success":false,"error":{"error":"X轴字段不存在:工作项目","available":["name","value"]}}}`
|
||||
got := registry.ModelToolResultForTool("execute_skill_script", &types.ToolResult{
|
||||
Success: false,
|
||||
Output: "=== Script Execution: smart-charts/scripts/cli.py ===\n\n## Standard Output\n\n```\n" + stdout + "\n```\n",
|
||||
Error: "Script exited with code 1\n\n[Analyze the error above and try a different approach.]",
|
||||
})
|
||||
require.Contains(t, got, "X轴字段不存在:工作项目")
|
||||
require.Contains(t, got, "available")
|
||||
require.Contains(t, got, "Error: Script exited with code 1")
|
||||
}
|
||||
|
||||
func TestRegistryCompactsDatabaseQueryIDColumnsForBuiltInFollowUps(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
modelOutput := registry.ModelToolResultForTool("database_query", &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "knowledge_id | knowledge_base_id\ndoc-real | kb-real",
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "database_query",
|
||||
"rows": []map[string]interface{}{{
|
||||
"knowledge_id": "doc-real",
|
||||
"knowledge_base_id": "kb-real",
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.Contains(t, modelOutput, "doc://1 | kb://1")
|
||||
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "wiki_read_source_doc",
|
||||
Arguments: `{"knowledge_id":"doc://1"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"knowledge_id":"doc-real"}`, calls[0].Function.Arguments)
|
||||
}
|
||||
|
||||
func TestRegistryDecodesCanonicalArgumentsForEveryBuiltInReferenceTool(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument("doc-real")
|
||||
registry.RegisterKnowledgeBase("kb-real")
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-real", KnowledgeID: "doc-real", KnowledgeBaseID: "kb-real"})
|
||||
registry.RegisterWeb("https://example.com/page", "Example")
|
||||
registry.EncodeMessages([]chat.Message{{Role: "user", Content: "summary/00000000-0000-0000-0000-000000000001"}})
|
||||
registry.ModelToolResultForTool("wiki_read_issue", &types.ToolResult{Success: true, Output: `{"id":"issue-real"}`})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
tool string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"knowledge search KB", "knowledge_search",
|
||||
`{"queries":["doc://1"],"knowledge_base_ids":["kb://1"]}`,
|
||||
`{"queries":["academy://doc/doc-real"],"knowledge_base_ids":["kb-real"]}`,
|
||||
},
|
||||
{"list document", "list_knowledge_chunks", `{"knowledge_id":"doc://1"}`, `{"knowledge_id":"doc-real"}`},
|
||||
{"list chunk", "list_knowledge_chunks", `{"chunk_id":"chunk://1"}`, `{"chunk_id":"chunk-real"}`},
|
||||
{
|
||||
"document info", "get_document_info",
|
||||
`{"knowledge_ids":["doc://1"],"faq_ids":["chunk://1"]}`,
|
||||
`{"knowledge_ids":["doc-real"],"faq_ids":["chunk-real"]}`,
|
||||
},
|
||||
{
|
||||
"knowledge graph", "query_knowledge_graph",
|
||||
`{"knowledge_base_ids":["kb://1"],"query":"topic"}`,
|
||||
`{"knowledge_base_ids":["kb-real"],"query":"topic"}`,
|
||||
},
|
||||
{
|
||||
"data analysis SQL", "data_analysis",
|
||||
`{"knowledge_id":"doc://1","sql":"SELECT COUNT(*) FROM dataset WHERE label = 'doc://1'"}`,
|
||||
`{"knowledge_id":"doc-real","sql":"SELECT COUNT(*) FROM dataset WHERE label = 'academy://doc/doc-real'"}`,
|
||||
},
|
||||
{"data schema", "data_schema", `{"knowledge_id":"doc://1"}`, `{"knowledge_id":"doc-real"}`},
|
||||
{
|
||||
"database SQL", "database_query",
|
||||
`{"sql":"SELECT * FROM chunks WHERE knowledge_base_id='kb://1'"}`,
|
||||
`{"sql":"SELECT * FROM chunks WHERE knowledge_base_id='kb-real'"}`,
|
||||
},
|
||||
{
|
||||
"web fetch", "web_fetch",
|
||||
`{"items":[{"url":"url://1"}]}`,
|
||||
`{"items":[{"url":"https://example.com/page"}]}`,
|
||||
},
|
||||
{"wiki source", "wiki_read_source_doc", `{"knowledge_id":"doc://1"}`, `{"knowledge_id":"doc-real"}`},
|
||||
{
|
||||
"wiki source refs", "wiki_write_page",
|
||||
`{"slug":"res://0001","source_refs":["doc://1"]}`,
|
||||
`{"slug":"summary/00000000-0000-0000-0000-000000000001","source_refs":["doc-real"]}`,
|
||||
},
|
||||
{
|
||||
"wiki suspected refs", "wiki_flag_issue",
|
||||
`{"slug":"concept/a","suspected_knowledge_ids":["doc://1"]}`,
|
||||
`{"slug":"concept/a","suspected_knowledge_ids":["doc-real"]}`,
|
||||
},
|
||||
{
|
||||
"wiki search KB", "wiki_search",
|
||||
`{"queries":["topic"],"knowledge_base_id":"kb://1"}`,
|
||||
`{"queries":["topic"],"knowledge_base_id":"kb-real"}`,
|
||||
},
|
||||
{
|
||||
"wiki issue", "wiki_update_issue",
|
||||
`{"issue_id":"i1","status":"resolved"}`,
|
||||
`{"issue_id":"issue-real","status":"resolved"}`,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Name: test.tool, Arguments: test.raw}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, test.want, calls[0].Function.Arguments)
|
||||
require.NotEqual(t, ArgumentResolutionUnresolved, calls[0].ArgumentResolution)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelToolResultProtectsSummarySlugBeforeSourceCompaction(t *testing.T) {
|
||||
const knowledgeID = "07a20bb1-a662-47cf-9929-06fb5d5b5b5e"
|
||||
const kbID = "250368ff-f5a2-4e9e-868a-07bc9b857c44"
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument(knowledgeID)
|
||||
registry.RegisterKnowledgeBase(kbID)
|
||||
|
||||
got := registry.ModelToolResult(&types.ToolResult{
|
||||
Success: true, Output: "<knowledge_base_id>" + kbID + "</knowledge_base_id>\n" +
|
||||
"<link>[[summary/" + knowledgeID + "|Summary]]</link>\n" +
|
||||
"<knowledge_id>" + knowledgeID + "</knowledge_id>",
|
||||
})
|
||||
require.Contains(t, got, "[[res://0001|Summary]]")
|
||||
require.Contains(t, got, "<knowledge_base_id>kb://1</knowledge_base_id>")
|
||||
require.Contains(t, got, "<knowledge_id>doc://1</knowledge_id>")
|
||||
require.NotContains(t, got, "summary/d1")
|
||||
}
|
||||
|
||||
func TestRegistryStreamDecoderRestoresSplitResourceAndCitationHandles(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.EncodeMessages([]chat.Message{{Role: "user", Content: "resource://AbCdEfGhIjKlMnOpQrStUv"}})
|
||||
registry.RegisterChunk(ChunkReference{
|
||||
ChunkID: "chunk-real",
|
||||
KnowledgeID: "doc-real",
|
||||
KnowledgeBaseID: "kb-real",
|
||||
DocumentTitle: "Doc",
|
||||
})
|
||||
|
||||
decoder := registry.StreamDecoder()
|
||||
got := decoder.Feed("image res://0") +
|
||||
decoder.Feed("001 claim <ref id=\"chunk:/") +
|
||||
decoder.Feed("/1\"/>") + decoder.Flush()
|
||||
require.Contains(t, got, "resource://AbCdEfGhIjKlMnOpQrStUv")
|
||||
require.Contains(t, got, `chunk_id="chunk-real"`)
|
||||
}
|
||||
|
||||
func TestRegistryDropsUnknownResourceHandlesFromCompleteAndStreamOutput(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
require.Equal(t, "broken ", registry.DecodeOutputText("broken res://9999"))
|
||||
|
||||
decoder := registry.StreamDecoder()
|
||||
got := decoder.Feed("broken res:/") + decoder.Feed("/99") + decoder.Feed("99 end") + decoder.Flush()
|
||||
require.Equal(t, "broken end", got)
|
||||
}
|
||||
|
||||
func TestHandleTableRoundTripAndIsolation(t *testing.T) {
|
||||
chunks := NewHandleTable("c", 3, 0)
|
||||
require.Equal(t, "c000", chunks.Register("chunk-a"))
|
||||
require.Equal(t, "c000", chunks.Register("chunk-a"))
|
||||
require.Equal(t, "c001", chunks.Register("chunk-b"))
|
||||
require.Equal(t, "chunk-b", mustResolve(t, chunks, "c001"))
|
||||
|
||||
slugs := NewHandleTable("ref-", 0, 1)
|
||||
require.Equal(t, "ref-1", slugs.Register("summary/uuid"))
|
||||
require.Equal(t, "summary/uuid", mustResolve(t, slugs, "ref-1"))
|
||||
require.Equal(t, "", mustNotResolve(t, slugs, "c000"))
|
||||
}
|
||||
|
||||
func TestHandleTableKnownTextRoundTrip(t *testing.T) {
|
||||
table := NewHandleTable("i", 0, 1)
|
||||
require.Equal(t, "i1", table.Register("issue-uuid"))
|
||||
require.Equal(t, "read i1", table.EncodeKnownText("read issue-uuid"))
|
||||
require.Equal(t, "read issue-uuid", table.DecodeKnownText("read i1"))
|
||||
require.Equal(t, "read issue-$1", func() string {
|
||||
literal := NewHandleTable("i", 0, 1)
|
||||
literal.Register("issue-$1")
|
||||
return literal.DecodeKnownText("read i1")
|
||||
}())
|
||||
}
|
||||
|
||||
func mustResolve(t *testing.T, table *HandleTable, handle string) string {
|
||||
t.Helper()
|
||||
value, ok := table.Resolve(handle)
|
||||
require.True(t, ok)
|
||||
return value
|
||||
}
|
||||
|
||||
func mustNotResolve(t *testing.T, table *HandleTable, handle string) string {
|
||||
t.Helper()
|
||||
value, ok := table.Resolve(handle)
|
||||
require.False(t, ok)
|
||||
return value
|
||||
}
|
||||
|
||||
func TestMCPBridgeKeepsExternalSchemasAndArgumentsOpaque(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
for _, name := range []string{"discover_mcp_tools", "call_mcp_tool"} {
|
||||
require.True(t, HasToolPolicy(name))
|
||||
raw := `{"arguments":{"knowledge_id":"d1","issue_id":"i1","url":"w1"},"tool_ref":"mcpt_abc"}`
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Name: name, Arguments: raw}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, raw, calls[0].Function.Arguments)
|
||||
require.Empty(t, calls[0].UnresolvedHandles)
|
||||
schema := `{"input_schema":{"properties":{"knowledge_id":{"const":"doc://1"}}}}`
|
||||
require.Equal(
|
||||
t,
|
||||
schema,
|
||||
registry.ModelToolResultForTool(name, &types.ToolResult{Success: true, Output: schema}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCitationPolicyDoesNotSuppressRequestedResourcesOrBreakOutputFormat(t *testing.T) {
|
||||
disabled := NewRegistry(false).ProtocolPrompt()
|
||||
require.Contains(t, disabled, "Source citations are disabled")
|
||||
require.Contains(t, disabled, "a URL explicitly requested by the user")
|
||||
require.Contains(t, disabled, "downloadable deliverables")
|
||||
require.NotContains(t, disabled, "Do not output <ref>, <kb>, <web>, raw source URLs")
|
||||
enabled := NewRegistry(true).ProtocolPrompt()
|
||||
require.Contains(t, enabled, "do not break a required schema")
|
||||
}
|
||||
|
||||
func TestRegistryDecodesReadDocumentIDAgainstBothHandleTables(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument("doc-real")
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-real", KnowledgeID: "doc-real", KnowledgeBaseID: "kb-real"})
|
||||
registry.RegisterKnowledgeBase("kb-real")
|
||||
|
||||
for _, tc := range []struct{ name, tool, raw, want string }{
|
||||
{
|
||||
"read document by dN", "read_document",
|
||||
`{"id":"doc://1","offset":20}`, `{"id":"doc-real","offset":20}`,
|
||||
},
|
||||
{
|
||||
"read document by cN", "read_document",
|
||||
`{"id":"chunk://1","context":2}`, `{"id":"chunk-real","context":2}`,
|
||||
},
|
||||
{
|
||||
"read document query stays literal", "read_document",
|
||||
`{"id":"doc://1","query":"d1 c1"}`, `{"id":"doc-real","query":"d1 c1"}`,
|
||||
},
|
||||
{
|
||||
"read document query decodes handles to durable text", "read_document",
|
||||
`{"id":"doc://1","query":"doc://1 chunk://1"}`,
|
||||
`{"id":"doc-real","query":"academy://doc/doc-real academy://chunk/chunk-real"}`,
|
||||
},
|
||||
{
|
||||
"search knowledge KB", "search_knowledge",
|
||||
`{"query":"b1","knowledge_base_ids":["kb://1"]}`, `{"query":"b1","knowledge_base_ids":["kb-real"]}`,
|
||||
},
|
||||
{
|
||||
"list documents KB", "list_documents",
|
||||
`{"knowledge_base_id":"kb://1","keyword":"b1"}`, `{"knowledge_base_id":"kb-real","keyword":"b1"}`,
|
||||
},
|
||||
{
|
||||
"wiki search KBs", "wiki_search",
|
||||
`{"query":"topic","knowledge_base_ids":["kb://1"]}`, `{"query":"topic","knowledge_base_ids":["kb-real"]}`,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Name: tc.tool, Arguments: tc.raw}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, tc.want, calls[0].Function.Arguments)
|
||||
require.Equal(t, ArgumentResolutionResolved, calls[0].ArgumentResolution)
|
||||
})
|
||||
}
|
||||
|
||||
// A bare "id" on a tool without the read_document contract is not an ID
|
||||
// field: the handle becomes durable text instead of a bare ID.
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Name: "thinking", Arguments: `{"id":"doc://1"}`}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"id":"academy://doc/doc-real"}`, calls[0].Function.Arguments)
|
||||
|
||||
unknown := []types.LLMToolCall{{Function: types.FunctionCall{Name: "read_document", Arguments: `{"id":"doc://9"}`}}}
|
||||
registry.DecodeToolCalls(unknown)
|
||||
require.Equal(t, ArgumentResolutionUnresolved, unknown[0].ArgumentResolution)
|
||||
require.Equal(t, []string{"doc://9"}, unknown[0].UnresolvedHandles)
|
||||
}
|
||||
|
||||
func TestModelOutputRendersReadDocumentHeaderAndNavigation(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
paged := registry.ModelToolResultForTool("read_document", &types.ToolResult{Success: true, Data: map[string]any{
|
||||
"display_type": "knowledge_chunks_list",
|
||||
"knowledge_id": "doc-real",
|
||||
"knowledge_title": "Engine Manual",
|
||||
"total_chunks": 12,
|
||||
"fetched_chunks": 2,
|
||||
"offset": 4,
|
||||
"next_offset": 6,
|
||||
"document": map[string]interface{}{
|
||||
"knowledge_id": "doc-real", "title": "Engine Manual", "source": "File Upload", "file_type": "pdf",
|
||||
"parse_status": "completed", "chunk_count": 12, "description": "How the engine works",
|
||||
"metadata": map[string]interface{}{"region": "EU", "author": "Ada"},
|
||||
},
|
||||
"chunks": []map[string]interface{}{
|
||||
{"chunk_id": "chunk-4", "chunk_index": 4, "content": "four", "knowledge_base": "kb-real"},
|
||||
{"chunk_id": "chunk-5", "chunk_index": 5, "content": "five", "knowledge_base": "kb-real"},
|
||||
},
|
||||
}})
|
||||
require.Contains(t, paged, `<retrieval type="knowledge" mode="deep_read">`)
|
||||
require.Contains(t, paged, `<document id="doc://1" kb="kb://1" title="Engine Manual">`)
|
||||
require.Contains(t, paged, `<info source="File Upload" file_type="pdf" parse_status="completed" chunk_count="12">`)
|
||||
require.Contains(t, paged, `<description>How the engine works</description>`)
|
||||
require.Contains(t, paged, `<metadata>author: Ada; region: EU</metadata>`)
|
||||
require.Contains(t, paged, `<chunk id="chunk://1" index="4" view="full">`)
|
||||
require.Contains(t, paged, `<pagination next_offset="6" remaining="6" />`)
|
||||
require.NotContains(t, paged, "doc-real")
|
||||
|
||||
matched := registry.ModelToolResultForTool("read_document", &types.ToolResult{Success: true, Data: map[string]any{
|
||||
"display_type": "knowledge_chunks_list",
|
||||
"knowledge_id": "doc-real",
|
||||
"knowledge_title": "Engine Manual",
|
||||
"total_chunks": 12,
|
||||
"fetched_chunks": 3,
|
||||
"query": "psionic",
|
||||
"match_count": 1,
|
||||
"truncated": false,
|
||||
"document": map[string]any{"knowledge_id": "doc-real", "title": "Engine Manual", "chunk_count": 12},
|
||||
"chunks": []map[string]interface{}{
|
||||
{"chunk_id": "chunk-3", "chunk_index": 3, "content": "three", "role": "context_before"},
|
||||
{
|
||||
"chunk_id": "chunk-4", "chunk_index": 4, "content": "psionic four",
|
||||
"role": "match", "match_snippet": "... psionic ...",
|
||||
},
|
||||
{"chunk_id": "chunk-5", "chunk_index": 5, "content": "five", "role": "context_after"},
|
||||
},
|
||||
}})
|
||||
require.Contains(t, matched, `role="match"`)
|
||||
require.Contains(t, matched, `role="context_before"`)
|
||||
require.Contains(t, matched, `<match>... psionic ...</match>`)
|
||||
require.Contains(t, matched, `<matches query="psionic" count="1" />`)
|
||||
require.NotContains(t, matched, "<pagination")
|
||||
|
||||
empty := registry.ModelToolResultForTool("read_document", &types.ToolResult{Success: true, Data: map[string]any{
|
||||
"display_type": "knowledge_chunks_list",
|
||||
"knowledge_id": "doc-real",
|
||||
"knowledge_title": "Engine Manual",
|
||||
"total_chunks": 12,
|
||||
"fetched_chunks": 0,
|
||||
"query": "absent",
|
||||
"match_count": 0,
|
||||
"document": map[string]any{"knowledge_id": "doc-real", "title": "Engine Manual", "chunk_count": 12},
|
||||
"chunks": []map[string]interface{}{},
|
||||
}})
|
||||
require.Contains(t, empty, `<document id="doc://1" title="Engine Manual">`)
|
||||
require.Contains(t, empty, `<matches query="absent" count="0" />`)
|
||||
require.Contains(t, empty, "<hint>No chunk contains every word of the query.")
|
||||
}
|
||||
|
||||
func TestModelOutputRendersDocumentListWithPagination(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
out := registry.ModelToolResultForTool("list_documents", &types.ToolResult{Success: true, Data: map[string]any{
|
||||
"display_type": "document_info",
|
||||
"knowledge_base_id": "kb-real",
|
||||
"total_docs": int64(3),
|
||||
"page": 1,
|
||||
"page_size": 2,
|
||||
"next_page": 2,
|
||||
"documents": []map[string]interface{}{
|
||||
{
|
||||
"knowledge_id": "doc-a", "title": "Alpha", "file_type": "pdf", "parse_status": "completed",
|
||||
"updated_at": "2026-03-04T05:06:07Z", "description": "First",
|
||||
},
|
||||
{"knowledge_id": "doc-b", "title": "Beta", "file_type": "md", "parse_status": "completed"},
|
||||
},
|
||||
}})
|
||||
require.Contains(t, out, `<documents kb="kb://1" total="3" page="1" next_page="2">`)
|
||||
require.Contains(t, out,
|
||||
`<document id="doc://1" title="Alpha" file_type="pdf" parse_status="completed" updated_at="2026-03-04">`)
|
||||
require.Contains(t, out, `<description>First</description>`)
|
||||
require.Contains(t, out, `<document id="doc://2" title="Beta"`)
|
||||
require.NotContains(t, out, "doc-a")
|
||||
require.NotContains(t, out, "kb-real")
|
||||
}
|
||||
|
||||
func TestModelOutputReportsSearchModeAndFallbacks(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
row := map[string]interface{}{
|
||||
"chunk_id": "chunk-1", "knowledge_id": "doc-1", "knowledge_base_id": "kb-faq",
|
||||
"knowledge_title": "FAQ", "content": "reset the device",
|
||||
}
|
||||
keyword := registry.ModelToolResultForTool("search_knowledge", &types.ToolResult{
|
||||
Success: true, Data: map[string]any{
|
||||
"display_type": "search_results", "mode": "keyword", "results": []map[string]interface{}{row},
|
||||
},
|
||||
})
|
||||
require.Contains(t, keyword, `<retrieval type="knowledge" mode="keyword">`)
|
||||
|
||||
const faqReason = "FAQ bases are indexed for semantic search only"
|
||||
fallback := registry.ModelToolResultForTool("search_knowledge", &types.ToolResult{
|
||||
Success: true, Data: map[string]any{
|
||||
"display_type": "search_results", "mode": "semantic", "requested_mode": "keyword",
|
||||
"results": []map[string]interface{}{row},
|
||||
"mode_fallbacks": []map[string]interface{}{
|
||||
{"knowledge_base_id": "kb-faq", "mode": "semantic", "reason": faqReason},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.Contains(t, fallback, `<retrieval requested_mode="keyword" type="knowledge" mode="semantic">`)
|
||||
require.Contains(t, fallback,
|
||||
`<mode_fallback kb="kb://1" mode="semantic" reason="FAQ bases are indexed for semantic search only" />`)
|
||||
require.NotContains(t, fallback, "kb-faq")
|
||||
|
||||
legacy := registry.ModelToolResultForTool("knowledge_search", &types.ToolResult{Success: true, Data: map[string]any{
|
||||
"display_type": "search_results", "results": []map[string]interface{}{row},
|
||||
}})
|
||||
require.Contains(t, legacy, `mode="semantic"`, "legacy knowledge_search payloads were semantic")
|
||||
}
|
||||
|
||||
func TestDecodeResponseDropsSignatureWhenReasoningIsDecoded(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
// The handle only exists after the outbound half assigned it.
|
||||
registry.EncodeMessages([]chat.Message{{Role: "assistant", Content: ref}})
|
||||
|
||||
decoded := &types.ChatResponse{
|
||||
Content: "done",
|
||||
ReasoningContent: "read res://0001",
|
||||
ReasoningSignature: "anthropic-messages:sig",
|
||||
}
|
||||
registry.DecodeResponse(decoded)
|
||||
require.Equal(t, "read "+ref, decoded.ReasoningContent)
|
||||
require.Empty(t, decoded.ReasoningSignature, "decoded text is no longer what the provider signed")
|
||||
|
||||
untouched := &types.ChatResponse{
|
||||
Content: "done",
|
||||
ReasoningContent: "no handles here",
|
||||
ReasoningSignature: "anthropic-messages:sig",
|
||||
}
|
||||
registry.DecodeResponse(untouched)
|
||||
require.Equal(t, "anthropic-messages:sig", untouched.ReasoningSignature)
|
||||
}
|
||||
|
||||
func TestWebFetchReferencesStayBoundToSuppliedPages(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterWeb("https://example.com/one?a=1&b=2", "First")
|
||||
messages := []chat.Message{{
|
||||
Role: "tool", Name: "web_search",
|
||||
Content: `<retrieval><page id="url://1" title="First"></page></retrieval>`,
|
||||
}}
|
||||
encoded := registry.EncodeMessages(messages)
|
||||
require.Contains(t, encoded[0].Content, `url="https://example.com/one?a=1&b=2"`)
|
||||
require.Equal(t, encoded[0].Content, registry.EncodeMessages(encoded)[0].Content)
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "web_fetch",
|
||||
Arguments: `{"items":[{"url":"url://1"},{"url":"url://2"}]}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.Contains(t, calls[0].Function.Arguments, "https://example.com/one")
|
||||
require.Equal(t, []string{"url://2"}, calls[0].UnresolvedHandles)
|
||||
// Failed results for invented IDs do not allocate them or shift future IDs.
|
||||
failed := registry.ModelToolResultForTool("web_fetch", &types.ToolResult{Data: map[string]interface{}{
|
||||
"display_type": "web_fetch_results",
|
||||
"results": []map[string]interface{}{{
|
||||
"url": "url://2", "status": "failed", "error_code": "unknown_page_reference",
|
||||
}},
|
||||
}})
|
||||
require.Contains(t, failed, `requested_reference="url://2"`)
|
||||
require.NotContains(t, failed, `id="url://2"`)
|
||||
require.Equal(t, "url://2", registry.RegisterWeb("https://example.com/two", "Second"))
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// resources.go is the durable-resource half of the model-context registry:
|
||||
// it assigns request-local res://NNNN handles to stored resource references
|
||||
// and restores them before application code consumes model output.
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// storedRefRE also recognizes legacy physical references. New writes persist
|
||||
// resource:// handles, but old chunks and message history can still contain a
|
||||
// provider URL. Giving both forms the same request-local handle makes rollout
|
||||
// safe without a blocking full-table content rewrite.
|
||||
//
|
||||
// The final alternative handles wiki summary-page slugs (summary/<uuid>). They
|
||||
// are not storage handles, but they share the exact failure mode this registry
|
||||
// exists to prevent: a high-entropy identifier the model must reproduce
|
||||
// verbatim (inside [[slug|display]] links and as wiki-tool slug arguments).
|
||||
// Models routinely mangle the UUID by inserting or dropping hex digits, which
|
||||
// yields dead cross-links. Aliasing the slug to a low-entropy res:// token
|
||||
// removes the opportunity to mangle at the source; the token round-trips back
|
||||
// to the real slug on stream output and in decoded tool-call arguments before
|
||||
// anything is persisted. Entity slugs (entity/<readable-title>) are low-entropy
|
||||
// and semantically meaningful, so they are deliberately left untouched.
|
||||
var storedRefRE = regexp.MustCompile(
|
||||
`resource://[0-9A-Za-z_-]{22}|` +
|
||||
`(?:storage://[0-9A-Za-z_-]+/)?` +
|
||||
`(?:local|minio|cos|tos|s3|oss|ks3|obs)://[^\s)\]>"']+|` +
|
||||
`summary/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`,
|
||||
)
|
||||
|
||||
// resourceHandleShapeRE matches the handle syntax produced by EncodeText. It
|
||||
// is used to spot handle-shaped tokens the registry cannot map back — either a
|
||||
// hallucinated reference or a coincidental collision — and by the stream-side
|
||||
// orphan filter.
|
||||
var resourceHandleShapeRE = regexp.MustCompile(`res://\d+`)
|
||||
|
||||
// resourceRegistry assigns low-entropy, request-local handles to stable resource
|
||||
// handles. It is safe to reuse across all rounds of one Agent execution.
|
||||
type resourceRegistry struct {
|
||||
table *handleTable[struct{}]
|
||||
}
|
||||
|
||||
// newResourceRegistry creates an empty request-local handle registry.
|
||||
func newResourceRegistry() *resourceRegistry {
|
||||
// A URL-shaped handle (scheme://digits) keeps the token low-entropy while
|
||||
// looking enough like a link that the model reuses it verbatim inside
|
||||
// Markdown image/link syntax instead of reasoning about or rewriting it.
|
||||
return &resourceRegistry{table: newHandleTable[struct{}]("res://", 4, 1)}
|
||||
}
|
||||
|
||||
// EncodeText replaces stored references with compact, stable handles.
|
||||
func (r *resourceRegistry) EncodeText(value string) string {
|
||||
if r == nil || value == "" {
|
||||
return value
|
||||
}
|
||||
return storedRefRE.ReplaceAllStringFunc(value, func(ref string) string {
|
||||
return r.table.register(ref, ref, struct{}{}, nil)
|
||||
})
|
||||
}
|
||||
|
||||
// DecodeText restores every handle currently known to the registry. Handles are
|
||||
// replaced longest-first with no word-boundary check — this plain substring
|
||||
// behavior is load-bearing for handles adjacent to punctuation in Markdown.
|
||||
func (r *resourceRegistry) DecodeText(value string) string {
|
||||
if r == nil || value == "" {
|
||||
return value
|
||||
}
|
||||
pairs := r.table.pairs()
|
||||
sort.SliceStable(pairs, func(i, j int) bool { return len(pairs[i].handle) > len(pairs[j].handle) })
|
||||
for _, item := range pairs {
|
||||
value = strings.ReplaceAll(value, item.handle, item.value)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// StripOrphanHandles removes handle-shaped tokens after all known handles have
|
||||
// been restored. Use this only on model output; tool arguments must retain
|
||||
// unknown handles long enough for modelcontext to reject the call.
|
||||
func (r *resourceRegistry) StripOrphanHandles(value string) string {
|
||||
if value == "" {
|
||||
return value
|
||||
}
|
||||
return resourceHandleShapeRE.ReplaceAllString(value, "")
|
||||
}
|
||||
|
||||
// EncodeMessages returns a copied message slice with textual references
|
||||
// compacted. Binary/image content fields are intentionally left untouched.
|
||||
func (r *resourceRegistry) EncodeMessages(messages []chat.Message) []chat.Message {
|
||||
if r == nil || len(messages) == 0 {
|
||||
return messages
|
||||
}
|
||||
encoded := make([]chat.Message, len(messages))
|
||||
copy(encoded, messages)
|
||||
for i := range encoded {
|
||||
encoded[i].Content = r.EncodeText(encoded[i].Content)
|
||||
reasoningBefore := encoded[i].ReasoningContent
|
||||
encoded[i].ReasoningContent = r.EncodeText(encoded[i].ReasoningContent)
|
||||
dropStaleReasoningSignature(&encoded[i], reasoningBefore)
|
||||
if len(encoded[i].MultiContent) > 0 {
|
||||
encoded[i].MultiContent = append([]chat.MessageContentPart(nil), encoded[i].MultiContent...)
|
||||
for j := range encoded[i].MultiContent {
|
||||
encoded[i].MultiContent[j].Text = r.EncodeText(encoded[i].MultiContent[j].Text)
|
||||
}
|
||||
}
|
||||
if len(encoded[i].ToolCalls) > 0 {
|
||||
encoded[i].ToolCalls = append([]chat.ToolCall(nil), encoded[i].ToolCalls...)
|
||||
for j := range encoded[i].ToolCalls {
|
||||
encoded[i].ToolCalls[j].Function.Arguments = r.EncodeText(encoded[i].ToolCalls[j].Function.Arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
|
||||
// DecodeToolCalls restores handles in tool-call JSON arguments.
|
||||
func (r *resourceRegistry) DecodeToolCalls(toolCalls []types.LLMToolCall) {
|
||||
for i := range toolCalls {
|
||||
toolCalls[i].Function.Arguments = r.DecodeText(toolCalls[i].Function.Arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// OrphanHandles returns the distinct handle-shaped tokens in an already-decoded
|
||||
// string that the registry cannot resolve. A non-empty result means the model
|
||||
// emitted a reference no real resource backs (hallucination) or the user text
|
||||
// happened to collide with the handle syntax. Callers should log/observe these
|
||||
// rather than surfacing them to end users as broken links.
|
||||
func (r *resourceRegistry) OrphanHandles(decoded string) []string {
|
||||
if decoded == "" {
|
||||
return nil
|
||||
}
|
||||
var orphans []string
|
||||
seen := make(map[string]struct{})
|
||||
for _, match := range resourceHandleShapeRE.FindAllString(decoded, -1) {
|
||||
if r != nil && r.table.has(match) {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[match]; dup {
|
||||
continue
|
||||
}
|
||||
seen[match] = struct{}{}
|
||||
orphans = append(orphans, match)
|
||||
}
|
||||
return orphans
|
||||
}
|
||||
|
||||
func (r *resourceRegistry) handles() []string {
|
||||
pairs := r.table.pairs()
|
||||
handles := make([]string, 0, len(pairs))
|
||||
for _, item := range pairs {
|
||||
handles = append(handles, item.handle)
|
||||
}
|
||||
return handles
|
||||
}
|
||||
|
||||
// dropStaleReasoningSignature clears a reasoning signature this registry just
|
||||
// invalidated by rewriting the text it covers.
|
||||
//
|
||||
// It applies only to Anthropic. Claude signs the exact thinking text, so a
|
||||
// block replayed with rewritten text and its original signature fails
|
||||
// verification. Gemini is deliberately excluded: its thought signatures ride
|
||||
// on the answer text and on each tool call's metadata, neither of which this
|
||||
// registry touches, so dropping one there would throw away a signature
|
||||
// Gemini 3 requires back.
|
||||
//
|
||||
// This is a safety net for assistant turns stored before
|
||||
// anthropicmessages.MetadataThinkingBlocks existed. Current turns replay from
|
||||
// that metadata, which carries the signed bytes verbatim and is opaque to
|
||||
// every rewrite here, so they do not depend on this at all.
|
||||
func dropStaleReasoningSignature(msg *chat.Message, before string) {
|
||||
if msg.ReasoningContent == before {
|
||||
return
|
||||
}
|
||||
if api.SignatureFor(api.APIAnthropicMessages, msg.ReasoningSignature) == "" {
|
||||
return
|
||||
}
|
||||
msg.ReasoningSignature = ""
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRegistryRoundTripAndDeduplicate(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
encoded := r.EncodeText(" and " + ref)
|
||||
require.Equal(t, " and res://0001", encoded)
|
||||
require.Equal(t, " and "+ref, r.DecodeText(encoded))
|
||||
}
|
||||
|
||||
func TestRegistryAliasesLegacyPhysicalReferencesDuringRollout(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "storage://c0d93536-702c-4977-aa5e-fe670073c3cb/local://10000/exports/image.png"
|
||||
encoded := r.EncodeText("")
|
||||
require.Equal(t, "", encoded)
|
||||
require.Equal(t, "", r.DecodeText(encoded))
|
||||
}
|
||||
|
||||
func TestRegistryAliasesWikiSummarySlug(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
slug := "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e"
|
||||
// Inside a [[slug|display]] link the model must copy verbatim.
|
||||
encoded := r.EncodeText("see [[" + slug + "|Foo.md - Summary]]")
|
||||
require.Equal(t, "see [[res://0001|Foo.md - Summary]]", encoded)
|
||||
require.Equal(t, "see [["+slug+"|Foo.md - Summary]]", r.DecodeText(encoded))
|
||||
|
||||
// The same slug as a tool-call argument value resolves to one handle.
|
||||
require.Equal(t, "res://0001", r.EncodeText(slug))
|
||||
}
|
||||
|
||||
func TestRegistryLeavesEntitySlugUntouched(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
// Entity slugs are low-entropy and semantically meaningful; not aliased.
|
||||
entity := "[[entity/academy-error-log|Academy 试错记录]]"
|
||||
require.Equal(t, entity, r.EncodeText(entity))
|
||||
}
|
||||
|
||||
func TestRegistryEncodesMessageCopies(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
original := []chat.Message{{Role: "tool", Content: ref}}
|
||||
encoded := r.EncodeMessages(original)
|
||||
require.Equal(t, ref, original[0].Content)
|
||||
require.Equal(t, "res://0001", encoded[0].Content)
|
||||
}
|
||||
|
||||
func TestStreamDecoderRestoresSplitAlias(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
require.Equal(t, "res://0001", r.EncodeText(ref))
|
||||
d := newResourceStreamDecoder(r)
|
||||
require.Equal(t, "before ", d.Feed("before res://0"))
|
||||
require.Equal(t, ref+" afte", d.Feed("001 after"))
|
||||
require.Equal(t, "r", d.Flush())
|
||||
}
|
||||
|
||||
func TestStreamDecoderRestoresAliasSplitBeforeScheme(t *testing.T) {
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
r := newResourceRegistry()
|
||||
require.Equal(t, "res://0001", r.EncodeText(ref))
|
||||
d := newResourceStreamDecoder(r)
|
||||
require.Equal(t, "see ", d.Feed("see re"))
|
||||
require.Equal(t, ref, d.Feed("s://0001"))
|
||||
require.Empty(t, d.Flush())
|
||||
}
|
||||
|
||||
func TestOrphanAliasesReportsUnresolvableTokens(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
require.Equal(t, "res://0001", r.EncodeText(ref))
|
||||
|
||||
// Known handle resolves and leaves no orphan once decoded.
|
||||
require.Nil(t, r.OrphanHandles(r.DecodeText("see res://0001")))
|
||||
|
||||
// A reference the registry never assigned is reported (deduplicated).
|
||||
require.Equal(t, []string{"res://0099"}, r.OrphanHandles("look at res://0099 and res://0099"))
|
||||
}
|
||||
|
||||
func TestStripOrphanAliasesRemovesIncompleteNumericHandle(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
require.Equal(t, "broken ", r.StripOrphanHandles("broken res://1"))
|
||||
}
|
||||
|
||||
func TestOrphanAliasesNilRegistry(t *testing.T) {
|
||||
var r *resourceRegistry
|
||||
require.Equal(t, []string{"res://0001"}, r.OrphanHandles("res://0001"))
|
||||
}
|
||||
|
||||
// Aliases belong to one execution, and never follow mutable file names.
|
||||
func TestResourceVersionsStayImmutableAcrossRounds(t *testing.T) {
|
||||
old := "resource://dHZ_fFslfs0GgJGaJZGjGA"
|
||||
latest := "resource://4N1nAo-FZZoDEExDQz2yoA"
|
||||
r := newResourceRegistry()
|
||||
r.EncodeText("resource://aaaaaaaaaaaaaaaaaaaaaa resource://bbbbbbbbbbbbbbbbbbbbbb")
|
||||
require.Equal(t, "res://0003", r.EncodeText(old))
|
||||
require.Equal(t, "res://0004", r.EncodeText(latest))
|
||||
require.Equal(t, old, r.DecodeText("res://0003"))
|
||||
require.Equal(t, latest, r.DecodeText("res://0004"))
|
||||
require.Equal(t, "res://0003", r.EncodeText(old))
|
||||
nextRequest := newResourceRegistry()
|
||||
require.Equal(t, "res://0001", nextRequest.EncodeText(latest))
|
||||
require.Equal(t, old, r.DecodeText("res://0003"))
|
||||
}
|
||||
|
||||
func TestEncodeMessagesDropsSignatureOnlyWhenReasoningIsRewritten(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
messages := []chat.Message{
|
||||
{
|
||||
Role: "assistant",
|
||||
Content: "answer",
|
||||
ReasoningContent: "I looked at " + ref,
|
||||
ReasoningSignature: "anthropic-messages:sig-1",
|
||||
},
|
||||
{
|
||||
Role: "assistant",
|
||||
Content: "see " + ref,
|
||||
ReasoningContent: "plain thought with nothing to encode",
|
||||
ReasoningSignature: "anthropic-messages:sig-2",
|
||||
},
|
||||
}
|
||||
|
||||
encoded := r.EncodeMessages(messages)
|
||||
|
||||
// The first message's thinking text was rewritten, so its signature no
|
||||
// longer covers what would go on the wire.
|
||||
require.Equal(t, "I looked at res://0001", encoded[0].ReasoningContent)
|
||||
require.Empty(t, encoded[0].ReasoningSignature)
|
||||
// The second one's thinking text is untouched (only Content changed), so
|
||||
// the block stays replayable.
|
||||
require.Equal(t, "plain thought with nothing to encode", encoded[1].ReasoningContent)
|
||||
require.Equal(t, "anthropic-messages:sig-2", encoded[1].ReasoningSignature)
|
||||
// Callers' own slice is never mutated.
|
||||
require.Equal(t, "anthropic-messages:sig-1", messages[0].ReasoningSignature)
|
||||
}
|
||||
|
||||
func TestEncodeMessagesKeepsGeminiSignatureWhenReasoningIsRewritten(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
messages := []chat.Message{{
|
||||
Role: "assistant",
|
||||
Content: "answer",
|
||||
ReasoningContent: "I looked at " + ref,
|
||||
// Gemini replays this signature on the answer text and on each tool
|
||||
// call's own metadata; it never replays the reasoning text, so a
|
||||
// rewrite here does not invalidate it.
|
||||
ReasoningSignature: "google-generative-ai:thought-sig",
|
||||
}}
|
||||
|
||||
encoded := r.EncodeMessages(messages)
|
||||
|
||||
require.Equal(t, "I looked at res://0001", encoded[0].ReasoningContent)
|
||||
require.Equal(t, "google-generative-ai:thought-sig", encoded[0].ReasoningSignature)
|
||||
}
|
||||
|
||||
func TestDecodeResponseKeepsGeminiSignature(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
registry.EncodeMessages([]chat.Message{{Role: "assistant", Content: ref}})
|
||||
|
||||
decoded := &types.ChatResponse{
|
||||
Content: "done",
|
||||
ReasoningContent: "read res://0001",
|
||||
ReasoningSignature: "google-generative-ai:thought-sig",
|
||||
}
|
||||
registry.DecodeResponse(decoded)
|
||||
require.Equal(t, "read "+ref, decoded.ReasoningContent)
|
||||
require.Equal(t, "google-generative-ai:thought-sig", decoded.ReasoningSignature)
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package modelcontext
|
||||
|
||||
// source_text.go owns the textual syntax of source handles. Handles are
|
||||
// scheme-shaped (kb://N, doc://N, chunk://N, url://N) so they cannot collide
|
||||
// with prose such as "B1" or "W6"; that is what makes it safe to decode them
|
||||
// in any text the model writes — reasoning, answers and free-text tool
|
||||
// arguments alike — instead of only in a fixed list of ID fields.
|
||||
//
|
||||
// Durable text forms are what a decoded handle becomes outside an ID field:
|
||||
// a web page becomes its URL, and workspace objects become academy:// URIs
|
||||
// that a later request encodes back into its own handles.
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
chunkHandlePrefix = "chunk://"
|
||||
docHandlePrefix = "doc://"
|
||||
kbHandlePrefix = "kb://"
|
||||
webHandlePrefix = "url://"
|
||||
|
||||
durableURIScheme = "academy://"
|
||||
)
|
||||
|
||||
const (
|
||||
durableKindKnowledgeBase = "kb"
|
||||
durableKindDocument = "doc"
|
||||
durableKindChunk = "chunk"
|
||||
)
|
||||
|
||||
var sourceHandlePrefixes = []string{chunkHandlePrefix, docHandlePrefix, kbHandlePrefix, webHandlePrefix}
|
||||
|
||||
// sourceHandleTokenRE finds scheme-shaped tokens. The token body is matched
|
||||
// greedily over identifier characters and validated in code, so "url://3a"
|
||||
// is not mistaken for url://3 followed by text.
|
||||
var sourceHandleTokenRE = regexp.MustCompile(`(?i)\b(?:chunk|doc|kb|url)://[0-9A-Za-z_\-]*`)
|
||||
|
||||
var sourceHandleNumberRE = regexp.MustCompile(`^[1-9][0-9]*$`)
|
||||
|
||||
// legacySourceHandleRE is the pre-scheme cN/dN/bN/wN syntax. It is accepted
|
||||
// only as the whole value of a declared ID field, where it cannot be prose.
|
||||
var legacySourceHandleRE = regexp.MustCompile(`(?i)^([cdbw])([1-9][0-9]*)$`)
|
||||
|
||||
var legacyHandlePrefixes = map[byte]string{
|
||||
'c': chunkHandlePrefix, 'd': docHandlePrefix, 'b': kbHandlePrefix, 'w': webHandlePrefix,
|
||||
}
|
||||
|
||||
var durableURIRE = regexp.MustCompile(`(?i)academy://(kb|doc|chunk)/([0-9A-Za-z][0-9A-Za-z_\-]*)`)
|
||||
|
||||
// parseSourceHandleToken returns the canonical handle for one scheme-shaped
|
||||
// token, or "" when the token body is not a positive integer.
|
||||
func parseSourceHandleToken(token string) string {
|
||||
lower := strings.ToLower(token)
|
||||
for _, prefix := range sourceHandlePrefixes {
|
||||
if strings.HasPrefix(lower, prefix) && sourceHandleNumberRE.MatchString(lower[len(prefix):]) {
|
||||
return lower
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// canonicalSourceHandle returns the canonical handle when value is exactly
|
||||
// one source handle in the current or the legacy syntax.
|
||||
func canonicalSourceHandle(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if handle := parseSourceHandleToken(value); handle != "" {
|
||||
return handle
|
||||
}
|
||||
if match := legacySourceHandleRE.FindStringSubmatch(value); len(match) == 3 {
|
||||
return legacyHandlePrefixes[strings.ToLower(match[1])[0]] + match[2]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func isSourceHandleShaped(value string) bool {
|
||||
return canonicalSourceHandle(value) != ""
|
||||
}
|
||||
|
||||
// durableURI renders a workspace object as its durable text form.
|
||||
func durableURI(kind, id string) string {
|
||||
return durableURIScheme + kind + "/" + id
|
||||
}
|
||||
|
||||
// parseDurableURI returns the kind and ID when value is exactly one
|
||||
// academy:// URI.
|
||||
func parseDurableURI(value string) (kind, id string, ok bool) {
|
||||
value = strings.TrimSpace(value)
|
||||
match := durableURIRE.FindStringSubmatch(value)
|
||||
if len(match) != 3 || match[0] != value {
|
||||
return "", "", false
|
||||
}
|
||||
return strings.ToLower(match[1]), match[2], true
|
||||
}
|
||||
|
||||
// resolveSourceHandle returns the durable value behind a handle together with
|
||||
// the table it lives in.
|
||||
func (r *sourceRegistry) resolveSourceHandle(handle string) (prefix, durable string, chunk ChunkReference, ok bool) {
|
||||
if r == nil {
|
||||
return "", "", ChunkReference{}, false
|
||||
}
|
||||
handle = canonicalSourceHandle(handle)
|
||||
switch {
|
||||
case strings.HasPrefix(handle, chunkHandlePrefix):
|
||||
durable, chunk, ok = r.chunks.resolve(handle)
|
||||
return chunkHandlePrefix, durable, chunk, ok
|
||||
case strings.HasPrefix(handle, docHandlePrefix):
|
||||
durable, _, ok = r.docs.resolve(handle)
|
||||
return docHandlePrefix, durable, ChunkReference{}, ok
|
||||
case strings.HasPrefix(handle, kbHandlePrefix):
|
||||
durable, _, ok = r.kbs.resolve(handle)
|
||||
return kbHandlePrefix, durable, ChunkReference{}, ok
|
||||
case strings.HasPrefix(handle, webHandlePrefix):
|
||||
durable, _, ok = r.webs.resolve(handle)
|
||||
return webHandlePrefix, durable, ChunkReference{}, ok
|
||||
}
|
||||
return "", "", ChunkReference{}, false
|
||||
}
|
||||
|
||||
// durableTextForHandle is the form a handle takes in stored or forwarded
|
||||
// text: a URL for web pages, a academy:// URI for workspace objects.
|
||||
func (r *sourceRegistry) durableTextForHandle(handle string) string {
|
||||
prefix, durable, _, ok := r.resolveSourceHandle(handle)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
switch prefix {
|
||||
case chunkHandlePrefix:
|
||||
return durableURI(durableKindChunk, durable)
|
||||
case docHandlePrefix:
|
||||
return durableURI(durableKindDocument, durable)
|
||||
case kbHandlePrefix:
|
||||
return durableURI(durableKindKnowledgeBase, durable)
|
||||
default:
|
||||
return durable
|
||||
}
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) rewriteHandleTokens(text string, rewrite func(token, handle string) string) string {
|
||||
if text == "" || !strings.Contains(text, "://") {
|
||||
return text
|
||||
}
|
||||
return sourceHandleTokenRE.ReplaceAllStringFunc(text, func(token string) string {
|
||||
handle := parseSourceHandleToken(token)
|
||||
if handle == "" {
|
||||
return token
|
||||
}
|
||||
return rewrite(token, handle)
|
||||
})
|
||||
}
|
||||
|
||||
// DecodeDurableText restores every registered handle in free text to its
|
||||
// durable text form. Unknown handles are left for the caller to reject.
|
||||
func (r *sourceRegistry) DecodeDurableText(text string) string {
|
||||
if r == nil {
|
||||
return text
|
||||
}
|
||||
return r.rewriteHandleTokens(text, func(token, handle string) string {
|
||||
if durable := r.durableTextForHandle(handle); durable != "" {
|
||||
return durable
|
||||
}
|
||||
return token
|
||||
})
|
||||
}
|
||||
|
||||
// DecodeBareText restores registered handles to their raw durable values.
|
||||
// Structured expressions such as SQL need the bare ID, not a URI.
|
||||
func (r *sourceRegistry) DecodeBareText(text string) string {
|
||||
if r == nil {
|
||||
return text
|
||||
}
|
||||
return r.rewriteHandleTokens(text, func(token, handle string) string {
|
||||
if durable := r.durableForHandle(handle); durable != "" {
|
||||
return durable
|
||||
}
|
||||
return token
|
||||
})
|
||||
}
|
||||
|
||||
// UnresolvedTextHandles reports handle-shaped tokens that no table backs.
|
||||
func (r *sourceRegistry) UnresolvedTextHandles(text string) []string {
|
||||
var unresolved []string
|
||||
r.rewriteHandleTokens(text, func(token, handle string) string {
|
||||
if r == nil || r.durableForHandle(handle) == "" {
|
||||
unresolved = append(unresolved, handle)
|
||||
}
|
||||
return token
|
||||
})
|
||||
return unresolved
|
||||
}
|
||||
|
||||
// EncodeDurableURIs replaces academy:// URIs with this request's handles.
|
||||
// Registration only makes the object addressable; tools still authorize
|
||||
// every durable ID they receive.
|
||||
func (r *sourceRegistry) EncodeDurableURIs(text string) string {
|
||||
if r == nil || text == "" || !strings.Contains(strings.ToLower(text), durableURIScheme) {
|
||||
return text
|
||||
}
|
||||
return durableURIRE.ReplaceAllStringFunc(text, func(uri string) string {
|
||||
match := durableURIRE.FindStringSubmatch(uri)
|
||||
if handle := r.registerDurable(strings.ToLower(match[1]), match[2]); handle != "" {
|
||||
return handle
|
||||
}
|
||||
return uri
|
||||
})
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) registerDurable(kind, id string) string {
|
||||
switch kind {
|
||||
case durableKindKnowledgeBase:
|
||||
return r.RegisterKnowledgeBase(id)
|
||||
case durableKindDocument:
|
||||
return r.RegisterDocument(id)
|
||||
case durableKindChunk:
|
||||
return r.registerChunk(ChunkReference{ChunkID: id}, false)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ExpandHandleText renders handles in user-visible text. Workspace objects
|
||||
// become academy:// links the client resolves, web pages become their URL,
|
||||
// and a chunk becomes a citation when it is current evidence, or its
|
||||
// document otherwise. Unknown handles are dropped, like unknown <ref/> tags.
|
||||
func (r *sourceRegistry) ExpandHandleText(text string) string {
|
||||
if r == nil {
|
||||
return text
|
||||
}
|
||||
return r.rewriteHandleTokens(text, func(_, handle string) string {
|
||||
prefix, _, chunk, ok := r.resolveSourceHandle(handle)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if prefix != chunkHandlePrefix {
|
||||
return r.durableTextForHandle(handle)
|
||||
}
|
||||
if tag := r.citationTag(handle); tag != "" {
|
||||
return tag
|
||||
}
|
||||
if chunk.KnowledgeID != "" {
|
||||
return durableURI(durableKindDocument, chunk.KnowledgeID)
|
||||
}
|
||||
return ""
|
||||
})
|
||||
}
|
||||
|
||||
// sourceHandleHoldLen is the trailing byte run a stream must withhold because
|
||||
// the next provider chunk could still complete it into a handle.
|
||||
func sourceHandleHoldLen(combined string) int {
|
||||
lower := strings.ToLower(combined)
|
||||
hold := 0
|
||||
for _, prefix := range sourceHandlePrefixes {
|
||||
if idx := strings.LastIndex(lower, prefix); idx >= 0 && atTokenBoundary(lower, idx) {
|
||||
if rest := lower[idx+len(prefix):]; rest == "" || allDigits(rest) {
|
||||
hold = max(hold, len(lower)-idx)
|
||||
}
|
||||
}
|
||||
for n := 1; n < len(prefix); n++ {
|
||||
start := len(lower) - n
|
||||
if start >= 0 && strings.HasSuffix(lower, prefix[:n]) && atTokenBoundary(lower, start) {
|
||||
hold = max(hold, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
return hold
|
||||
}
|
||||
|
||||
func atTokenBoundary(text string, idx int) bool {
|
||||
if idx == 0 {
|
||||
return true
|
||||
}
|
||||
previous := text[idx-1]
|
||||
isIdentifierByte := previous >= 'a' && previous <= 'z' || previous >= 'A' && previous <= 'Z' ||
|
||||
previous >= '0' && previous <= '9' || previous == '_'
|
||||
return !isIdentifierByte
|
||||
}
|
||||
|
||||
// sourceHandleStreamDecoder expands handles split across provider chunks.
|
||||
type sourceHandleStreamDecoder struct {
|
||||
hold streamHold
|
||||
}
|
||||
|
||||
func newSourceHandleStreamDecoder(registry *sourceRegistry) *sourceHandleStreamDecoder {
|
||||
return &sourceHandleStreamDecoder{hold: streamHold{
|
||||
holdLen: sourceHandleHoldLen,
|
||||
emit: registry.ExpandHandleText,
|
||||
flush: registry.ExpandHandleText,
|
||||
}}
|
||||
}
|
||||
|
||||
func (d *sourceHandleStreamDecoder) Feed(chunk string) string {
|
||||
if d == nil {
|
||||
return chunk
|
||||
}
|
||||
return d.hold.Feed(chunk)
|
||||
}
|
||||
|
||||
func (d *sourceHandleStreamDecoder) Flush() string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
return d.hold.Flush()
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestOutputTextExpandsHandlesAnywhereWithoutTouchingProse(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterKnowledgeBase("kb-real")
|
||||
registry.RegisterDocument("doc-real")
|
||||
registry.RegisterWeb("https://example.com/hot", "Hot list")
|
||||
registry.RegisterContextChunk(ChunkReference{ChunkID: "chunk-nav", KnowledgeID: "doc-real"})
|
||||
|
||||
got := registry.DecodeOutputText(
|
||||
"维生素 B1 与 W6 型号; 入库 kb://1, 文档 doc://1, 来源 [榜单](url://1), 片段 chunk://1, 未知 kb://9.")
|
||||
require.Equal(t,
|
||||
"维生素 B1 与 W6 型号; 入库 academy://kb/kb-real, 文档 academy://doc/doc-real, "+
|
||||
"来源 [榜单](https://example.com/hot), 片段 academy://doc/doc-real, 未知 .",
|
||||
got)
|
||||
}
|
||||
|
||||
func TestOutputTextRendersCurrentEvidenceChunkAsCitation(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterChunk(ChunkReference{
|
||||
ChunkID: "chunk-real", KnowledgeID: "doc-real", KnowledgeBaseID: "kb-real", DocumentTitle: "Doc",
|
||||
})
|
||||
require.Equal(t,
|
||||
`见 <kb doc="Doc" chunk_id="chunk-real" kb_id="kb-real" />`,
|
||||
registry.DecodeOutputText("见 chunk://1"))
|
||||
}
|
||||
|
||||
func TestReasoningIsDecodedLikeContent(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterWeb("https://example.com/a", "")
|
||||
response := &types.ChatResponse{Content: "url://1", ReasoningContent: "fetch url://1 first"}
|
||||
registry.DecodeResponse(response)
|
||||
require.Equal(t, "https://example.com/a", response.Content)
|
||||
require.Equal(t, "fetch https://example.com/a first", response.ReasoningContent)
|
||||
}
|
||||
|
||||
func TestStreamDecoderExpandsHandlesSplitAtAnyByte(t *testing.T) {
|
||||
registry := NewRegistry(false)
|
||||
registry.RegisterKnowledgeBase("kb-real")
|
||||
registry.RegisterWeb("https://example.com/a", "")
|
||||
text := "undo: kb://1 then url://1; doc text ends with k"
|
||||
want := "undo: academy://kb/kb-real then https://example.com/a; doc text ends with k"
|
||||
for split := 1; split < len(text); split++ {
|
||||
decoder := registry.StreamDecoder()
|
||||
got := decoder.Feed(text[:split]) + decoder.Feed(text[split:]) + decoder.Flush()
|
||||
require.Equal(t, want, got, "split at %d", split)
|
||||
}
|
||||
decoder := registry.StreamDecoder()
|
||||
var got string
|
||||
for _, char := range text {
|
||||
got += decoder.Feed(string(char))
|
||||
}
|
||||
require.Equal(t, want, got+decoder.Flush())
|
||||
|
||||
// A stream that ends inside a scheme prefix keeps the ordinary text.
|
||||
decoder = registry.StreamDecoder()
|
||||
require.Equal(t, "see kb:/", decoder.Feed("see kb:/")+decoder.Flush())
|
||||
}
|
||||
|
||||
func TestHandleTokenMustBeAWholeNumber(t *testing.T) {
|
||||
registry := NewRegistry(false)
|
||||
registry.RegisterWeb("https://example.com/a", "")
|
||||
// Saved web pages use web://<resource handle>; url://1a is not url://1.
|
||||
require.Equal(t, "web://1abc url://1a", registry.DecodeOutputText("web://1abc url://1a"))
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "read_file", Arguments: `{"path":"web://1abc"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.Empty(t, calls[0].UnresolvedHandles)
|
||||
require.JSONEq(t, `{"path":"web://1abc"}`, calls[0].Function.Arguments)
|
||||
}
|
||||
|
||||
// An instruction written in one request keeps pointing at the same sources
|
||||
// when a later request reads it, even though both number handles from 1.
|
||||
func TestSavedInstructionRoundTripsAcrossRequests(t *testing.T) {
|
||||
writer := NewRegistry(true)
|
||||
writer.RegisterWeb("https://example.com/other", "")
|
||||
writer.RegisterWeb("https://dataxapi.com/zh/tools/hot-search/zhihu.md", "Zhihu")
|
||||
writer.RegisterKnowledgeBase("kb-other")
|
||||
writer.RegisterKnowledgeBase("kb-archive")
|
||||
|
||||
modelArgs := `{"operation":"automation.create","params":{"name":"Zhihu",` +
|
||||
`"instruction":"抓取 url://2 并用 knowledge.create_manual 写入 kb://2,参数 knowledge_base_id: kb://2"}}`
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{Name: "run_operation", Arguments: modelArgs}}}
|
||||
writer.DecodeToolCalls(calls)
|
||||
require.Empty(t, calls[0].UnresolvedHandles)
|
||||
var stored struct {
|
||||
Params struct {
|
||||
Instruction string `json:"instruction"`
|
||||
} `json:"params"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(calls[0].Function.Arguments), &stored))
|
||||
instruction := stored.Params.Instruction
|
||||
require.Equal(t,
|
||||
"抓取 https://dataxapi.com/zh/tools/hot-search/zhihu.md 并用 knowledge.create_manual 写入 "+
|
||||
"academy://kb/kb-archive,参数 knowledge_base_id: academy://kb/kb-archive",
|
||||
instruction)
|
||||
|
||||
// The echo of the saved instruction reads back in the writer's own handles,
|
||||
// so copying it into an update is lossless.
|
||||
echo := writer.ModelToolResultForTool("run_operation", &types.ToolResult{
|
||||
Success: true, Output: `{"instruction":` + mustJSON(t, instruction) + `}`,
|
||||
})
|
||||
require.Contains(t, echo, "抓取 url://2 并用 knowledge.create_manual 写入 kb://2,参数 knowledge_base_id: kb://2")
|
||||
|
||||
// A scheduled run is a fresh request that renders the instruction as the
|
||||
// user turn and gives it its own handle.
|
||||
runner := NewRegistry(true)
|
||||
encoded := runner.EncodeMessages([]chat.Message{{Role: "user", Content: instruction}})
|
||||
require.Contains(t, encoded[0].Content, "写入 kb://1,参数 knowledge_base_id: kb://1")
|
||||
runCalls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "run_operation",
|
||||
Arguments: `{"operation":"knowledge.create_manual","params":{"knowledge_base_id":"kb://1"}}`,
|
||||
}}}
|
||||
runner.DecodeToolCalls(runCalls)
|
||||
require.JSONEq(t,
|
||||
`{"operation":"knowledge.create_manual","params":{"knowledge_base_id":"kb-archive"}}`,
|
||||
runCalls[0].Function.Arguments)
|
||||
}
|
||||
|
||||
func TestDelegatedTaskCarriesDurableReferencesToTheChild(t *testing.T) {
|
||||
parent := NewRegistry(true)
|
||||
parent.RegisterKnowledgeBase("kb-a")
|
||||
parent.RegisterDocument("doc-a")
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "spawn_agent", Arguments: `{"task":"Summarize doc://1 from kb://1"}`,
|
||||
}}}
|
||||
parent.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"task":"Summarize academy://doc/doc-a from academy://kb/kb-a"}`, calls[0].Function.Arguments)
|
||||
|
||||
child := NewRegistry(true)
|
||||
child.RegisterKnowledgeBase("kb-child-bound")
|
||||
encoded := child.EncodeMessages([]chat.Message{{
|
||||
Role: "user", Content: "Summarize academy://doc/doc-a from academy://kb/kb-a",
|
||||
}})
|
||||
require.Equal(t, "Summarize doc://1 from kb://2", encoded[0].Content)
|
||||
}
|
||||
|
||||
func TestUnknownHandleInFreeTextFailsClosed(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "spawn_agent", Arguments: `{"task":"read kb://3"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.Equal(t, []string{"kb://3"}, calls[0].UnresolvedHandles)
|
||||
require.Equal(t, ArgumentResolutionUnresolved, calls[0].ArgumentResolution)
|
||||
}
|
||||
|
||||
func TestDurableURIInIDFieldDecodesToBareID(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
calls := []types.LLMToolCall{{Function: types.FunctionCall{
|
||||
Name: "list_documents", Arguments: `{"knowledge_base_id":"academy://kb/kb-real"}`,
|
||||
}}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
require.JSONEq(t, `{"knowledge_base_id":"kb-real"}`, calls[0].Function.Arguments)
|
||||
}
|
||||
|
||||
func TestHistoryAnswerWithDurableURIsReplaysAsHandles(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
encoded := registry.EncodeMessages([]chat.Message{
|
||||
{Role: "assistant", Content: "已写入 academy://kb/kb-real", ReasoningContent: "target academy://kb/kb-real"},
|
||||
})
|
||||
require.Equal(t, "已写入 kb://1", encoded[0].Content)
|
||||
require.Equal(t, "target kb://1", encoded[0].ReasoningContent)
|
||||
require.Equal(t, "已写入 academy://kb/kb-real", registry.DecodeOutputText(encoded[0].Content))
|
||||
}
|
||||
|
||||
func mustJSON(t *testing.T, value string) string {
|
||||
t.Helper()
|
||||
encoded, err := json.Marshal(value)
|
||||
require.NoError(t, err)
|
||||
return string(encoded)
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
// sources.go is the source-reference half of the model-context registry:
|
||||
// request-local chunk://N, doc://N, kb://N and url://N handles for chunks,
|
||||
// documents, knowledge bases and web pages, plus the tool-argument codec that
|
||||
// maps them back to durable
|
||||
// identifiers. Request lifecycles use Registry so source and resource handles
|
||||
// cannot be encoded or decoded out of order.
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"html"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
type ChunkReference struct {
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
DocumentTitle string
|
||||
ChunkIndex int
|
||||
ChunkType string
|
||||
}
|
||||
|
||||
// webMeta is the per-web-page metadata stored next to the raw URL.
|
||||
type webMeta struct {
|
||||
title string
|
||||
}
|
||||
|
||||
// sourceRegistry is scoped to one assistant response (including every Agent tool
|
||||
// round). Handles are never persisted or accepted across requests.
|
||||
type sourceRegistry struct {
|
||||
citationsEnabled bool
|
||||
// Addressable IDs from history, directory entries, and tool arguments are
|
||||
// not evidence until a current tool result supplies the source.
|
||||
citable sync.Map // handle -> true; registrations may run concurrently
|
||||
|
||||
chunks *handleTable[ChunkReference]
|
||||
docs *handleTable[struct{}]
|
||||
kbs *handleTable[struct{}]
|
||||
webs *handleTable[webMeta]
|
||||
}
|
||||
|
||||
func newSourceRegistry(citationsEnabled ...bool) *sourceRegistry {
|
||||
enabled := true
|
||||
if len(citationsEnabled) > 0 {
|
||||
enabled = citationsEnabled[0]
|
||||
}
|
||||
return &sourceRegistry{
|
||||
citationsEnabled: enabled,
|
||||
chunks: newHandleTable[ChunkReference](chunkHandlePrefix, 0, 1),
|
||||
docs: newHandleTable[struct{}](docHandlePrefix, 0, 1),
|
||||
kbs: newHandleTable[struct{}](kbHandlePrefix, 0, 1),
|
||||
webs: newHandleTable[webMeta](webHandlePrefix, 0, 1),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) Count() int {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
return r.chunks.size() + r.webs.size()
|
||||
}
|
||||
|
||||
// knownHandle implements the shared guard for handle-shaped registration
|
||||
// input: a model-emitted handle is echoed back only when it already exists,
|
||||
// and is never accepted as a new durable identity.
|
||||
func knownHandle[M any](table *handleTable[M], id string) string {
|
||||
handle := canonicalSourceHandle(id)
|
||||
if table.has(handle) {
|
||||
return handle
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) RegisterChunk(ref ChunkReference) string {
|
||||
return r.registerChunk(ref, true)
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) registerChunk(ref ChunkReference, evidence bool) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
ref.ChunkID = strings.TrimSpace(ref.ChunkID)
|
||||
if ref.ChunkID == "" {
|
||||
return ""
|
||||
}
|
||||
if isSourceHandleShaped(ref.ChunkID) {
|
||||
return knownHandle(r.chunks, ref.ChunkID)
|
||||
}
|
||||
handle := r.chunks.register(ref.ChunkID, ref.ChunkID, ref, mergeChunkReference)
|
||||
if evidence {
|
||||
r.citable.Store(handle, true)
|
||||
}
|
||||
return handle
|
||||
}
|
||||
|
||||
func mergeChunkReference(dst *ChunkReference, src ChunkReference) {
|
||||
if dst.KnowledgeID == "" {
|
||||
dst.KnowledgeID = src.KnowledgeID
|
||||
}
|
||||
if dst.KnowledgeBaseID == "" {
|
||||
dst.KnowledgeBaseID = src.KnowledgeBaseID
|
||||
}
|
||||
if dst.DocumentTitle == "" {
|
||||
dst.DocumentTitle = src.DocumentTitle
|
||||
}
|
||||
if dst.ChunkIndex == 0 {
|
||||
dst.ChunkIndex = src.ChunkIndex
|
||||
}
|
||||
if dst.ChunkType == "" {
|
||||
dst.ChunkType = src.ChunkType
|
||||
}
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) RegisterDocument(id string) string {
|
||||
id = strings.TrimSpace(id)
|
||||
if r == nil || id == "" {
|
||||
return ""
|
||||
}
|
||||
if isSourceHandleShaped(id) {
|
||||
return knownHandle(r.docs, id)
|
||||
}
|
||||
return r.docs.register(id, id, struct{}{}, nil)
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) RegisterKnowledgeBase(id string) string {
|
||||
id = strings.TrimSpace(id)
|
||||
if r == nil || id == "" {
|
||||
return ""
|
||||
}
|
||||
if isSourceHandleShaped(id) {
|
||||
return knownHandle(r.kbs, id)
|
||||
}
|
||||
return r.kbs.register(id, id, struct{}{}, nil)
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) RegisterWeb(rawURL, title string) string {
|
||||
return r.registerWeb(rawURL, title, true)
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) registerWeb(rawURL, title string, evidence bool) string {
|
||||
rawURL = strings.TrimSpace(rawURL)
|
||||
if r == nil || rawURL == "" {
|
||||
return ""
|
||||
}
|
||||
if isSourceHandleShaped(rawURL) {
|
||||
return knownHandle(r.webs, rawURL)
|
||||
}
|
||||
// Dedup on the canonical (fragment-stripped) URL while decoding back to
|
||||
// the raw URL the model was originally shown.
|
||||
handle := r.webs.register(canonicalWebURL(rawURL), rawURL, webMeta{title: title}, func(dst *webMeta, src webMeta) {
|
||||
if dst.title == "" && src.title != "" {
|
||||
dst.title = src.title
|
||||
}
|
||||
})
|
||||
if evidence {
|
||||
r.citable.Store(handle, true)
|
||||
}
|
||||
return handle
|
||||
}
|
||||
|
||||
func canonicalWebURL(raw string) string {
|
||||
parsed, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
parsed.Fragment = ""
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) RegisterSearchResults(results []*types.SearchResult) {
|
||||
for _, result := range results {
|
||||
if result == nil {
|
||||
continue
|
||||
}
|
||||
r.RegisterDocument(result.KnowledgeID)
|
||||
r.RegisterKnowledgeBase(result.KnowledgeBaseID)
|
||||
r.RegisterChunk(ChunkReference{
|
||||
ChunkID: result.ID,
|
||||
KnowledgeID: result.KnowledgeID,
|
||||
KnowledgeBaseID: result.KnowledgeBaseID,
|
||||
DocumentTitle: firstNonEmpty(result.KnowledgeTitle, result.KnowledgeFilename),
|
||||
ChunkIndex: result.ChunkIndex,
|
||||
ChunkType: result.ChunkType,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) ChunkHandle(id string) string {
|
||||
handle, _ := r.chunks.handleForKey(id)
|
||||
return handle
|
||||
}
|
||||
|
||||
// toolArgumentPolicy decides whether a source-bearing JSON key belongs to a
|
||||
// particular tool contract. Request lifecycles always pass the per-tool policy
|
||||
// (sourceArgumentAllowed); a nil policy allows every key and exists only for
|
||||
// package-internal replay paths that predate per-tool contracts.
|
||||
type toolArgumentPolicy func(toolName, key string) bool
|
||||
|
||||
// DecodeToolCallsWithPolicy restores handles in every string argument. Fields
|
||||
// explicitly owned by the named tool receive the bare durable ID, so dynamic
|
||||
// tools with coincidentally named fields do not inherit built-in source
|
||||
// semantics; bareText fields (SQL) receive bare IDs inside the expression;
|
||||
// all other text receives durable text forms (URLs and academy:// URIs).
|
||||
func (r *sourceRegistry) DecodeToolCallsWithPolicy(
|
||||
toolCalls []types.LLMToolCall,
|
||||
policy toolArgumentPolicy,
|
||||
bareText toolArgumentPolicy,
|
||||
) {
|
||||
for i := range toolCalls {
|
||||
toolName := toolCalls[i].Function.Name
|
||||
toolCalls[i].Function.Arguments = r.decodeJSONWithPolicy(
|
||||
toolCalls[i].Function.Arguments,
|
||||
false,
|
||||
func(key string) bool { return policy == nil || policy(toolName, key) },
|
||||
func(key string) bool { return bareText != nil && bareText(toolName, key) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// UnresolvedToolHandlesWithPolicy reports handles left in a decoded call: any
|
||||
// scheme-shaped handle in any string, plus legacy handles in ID fields that
|
||||
// belong to the named tool's declared source contract.
|
||||
func (r *sourceRegistry) UnresolvedToolHandlesWithPolicy(
|
||||
toolName, raw string,
|
||||
policy toolArgumentPolicy,
|
||||
) []string {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return nil
|
||||
}
|
||||
var value interface{}
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
r.collectUnresolvedToolHandles(
|
||||
"", value, seen,
|
||||
func(key string) bool { return policy == nil || policy(toolName, key) },
|
||||
)
|
||||
result := make([]string, 0, len(seen))
|
||||
for handle := range seen {
|
||||
result = append(result, handle)
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) collectUnresolvedToolHandles(
|
||||
key string,
|
||||
value interface{},
|
||||
seen map[string]struct{},
|
||||
allowed func(string) bool,
|
||||
) {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
for _, handle := range r.UnresolvedTextHandles(typed) {
|
||||
seen[handle] = struct{}{}
|
||||
}
|
||||
key = strings.ToLower(key)
|
||||
if _, ok := sourceKeySpaces[key]; !ok || !allowed(key) {
|
||||
return
|
||||
}
|
||||
handle := strings.TrimSpace(typed)
|
||||
if isSourceHandleShaped(handle) && (r == nil || r.durableForHandle(handle) == "") {
|
||||
seen[handle] = struct{}{}
|
||||
}
|
||||
case []interface{}:
|
||||
for _, item := range typed {
|
||||
r.collectUnresolvedToolHandles(key, item, seen, allowed)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
for childKey, item := range typed {
|
||||
r.collectUnresolvedToolHandles(childKey, item, seen, allowed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// EncodeMessagesWithPolicies compacts known real identifiers in replayed
|
||||
// messages and gates source processing for tool results by tool name. A nil
|
||||
// policy retains the legacy generic behavior for package-internal callers.
|
||||
func (r *sourceRegistry) EncodeMessagesWithPolicies(
|
||||
messages []chat.Message,
|
||||
argumentPolicy toolArgumentPolicy,
|
||||
resultPolicy func(toolName string) bool,
|
||||
) []chat.Message {
|
||||
if r == nil || len(messages) == 0 {
|
||||
return messages
|
||||
}
|
||||
out := make([]chat.Message, len(messages))
|
||||
copy(out, messages)
|
||||
// First register every durable identifier present in historical tool calls
|
||||
// and canonical assistant citations. This two-pass shape lets an early tool
|
||||
// message reuse metadata that appears only in the turn's final answer.
|
||||
for i := range out {
|
||||
processToolResult := out[i].Role == "tool" && (resultPolicy == nil || resultPolicy(out[i].Name))
|
||||
// Stored text (instructions, prompts, earlier answers) carries
|
||||
// workspace objects as academy:// URIs in every role.
|
||||
reasoningBefore := out[i].ReasoningContent
|
||||
if out[i].Role == "assistant" || processToolResult {
|
||||
out[i].Content = r.CompactPublicCitations(out[i].Content, false)
|
||||
out[i].ReasoningContent = r.CompactPublicCitations(out[i].ReasoningContent, false)
|
||||
}
|
||||
out[i].Content = r.EncodeDurableURIs(out[i].Content)
|
||||
out[i].ReasoningContent = r.EncodeDurableURIs(out[i].ReasoningContent)
|
||||
dropStaleReasoningSignature(&out[i], reasoningBefore)
|
||||
if len(out[i].MultiContent) > 0 {
|
||||
out[i].MultiContent = append([]chat.MessageContentPart(nil), out[i].MultiContent...)
|
||||
for j := range out[i].MultiContent {
|
||||
if out[i].MultiContent[j].Type != "text" {
|
||||
continue
|
||||
}
|
||||
if out[i].Role == "assistant" || processToolResult {
|
||||
out[i].MultiContent[j].Text = r.CompactPublicCitations(out[i].MultiContent[j].Text, false)
|
||||
}
|
||||
out[i].MultiContent[j].Text = r.EncodeDurableURIs(out[i].MultiContent[j].Text)
|
||||
}
|
||||
}
|
||||
if len(out[i].ToolCalls) > 0 {
|
||||
out[i].ToolCalls = append([]chat.ToolCall(nil), out[i].ToolCalls...)
|
||||
for j := range out[i].ToolCalls {
|
||||
toolName := out[i].ToolCalls[j].Function.Name
|
||||
r.registerToolArguments(
|
||||
out[i].ToolCalls[j].Function.Arguments,
|
||||
func(key string) bool { return argumentPolicy == nil || argumentPolicy(toolName, key) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range out {
|
||||
if out[i].Role == "tool" && (resultPolicy == nil || resultPolicy(out[i].Name)) {
|
||||
r.registerLegacyToolReferences(out[i].Content, false)
|
||||
out[i].Content = r.CompactKnownText(out[i].Content)
|
||||
if out[i].Name == "web_search" || out[i].Name == "web_fetch" {
|
||||
// Citation IDs and fetch targets are distinct: expose the actual URL after
|
||||
// compaction so models need not infer new sequential IDs for page links.
|
||||
out[i].Content = webPageHeaderRE.ReplaceAllStringFunc(out[i].Content, func(header string) string {
|
||||
match := webPageHeaderRE.FindStringSubmatch(header)
|
||||
header = webPageURLAttrRE.ReplaceAllString(header, "")
|
||||
rawURL := r.durableForHandle(match[1])
|
||||
if rawURL == "" {
|
||||
return header
|
||||
}
|
||||
return strings.TrimSuffix(header, ">") + ` url="` + html.EscapeString(rawURL) + `">`
|
||||
})
|
||||
}
|
||||
}
|
||||
for j := range out[i].ToolCalls {
|
||||
toolName := out[i].ToolCalls[j].Function.Name
|
||||
out[i].ToolCalls[j].Function.Arguments = r.decodeJSONWithPolicy(
|
||||
out[i].ToolCalls[j].Function.Arguments,
|
||||
true,
|
||||
func(key string) bool { return argumentPolicy == nil || argumentPolicy(toolName, key) },
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) registerToolArguments(raw string, allowed func(string) bool) {
|
||||
if r == nil || strings.TrimSpace(raw) == "" {
|
||||
return
|
||||
}
|
||||
var value interface{}
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return
|
||||
}
|
||||
r.registerToolArgumentValue("", value, allowed)
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) registerToolArgumentValue(key string, value interface{}, allowed func(string) bool) {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
if allowed(strings.ToLower(key)) {
|
||||
r.registerSourceIDByKey(key, typed, false)
|
||||
}
|
||||
case []interface{}:
|
||||
for _, item := range typed {
|
||||
r.registerToolArgumentValue(key, item, allowed)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
for childKey, item := range typed {
|
||||
r.registerToolArgumentValue(childKey, item, allowed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// registerSourceIDByKey is the single key→source-space dispatch used for tool
|
||||
// arguments, structured tool results, and database rows. It is driven by
|
||||
// sourceKeySpaces — the same table that gates handle decode — so the recognized
|
||||
// key set (and the http/https guard for web references) cannot drift between
|
||||
// registration and decoding.
|
||||
func (r *sourceRegistry) registerSourceIDByKey(key, value string, evidence bool) {
|
||||
value = strings.TrimSpace(value)
|
||||
if _, id, ok := parseDurableURI(value); ok {
|
||||
value = id
|
||||
}
|
||||
if value == "" || isSourceHandleShaped(value) {
|
||||
return
|
||||
}
|
||||
space, ok := sourceKeySpaces[strings.ToLower(key)]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
switch space {
|
||||
case spaceChunk:
|
||||
r.registerChunk(ChunkReference{ChunkID: value}, evidence)
|
||||
case spaceDocument:
|
||||
r.RegisterDocument(value)
|
||||
case spaceDocumentRef:
|
||||
// Stored refs use "knowledgeID|title"; only the ID part is durable.
|
||||
r.RegisterDocument(types.WikiSourceKnowledgeID(value))
|
||||
case spaceKnowledgeBase:
|
||||
r.RegisterKnowledgeBase(value)
|
||||
case spaceWeb:
|
||||
// Only public web pages become web references. Internal schemes
|
||||
// (res://, storage providers) must never enter the web handle space,
|
||||
// where CompactKnownText would rewrite them a second time.
|
||||
if parsed, err := url.Parse(value); err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") {
|
||||
r.registerWeb(value, "", evidence)
|
||||
}
|
||||
case spaceAnySource:
|
||||
// Decode-only: a bare "id" never registers a new source.
|
||||
}
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) decodeJSONWithPolicy(
|
||||
raw string,
|
||||
encode bool,
|
||||
allowed func(string) bool,
|
||||
bareText func(string) bool,
|
||||
) string {
|
||||
if r == nil || strings.TrimSpace(raw) == "" {
|
||||
return raw
|
||||
}
|
||||
var value interface{}
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return raw
|
||||
}
|
||||
if bareText == nil {
|
||||
bareText = func(string) bool { return false }
|
||||
}
|
||||
value = r.walkJSON("", value, encode, allowed, bareText)
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) walkJSON(
|
||||
key string,
|
||||
value interface{},
|
||||
encode bool,
|
||||
allowed func(string) bool,
|
||||
bareText func(string) bool,
|
||||
) interface{} {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
lower := strings.ToLower(key)
|
||||
_, idKey := sourceKeySpaces[lower]
|
||||
idField := idKey && allowed(lower)
|
||||
if encode {
|
||||
// Encode matches on exact real identifiers (UUIDs/URLs), which do
|
||||
// not collide with prose, so it stays key-agnostic.
|
||||
if allowed(lower) {
|
||||
if handle := r.handleForDurable(typed); handle != "" {
|
||||
return handle
|
||||
}
|
||||
}
|
||||
return r.EncodeDurableURIs(typed)
|
||||
}
|
||||
if idField {
|
||||
trimmed := strings.TrimSpace(typed)
|
||||
if isSourceHandleShaped(trimmed) {
|
||||
if durable := r.durableForHandle(trimmed); durable != "" {
|
||||
return durable
|
||||
}
|
||||
return typed
|
||||
}
|
||||
if _, id, ok := parseDurableURI(trimmed); ok {
|
||||
return id
|
||||
}
|
||||
}
|
||||
if bareText(lower) {
|
||||
return r.DecodeBareText(typed)
|
||||
}
|
||||
return r.DecodeDurableText(typed)
|
||||
case []interface{}:
|
||||
for i := range typed {
|
||||
typed[i] = r.walkJSON(key, typed[i], encode, allowed, bareText)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
for childKey, item := range typed {
|
||||
typed[childKey] = r.walkJSON(childKey, item, encode, allowed, bareText)
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) handleForDurable(real string) string {
|
||||
if handle, ok := r.chunks.handleForKey(real); ok {
|
||||
return handle
|
||||
}
|
||||
if handle, ok := r.docs.handleForKey(real); ok {
|
||||
return handle
|
||||
}
|
||||
if handle, ok := r.kbs.handleForKey(real); ok {
|
||||
return handle
|
||||
}
|
||||
if handle, ok := r.webs.handleForKey(canonicalWebURL(real)); ok {
|
||||
return handle
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *sourceRegistry) durableForHandle(handle string) string {
|
||||
_, durable, _, ok := r.resolveSourceHandle(handle)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return durable
|
||||
}
|
||||
|
||||
// CompactKnownText is intentionally limited to identifiers already registered
|
||||
// from structured runtime/tool data, plus explicit academy:// URIs. It is used
|
||||
// for metadata envelopes, not arbitrary retrieved prose.
|
||||
func (r *sourceRegistry) CompactKnownText(text string) string {
|
||||
if r == nil || text == "" {
|
||||
return text
|
||||
}
|
||||
// URIs first: their embedded IDs must become one handle, not "academy://kb/kb://1".
|
||||
text = r.EncodeDurableURIs(text)
|
||||
// The snapshot spans all four source tables and is sorted longest-value
|
||||
// first GLOBALLY: a web URL may contain a registered document UUID as a
|
||||
// substring, so per-table passes could corrupt the longer value.
|
||||
pairs := r.chunks.pairs()
|
||||
pairs = append(pairs, r.docs.pairs()...)
|
||||
pairs = append(pairs, r.kbs.pairs()...)
|
||||
pairs = append(pairs, r.webs.pairs()...)
|
||||
sort.SliceStable(pairs, func(i, j int) bool { return len(pairs[i].value) > len(pairs[j].value) })
|
||||
for _, item := range pairs {
|
||||
if item.value != "" {
|
||||
text = strings.ReplaceAll(text, item.value, item.handle)
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
var webPageHeaderRE = regexp.MustCompile(`<page id="(url://[1-9][0-9]*)"[^>]*>`)
|
||||
|
||||
var webPageURLAttrRE = regexp.MustCompile(` url="[^"]*"`)
|
||||
@@ -0,0 +1,582 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRegistryChunkAliasIsStableAndExpandsCanonicalCitation(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
first := registry.RegisterChunk(ChunkReference{
|
||||
ChunkID: "chunk-uuid-1",
|
||||
KnowledgeID: "knowledge-uuid-1",
|
||||
KnowledgeBaseID: "kb-uuid-1",
|
||||
DocumentTitle: "Architecture.md",
|
||||
ChunkIndex: 7,
|
||||
})
|
||||
second := registry.RegisterChunk(ChunkReference{
|
||||
ChunkID: "chunk-uuid-1",
|
||||
KnowledgeID: "knowledge-uuid-1",
|
||||
DocumentTitle: "Architecture.md",
|
||||
})
|
||||
|
||||
require.Equal(t, "chunk://1", first)
|
||||
require.Equal(t, first, second)
|
||||
require.Equal(t,
|
||||
`claim <kb doc="Architecture.md" chunk_id="chunk-uuid-1" kb_id="kb-uuid-1" />`,
|
||||
registry.ExpandText(`claim <ref id="chunk://1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestRegisterDoesNotTreatModelAliasesAsNewDurableIdentities(t *testing.T) {
|
||||
r := newSourceRegistry()
|
||||
require.Equal(t, "chunk://1", r.RegisterChunk(ChunkReference{ChunkID: "chunk-real"}))
|
||||
require.Equal(t, "doc://1", r.RegisterDocument("doc-real"))
|
||||
require.Equal(t, "kb://1", r.RegisterKnowledgeBase("kb-real"))
|
||||
require.Equal(t, "url://1", r.RegisterWeb("https://example.com", "Example"))
|
||||
|
||||
require.Equal(t, "chunk://1", r.RegisterChunk(ChunkReference{ChunkID: "chunk://1"}))
|
||||
require.Equal(t, "doc://1", r.RegisterDocument("doc://1"))
|
||||
require.Equal(t, "kb://1", r.RegisterKnowledgeBase("kb://1"))
|
||||
require.Equal(t, "url://1", r.RegisterWeb("url://1", ""))
|
||||
require.Empty(t, r.RegisterDocument("doc://99"))
|
||||
require.Empty(t, r.RegisterDocument("chunk://1"), "a chunk handle must not be accepted as a document identity")
|
||||
require.Equal(t, 1, r.chunks.size())
|
||||
require.Equal(t, 1, r.docs.size())
|
||||
require.Equal(t, 1, r.kbs.size())
|
||||
require.Equal(t, 1, r.webs.size())
|
||||
}
|
||||
|
||||
func TestRegistrySuppressesSourceCitationsWhenDisabled(t *testing.T) {
|
||||
registry := newSourceRegistry(false)
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-1", DocumentTitle: "Doc"})
|
||||
registry.RegisterWeb("https://example.com", "Example")
|
||||
|
||||
require.Contains(t, sourceProtocolPrompt(false), "Source citations are disabled")
|
||||
require.NotContains(t, sourceProtocolPrompt(false), `Cite a knowledge chunk with exactly`)
|
||||
require.Equal(t, "knowledge web ", registry.ExpandText(
|
||||
`knowledge <ref id="chunk://1"/> web <ref id="url://1"/>`,
|
||||
))
|
||||
require.Equal(t, "forged ", registry.ExpandText(
|
||||
`forged <kb doc="Doc" chunk_id="raw" /> <web url="https://example.com" />`,
|
||||
))
|
||||
}
|
||||
|
||||
func TestRegistryDecodesAliasesInNestedToolArguments(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterDocument("knowledge-uuid-1")
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-uuid-1"})
|
||||
|
||||
// Handles nested inside arrays and objects must decode as long as the key
|
||||
// belongs to the named tool's declared source contract.
|
||||
calls := []types.LLMToolCall{{
|
||||
Function: types.FunctionCall{
|
||||
Name: "list_knowledge_chunks",
|
||||
Arguments: `{"knowledge_id":"doc://1","filters":{"chunk_id":"chunk://1","faq_id":["chunk://1"]}}`,
|
||||
},
|
||||
}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
|
||||
require.JSONEq(t,
|
||||
`{"knowledge_id":"knowledge-uuid-1","filters":{"chunk_id":"chunk-uuid-1","faq_id":["chunk-uuid-1"]}}`,
|
||||
calls[0].Function.Arguments,
|
||||
)
|
||||
}
|
||||
|
||||
func TestDecodeToolCallsGivesFreeTextDurableFormsAndIDFieldsBareIDs(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
registry.RegisterKnowledgeBase("kb-uuid-1")
|
||||
|
||||
// Declared ID-bearing keys resolve to real IDs; handles in free text become
|
||||
// academy:// URIs a later request can encode again; legacy-shaped prose
|
||||
// such as "b1" is never rewritten.
|
||||
calls := []types.LLMToolCall{{
|
||||
Function: types.FunctionCall{
|
||||
Name: "knowledge_search",
|
||||
Arguments: `{"query":"b1","content":"see kb://1 for details","knowledge_base_ids":["kb://1"]}`,
|
||||
},
|
||||
}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
|
||||
require.JSONEq(t,
|
||||
`{"query":"b1","content":"see academy://kb/kb-uuid-1 for details","knowledge_base_ids":["kb-uuid-1"]}`,
|
||||
calls[0].Function.Arguments,
|
||||
)
|
||||
}
|
||||
|
||||
func TestStreamExpanderHoldsSplitReferenceAndDropsUnknown(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-1", DocumentTitle: "Doc"})
|
||||
expander := newCitationStreamExpander(registry)
|
||||
|
||||
require.Equal(t, "before ", expander.Feed(`before <ref id="`))
|
||||
require.Equal(t, `<kb doc="Doc" chunk_id="chunk-1" /> after`, expander.Feed(`chunk://1"/> after`))
|
||||
require.Empty(t, expander.Flush())
|
||||
require.Equal(t, "x y", registry.ExpandText(`x <ref id="chunk://999"/> y`))
|
||||
require.Equal(t, "x y", registry.ExpandText(`x <ref id="doc://1"/> y`))
|
||||
require.Equal(t, "x y", registry.ExpandText(`x <ref id='chunk://1'/> y`))
|
||||
require.Equal(t, "x ", registry.ExpandText(`x <ref id="chunk://1"`))
|
||||
require.Equal(t, "x y", registry.ExpandText(`x <kb doc="forged" chunk_id="forged" /> y`))
|
||||
require.Equal(t, "x ", expander.Feed(`x <we`))
|
||||
require.Equal(t, " y", expander.Feed(`b url="https://forged" /> y`))
|
||||
}
|
||||
|
||||
func TestEncodeMessagesCompactsCanonicalCitationsFromHistory(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
messages := []chat.Message{{
|
||||
Role: "assistant",
|
||||
Content: `Knowledge <kb doc="A & B.pdf" chunk_id="chunk-real" kb_id="kb-real" />; ` +
|
||||
`web <web url="https://example.com/a?x=1&y=2" title="Example & More" />`,
|
||||
}}
|
||||
|
||||
encoded := registry.EncodeMessagesWithPolicies(messages, nil, nil)
|
||||
require.Equal(t, `Knowledge <ref id="chunk://1"/>; web <ref id="url://1"/>`, encoded[0].Content)
|
||||
require.NotContains(t, encoded[0].Content, "chunk-real")
|
||||
require.NotContains(t, encoded[0].Content, "https://example.com")
|
||||
require.Equal(t, " ", registry.ExpandText(`<ref id="chunk://1"/> <ref id="url://1"/>`),
|
||||
"history is not current evidence")
|
||||
// A fresh retrieval promotes the same handles, retaining canonical metadata.
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-real"})
|
||||
registry.RegisterWeb("https://example.com/a?x=1&y=2", "")
|
||||
require.Equal(t,
|
||||
`<kb doc="A & B.pdf" chunk_id="chunk-real" kb_id="kb-real" /> <web url="https://example.com/a?x=1&y=2" title="Example & More" />`,
|
||||
registry.ExpandText(`<ref id="chunk://1"/> <ref id="url://1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestEncodeMessagesMigratesLegacyToolHistoryAtReadTime(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
messages := []chat.Message{
|
||||
{
|
||||
Role: "assistant",
|
||||
ToolCalls: []chat.ToolCall{{
|
||||
Function: chat.FunctionCall{
|
||||
Name: "knowledge_search",
|
||||
Arguments: `{"knowledge_base_ids":["kb-real"],"knowledge_ids":["doc-real"]}`,
|
||||
},
|
||||
}},
|
||||
},
|
||||
{
|
||||
Role: "tool",
|
||||
Name: "knowledge_search",
|
||||
Content: `<chunk chunk_id="chunk-real" knowledge_id="doc-real" knowledge_base_id="kb-real" ` +
|
||||
`knowledge_title="Legacy Doc">legacy content</chunk>`,
|
||||
},
|
||||
{
|
||||
Role: "assistant",
|
||||
Content: `Legacy answer <kb doc="Legacy Doc" chunk_id="chunk-real" kb_id="kb-real" />`,
|
||||
},
|
||||
}
|
||||
|
||||
encoded := registry.EncodeMessagesWithPolicies(messages, nil, nil)
|
||||
require.JSONEq(t, `{"knowledge_base_ids":["kb://1"],"knowledge_ids":["doc://1"]}`,
|
||||
encoded[0].ToolCalls[0].Function.Arguments)
|
||||
require.Contains(t, encoded[1].Content, `chunk_id="chunk://1"`)
|
||||
require.Contains(t, encoded[1].Content, `knowledge_id="doc://1"`)
|
||||
require.Contains(t, encoded[1].Content, `knowledge_base_id="kb://1"`)
|
||||
require.Equal(t, `Legacy answer <ref id="chunk://1"/>`, encoded[2].Content)
|
||||
require.Empty(t, registry.ExpandText(`<ref id="chunk://1"/>`),
|
||||
"legacy tool history does not authorize new citations")
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-real"})
|
||||
require.Equal(t,
|
||||
`<kb doc="Legacy Doc" chunk_id="chunk-real" kb_id="kb-real" />`,
|
||||
registry.ExpandText(`<ref id="chunk://1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestEncodeMessagesDoesNotTreatLegacyPromptExampleAsARealSource(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
messages := []chat.Message{{
|
||||
Role: "system",
|
||||
Content: `Old rule: cite <kb doc="..." chunk_id="..." />`,
|
||||
}}
|
||||
|
||||
encoded := registry.EncodeMessagesWithPolicies(messages, nil, nil)
|
||||
require.Equal(t, messages[0].Content, encoded[0].Content)
|
||||
require.Zero(t, registry.Count())
|
||||
}
|
||||
|
||||
func TestModelOutputGroupsChunksAndReusesAliasAcrossTools(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
search := &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "raw UUID output",
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "search_results",
|
||||
"results": []map[string]interface{}{
|
||||
{
|
||||
"chunk_id": "chunk-uuid-1",
|
||||
"knowledge_id": "knowledge-uuid-1",
|
||||
"knowledge_base_id": "kb-uuid-1",
|
||||
"knowledge_title": "Doc A",
|
||||
"chunk_index": 3,
|
||||
"content": "full content",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
first := registry.ModelOutput(search)
|
||||
require.Contains(t, first, `<document id="doc://1" kb="kb://1" title="Doc A">`)
|
||||
require.Contains(t, first, `<chunk id="chunk://1" index="3" view="full">`)
|
||||
require.NotContains(t, first, "chunk-uuid-1")
|
||||
require.NotContains(t, first, "knowledge-uuid-1")
|
||||
|
||||
deepRead := &types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "knowledge_chunks_list",
|
||||
"knowledge_id": "knowledge-uuid-1",
|
||||
"knowledge_title": "Doc A",
|
||||
"total_chunks": int64(1),
|
||||
"fetched_chunks": 1,
|
||||
"chunks": []map[string]interface{}{
|
||||
{"chunk_id": "chunk-uuid-1", "knowledge_id": "knowledge-uuid-1", "knowledge_base": "kb-uuid-1", "chunk_index": 3, "content": "deep content"},
|
||||
},
|
||||
},
|
||||
}
|
||||
second := registry.ModelOutput(deepRead)
|
||||
require.Contains(t, second, `<chunk id="chunk://1"`)
|
||||
require.False(t, strings.Contains(second, "chunk://2"))
|
||||
}
|
||||
|
||||
func TestModelOutputRendersKnowledgeMetadataOncePerDocument(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "search_results",
|
||||
"results": []map[string]interface{}{
|
||||
{
|
||||
"chunk_id": "chunk-1", "chunk_index": 1, "content": "first",
|
||||
"knowledge_id": "document-1", "knowledge_base_id": "kb-1", "knowledge_title": "Doc",
|
||||
"knowledge_metadata": "region: Shanghai & Suzhou",
|
||||
},
|
||||
{
|
||||
"chunk_id": "chunk-2", "chunk_index": 2, "content": "second",
|
||||
"knowledge_id": "document-1", "knowledge_base_id": "kb-1", "knowledge_title": "Doc",
|
||||
"knowledge_metadata": "region: Shanghai & Suzhou",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
require.Equal(t, 1, strings.Count(output, "<metadata>"))
|
||||
require.Contains(t, output, "<metadata>region: Shanghai & Suzhou</metadata>")
|
||||
require.Equal(t, 2, strings.Count(output, "<chunk "))
|
||||
}
|
||||
|
||||
func TestModelOutputWebAliasExpandsToWebCitation(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_search_results",
|
||||
"results": []map[string]interface{}{
|
||||
{"title": "Example", "url": "https://example.com/a", "snippet": "snippet"},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.Contains(t, output, `<page id="url://1" title="Example">`)
|
||||
require.Contains(t, output, `<evidence type="search_summary" verified="false" />`)
|
||||
require.NotContains(t, output, "https://example.com/a")
|
||||
require.Equal(t,
|
||||
`<web url="https://example.com/a" title="Example" />`,
|
||||
registry.ExpandText(`<ref id="url://1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestModelOutputWebSearchRetainsContentOnlyEvidence(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_search_results",
|
||||
"results": []map[string]interface{}{
|
||||
{
|
||||
"title": "Content-only provider",
|
||||
"url": "https://example.com/content",
|
||||
"content": "search evidence from provider content",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `<content>search evidence from provider content</content>`)
|
||||
require.Contains(t, output, `<evidence type="search_summary" verified="false" />`)
|
||||
}
|
||||
|
||||
func TestModelOutputWebSearchLimitsProviderContent(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
content := strings.Repeat("provider evidence ", 1000)
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_search_results",
|
||||
"results": []map[string]interface{}{{
|
||||
"title": "Long provider result",
|
||||
"url": "https://example.com/long",
|
||||
"content": content,
|
||||
}},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `<content truncated="true">`)
|
||||
require.NotContains(t, output, content)
|
||||
}
|
||||
|
||||
func TestModelOutputWebFetchPreservesPartialFailureStatus(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
registry.RegisterWeb("https://example.com/verified", "Verified")
|
||||
registry.RegisterWeb("https://example.com/forbidden", "Forbidden")
|
||||
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_fetch_results",
|
||||
"results": []map[string]interface{}{
|
||||
{
|
||||
"url": "https://example.com/verified",
|
||||
"status": "success",
|
||||
"raw_content": "verified page content",
|
||||
},
|
||||
{
|
||||
"url": "https://example.com/forbidden",
|
||||
"status": "failed",
|
||||
"retryable": false,
|
||||
"error_code": "http_403",
|
||||
"error_message": "access denied",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `<page id="url://1" status="success" view="excerpt">`)
|
||||
require.Contains(t, output, "verified page content")
|
||||
require.Contains(t, output, `<page id="url://2" status="failed" retryable="false" error_code="http_403">`)
|
||||
require.Contains(t, output, `<error>access denied</error>`)
|
||||
require.Contains(t, output, "failed URLs do not invalidate successful evidence")
|
||||
require.NotContains(t, output, "https://example.com")
|
||||
}
|
||||
|
||||
func TestModelOutputWebFetchAllFailuresIncludeSearchFallback(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_fetch_results",
|
||||
"results": []map[string]interface{}{
|
||||
{
|
||||
"url": "https://example.com/dns",
|
||||
"status": "failed",
|
||||
"retryable": true,
|
||||
"error_code": "dns_failed",
|
||||
"error_message": "DNS lookup failed",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `status="failed" retryable="true" error_code="dns_failed"`)
|
||||
require.Contains(t, output, "use another relevant source")
|
||||
require.Contains(t, output, "page content was not verified")
|
||||
}
|
||||
|
||||
func TestModelOutputWebFetchAllFailuresStillStructuredWhenToolNotSuccessful(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: false,
|
||||
Error: "all page fetches failed",
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_fetch_results",
|
||||
"results": []map[string]interface{}{
|
||||
{
|
||||
"url": "https://example.com/dns",
|
||||
"status": "failed",
|
||||
"retryable": true,
|
||||
"error_code": "dns_failed",
|
||||
"error_message": "DNS lookup failed",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `status="failed" retryable="true" error_code="dns_failed"`)
|
||||
require.Contains(t, output, "use another relevant source")
|
||||
require.NotContains(t, output, "Error: all page fetches failed")
|
||||
}
|
||||
|
||||
func TestModelOutputWebFetchKeepsContentWhenSummaryFails(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_fetch_results",
|
||||
"results": []map[string]interface{}{
|
||||
{
|
||||
"url": "https://example.com/specs",
|
||||
"status": "success",
|
||||
"summary_status": "failed",
|
||||
"summary_error_code": "summary_failed",
|
||||
"summary_error_message": "model unavailable",
|
||||
"raw_content": "official specifications",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `<summary_error code="summary_failed">model unavailable</summary_error>`)
|
||||
require.Contains(t, output, `<content>official specifications</content>`)
|
||||
}
|
||||
|
||||
func TestModelOutputWebFetchLimitsRawContentAcrossPages(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
pageContent := strings.Repeat("verified page content ", 1000)
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_fetch_results",
|
||||
"results": []map[string]interface{}{
|
||||
{"url": "https://example.com/one", "status": "success", "raw_content": pageContent},
|
||||
{"url": "https://example.com/two", "status": "success", "raw_content": pageContent},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `truncated="true"`)
|
||||
require.Less(t, len([]rune(output)), modelWebFetchTotalMaxRunes+3000)
|
||||
}
|
||||
|
||||
func TestModelOutputDocumentInfoUsesDocumentAndFAQAliases(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
result := &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "raw IDs must not be used",
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "document_info",
|
||||
"documents": []map[string]interface{}{
|
||||
{
|
||||
"knowledge_id": "doc-real-id",
|
||||
"title": "Architecture",
|
||||
"description": "System overview",
|
||||
"type": "file",
|
||||
"chunk_count": 12,
|
||||
},
|
||||
{
|
||||
"faq_id": "faq-chunk-real-id",
|
||||
"knowledge_id": "faq-container-real-id",
|
||||
"faq_question": "How does it work?",
|
||||
"faq_answers": []string{"With short aliases."},
|
||||
"is_faq": true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
output := registry.ModelOutput(result)
|
||||
for _, raw := range []string{"doc-real-id", "faq-chunk-real-id", "faq-container-real-id"} {
|
||||
require.NotContains(t, output, raw)
|
||||
}
|
||||
require.Contains(t, output, `<document id="doc://1" title="Architecture"`)
|
||||
require.Contains(t, output, `<chunk id="chunk://1" type="faq">`)
|
||||
require.Contains(t, registry.ExpandText(`Answer <ref id="chunk://1"/>`), `chunk_id="faq-chunk-real-id"`)
|
||||
}
|
||||
|
||||
func TestModelOutputCompactsLabeledWikiReferences(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
result := &types.ToolResult{
|
||||
Success: true,
|
||||
Output: `<wiki_page>
|
||||
<knowledge_base_id>kb-real-id</knowledge_base_id>
|
||||
<sources><source knowledge_id="doc-real-id">Source</source></sources>
|
||||
</wiki_page>`,
|
||||
}
|
||||
|
||||
output := registry.ModelOutput(result)
|
||||
require.NotContains(t, output, "kb-real-id")
|
||||
require.NotContains(t, output, "doc-real-id")
|
||||
require.Contains(t, output, `<knowledge_base_id>kb://1</knowledge_base_id>`)
|
||||
require.Contains(t, output, `knowledge_id="doc://1"`)
|
||||
|
||||
toolCalls := []types.LLMToolCall{
|
||||
{Function: types.FunctionCall{Name: "wiki_read_source_doc", Arguments: `{"knowledge_id":"doc://1"}`}},
|
||||
{Function: types.FunctionCall{Name: "wiki_search", Arguments: `{"knowledge_base_id":"kb://1"}`}},
|
||||
}
|
||||
registry.DecodeToolCallsWithPolicy(toolCalls, sourceArgumentAllowed, sourceBareTextAllowed)
|
||||
require.JSONEq(t, `{"knowledge_id":"doc-real-id"}`, toolCalls[0].Function.Arguments)
|
||||
require.JSONEq(t, `{"knowledge_base_id":"kb-real-id"}`, toolCalls[1].Function.Arguments)
|
||||
}
|
||||
|
||||
func TestModelOutputGraphResultsUseChunkAliases(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "graph_query_results",
|
||||
"results": []map[string]interface{}{{
|
||||
"chunk_id": "graph-chunk-real",
|
||||
"chunk_index": 4,
|
||||
"knowledge_id": "graph-doc-real",
|
||||
"knowledge_base_id": "graph-kb-real",
|
||||
"knowledge_title": "Graph Source",
|
||||
"content": "A relates to B.",
|
||||
}},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `<retrieval type="knowledge" mode="graph">`)
|
||||
require.Contains(t, output, `<chunk id="chunk://1" index="4" view="full">`)
|
||||
require.NotContains(t, output, "graph-chunk-real")
|
||||
require.Equal(t,
|
||||
`<kb doc="Graph Source" chunk_id="graph-chunk-real" kb_id="graph-kb-real" />`,
|
||||
registry.ExpandText(`<ref id="chunk://1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestModelOutputDoesNotRegisterInternalSchemesAsWebSources(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Output: `{"url":"res://0001","knowledge_id":"doc-real-id"}`,
|
||||
})
|
||||
|
||||
// An internal handle in a url-labeled field must never enter the web
|
||||
// handle space, where CompactKnownText would rewrite it a second time.
|
||||
require.Contains(t, output, "res://0001")
|
||||
require.NotContains(t, output, "url://1")
|
||||
require.Contains(t, output, "doc://1")
|
||||
require.NotContains(t, output, "doc-real-id")
|
||||
|
||||
registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Output: `{"url":"https://example.com/page"}`,
|
||||
})
|
||||
require.Equal(t,
|
||||
`<web url="https://example.com/page" title="" />`,
|
||||
registry.ExpandText(`<ref id="url://1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestModelOutputWebFetchKeepsEveryPageAndAccurateContinuation(t *testing.T) {
|
||||
registry := newSourceRegistry()
|
||||
rows := []map[string]interface{}{}
|
||||
for i := 0; i < 8; i++ {
|
||||
rows = append(rows, map[string]interface{}{
|
||||
"url": fmt.Sprintf("https://example.com/%d", i), "status": "success",
|
||||
"raw_content": strings.Repeat("文字", 5000), "offset": 100, "content_length": 20000, "truncated": true,
|
||||
})
|
||||
}
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true, Data: map[string]interface{}{"display_type": "web_fetch_results", "results": rows},
|
||||
})
|
||||
for i := 1; i <= 8; i++ {
|
||||
require.Contains(t, output, fmt.Sprintf(`url="url://%d" next_offset="2100"`, i))
|
||||
}
|
||||
require.Equal(t, 8, strings.Count(output, `<content truncated="true">文字`))
|
||||
require.NotContains(t, output, `view="full"`)
|
||||
require.Contains(t, output, `trust="untrusted"`)
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
// stream.go owns streaming-safe handle decoding: the shared suffix-hold
|
||||
// primitive, the per-space decoders built on it, and the composed public
|
||||
// StreamDecoder that applies every stage in the only safe order.
|
||||
package modelcontext
|
||||
|
||||
import "strings"
|
||||
|
||||
// streamHold is the shared primitive for decoders that must never emit a
|
||||
// partial model handle: each Feed withholds a trailing byte run that could
|
||||
// still grow into a handle in the next provider chunk, and applies the
|
||||
// space-specific decode to everything released. flush decides what happens to
|
||||
// a suffix still held when the stream closes.
|
||||
type streamHold struct {
|
||||
pending string
|
||||
holdLen func(combined string) int // trailing bytes to withhold
|
||||
emit func(released string) string // decode applied to released text
|
||||
flush func(pending string) string // end-of-stream disposition
|
||||
}
|
||||
|
||||
func (h *streamHold) Feed(chunk string) string {
|
||||
combined := h.pending + chunk
|
||||
h.pending = ""
|
||||
if combined == "" {
|
||||
return ""
|
||||
}
|
||||
if hold := h.holdLen(combined); hold > 0 && hold <= len(combined) {
|
||||
h.pending = combined[len(combined)-hold:]
|
||||
combined = combined[:len(combined)-hold]
|
||||
}
|
||||
return h.emit(combined)
|
||||
}
|
||||
|
||||
func (h *streamHold) Flush() string {
|
||||
pending := h.pending
|
||||
h.pending = ""
|
||||
return h.flush(pending)
|
||||
}
|
||||
|
||||
// resourceStreamDecoder restores res:// handles split across provider chunks.
|
||||
type resourceStreamDecoder struct {
|
||||
hold streamHold
|
||||
}
|
||||
|
||||
func newResourceStreamDecoder(registry *resourceRegistry) *resourceStreamDecoder {
|
||||
return &resourceStreamDecoder{hold: streamHold{
|
||||
holdLen: func(combined string) int {
|
||||
hold := 0
|
||||
for _, handle := range registry.handles() {
|
||||
// A provider may split the token at any byte boundary, including
|
||||
// "re" + "s://0001". Holding at most the short matching suffix is
|
||||
// the only way to guarantee a request-local handle never leaks.
|
||||
for n := 1; n < len(handle); n++ {
|
||||
if n > hold && strings.HasSuffix(combined, handle[:n]) {
|
||||
hold = n
|
||||
}
|
||||
}
|
||||
}
|
||||
return hold
|
||||
},
|
||||
emit: registry.DecodeText,
|
||||
flush: registry.DecodeText,
|
||||
}}
|
||||
}
|
||||
|
||||
func (d *resourceStreamDecoder) Feed(chunk string) string {
|
||||
if d == nil {
|
||||
return chunk
|
||||
}
|
||||
return d.hold.Feed(chunk)
|
||||
}
|
||||
|
||||
func (d *resourceStreamDecoder) Flush() string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
return d.hold.Flush()
|
||||
}
|
||||
|
||||
// HandleStreamDecoder restores HandleTable values without leaking a handle
|
||||
// split across provider chunks.
|
||||
type HandleStreamDecoder struct {
|
||||
table *HandleTable
|
||||
hold streamHold
|
||||
}
|
||||
|
||||
func NewHandleStreamDecoder(table *HandleTable) *HandleStreamDecoder {
|
||||
return &HandleStreamDecoder{table: table, hold: streamHold{
|
||||
holdLen: func(combined string) int {
|
||||
start := len(combined)
|
||||
for start > 0 && isHandleTokenByte(combined[start-1]) {
|
||||
start--
|
||||
}
|
||||
tail := combined[start:]
|
||||
// The prefix is immutable after construction, so no lock is needed.
|
||||
if couldBeNumericHandle(tail, table.table.prefix) {
|
||||
return len(tail)
|
||||
}
|
||||
return 0
|
||||
},
|
||||
emit: table.DecodeKnownText,
|
||||
flush: table.DecodeKnownText,
|
||||
}}
|
||||
}
|
||||
|
||||
func (d *HandleStreamDecoder) Feed(chunk string) string {
|
||||
if d == nil || d.table == nil {
|
||||
return chunk
|
||||
}
|
||||
return d.hold.Feed(chunk)
|
||||
}
|
||||
|
||||
func (d *HandleStreamDecoder) Flush() string {
|
||||
if d == nil || d.table == nil {
|
||||
return ""
|
||||
}
|
||||
return d.hold.Flush()
|
||||
}
|
||||
|
||||
func isHandleTokenByte(value byte) bool {
|
||||
return value >= 'a' && value <= 'z' || value >= 'A' && value <= 'Z' ||
|
||||
value >= '0' && value <= '9' || value == '-' || value == '_'
|
||||
}
|
||||
|
||||
func couldBeNumericHandle(value, prefix string) bool {
|
||||
if value == "" || prefix == "" {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(prefix, value) {
|
||||
return true
|
||||
}
|
||||
if !strings.HasPrefix(value, prefix) || len(value) == len(prefix) {
|
||||
return false
|
||||
}
|
||||
for _, char := range value[len(prefix):] {
|
||||
if char < '0' || char > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// orphanResourceStreamFilter removes unresolved resource handles only after
|
||||
// the registered resource decoder has had a chance to restore known ones. It
|
||||
// buffers a possible handle suffix so provider chunk boundaries cannot leak a
|
||||
// partial internal token to the UI.
|
||||
type orphanResourceStreamFilter struct {
|
||||
hold streamHold
|
||||
}
|
||||
|
||||
func newOrphanResourceStreamFilter() *orphanResourceStreamFilter {
|
||||
return &orphanResourceStreamFilter{hold: streamHold{
|
||||
holdLen: orphanResourceHoldLen,
|
||||
emit: func(released string) string {
|
||||
return resourceHandleShapeRE.ReplaceAllString(released, "")
|
||||
},
|
||||
flush: orphanResourceFlush,
|
||||
}}
|
||||
}
|
||||
|
||||
func orphanResourceHoldLen(combined string) int {
|
||||
const prefix = "res://"
|
||||
holdAt := -1
|
||||
// Unknown handles must be safe across every provider split, including
|
||||
// "re" + "s://9999". This may defer at most a few ordinary characters
|
||||
// until the next chunk; Flush preserves them when they are normal prose.
|
||||
for n := 1; n < len(prefix); n++ {
|
||||
if strings.HasSuffix(combined, prefix[:n]) {
|
||||
holdAt = len(combined) - n
|
||||
}
|
||||
}
|
||||
if idx := strings.LastIndex(combined, prefix); idx >= 0 {
|
||||
suffix := combined[idx+len(prefix):]
|
||||
if suffix == "" || allDigits(suffix) {
|
||||
holdAt = idx
|
||||
}
|
||||
}
|
||||
if holdAt < 0 {
|
||||
return 0
|
||||
}
|
||||
return len(combined) - holdAt
|
||||
}
|
||||
|
||||
func orphanResourceFlush(pending string) string {
|
||||
// A stream that ends mid-token must not surface the model-context
|
||||
// protocol fragment. Preserve ordinary r/re/res prose, but discard any
|
||||
// suffix that has already crossed into the reserved URL-like syntax.
|
||||
if strings.HasPrefix("res://", pending) && len(pending) >= len("res:") {
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(pending, "res://") {
|
||||
digits := strings.TrimPrefix(pending, "res://")
|
||||
if digits == "" || allDigits(digits) {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return resourceHandleShapeRE.ReplaceAllString(pending, "")
|
||||
}
|
||||
|
||||
func (f *orphanResourceStreamFilter) Feed(chunk string) string {
|
||||
if f == nil {
|
||||
return chunk
|
||||
}
|
||||
return f.hold.Feed(chunk)
|
||||
}
|
||||
|
||||
func (f *orphanResourceStreamFilter) Flush() string {
|
||||
if f == nil {
|
||||
return ""
|
||||
}
|
||||
return f.hold.Flush()
|
||||
}
|
||||
|
||||
func allDigits(value string) bool {
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if char < '0' || char > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// StreamDecoder composes resource restoration, source-citation expansion,
|
||||
// source-handle expansion, issue-handle decoding and orphan filtering so callers cannot split handle
|
||||
// processing or apply stages in the wrong order.
|
||||
type StreamDecoder struct {
|
||||
resources *resourceStreamDecoder
|
||||
sources *citationStreamExpander
|
||||
handles *sourceHandleStreamDecoder
|
||||
issues *HandleStreamDecoder
|
||||
mcpServers *HandleStreamDecoder
|
||||
mcpTools *HandleStreamDecoder
|
||||
orphans *orphanResourceStreamFilter
|
||||
}
|
||||
|
||||
func (d *StreamDecoder) Feed(chunk string) string {
|
||||
if d == nil {
|
||||
return chunk
|
||||
}
|
||||
if d.resources != nil {
|
||||
chunk = d.resources.Feed(chunk)
|
||||
}
|
||||
if d.sources != nil {
|
||||
chunk = d.sources.Feed(chunk)
|
||||
}
|
||||
if d.handles != nil {
|
||||
chunk = d.handles.Feed(chunk)
|
||||
}
|
||||
if d.issues != nil {
|
||||
chunk = d.issues.Feed(chunk)
|
||||
}
|
||||
if d.mcpServers != nil {
|
||||
chunk = d.mcpServers.Feed(chunk)
|
||||
}
|
||||
if d.mcpTools != nil {
|
||||
chunk = d.mcpTools.Feed(chunk)
|
||||
}
|
||||
if d.orphans != nil {
|
||||
chunk = d.orphans.Feed(chunk)
|
||||
}
|
||||
return chunk
|
||||
}
|
||||
|
||||
func (d *StreamDecoder) Flush() string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
// Each stage's tail must be fed THROUGH the later stages before those
|
||||
// stages flush their own pending suffix, otherwise a handle completed by
|
||||
// an earlier stage's tail would bypass later decoding.
|
||||
var tail string
|
||||
if d.resources != nil {
|
||||
tail = d.resources.Flush()
|
||||
}
|
||||
if d.sources != nil {
|
||||
tail = d.sources.Feed(tail) + d.sources.Flush()
|
||||
}
|
||||
if d.handles != nil {
|
||||
tail = d.handles.Feed(tail) + d.handles.Flush()
|
||||
}
|
||||
if d.issues != nil {
|
||||
tail = d.issues.Feed(tail) + d.issues.Flush()
|
||||
}
|
||||
if d.mcpServers != nil {
|
||||
tail = d.mcpServers.Feed(tail) + d.mcpServers.Flush()
|
||||
}
|
||||
if d.mcpTools != nil {
|
||||
tail = d.mcpTools.Feed(tail) + d.mcpTools.Flush()
|
||||
}
|
||||
if d.orphans != nil {
|
||||
tail = d.orphans.Feed(tail) + d.orphans.Flush()
|
||||
}
|
||||
return tail
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package modelcontext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
toolDatabaseQuery = "database_query"
|
||||
toolDataAnalysis = "data_analysis"
|
||||
toolWikiReadIssue = "wiki_read_issue"
|
||||
toolWikiUpdateIssue = "wiki_update_issue"
|
||||
)
|
||||
|
||||
var issueHandleShapeRE = regexp.MustCompile(`^i[1-9][0-9]*$`)
|
||||
|
||||
// sourceKeySpace identifies which source-handle space an ID-bearing JSON key
|
||||
// belongs to.
|
||||
type sourceKeySpace int
|
||||
|
||||
const (
|
||||
spaceChunk sourceKeySpace = iota
|
||||
spaceDocument
|
||||
spaceDocumentRef // "knowledgeID|title" stored refs; only the ID is durable
|
||||
spaceKnowledgeBase
|
||||
spaceWeb
|
||||
// spaceAnySource accepts a chunk or a document handle in one argument
|
||||
// (read_document's id). It is decode-only: registration never learns a
|
||||
// source from a bare "id" key, whose meaning differs from tool to tool.
|
||||
spaceAnySource
|
||||
)
|
||||
|
||||
// sourceKeySpaces is the single table of ID-bearing keys the source codec
|
||||
// understands. It drives both handle registration (registerSourceIDByKey) and
|
||||
// the handle-shaped-value decode gate (walkJSON), so registration and decoding
|
||||
// cannot drift apart. Every key referenced by a toolHandlePolicies sourceIDKeys
|
||||
// set must appear here (enforced by a test).
|
||||
var sourceKeySpaces = map[string]sourceKeySpace{
|
||||
"chunk_id": spaceChunk, "faq_id": spaceChunk, "chunk_ids": spaceChunk, "faq_ids": spaceChunk,
|
||||
"knowledge_id": spaceDocument, "knowledge_ids": spaceDocument, "suspected_knowledge_ids": spaceDocument,
|
||||
"source_refs": spaceDocumentRef,
|
||||
"knowledge_base": spaceKnowledgeBase, "knowledge_base_id": spaceKnowledgeBase,
|
||||
"knowledge_base_ids": spaceKnowledgeBase, "kb_id": spaceKnowledgeBase, "kb_ids": spaceKnowledgeBase,
|
||||
"source_knowledge_base_id": spaceKnowledgeBase,
|
||||
"url": spaceWeb, "urls": spaceWeb,
|
||||
"id": spaceAnySource,
|
||||
}
|
||||
|
||||
type toolHandlePolicy struct {
|
||||
mcpRoutingKey string // Only the bridge's top-level argument, never external arguments.
|
||||
mcpDirectoryOutput bool
|
||||
opaqueOutput bool // MCP bridge payloads use external identities and schemas.
|
||||
sourceIDKeys map[string]struct{}
|
||||
sourceTextKeys map[string]struct{}
|
||||
sourceOutput bool
|
||||
decodedIssueIDKeys map[string]struct{}
|
||||
encodedIssueIDKeys map[string]struct{}
|
||||
encodeKnownIssueIDs bool
|
||||
}
|
||||
|
||||
// toolHandlePolicies is the complete allowlist for built-in tool fields whose
|
||||
// identifiers need more than the generic resource/source codecs. Field names
|
||||
// alone are deliberately insufficient: a dynamic MCP tool may use the same
|
||||
// name with unrelated semantics and must remain opaque.
|
||||
var toolHandlePolicies = map[string]toolHandlePolicy{
|
||||
"discover_mcp_tools": {opaqueOutput: true, mcpRoutingKey: "server_id", mcpDirectoryOutput: true},
|
||||
"call_mcp_tool": {opaqueOutput: true, mcpRoutingKey: "tool_ref"},
|
||||
"read_file": {},
|
||||
"search_knowledge": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_base_ids": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
// read_document takes one id that may name a document (doc://N) or a chunk
|
||||
// (chunk://N); the "id" key resolves against both handle tables.
|
||||
"read_document": {
|
||||
sourceIDKeys: map[string]struct{}{"id": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
"list_documents": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_base_id": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
// Retired retrieval tools keep their policies so stored histories that
|
||||
// still carry their calls decode and compact exactly as they did.
|
||||
"knowledge_search": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_base_ids": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
"grep_chunks": {
|
||||
sourceOutput: true,
|
||||
},
|
||||
"list_knowledge_chunks": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_id": {}, "faq_id": {}, "chunk_id": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
"get_document_info": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_ids": {}, "faq_ids": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
// Past conversations carry no durable chunk or document IDs, so there is
|
||||
// nothing to compact; the output is prose the model may quote.
|
||||
"search_conversations": {},
|
||||
// Memories are single sentences about the person. They carry no chunk or
|
||||
// document IDs of their own, and the memory item IDs never leave the
|
||||
// service, so there is nothing here for the model to hold a handle on.
|
||||
"search_memory": {},
|
||||
"query_knowledge_graph": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_base_ids": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
toolDatabaseQuery: {
|
||||
sourceTextKeys: map[string]struct{}{"sql": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
// data_analysis exposes the selected document as a fixed table name, so
|
||||
// its SQL never carries a document handle; only knowledge_id is decoded.
|
||||
toolDataAnalysis: {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_id": {}},
|
||||
},
|
||||
"data_schema": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_id": {}},
|
||||
},
|
||||
"web_fetch": {
|
||||
sourceIDKeys: map[string]struct{}{"url": {}, "urls": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
"web_search": {
|
||||
sourceOutput: true,
|
||||
},
|
||||
"wiki_read_page": {
|
||||
sourceOutput: true,
|
||||
},
|
||||
"wiki_read_source_doc": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_id": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
"wiki_write_page": {
|
||||
sourceIDKeys: map[string]struct{}{"source_refs": {}},
|
||||
},
|
||||
"wiki_replace_text": {
|
||||
sourceIDKeys: map[string]struct{}{"source_refs": {}},
|
||||
},
|
||||
"wiki_flag_issue": {
|
||||
sourceIDKeys: map[string]struct{}{"suspected_knowledge_ids": {}},
|
||||
},
|
||||
"wiki_search": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_base_id": {}, "knowledge_base_ids": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
toolWikiReadIssue: {
|
||||
decodedIssueIDKeys: map[string]struct{}{"issue_id": {}},
|
||||
encodedIssueIDKeys: map[string]struct{}{"id": {}},
|
||||
encodeKnownIssueIDs: true,
|
||||
sourceOutput: true,
|
||||
},
|
||||
toolWikiUpdateIssue: {
|
||||
decodedIssueIDKeys: map[string]struct{}{"issue_id": {}},
|
||||
encodeKnownIssueIDs: true,
|
||||
},
|
||||
// The bundled documentation is static text with public URLs; it carries no
|
||||
// workspace identifiers.
|
||||
"search_academy_docs": {},
|
||||
"read_academy_doc": {},
|
||||
// The operation catalog names parameters and result fields with the
|
||||
// canonical keys below, so handles decode inside params and returned IDs
|
||||
// come back as handles. Catalog metadata itself carries no identifiers.
|
||||
"find_operations": {},
|
||||
"run_operation": {
|
||||
sourceIDKeys: map[string]struct{}{
|
||||
"knowledge_base_id": {}, "knowledge_base_ids": {}, "source_knowledge_base_id": {},
|
||||
"knowledge_id": {}, "knowledge_ids": {},
|
||||
},
|
||||
decodedIssueIDKeys: map[string]struct{}{"issue_id": {}},
|
||||
encodedIssueIDKeys: map[string]struct{}{"issue_id": {}},
|
||||
encodeKnownIssueIDs: true,
|
||||
sourceOutput: true,
|
||||
},
|
||||
"spawn_agent": {},
|
||||
"list_agents": {},
|
||||
"send_message": {},
|
||||
"followup_task": {},
|
||||
"interrupt_agent": {},
|
||||
"wait_agent": {},
|
||||
// open_page and view_page link to a knowledge base or document by the
|
||||
// handles the model was shown; the client needs the real IDs.
|
||||
"open_page": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_base_id": {}, "knowledge_id": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
"view_page": {
|
||||
sourceIDKeys: map[string]struct{}{"knowledge_base_id": {}, "knowledge_id": {}},
|
||||
sourceOutput: true,
|
||||
},
|
||||
// Mutation tools echo the slug they acted on and surface validation errors
|
||||
// that can quote a durable KB or document ID. They own no source arguments,
|
||||
// but their output must still be compacted before the model sees it.
|
||||
"wiki_rename_page": {
|
||||
sourceOutput: true,
|
||||
},
|
||||
"wiki_delete_page": {
|
||||
sourceOutput: true,
|
||||
},
|
||||
// Agent-private bookkeeping tools echo model-authored text. They need
|
||||
// compaction so a durable ID quoted back by the model is re-compacted, but
|
||||
// never structured source rendering.
|
||||
"thinking": {},
|
||||
"todo_write": {},
|
||||
"ask_user": {},
|
||||
// The page tools quote the user's screen and echo the text they typed
|
||||
// into it: compact any durable ID shown there, mine nothing structured.
|
||||
"read_page": {},
|
||||
"select_tab": {},
|
||||
"fill_page": {},
|
||||
// Skill output is user-authored content of unknown shape. Compact known
|
||||
// durable IDs, but do not mine it for source keys: a skill's JSON may use
|
||||
// "url"/"knowledge_id" with unrelated semantics.
|
||||
"read_skill": {},
|
||||
"execute_skill_script": {},
|
||||
// Sandbox shell/file tools return whatever a skill script produced, so they
|
||||
// carry the same unknown-shape caveat as skill output above.
|
||||
"shell_exec": {},
|
||||
// shell_exec_async results carry opaque work handles (sj_...) that the
|
||||
// work_wait / work_cancel tools consume; they are not source identities.
|
||||
"shell_exec_async": {},
|
||||
"list_sandbox_files": {},
|
||||
"read_sandbox_file": {},
|
||||
"write_sandbox_file": {},
|
||||
"edit_sandbox_file": {},
|
||||
// Installer-only writers for the skill image tree. Same unknown-shape
|
||||
// caveat: they echo paths and byte counts, never knowledge identifiers.
|
||||
"write_skill_file": {},
|
||||
"edit_skill_file": {},
|
||||
// Background-work tools echo work IDs, states and command output; they
|
||||
// never carry knowledge identifiers.
|
||||
"work_wait": {},
|
||||
"work_cancel": {},
|
||||
}
|
||||
|
||||
// HasToolPolicy reports whether a tool has an explicit model-handle policy.
|
||||
// Built-in tools must declare one (even an empty policy) so that adding a tool
|
||||
// is a deliberate decision about what the model may see, rather than a silent
|
||||
// fall-through to fully opaque output.
|
||||
func HasToolPolicy(toolName string) bool {
|
||||
_, ok := toolHandlePolicies[toolName]
|
||||
return ok
|
||||
}
|
||||
|
||||
func sourceArgumentAllowed(toolName, key string) bool {
|
||||
policy, ok := toolHandlePolicies[toolName]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
_, ok = policy.sourceIDKeys[strings.ToLower(key)]
|
||||
return ok
|
||||
}
|
||||
|
||||
// sourceBareTextAllowed reports structured-text arguments (SQL) whose handles
|
||||
// must decode to bare durable IDs rather than academy:// URIs.
|
||||
func sourceBareTextAllowed(toolName, key string) bool {
|
||||
policy, ok := toolHandlePolicies[toolName]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
_, ok = policy.sourceTextKeys[strings.ToLower(key)]
|
||||
return ok
|
||||
}
|
||||
|
||||
func sourceOutputAllowed(toolName string) bool {
|
||||
if toolName == "" {
|
||||
// Preserve the generic low-level facade for non-Agent callers. Agent
|
||||
// lifecycles always provide the concrete tool name.
|
||||
return true
|
||||
}
|
||||
policy, ok := toolHandlePolicies[toolName]
|
||||
return ok && policy.sourceOutput
|
||||
}
|
||||
|
||||
func sourceCompactionAllowed(toolName string) bool {
|
||||
if toolName == "" {
|
||||
return true
|
||||
}
|
||||
policy, ok := toolHandlePolicies[toolName]
|
||||
return ok && !policy.opaqueOutput
|
||||
}
|
||||
|
||||
// decodeToolPolicies handles arguments whose model handles belong to a
|
||||
// tool-private identity space. Source handles are decoded for every tool by
|
||||
// the source codec, because their scheme syntax cannot collide with prose.
|
||||
func (r *Registry) decodeToolPolicies(call *types.LLMToolCall) {
|
||||
if r == nil || call == nil {
|
||||
return
|
||||
}
|
||||
policy, ok := toolHandlePolicies[call.Function.Name]
|
||||
if !ok || len(policy.decodedIssueIDKeys) == 0 {
|
||||
return
|
||||
}
|
||||
call.Function.Arguments = rewriteJSONStringValues(
|
||||
call.Function.Arguments,
|
||||
func(key, value string) string {
|
||||
if _, ok := policy.decodedIssueIDKeys[key]; ok && issueHandleShapeRE.MatchString(strings.TrimSpace(value)) {
|
||||
if durable, ok := r.issues.Resolve(value); ok {
|
||||
return durable
|
||||
}
|
||||
}
|
||||
return value
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// encodeReplayedToolPolicies applies the exact inverse of decodeToolPolicies
|
||||
// to assistant tool calls replayed into a later model round. Only durable
|
||||
// values already proven and registered in this request are compacted.
|
||||
func (r *Registry) encodeReplayedToolPolicies(call *chat.ToolCall) {
|
||||
if r == nil || call == nil {
|
||||
return
|
||||
}
|
||||
policy, ok := toolHandlePolicies[call.Function.Name]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
call.Function.Arguments = r.encodeMCPArguments(call.Function.Name, call.Function.Arguments)
|
||||
call.Function.Arguments = rewriteJSONStringValues(
|
||||
call.Function.Arguments,
|
||||
func(key, value string) string {
|
||||
if _, ok := policy.sourceTextKeys[key]; ok {
|
||||
return r.sources.CompactKnownText(value)
|
||||
}
|
||||
if _, ok := policy.decodedIssueIDKeys[key]; ok {
|
||||
return r.issues.EncodeKnownText(value)
|
||||
}
|
||||
return value
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (r *Registry) unresolvedPrivateToolHandles(toolName, raw string) []string {
|
||||
if r == nil || raw == "" {
|
||||
return nil
|
||||
}
|
||||
policy, ok := toolHandlePolicies[toolName]
|
||||
if !ok || len(policy.decodedIssueIDKeys) == 0 {
|
||||
return nil
|
||||
}
|
||||
var unresolved []string
|
||||
_ = walkJSONStringValues(raw, func(key, value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if _, ok := policy.decodedIssueIDKeys[key]; ok && issueHandleShapeRE.MatchString(value) {
|
||||
if _, ok := r.issues.Resolve(value); !ok {
|
||||
unresolved = append(unresolved, value)
|
||||
}
|
||||
}
|
||||
return value
|
||||
})
|
||||
return unresolved
|
||||
}
|
||||
|
||||
// encodeToolPrivateResult registers and compacts identifiers that are local to
|
||||
// one built-in tool family. MCP routing fields have an explicit envelope
|
||||
// policy; remote schemas, arguments and execution results remain opaque.
|
||||
func (r *Registry) encodeToolPrivateResult(toolName, output string) string {
|
||||
if r == nil || output == "" {
|
||||
return output
|
||||
}
|
||||
policy, ok := toolHandlePolicies[toolName]
|
||||
if !ok {
|
||||
return output
|
||||
}
|
||||
if policy.mcpDirectoryOutput {
|
||||
return r.encodeMCPDirectory(output)
|
||||
}
|
||||
if len(policy.encodedIssueIDKeys) > 0 {
|
||||
output = rewriteJSONStringValues(output, func(key, value string) string {
|
||||
if _, ok := policy.encodedIssueIDKeys[key]; ok && strings.TrimSpace(value) != "" {
|
||||
if issueHandleShapeRE.MatchString(strings.TrimSpace(value)) {
|
||||
// Model-facing tool messages can be replayed across several
|
||||
// rounds. Never treat an existing temporary handle as a new
|
||||
// durable issue identity and allocate i2/i3 drift.
|
||||
return value
|
||||
}
|
||||
return r.issues.Register(value)
|
||||
}
|
||||
return value
|
||||
})
|
||||
}
|
||||
if policy.encodeKnownIssueIDs {
|
||||
output = r.issues.EncodeKnownText(output)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
func rewriteJSONStringValues(raw string, rewrite func(key, value string) string) string {
|
||||
var value interface{}
|
||||
if json.Unmarshal([]byte(raw), &value) != nil {
|
||||
return raw
|
||||
}
|
||||
value = walkJSONValue("", value, rewrite)
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func walkJSONStringValues(raw string, rewrite func(key, value string) string) error {
|
||||
var value interface{}
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return err
|
||||
}
|
||||
walkJSONValue("", value, rewrite)
|
||||
return nil
|
||||
}
|
||||
|
||||
func walkJSONValue(key string, value interface{}, rewrite func(key, value string) string) interface{} {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return rewrite(strings.ToLower(key), typed)
|
||||
case []interface{}:
|
||||
for i := range typed {
|
||||
typed[i] = walkJSONValue(key, typed[i], rewrite)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
for childKey, item := range typed {
|
||||
typed[childKey] = walkJSONValue(childKey, item, rewrite)
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// Some providers double-encode items. Unwrap only this built-in's array before
|
||||
// resolving source handles; doing it at Execute time leaves nested url://N values
|
||||
// unresolved. ModelArguments has already retained the exact provider payload.
|
||||
func normalizeWebFetchItems(calls []types.LLMToolCall) {
|
||||
for i := range calls {
|
||||
if calls[i].Function.Name != "web_fetch" {
|
||||
continue
|
||||
}
|
||||
var args map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(calls[i].Function.Arguments), &args) != nil {
|
||||
continue
|
||||
}
|
||||
var wrapped string
|
||||
if json.Unmarshal(args["items"], &wrapped) != nil {
|
||||
continue
|
||||
}
|
||||
var items []json.RawMessage
|
||||
if json.Unmarshal([]byte(wrapped), &items) != nil || len(items) == 0 {
|
||||
continue
|
||||
}
|
||||
args["items"] = json.RawMessage(wrapped)
|
||||
if encoded, err := json.Marshal(args); err == nil {
|
||||
calls[i].Function.Arguments = string(encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package modelcontext
|
||||
|
||||
import "testing"
|
||||
|
||||
// Every key a tool declares as a source-ID argument must have a registration
|
||||
// space, otherwise its values could be decoded from handles but never
|
||||
// registered (or vice versa) — the drift this table exists to prevent.
|
||||
func TestEverySourceIDKeyHasARegistrationSpace(t *testing.T) {
|
||||
for tool, policy := range toolHandlePolicies {
|
||||
for key := range policy.sourceIDKeys {
|
||||
if _, ok := sourceKeySpaces[key]; !ok {
|
||||
t.Errorf("tool %s declares source key %q with no entry in sourceKeySpaces", tool, key)
|
||||
}
|
||||
}
|
||||
for key := range policy.sourceTextKeys {
|
||||
if _, ok := sourceKeySpaces[key]; ok {
|
||||
t.Errorf("tool %s declares %q as free text but sourceKeySpaces also claims it as an ID key", tool, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user