refactor(modelcontext): unify handle terminology and document the merged package

Internal-only rename of the remaining alias-era names (ChunkAlias ->
ChunkHandle, aliasForRealValue -> handleForDurable, realForAlias ->
durableForHandle, OrphanAliases -> OrphanHandles, shortSourceAliasRE ->
shortSourceHandleRE, locals and comments). Exported API names are
unchanged. The README now describes the single-package layout, the
handleTable/streamHold primitives and the sourceKeySpaces policy table.
main
wizardchen 2026-07-27 01:17:36 +08:00 committed by lyingbug
parent 69b792398e
commit 6663268504
10 changed files with 125 additions and 109 deletions

View File

@ -1,7 +1,20 @@
# Model context boundary
`modelcontext.Registry` is the only application-facing boundary for values
that are shortened before an LLM call and restored afterwards.
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 (`cN`/`dN`/`bN`/`wN`) and the tool-argument codec |
| `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 |
| `handles.go` | exported `HandleTable` for invocation-local spaces (`iN`, `ref-N`, `c000`) |
## Identity rules
@ -24,7 +37,7 @@ that are shortened before an LLM call and restored afterwards.
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 aliases neither disappear nor drift to
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
@ -45,7 +58,10 @@ 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.
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` and `data_analysis.sql` have an explicit policy because
source handles can be embedded inside quoted SQL values; unquoted SQL aliases
and arbitrary prose are never rewritten. Wiki issue IDs use the same lifecycle

View File

@ -11,7 +11,7 @@ import (
"strings"
)
const sourceAliasProtocolPrompt = `
const sourceHandleProtocolPrompt = `
## Source handling protocol (system-owned)
Retrieved content uses request-local source handles: cN identifies a knowledge chunk, wN a web page, dN a document, and bN a knowledge base.
@ -33,9 +33,9 @@ const citationDisabledProtocolPrompt = `
// model call. Citation formatting stays out of custom and template prompts.
func sourceProtocolPrompt(citationsEnabled bool) string {
if citationsEnabled {
return sourceAliasProtocolPrompt + citationEnabledProtocolPrompt
return sourceHandleProtocolPrompt + citationEnabledProtocolPrompt
}
return sourceAliasProtocolPrompt + citationDisabledProtocolPrompt
return sourceHandleProtocolPrompt + citationDisabledProtocolPrompt
}
// ProtocolPrompt returns the source protocol configured for this registry.
@ -91,20 +91,20 @@ func (r *sourceRegistry) CompactPublicCitations(text string) string {
if chunkID == "" {
return tag
}
alias := r.RegisterChunk(ChunkReference{
handle := r.RegisterChunk(ChunkReference{
ChunkID: chunkID,
KnowledgeBaseID: publicAttr(publicKBAttrRE, tag),
DocumentTitle: publicAttr(docAttrRE, tag),
})
return `<ref id="` + alias + `"/>`
return `<ref id="` + handle + `"/>`
})
return publicWebTagRE.ReplaceAllStringFunc(text, func(tag string) string {
rawURL := publicAttr(urlAttrRE, tag)
if rawURL == "" {
return tag
}
alias := r.RegisterWeb(rawURL, publicAttr(titleAttrRE, tag))
return `<ref id="` + alias + `"/>`
handle := r.RegisterWeb(rawURL, publicAttr(titleAttrRE, tag))
return `<ref id="` + handle + `"/>`
})
}
@ -154,13 +154,13 @@ func (r *sourceRegistry) registerLabeledReferences(text string) {
}
// ExpandText converts the private model protocol into the existing public
// <kb/> / <web/> contract. Unknown aliases fail closed and disappear.
// <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 aliases.
// by the model, then create canonical tags solely from registered handles.
text = modelKBTagRE.ReplaceAllString(text, "")
text = modelWebTagRE.ReplaceAllString(text, "")
if !r.citationsEnabled {
@ -171,15 +171,15 @@ func (r *sourceRegistry) ExpandText(text string) string {
if len(match) != 2 {
return ""
}
alias := strings.ToLower(match[1])
if chunkID, chunkRef, ok := r.chunks.resolve(alias); ok {
handle := strings.ToLower(match[1])
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(alias); ok {
if rawURL, web, ok := r.webs.resolve(handle); ok {
return fmt.Sprintf(`<web url="%s" title="%s" />`, escapeAttr(rawURL), escapeAttr(web.title))
}
return ""

View File

@ -92,21 +92,21 @@ func (r *sourceRegistry) modelDocumentInfoOutput(rows []map[string]interface{},
count := 0
for _, row := range rows {
knowledgeID := stringValue(row, "knowledge_id")
docAlias := r.RegisterDocument(knowledgeID)
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"))
chunkAlias := r.RegisterChunk(ChunkReference{
chunkHandle := r.RegisterChunk(ChunkReference{
ChunkID: chunkID,
KnowledgeID: knowledgeID,
DocumentTitle: title,
ChunkType: "faq",
})
fmt.Fprintf(&b, " <document id=\"%s\" type=\"faq\">\n", escapeAttr(docAlias))
fmt.Fprintf(&b, " <chunk id=\"%s\" type=\"faq\">\n", escapeAttr(chunkAlias))
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))
}
@ -118,10 +118,10 @@ func (r *sourceRegistry) modelDocumentInfoOutput(rows []map[string]interface{},
continue
}
if docAlias == "" {
if docHandle == "" {
continue
}
fmt.Fprintf(&b, " <document id=\"%s\"", escapeAttr(docAlias))
fmt.Fprintf(&b, " <document id=\"%s\"", escapeAttr(docHandle))
if title := stringValue(row, "title"); title != "" {
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(title))
}
@ -146,9 +146,9 @@ func (r *sourceRegistry) modelDocumentInfoOutput(rows []map[string]interface{},
}
type modelChunk struct {
alias string
docAlias string
kbAlias string
handle string
docHandle string
kbHandle string
title string
chunkType string
index int
@ -182,7 +182,7 @@ func (r *sourceRegistry) modelKnowledgeOutput(mode string, rows []map[string]int
if chunkIndex == 0 {
chunkIndex = intValue(row, "index")
}
chunkAlias := r.RegisterChunk(ChunkReference{
chunkHandle := r.RegisterChunk(ChunkReference{
ChunkID: chunkID,
KnowledgeID: knowledgeID,
KnowledgeBaseID: kbID,
@ -191,9 +191,9 @@ func (r *sourceRegistry) modelKnowledgeOutput(mode string, rows []map[string]int
ChunkType: chunkType,
})
chunks = append(chunks, modelChunk{
alias: chunkAlias,
docAlias: r.RegisterDocument(knowledgeID),
kbAlias: r.RegisterKnowledgeBase(kbID),
handle: chunkHandle,
docHandle: r.RegisterDocument(knowledgeID),
kbHandle: r.RegisterKnowledgeBase(kbID),
title: title,
chunkType: chunkType,
index: chunkIndex,
@ -252,22 +252,22 @@ func (r *sourceRegistry) modelKnowledgeChunksOutput(data map[string]interface{},
func renderKnowledgeChunks(mode string, chunks []modelChunk) string {
type docGroup struct {
alias string
kbAlias string
title string
chunks []modelChunk
order int
handle string
kbHandle string
title string
chunks []modelChunk
order int
}
groupsByKey := make(map[string]*docGroup)
var groups []*docGroup
for _, chunk := range chunks {
key := chunk.docAlias
key := chunk.docHandle
if key == "" {
key = "chunk:" + chunk.alias
key = "chunk:" + chunk.handle
}
group := groupsByKey[key]
if group == nil {
group = &docGroup{alias: chunk.docAlias, kbAlias: chunk.kbAlias, title: chunk.title, order: chunk.inputOrder}
group = &docGroup{handle: chunk.docHandle, kbHandle: chunk.kbHandle, title: chunk.title, order: chunk.inputOrder}
groupsByKey[key] = group
groups = append(groups, group)
}
@ -279,18 +279,18 @@ func renderKnowledgeChunks(mode string, chunks []modelChunk) string {
fmt.Fprintf(&b, "<retrieval type=\"knowledge\" mode=\"%s\">\n", escapeAttr(mode))
for _, group := range groups {
b.WriteString(" <document")
if group.alias != "" {
fmt.Fprintf(&b, " id=\"%s\"", escapeAttr(group.alias))
if group.handle != "" {
fmt.Fprintf(&b, " id=\"%s\"", escapeAttr(group.handle))
}
if group.kbAlias != "" {
fmt.Fprintf(&b, " kb=\"%s\"", escapeAttr(group.kbAlias))
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")
for _, chunk := range group.chunks {
fmt.Fprintf(&b, " <chunk id=\"%s\" index=\"%d\" view=\"%s\"", chunk.alias, chunk.index, chunk.view)
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))
}
@ -335,8 +335,8 @@ func (r *sourceRegistry) modelWebSearchOutput(rows []map[string]interface{}, fal
if rawURL == "" {
continue
}
alias := r.RegisterWeb(rawURL, stringValue(row, "title"))
fmt.Fprintf(&b, " <page id=\"%s\" title=\"%s\">\n", alias, escapeAttr(stringValue(row, "title")))
handle := r.RegisterWeb(rawURL, stringValue(row, "title"))
fmt.Fprintf(&b, " <page id=\"%s\" title=\"%s\">\n", handle, escapeAttr(stringValue(row, "title")))
if snippet := stringValue(row, "snippet"); snippet != "" {
fmt.Fprintf(&b, " <match>%s</match>\n", escapeText(snippet))
}
@ -366,8 +366,8 @@ func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fall
continue
}
title := stringValue(row, "title")
alias := r.RegisterWeb(rawURL, title)
fmt.Fprintf(&b, " <page id=\"%s\"", alias)
handle := r.RegisterWeb(rawURL, title)
fmt.Fprintf(&b, " <page id=\"%s\"", handle)
if title != "" {
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(title))
}

View File

@ -106,7 +106,7 @@ func (r *Registry) DecodeToolCalls(toolCalls []types.LLMToolCall) {
r.decodeToolPolicies(&toolCalls[i])
resolved := toolCalls[i].Function.Arguments
unresolved := append(
r.resources.OrphanAliases(resolved),
r.resources.OrphanHandles(resolved),
r.sources.UnresolvedToolHandlesWithPolicy(
toolCalls[i].Function.Name, resolved, sourceArgumentAllowed,
)...,
@ -181,7 +181,7 @@ func (r *Registry) OrphanResourceHandles(decoded string) []string {
if r == nil {
return nil
}
return r.resources.OrphanAliases(decoded)
return r.resources.OrphanHandles(decoded)
}
func (r *Registry) RegisterChunk(ref ChunkReference) string {
@ -223,7 +223,7 @@ func (r *Registry) ChunkHandle(id string) string {
if r == nil || r.sources == nil {
return ""
}
return r.sources.ChunkAlias(id)
return r.sources.ChunkHandle(id)
}
// CompactKnownText replaces only previously registered durable source IDs.
@ -285,7 +285,7 @@ func (r *Registry) DecodeOutputText(text string) string {
return text
}
text = r.resources.DecodeText(text)
text = r.resources.StripOrphanAliases(text)
text = r.resources.StripOrphanHandles(text)
text = r.sources.ExpandText(text)
return r.issues.DecodeKnownText(text)
}

View File

@ -14,10 +14,10 @@ import (
// 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 alias makes rollout
// provider URL. Giving both forms the same request-local handle makes rollout
// safe without a blocking full-table content rewrite.
//
// The final alternative aliases wiki summary-page slugs (summary/<uuid>). They
// 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).
@ -40,13 +40,13 @@ var storedRefRE = regexp.MustCompile(
// orphan filter.
var resourceHandleShapeRE = regexp.MustCompile(`res://\d+`)
// resourceRegistry assigns low-entropy, request-local aliases to stable resource
// 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 alias registry.
// 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
@ -54,7 +54,7 @@ func newResourceRegistry() *resourceRegistry {
return &resourceRegistry{table: newHandleTable[struct{}]("res://", 4, 1)}
}
// EncodeText replaces stored references with compact, stable aliases.
// EncodeText replaces stored references with compact, stable handles.
func (r *resourceRegistry) EncodeText(value string) string {
if r == nil || value == "" {
return value
@ -64,7 +64,7 @@ func (r *resourceRegistry) EncodeText(value string) string {
})
}
// DecodeText restores every alias currently known to the registry. Aliases are
// 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 {
@ -79,10 +79,10 @@ func (r *resourceRegistry) DecodeText(value string) string {
return value
}
// StripOrphanAliases removes alias-shaped tokens after all known aliases have
// StripOrphanHandles removes handle-shaped tokens after all known handles have
// been restored. Use this only on model output; tool arguments must retain
// unknown aliases long enough for modelcontext to reject the call.
func (r *resourceRegistry) StripOrphanAliases(value string) string {
// unknown handles long enough for modelcontext to reject the call.
func (r *resourceRegistry) StripOrphanHandles(value string) string {
if value == "" {
return value
}
@ -116,19 +116,19 @@ func (r *resourceRegistry) EncodeMessages(messages []chat.Message) []chat.Messag
return encoded
}
// DecodeToolCalls restores aliases in tool-call JSON arguments.
// 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)
}
}
// OrphanAliases returns the distinct alias-shaped tokens in an already-decoded
// 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 alias syntax. Callers should log/observe these
// 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) OrphanAliases(decoded string) []string {
func (r *resourceRegistry) OrphanHandles(decoded string) []string {
if decoded == "" {
return nil
}
@ -147,11 +147,11 @@ func (r *resourceRegistry) OrphanAliases(decoded string) []string {
return orphans
}
func (r *resourceRegistry) aliases() []string {
func (r *resourceRegistry) handles() []string {
pairs := r.table.pairs()
aliases := make([]string, 0, len(pairs))
handles := make([]string, 0, len(pairs))
for _, item := range pairs {
aliases = append(aliases, item.handle)
handles = append(handles, item.handle)
}
return aliases
return handles
}

View File

@ -31,7 +31,7 @@ func TestRegistryAliasesWikiSummarySlug(t *testing.T) {
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 alias.
// The same slug as a tool-call argument value resolves to one handle.
require.Equal(t, "res://0001", r.EncodeText(slug))
}
@ -76,19 +76,19 @@ func TestOrphanAliasesReportsUnresolvableTokens(t *testing.T) {
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
require.Equal(t, "res://0001", r.EncodeText(ref))
// Known alias resolves and leaves no orphan once decoded.
require.Nil(t, r.OrphanAliases(r.DecodeText("see res://0001")))
// 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.OrphanAliases("look at res://0099 and res://0099"))
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.StripOrphanAliases("broken res://1"))
require.Equal(t, "broken ", r.StripOrphanHandles("broken res://1"))
}
func TestOrphanAliasesNilRegistry(t *testing.T) {
var r *resourceRegistry
require.Equal(t, []string{"res://0001"}, r.OrphanAliases("res://0001"))
require.Equal(t, []string{"res://0001"}, r.OrphanHandles("res://0001"))
}

View File

@ -81,7 +81,7 @@ func (r *sourceRegistry) RegisterChunk(ref ChunkReference) string {
if ref.ChunkID == "" {
return ""
}
if shortSourceAliasRE.MatchString(ref.ChunkID) {
if shortSourceHandleRE.MatchString(ref.ChunkID) {
return knownHandle(r.chunks, ref.ChunkID)
}
return r.chunks.register(ref.ChunkID, ref.ChunkID, ref, mergeChunkReference)
@ -110,7 +110,7 @@ func (r *sourceRegistry) RegisterDocument(id string) string {
if r == nil || id == "" {
return ""
}
if shortSourceAliasRE.MatchString(id) {
if shortSourceHandleRE.MatchString(id) {
return knownHandle(r.docs, id)
}
return r.docs.register(id, id, struct{}{}, nil)
@ -121,7 +121,7 @@ func (r *sourceRegistry) RegisterKnowledgeBase(id string) string {
if r == nil || id == "" {
return ""
}
if shortSourceAliasRE.MatchString(id) {
if shortSourceHandleRE.MatchString(id) {
return knownHandle(r.kbs, id)
}
return r.kbs.register(id, id, struct{}{}, nil)
@ -132,7 +132,7 @@ func (r *sourceRegistry) RegisterWeb(rawURL, title string) string {
if r == nil || rawURL == "" {
return ""
}
if shortSourceAliasRE.MatchString(rawURL) {
if shortSourceHandleRE.MatchString(rawURL) {
return knownHandle(r.webs, rawURL)
}
// Dedup on the canonical (fragment-stripped) URL while decoding back to
@ -180,7 +180,7 @@ func firstNonEmpty(values ...string) string {
return ""
}
func (r *sourceRegistry) ChunkAlias(id string) string {
func (r *sourceRegistry) ChunkHandle(id string) string {
handle, _ := r.chunks.handleForKey(id)
return handle
}
@ -191,7 +191,7 @@ func (r *sourceRegistry) ChunkAlias(id string) string {
// package-internal replay paths that predate per-tool contracts.
type toolArgumentPolicy func(toolName, key string) bool
// DecodeToolCallsWithPolicy restores aliases only for fields explicitly owned
// DecodeToolCallsWithPolicy restores handles only for fields explicitly owned
// by the named tool. This prevents dynamic tools with coincidentally named
// fields from inheriting built-in source semantics.
func (r *sourceRegistry) DecodeToolCallsWithPolicy(toolCalls []types.LLMToolCall, policy toolArgumentPolicy) {
@ -244,7 +244,7 @@ func (r *sourceRegistry) collectUnresolvedToolHandles(
return
}
handle := strings.TrimSpace(typed)
if shortSourceAliasRE.MatchString(handle) && (r == nil || r.realForAlias(handle) == "") {
if shortSourceHandleRE.MatchString(handle) && (r == nil || r.durableForHandle(handle) == "") {
seen[handle] = struct{}{}
}
case []interface{}:
@ -316,9 +316,9 @@ func (r *sourceRegistry) EncodeMessagesWithPolicies(
return out
}
var shortSourceAliasRE = regexp.MustCompile(`(?i)^[cdbw][1-9][0-9]*$`)
var shortSourceHandleRE = regexp.MustCompile(`(?i)^[cdbw][1-9][0-9]*$`)
var shortSourceAliasInTextRE = regexp.MustCompile(`(?i)\b[cdbw][1-9][0-9]*\b`)
var shortSourceHandleInTextRE = regexp.MustCompile(`(?i)\b[cdbw][1-9][0-9]*\b`)
// DecodeKnownText restores registered source handles embedded in a structured
// expression such as a built-in SQL tool argument. It must not be used for
@ -327,8 +327,8 @@ func (r *sourceRegistry) DecodeKnownText(text string) string {
if r == nil || text == "" {
return text
}
return shortSourceAliasInTextRE.ReplaceAllStringFunc(text, func(handle string) string {
if real := r.realForAlias(handle); real != "" {
return shortSourceHandleInTextRE.ReplaceAllStringFunc(text, func(handle string) string {
if real := r.durableForHandle(handle); real != "" {
return real
}
return handle
@ -338,14 +338,14 @@ func (r *sourceRegistry) DecodeKnownText(text string) string {
// DecodeKnownQuotedText restores source handles only inside single-quoted,
// double-quoted, or backtick-quoted segments. It is intended for structured
// expressions such as SQL, where replacing an unquoted token could corrupt a
// legitimate table/column alias that happens to look like d1 or b2.
// legitimate table/column handle that happens to look like d1 or b2.
func (r *sourceRegistry) DecodeKnownQuotedText(text string) string {
if r == nil || text == "" {
return text
}
return rewriteQuotedText(text, func(segment string) string {
return shortSourceAliasInTextRE.ReplaceAllStringFunc(segment, func(handle string) string {
if real := r.realForAlias(handle); real != "" {
return shortSourceHandleInTextRE.ReplaceAllStringFunc(segment, func(handle string) string {
if real := r.durableForHandle(handle); real != "" {
return real
}
return handle
@ -353,7 +353,7 @@ func (r *sourceRegistry) DecodeKnownQuotedText(text string) string {
})
}
// UnresolvedQuotedTextHandles reports alias-shaped values inside quoted
// UnresolvedQuotedTextHandles reports handle-shaped values inside quoted
// structured-text segments that do not exist in this request registry.
func (r *sourceRegistry) UnresolvedQuotedTextHandles(text string) []string {
if text == "" {
@ -361,8 +361,8 @@ func (r *sourceRegistry) UnresolvedQuotedTextHandles(text string) []string {
}
seen := make(map[string]struct{})
rewriteQuotedText(text, func(segment string) string {
for _, handle := range shortSourceAliasInTextRE.FindAllString(segment, -1) {
if r == nil || r.realForAlias(handle) == "" {
for _, handle := range shortSourceHandleInTextRE.FindAllString(segment, -1) {
if r == nil || r.durableForHandle(handle) == "" {
seen[handle] = struct{}{}
}
}
@ -441,12 +441,12 @@ func (r *sourceRegistry) registerToolArgumentValue(key string, value interface{}
// 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 alias decode — so the recognized
// 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) {
value = strings.TrimSpace(value)
if value == "" || shortSourceAliasRE.MatchString(value) {
if value == "" || shortSourceHandleRE.MatchString(value) {
return
}
space, ok := sourceKeySpaces[strings.ToLower(key)]
@ -498,20 +498,20 @@ func (r *sourceRegistry) walkJSON(key string, value interface{}, encode bool, al
if encode {
// Encode matches on exact real identifiers (UUIDs/URLs), which do
// not collide with prose, so it stays key-agnostic.
if alias := r.aliasForRealValue(typed); alias != "" {
return alias
if handle := r.handleForDurable(typed); handle != "" {
return handle
}
return typed
}
// Decode only ID-bearing keys, and only when the value is alias-shaped,
// so ordinary strings that coincidentally equal an alias are preserved.
// Decode only ID-bearing keys, and only when the value is handle-shaped,
// so ordinary strings that coincidentally equal an handle are preserved.
if _, ok := sourceKeySpaces[strings.ToLower(key)]; !ok {
return typed
}
if !shortSourceAliasRE.MatchString(strings.TrimSpace(typed)) {
if !shortSourceHandleRE.MatchString(strings.TrimSpace(typed)) {
return typed
}
if real := r.realForAlias(typed); real != "" {
if real := r.durableForHandle(typed); real != "" {
return real
}
return typed
@ -527,7 +527,7 @@ func (r *sourceRegistry) walkJSON(key string, value interface{}, encode bool, al
return value
}
func (r *sourceRegistry) aliasForRealValue(real string) string {
func (r *sourceRegistry) handleForDurable(real string) string {
if handle, ok := r.chunks.handleForKey(real); ok {
return handle
}
@ -543,18 +543,18 @@ func (r *sourceRegistry) aliasForRealValue(real string) string {
return ""
}
func (r *sourceRegistry) realForAlias(alias string) string {
alias = strings.ToLower(strings.TrimSpace(alias))
if real, _, ok := r.chunks.resolve(alias); ok {
func (r *sourceRegistry) durableForHandle(handle string) string {
handle = strings.ToLower(strings.TrimSpace(handle))
if real, _, ok := r.chunks.resolve(handle); ok {
return real
}
if real, _, ok := r.docs.resolve(alias); ok {
if real, _, ok := r.docs.resolve(handle); ok {
return real
}
if real, _, ok := r.kbs.resolve(alias); ok {
if real, _, ok := r.kbs.resolve(handle); ok {
return real
}
if real, _, ok := r.webs.resolve(alias); ok {
if real, _, ok := r.webs.resolve(handle); ok {
return real
}
return ""

View File

@ -347,7 +347,7 @@ func TestModelOutputDoesNotRegisterInternalSchemesAsWebSources(t *testing.T) {
})
// An internal handle in a url-labeled field must never enter the web
// alias space, where CompactKnownText would rewrite it a second time.
// handle space, where CompactKnownText would rewrite it a second time.
require.Contains(t, output, "res://0001")
require.NotContains(t, output, "w1")
require.Contains(t, output, "d1")

View File

@ -45,12 +45,12 @@ func newResourceStreamDecoder(registry *resourceRegistry) *resourceStreamDecoder
return &resourceStreamDecoder{hold: streamHold{
holdLen: func(combined string) int {
hold := 0
for _, alias := range registry.aliases() {
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(alias); n++ {
if n > hold && strings.HasSuffix(combined, alias[:n]) {
for n := 1; n < len(handle); n++ {
if n > hold && strings.HasSuffix(combined, handle[:n]) {
hold = n
}
}

View File

@ -32,7 +32,7 @@ const (
// sourceKeySpaces is the single table of ID-bearing keys the source codec
// understands. It drives both handle registration (registerSourceIDByKey) and
// the alias-shaped-value decode gate (walkJSON), so registration and decoding
// 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{