schema

package
v0.6.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 8 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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, static message-SHAPE validation, and the prompt-cache breakpoint rule: MaxBreakpoints (the provider's cap), CountBreakpoints / CountBreakpointsEscaped (the one structural count of a wire body), ElemMarks, MayHoldBreakpoint and HasBlockBreakpoint. ContentText and ToolResultText apply the MessageText rule to raw gjson values.

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

View Source
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.

View Source
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.

View Source
const (
	WireAnthropic = "anthropic"
	WireOpenAI    = "openai" // Chat Completions
	WireResponses = "responses"
)

The wire dialects a request body can be in. The provider alone does not say: OpenAI speaks two (Chat Completions and Responses), and they differ in where the transcript lives (`messages` or `input`), how a tool is declared and how a tool call is written.

View Source
const LookbackBlocks = 20

LookbackBlocks is how far the provider's backward read-walk reaches from a cache_control breakpoint, in content blocks. Here so cacheinject and the host's breakpoint steps (apply.MarkInBandFollowUp) read one figure; see docs/components/caching.md.

View Source
const MaxBreakpoints = 4

MaxBreakpoints is the provider's hard cap on cache breakpoints per request. Over it, the request fails with a 400. Every host and component reads this one figure.

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 CanonicalMessage added in v0.6.5

func CanonicalMessage(m schemas.ChatMessage) schemas.ChatMessage

CanonicalMessage returns m in canonical form: every content block's cache_control removed, and a list of one plain text block written as its string. It copies rather than mutates: m may be a live request's own message, and clearing a field in place would remove the real breakpoint from the request itself.

func CanonicalWireMessage added in v0.6.5

func CanonicalWireMessage(raw string) (b []byte, ok bool)

CanonicalWireMessage returns the canonical JSON of one wire message (an element of `messages`, or of a Responses `input`): cache_control removed at every depth, a one-plain-text-block `content` written as its string (on the message, and on a `tool_result` block inside it), keys in sorted order, and numbers as their literal text. Decoded as float64, two integers above 2^53 that differ would read as one, and so would the two messages. ok is false for bytes that are not JSON.

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 ContentText added in v0.6.5

func ContentText(v gjson.Result) string

ContentText returns the text of a raw wire `content` (or `output`) value. It is the gjson twin of MessageText and follows the same rule:

  • a string is returned as it is;
  • an array gives the text of its blocks joined with no separator, in order;
  • a block that carries no string `text` (an image, a nested object) adds nothing;
  • any other value (null, number, missing) gives "".

Use it instead of gjson's String() on a value that may be an array. String() on an array returns the raw JSON, quotes and escapes included, so a comparison against the original text never matches and a token count is wrong.

func ElemMarks added in v0.6.5

func ElemMarks(v gjson.Result) int

ElemMarks counts the breakpoint marks on one array element (a system block, a tool, or a content block) with the hot-path prefilter. The host placer uses it to see whether a target block already holds one.

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 HasBlockBreakpoint added in v0.6.5

func HasBlockBreakpoint(m *bschemas.ChatMessage) bool

HasBlockBreakpoint reports whether a chat-schema message already carries a breakpoint on one of its content blocks. The chat-schema twin of CountBreakpoints, for components that hold bifrost messages and not the wire body.

func IsResponses added in v0.6.5

func IsResponses(wire string) bool

IsResponses reports whether wire is the Responses dialect.

func MayHoldBreakpoint added in v0.6.5

func MayHoldBreakpoint(raw string) bool

MayHoldBreakpoint is the cheap prefilter in front of every structural parse on the hot path. A mark key can be a field of raw only if "cache" is a substring of raw (a key spelled with a JSON \u escape is the one miss; see CountBreakpointsEscaped). A plain substring scan is memchr-fast. gjson.Get on a message with 50 KB of tool output parses that text. The filter errs only toward doing the parse, never toward missing a plainly spelled mark.

It must NOT also accept "\u". Go's encoder writes <, > and & as \u escapes, so most tool output holds one, and the parse would run on nearly every message.

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

func TextTokens(s string) int

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 ToolResultText added in v0.6.5

func ToolResultText(blk gjson.Result) string

ToolResultText returns the text of an Anthropic tool_result block: its `content`, as a string or as an array of blocks.

func WireFor added in v0.6.5

func WireFor(provider, api string) string

WireFor returns the wire dialect of a request. This is the one place that decides it; every host and library package asks here instead of testing the route or the API name itself.

api is the API name a route carries ("responses", or "" for the provider's default) or the upstream path ("/v1/responses"). Both name the Responses dialect.

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 Breakpoints added in v0.6.5

type Breakpoints struct {
	System   int // system.#.cache_control / .cachePoint
	Tools    int // tools.#.cache_control / .cachePoint
	Messages int // messages.#.cache_control (message level)
	Blocks   int // messages.#.content.#.cache_control / .cachePoint (content-block level)
}

Breakpoints is where a request's prompt-cache breakpoints sit, split by the location the provider hashes them at. `tools` and `system` render AHEAD of `messages`, so the location decides how much of the prefix a breakpoint protects.

func CountBreakpoints added in v0.6.5

func CountBreakpoints(body []byte) Breakpoints

CountBreakpoints counts every breakpoint the provider will see in this request, by location. It takes the raw wire body, so it sees `system` and `tools` and the marks on `tool_result` blocks, which a component working on the chat schema cannot see (issue #32).

This is the HOT-PATH count: it runs twice per request. Its prefilter is "cache" only, so a key spelled with a \u escape is not counted. Use CountBreakpointsEscaped when that must be exact.

ONE pass over the top-level object, not one gjson `#.field` query per location. The path form re-scanned the whole body seven times and cost about 22% of the rewrite path's CPU on real 600 KB Claude Code requests.

func CountBreakpointsEscaped added in v0.6.5

func CountBreakpointsEscaped(body []byte) Breakpoints

CountBreakpointsEscaped is CountBreakpoints with an exact prefilter: it also counts a mark whose key is spelled with a \u escape. It is slower on bodies that hold any \u, so only the callers that need "is there any mark at all" use it (apply.hasCacheBreakpoint).

func (Breakpoints) Total added in v0.6.5

func (b Breakpoints) Total() int

Total is the figure the provider's cap (MaxBreakpoints) applies to.

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.

func (ToolCall) Command added in v0.1.1

func (t ToolCall) Command() string

Command renders the call as a single command-ish line: the `command` string for a shell tool, else the tool name followed by its arguments. It is the string a command-keyed filter selector matches against.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL