Documentation
¶
Overview ¶
Package schema holds the helpers this project layers over bifrost's message schema: token counting, deep-clone, MessageText/SetMessageText, Rewritable, ToolCalls (which pairs a tool result with the call that produced it), SessionHead, and static message-SHAPE validation.
Message-shape validation ¶
ValidateShapeFor checks a message list against the provider's message-SHAPE rules — the rules that make a request well-formed regardless of its content.
WHY THIS EXISTS. Four separate shape violations shipped in `summarize` and every one of them was found REACTIVELY, by a live provider rejection or a benchmark failure, each masked by the one before it:
2edb9d4 400 messages.1: role 'system' must precede an 'assistant' message or end the array fb5c460 400 messages.N.content.M: unexpected `tool_use_id` found in `tool_result` blocks e7d1aa8 400 messages.N: `tool_use` ids were found without `tool_result` blocks immediately after e9bf3a7 panic: index out of range [-1] (a short transcript; see NOT CHECKED below)
None was findable by the project's existing methods. No test asserted the shape of what a component emitted, and every offline measurement replayed through the `/compact` endpoint, which runs the pipeline and returns the rewritten body WITHOUT forwarding it upstream — so no provider ever validated it. Replay can tell you what a component removed; it is structurally incapable of telling you whether the result is a sendable request.
The first three are checkable statically, with no provider and no model, because they are properties of the message list alone. That is what this is for: a component that mutates a message list can be asserted well-formed in a unit test, closing the blind spot without paying for live traffic on every change.
WHERE IT RUNS. Unit tests, over the pipeline's NORMALIZED view of a transcript — the shape apply.normalize produces and components mutate, where an Anthropic `tool_use` block has been lifted into bifrost's ToolCalls and each `tool_result` block is its own synthetic role=tool message.
It is deliberately NOT on the request hot path, but NOT because of cost. Measured on the eval box:
BenchmarkValidateShape166-16 25543 ns/op 9495 B/op 121 allocs/op BenchmarkValidateShape500-16 72796 ns/op 35492 B/op 357 allocs/op BenchmarkValidateShape5000-16 801821 ns/op 307919 B/op 3508 allocs/op
73 µs on a 500-message transcript is ~0.007% of a one-second provider call, and less than this package's own tokenizer plus apply.normalize already cost per request. Nor is "fail-open" a reason to stay off: fail-open IS a decision — validate the compacted body, revert to the original on violation, forward that. It converts a guaranteed provider 400 into a silently-lost saving, which is the trade this repo makes everywhere else.
The real blocker is the DIALECT GATE, and it is why ValidateShapeFor takes a provider. system-position is an Anthropic rule; OpenAI imposes no positional constraint on system/developer messages, and `/compact` defaults to OpenAI (proxy/proxy.go:566). Wired to the hot path with that rule ungated, every OpenAI request whose client re-injects a system message mid-array would be reverted and its saving silently lost — a savings regression dressed as a safety check. With the gate in place the remaining work is a post-pipeline check in apply.Body that reverts on violation. That is a separate change.
NOT CHECKED, and why — so nobody "fixes" these:
- CONSECUTIVE SAME-ROLE messages. Must NOT be checked. `summarize`'s own legal output is [msgs[0], summary(user), user-tail...] — consecutive user messages. An alternation rule would reject the very output this validator exists to bless, and Anthropic accepts it.
- e9bf3a7's PANIC inside boundary arithmetic. No check on the output list can see it: by the time there is a list to inspect the panic has already happened (and pipeline.runOne swallowed it into verdict=reverted). Shape validation is not a substitute for exercising a component on transcripts shorter than its own thresholds.
- role="tool" reaching the Anthropic wire. Structurally invisible here, because apply.normalize maps a legal wire and one carrying the illegal role onto the IDENTICAL normalized list. It is a raw-BYTES property, so it is checked on the bytes, by apply/toolrole_wire_test.go and by the role predicate in apply/shape_validate_test.go.
- ORPHANED `<<cg:HASH>>` markers. Deciding one needs the expansion Store, and a Store dependency does not belong in this package.
- FIRST message not user, and a TRAILING assistant message. Neither is a hard provider rejection, and prefill (a trailing assistant turn) is a supported Anthropic feature.
- Token limits, model names, sampling parameters, or anything content-dependent. This is a shape validator, not a request validator.
Package schema wraps bifrost's provider-agnostic chat schema with the helpers context-guru components need: token accounting, deep-clone for fail-open snapshots, tool-result iteration, and byte-preservation for lossless round-trips of provider-specific fields.
Components operate directly on *schemas.BifrostChatRequest (see package components); this package is the small toolbox around that type, not a competing model. Wire<->schema conversion lives in the host adapters — the bifrost proxy gets it for free from bifrost's transport, a sidecar plugin uses FromOpenAIBytes/FromAnthropicBytes (added in P3).
Index ¶
- Constants
- func BlockText(b schemas.ChatContentBlock) string
- func CloneMessages(in []schemas.ChatMessage) []schemas.ChatMessage
- func FormatShapeViolations(vs []ShapeViolation, msgs []schemas.ChatMessage) string
- func MessageText(m schemas.ChatMessage) string
- func MessagesTokens(req *schemas.BifrostChatRequest) int
- func Rewritable(m schemas.ChatMessage) bool
- func SessionHead(msgs []schemas.ChatMessage) (sys, firstUser string)
- func SetMessageText(m *schemas.ChatMessage, text string)
- func TextTokens(s string) int
- func ToolCalls(req *schemas.BifrostChatRequest) map[int]ToolCall
- func WorkingDirOf(msgs []schemas.ChatMessage) string
- type Provider
- type ShapeViolation
- type ToolCall
Constants ¶
const ( SummaryHeader = "=== History Summary ===" // summarize CacheAwareSummaryHeader = "=== Compacted Context (cache-aware summary) ===" // cache_aware_summarizer )
The first line of the message a summarizer splices in place of the turns it replaces. apply reads them to recognise a splice that kept the message count (a one-message span), which must still go through the count-changing rebuild (#727 review). One place for both, so a builder and the check cannot drift apart.
const ( RuleSystemPosition = "system-position" RuleAnsweredToolUse = "answered-tool-use" RulePairedToolResult = "paired-tool-result" RuleNonEmptyContent = "non-empty-content" )
Shape rule identifiers, so a test can assert on the specific invariant it exists for rather than on wording.
Variables ¶
This section is empty.
Functions ¶
func BlockText ¶
func BlockText(b schemas.ChatContentBlock) string
BlockText returns the text payload of a content block, or "" if the block carries no text (image/audio/file/refusal).
func CloneMessages ¶
func CloneMessages(in []schemas.ChatMessage) []schemas.ChatMessage
CloneMessages deep-copies a message slice via JSON round-trip. Used to snapshot a request before a component runs so the pipeline can restore it on error/panic or when a component fails the never-worse gate. JSON round-trip is safe because bifrost's content types implement custom (Un)MarshalJSON that preserve cache_control/citations/cachePoint.
func FormatShapeViolations ¶ added in v0.1.1
func FormatShapeViolations(vs []ShapeViolation, msgs []schemas.ChatMessage) string
FormatShapeViolations renders violations one per line for a test failure message, with the list's roles appended — the roles are what makes a shape failure diagnosable.
func MessageText ¶
func MessageText(m schemas.ChatMessage) string
MessageText returns the concatenated text of a message, handling both the string-content and block-content representations.
func MessagesTokens ¶
func MessagesTokens(req *schemas.BifrostChatRequest) int
MessagesTokens estimates the token cost of a request's messages by counting the message CONTENT text — what the model actually reads — not the JSON envelope. This is the signal the never-worse gate needs: control metadata like cache_control adds envelope bytes but no model-visible tokens, so a cache-injection Reformat must not look "worse" for adding it.
func Rewritable ¶
func Rewritable(m schemas.ChatMessage) bool
Rewritable reports whether m's content can be safely replaced with a plain text string (via SetMessageText) without losing data. It is false when the message carries any non-text content block — image/audio/file/refusal, or a block type bifrost does not model (e.g. Anthropic tool_result, whose payload lives in fields MessageText never reads). Those bytes would vanish on a text-only rewrite and were never stashed, so components must skip such messages. String content and all-text block content are rewritable.
func SessionHead ¶ added in v0.1.1
func SessionHead(msgs []schemas.ChatMessage) (sys, firstUser string)
SessionHead returns the two strings the derived session key is hashed from: the conversation's HEAD system text and its first user message.
"Head" is load-bearing. The obvious reading — concatenate every system-role message — is what this replaced, and it is wrong for the Claude Agent SDK: that host APPENDS a fresh system-role message on every turn carrying its remaining- budget reminder (`<system-reminder><total_tokens>N tokens left</total_tokens>`), so the concatenation changed on every single request and each turn of one conversation derived a DIFFERENT key. Dedup memory, the extract_llm result cache and frozen offload decisions are all scoped to that key, so none of them ever accumulated past one turn.
A conversation only ever grows at the TAIL, so its head is the one part that is immutable by construction. Taking the first system-role message (plus the first user message, already head-only) is therefore stable across turns without asking the host for anything. Later system-role messages are deliberately ignored: they are per-turn host injections, never conversation identity.
func SetMessageText ¶
func SetMessageText(m *schemas.ChatMessage, text string)
SetMessageText replaces a message's content with a single text string, collapsing any block structure. Components that rewrite a whole message's text (e.g. cmdfilter, offload markers) use this.
func TextTokens ¶
TextTokens counts tokens in a raw string via the shared tokenizer.
func ToolCalls ¶ added in v0.1.1
func ToolCalls(req *schemas.BifrostChatRequest) map[int]ToolCall
ToolCalls pairs every tool-result message in req with the call that produced it, keyed by the message's index in req.Input. A message whose id matches no call — unmatched, missing, or a tool result with no preceding tool_use at all — simply has no entry, so a caller reads the zero ToolCall and falls back to whatever it did before. Ids are collected as the transcript is walked, so a result can only pair with a call that PRECEDES it, and several results in one message (Anthropic packs them into one user message; normalize splits them) each pair on their own id.
func WorkingDirOf ¶ added in v0.5.4
func WorkingDirOf(msgs []schemas.ChatMessage) string
WorkingDirOf returns the agent's launch directory, or "" when the request does not state one.
Scans every message rather than indexing the one the marker occupies today (messages[1]): a host may inject a message ahead of it and the environment block sometimes rides in the system prompt, and a dimension that silently stops recording when a client reorders its preamble is worse than one pass over an already-normalized slice.
The FIRST marker wins, because a transcript accumulates. Later turns quote other directories — this function's own test file does — and the last match would attribute a request to whatever folder was most recently mentioned in conversation.
Types ¶
type Provider ¶
type Provider = schemas.ModelProvider
Provider identifies the wire dialect a request arrived in. It drives provider-specific behaviour (e.g. cache_control is Anthropic-family) and how the adapter renders bytes back out.
type ShapeViolation ¶ added in v0.1.1
type ShapeViolation struct {
Index int // message index, or -1 when the violation is about the list as a whole
Rule string // short, stable identifier for the invariant
Msg string // human-readable, mirroring the provider's own wording where possible
}
ShapeViolation is one broken invariant, phrased to point at the message that broke it.
func ValidateShape ¶ added in v0.1.1
func ValidateShape(msgs []schemas.ChatMessage) []ShapeViolation
ValidateShape reports every message-shape invariant the list breaks, judged as an ANTHROPIC request. It is the Anthropic-dialect shorthand for ValidateShapeFor; see there for the invariants and for why the dialect matters.
func ValidateShapeFor ¶ added in v0.1.1
func ValidateShapeFor(provider schemas.ModelProvider, msgs []schemas.ChatMessage) []ShapeViolation
ValidateShapeFor reports every message-shape invariant the list breaks when sent to `provider`. An empty result means the list is well-formed in the ways that provider enforces structurally.
THE PROVIDER ARGUMENT IS NOT DECORATION. Two of the four invariants are properties of the Anthropic-style tool protocol and hold for every provider that speaks it; the other two are Anthropic's own rules and are simply FALSE elsewhere. OpenAI imposes no positional constraint on system/developer messages, so checking system-position against an OpenAI transcript reports a violation on every turn where the client re-injects a system message — ordinary traffic, and `/compact` defaults to OpenAI (proxy/proxy.go:566). An ungated rule would therefore be a savings regression the moment this is used on the request path, which is why the gate is a prerequisite for that wiring rather than a nicety.
The invariants, and why each one exists:
- system-position — ANTHROPIC ONLY. A system-role message away from index 0 must be immediately followed by an assistant message, or end the array. This is the provider's own wording, and it is the defect that made `summarize` unusable on every call: it emitted [msgs[0], summary(system), tail...], so with the usual system prompt at index 0 a second system role landed at index 1 in front of the kept tail.
- answered-tool-use — ALL PROVIDERS. Every `tool_use` must be answered by a `tool_result` in the messages immediately following it. Removing a span can delete the answer while keeping the call: preserving msgs[0] when it is an assistant tool-call message does exactly that.
- paired-tool-result — ALL PROVIDERS. Every `tool_result` must answer a `tool_use` that appeared earlier. Removing a span can delete the call while keeping the answer. The mirror of (2), and the reason both are checked: e7d1aa8 showed they are one mistake seen from either side, and fixing one alone leaves the other live — which is what happened.
- non-empty-content — ANTHROPIC ONLY, on the evidence available. A message that CARRIES content whose text is blank is a hard 400 ("text content blocks must be non-empty"), and this pipeline has ~20 places that can produce one: every component that rewrites a message does it through SetMessageText, and any of them reducing a message to the empty string writes `""` straight onto the wire. `summarize` itself is NOT one of them — it refuses a blank summary (components/offload/summarize.go:201), confirmed by mutation: making its model return "" makes it decline rather than emit empty content. So this rule guards the OTHER rewriters (cmdfilter, dedup, skeleton, textclean and the rest), which have no such guard. Gated to Anthropic because an Anthropic rejection is what is on record; widen it when another provider's 400 is.
The rule is deliberately narrow in three ways, to preserve the property that makes this validator usable at all — content-shape false positives being impossible rather than merely absent. It fires only when Content is non-nil (a pure tool-call assistant message has nil content and is legal), only when the message carries no non-text block (Rewritable, so an image-only, thinking-only or tool_result-payload message is never judged by its text), and never on a role=tool message or an assistant message carrying ToolCalls, whose meaning lives in fields other than their text.
func ValidateShapeGrouped ¶ added in v0.6.2
func ValidateShapeGrouped(provider schemas.ModelProvider, msgs []schemas.ChatMessage, groups []int) []ShapeViolation
ValidateShapeGrouped is ValidateShapeFor with #457's wire grouping: groups[i] names the ORIGINAL wire message normalized message i was extracted from, so several normalized messages (an Anthropic tool_result's synthetic tool message and the sibling text block beside it) can share one group. Pass nil when every normalized message is its own wire message, which is the OpenAI-shaped case and every legacy caller.
The grouping matters for exactly one rule. A wire message that holds a sibling text block BESIDE a tool_result (#460) normalizes to two messages in body order — the sibling (role=user), then the result (role=tool) — so a tool_use answered by it is still answered correctly ON THE WIRE but is no longer ADJACENT in the normalized list, and a literal-adjacency answered-tool-use check reports a violation the provider would not. With groups, the "run" that may answer a call is the members of the ONE wire group that follows it, which is the adjacency the provider actually enforces. A groups slice whose length disagrees with msgs (an earlier component changed the count; see summarizeSpan's own defensive collapse of the same condition) is ignored rather than trusted.
The grouped scan assumes the message AFTER a call STARTS a wire group — a call never shares a group with the message that follows it. apply's normalize guarantees this (an assistant message is one whole-message slot, so a new group begins right after it). A grouping that does not hold that property gets a silently wrong scan, so a caller must build groups the way normalize does.
func (ShapeViolation) String ¶ added in v0.1.1
func (v ShapeViolation) String() string
type ToolCall ¶ added in v0.1.1
type ToolCall struct {
Name string // "Bash", "Read", "Grep", …
Args string // raw JSON arguments, e.g. `{"command":"rg -n foo"}`; "" when absent
}
ToolCall is the call that PRODUCED a tool result: the tool's name and its raw input arguments (a JSON object, as the wire carried it).
It exists because the premise "a proxy never sees the command that produced an output" is false. Both dialects put the call and its result in the same request, joined by an id — Anthropic as an assistant `tool_use` block referenced by the `tool_result`'s `tool_use_id`, OpenAI as an assistant `tool_calls[]` entry referenced by the tool message's `tool_call_id` — so a filter can key on the command (`rg -n foo`, `Read /x/y.go`) and not only on the output's shape.
Anthropic's `tool_use` blocks are not modelled by bifrost's chat schema, so the host's normalize step lifts them into ToolCalls (see apply.attachToolUse); this helper then reads one uniform shape for both dialects.