schema

package
v0.7.15 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 10 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 BlockLoads added in v0.7.11

func BlockLoads(b gjson.Result, fn func(name string))

BlockLoads is both readers: the tools one content block loaded, whoever ran the search.

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 EachMark added in v0.7.11

func EachMark(v gjson.Result, fn func(mark gjson.Result))

EachMark calls fn with each breakpoint mark on one array element (a system block, a tool, or a content block): the value of cache_control and of cachePoint, when it is an object. A null, a string or a bool is no mark. It is the rule behind ElemMarks, for a caller that needs the marks themselves (the accountant reads each mark's ttl).

func EachMessageMark added in v0.7.11

func EachMessageMark(m gjson.Result, fn func(mark gjson.Result))

EachMessageMark calls fn with the mark on a message itself. A message carries only the Anthropic spelling, cache_control: cachePoint is a block, and never sits on a message.

func EachRequestCall added in v0.7.11

func EachRequestCall(wire string, body []byte, fn func(RequestCall))

EachRequestCall is RequestCalls without the slice, for a caller on the request path.

func EachRequestPart added in v0.7.11

func EachRequestPart(wire string, body []byte, onCall func(RequestCall), onResult func(RequestResult))

EachRequestPart reads the calls and the results of a request transcript in ONE walk, in transcript order. Either callback may be nil. A call or result with no id is left out (see RequestCalls).

func EachRequestResult added in v0.7.11

func EachRequestResult(wire string, body []byte, fn func(RequestResult))

EachRequestResult is RequestResults without the slice, for a caller on the request path.

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 HasToolNamed added in v0.7.11

func HasToolNamed(wire string, body []byte, name string) bool

HasToolNamed reports whether body's tools array holds a function declaration called name on wire.

func IsResponses added in v0.6.5

func IsResponses(wire string) bool

IsResponses reports whether wire is the Responses dialect.

func IsToolStopReason added in v0.7.11

func IsToolStopReason(reason string) bool

IsToolStopReason reports whether a stop reason says the response called a tool.

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 ResultReferenceLoads added in v0.7.11

func ResultReferenceLoads(b gjson.Result, fn func(name string))

ResultReferenceLoads calls fn with the name of each tool a client tool_result block loaded: the tool_reference blocks in its content, which Claude Code's own ToolSearch writes. It does nothing for any other block.

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 SSEData added in v0.7.11

func SSEData(body []byte, fn func(data []byte) bool)

SSEData walks a Server-Sent Events stream and calls fn with the data of each event, in order. fn returns false to stop. It is the one reader of SSE framing for the readers that only want the payloads; a reader that must forward the bytes unchanged keeps its own event splitter.

The rules, from the SSE spec:

  • A line ends at "\n", and a "\r" before it is dropped, so "\r\n" streams read the same.
  • A blank line ends an event. The end of the stream ends the last event.
  • A "data:" line adds to the event's data. Several lines of one event are joined with "\n". One exception, for a stream that leaves out the blank line between events: when the lines so far are already one whole JSON value (and are at most 64 KiB), the next data line starts a new event.
  • Other fields (event:, id:, retry:) and ":" comment lines are skipped.

Two rules are for this proxy and are not in the spec:

  • The payload is trimmed of white space. JSON does not care, and a provider may add a space.
  • An event with no data, and the "[DONE]" end marker of the OpenAI wires, call nothing.

The slice fn gets is only valid inside the call. For an event of one data line it points into body, so the common case copies nothing.

func SSEDataLine added in v0.7.11

func SSEDataLine(line []byte) (value []byte, ok bool)

SSEDataLine is the value of one "data:" line of a stream, without its field name and without a trailing "\r". ok is false for any other line. A reader that gets its bytes one line at a time, and cannot hold a whole event, uses this. It then reads an event of one data line only: that is all Anthropic sends, and an event of several data lines needs SSEData.

func SSEEventData added in v0.7.11

func SSEEventData(ev []byte) []byte

SSEEventData is the data of ONE event block (the lines of one event, with or without the blank line after them), by the rules of SSEData. It returns nil when the event has no data or carries the "[DONE]" marker. The result may point into ev.

func SearchResultLoads added in v0.7.11

func SearchResultLoads(b gjson.Result, fn func(name string))

SearchResultLoads calls fn with the name of each tool a server-side search result block loaded: a tool_search_tool_result block's content.tool_references. It does nothing for any other block. fn gets the name as written, empty names too; a caller that needs a clean set drops them itself.

func ServerHeldHistory added in v0.7.8

func ServerHeldHistory(body []byte) bool

ServerHeldHistory says whether an OpenAI Responses body leaves part of its prompt on the provider's side, so the host cannot see the prefix the provider reads. It is true for:

  • previous_response_id (the earlier turns of a response chain);
  • conversation (a stored conversation's items, a string id or an object);
  • an input item of type item_reference (an item the provider expands from its own store).

The accountant, apply and expand all use this one rule.

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 ToolDeclName added in v0.7.11

func ToolDeclName(t gjson.Result) string

ToolDeclName is the name a tools[] element goes by, on any wire. It is the one string the inventory shows, the removal matches, and the accountant keys on. A declaration that has no function name names itself through the first of these that is set: `mcp_server_name` (an Anthropic mcp_toolset connector, one element for a whole server), `server_label` (a Responses `mcp` tool), then `type` (a provider tool such as web_search_*).

func ToolFnName added in v0.7.11

func ToolFnName(t gjson.Result) string

ToolFnName is the name of a client function declaration, or "". Anthropic and Responses write it as a top-level `name`; Chat Completions nests it under `function`. The two places never both hold a name on one wire, so the reader needs no wire argument: a caller that sees only a bare tools array (the accountant's envelope diff) reads every wire the same way.

func ToolFnNameOn added in v0.7.11

func ToolFnNameOn(wire string, t gjson.Result) string

ToolFnNameOn is ToolFnName for a host that knows its wire: it reads the one place the wire writes the name, so a body of another shape is not read. Anthropic and Responses write a top-level `name`. Every other wire, an empty one too, is read as Chat Completions, which nests it under `function`.

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 ToolStopReasonList added in v0.7.11

func ToolStopReasonList() []string

ToolStopReasonList is a copy of the list, for a reader that needs the words (a SQL list, a map). It is a copy so that no reader can change the list the others use.

func TranscriptField added in v0.7.11

func TranscriptField(wire string) string

TranscriptField is the name of the array that holds the conversation: input on Responses, else messages.

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)
	// Root is 1 when the body has a top-level cache_control (Anthropic's automatic caching). The
	// provider puts one breakpoint on the last cacheable block, so it counts against the cap.
	Root int
}

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 CallStream added in v0.7.11

type CallStream struct {
	// contains filtered or unexported fields
}

CallStream rebuilds the tool calls of a streamed response from its events, one event at a time. It reads the three dialects with one set of rules, and a stream holds only one dialect:

Anthropic   content_block_start (a tool_use block), then input_json_delta pieces, by block index
Chat        choices[0].delta.tool_calls[], by index: id and name once, arguments in pieces
Responses   output_item.added (a function_call or custom_tool_call item), the argument delta
            events, output_item.done, and the output of the terminal response event

It is built for bytes that may be incomplete, such as the head and tail of a long response. A call whose pieces are missing still comes out, with the arguments it has. The caller checks that the arguments are JSON. The result matches OutputCalls on the whole message.

Every reader of a streamed call uses this type: the facts of a response (respfacts) and the rebuild of a whole message for the expand loop (expand).

func (*CallStream) Add added in v0.7.11

func (s *CallStream) Add(data []byte)

Add reads the data of one event. An event that is not a tool call event changes nothing.

func (*CallStream) Block added in v0.7.11

func (s *CallStream) Block(index int) (OutputCall, bool)

Block is the Anthropic tool_use block at a content block index, when the stream has one. The expand loop rebuilds a whole message, so it has to place each call among the other blocks.

func (*CallStream) Calls added in v0.7.11

func (s *CallStream) Calls() []OutputCall

Calls is the calls rebuilt so far, in the order they opened.

type OutputCall added in v0.6.7

type OutputCall struct {
	ID   string // the call id the result must name: tool_use id, call_id, or tool_calls[].id
	Name string
	// Args is the call's arguments as raw text: Anthropic's input object, a Responses or Chat
	// function call's arguments string, a Responses custom tool call's input string.
	Args string
	// Custom is true for a Responses custom_tool_call: its Args is free text, not JSON.
	Custom bool
}

OutputCall is one tool call in a model's response message, as the wire wrote it.

func OutputCalls added in v0.6.7

func OutputCalls(wire string, msg []byte) []OutputCall

OutputCalls reads the tool calls of one response message, in order: Anthropic content tool_use blocks, Responses output function_call and custom_tool_call items, or the first Chat Completions choice's tool_calls. wire is the dialect (WireAnthropic, WireResponses, else Chat Completions). Every reader that splits a response's calls into the host's and the client's reads them here.

func StreamCalls added in v0.7.11

func StreamCalls(body []byte) []OutputCall

StreamCalls rebuilds the tool calls of a whole event stream, in the order they open.

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 RequestCall added in v0.7.11

type RequestCall struct {
	ID   string // the id the result names: tool_use id, call_id, or tool_calls[].id
	Name string
	// Custom is true for a Responses custom_tool_call: its Args is free text, not JSON.
	Custom bool
	// At is the index of the transcript element that holds the call: the message, or the input item.
	At int
	// Raw is the call: the tool_use block, the tool_calls element, or the Responses item. Args reads
	// it on demand, so a caller that only needs ids and names does not pay for the arguments.
	Raw gjson.Result
	// contains filtered or unexported fields
}

RequestCall is one tool call in a REQUEST transcript: a call the model made on an earlier turn, as the client sent it back. OutputCalls reads the same thing in a response.

func RequestCalls added in v0.7.11

func RequestCalls(wire string, body []byte) []RequestCall

RequestCalls reads the tool calls of a request transcript, in order: Anthropic tool_use content blocks, Chat Completions tool_calls, or Responses function_call and custom_tool_call items. A call with no id is left out: an empty id would match a result that names no call, which belongs to someone else.

func (RequestCall) Args added in v0.7.11

func (c RequestCall) Args() string

Args is the call's arguments as raw text: Anthropic's input object, a Chat or Responses function call's arguments string, a Responses custom tool call's input string.

type RequestResult added in v0.7.11

type RequestResult struct {
	CallID string // the id of the call the result answers
	// At is the index of the transcript element, and Block the index of the result block in its
	// content, or -1 when the element is the result itself (a Chat tool message, a Responses output).
	At, Block int
	// Raw is the result element or block.
	Raw gjson.Result
}

RequestResult is one tool result in a request transcript.

func RequestResults added in v0.7.11

func RequestResults(wire string, body []byte) []RequestResult

RequestResults reads the tool results of a request transcript, in order: Anthropic tool_result content blocks, Chat Completions tool messages, or Responses function_call_output and custom_tool_call_output items. A result with no call id is left out, for the reason RequestCalls leaves out a call with none.

func (RequestResult) Path added in v0.7.11

func (r RequestResult) Path(wire string) string

Path is the gjson path of the result, under the transcript's own array name ("messages" or "input").

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