continuation

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 15 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 continuation defines provider-neutral fast and slow model continuations over one canonical trajectory.

The package is experimental and intentionally separate from stable api/v1. It models ordinary streamed reasoning, assistant content, and tool calls; it does not introduce a fast/slow advice protocol or alter the OpenAI Realtime wire format.

Index

Constants

View Source
const BackgroundResultHint = "" /* 249-byte string literal not displayed */

BackgroundResultHint opens the runtime hint that carries what a provider without speech authority produced.

A provider that cannot be heard does not take turns in the conversation, so its prose is not an assistant turn and must not be projected as one. It is runtime state: the background reasoner's chain finished and left a written result that the user has not been told. Rendering it as an assistant message makes it indistinguishable from what the agent actually said, and a continuation reading that cannot tell which turn the user heard - which is how a written answer ends up recited back, word for word, as a second spoken turn.

View Source
const CompletionMarker = "<<DONE>>"

CompletionMarker is what a fast continuation emits to say the turn is finished and needs no deliberation.

The marker says "stop", not "continue", and that direction is the whole point. A fast provider is a small model under a short budget being asked to answer and to classify at the same time, and it does not reliably emit a marker for either. The two ways of being wrong are not symmetric: a turn that was finished but not marked costs one extra utterance, while a turn that needed the reasoner and was not marked costs every capability the agent has - it says "let me look that up" and then nothing happens, for ever. So the absence of a marker means deliberate.

It is control, not speech. StripMarkers removes it before any item is committed, so it can never reach the trajectory, the speech commit boundary, or the user.

View Source
const HeardPreamble = "[runtime: "

HeardPreamble opens the runtime note that follows a turn the user did not hear all of. It is exported so a caller can tell the note apart from anything a model wrote.

View Source
const InternalStatePreamble = "[Internal working state from an earlier continuation; not user-visible]\n"

InternalStatePreamble fences reasoning retained from an earlier continuation, so a provider reading it cannot mistake deliberation for something the agent said.

View Source
const NothingSaidSincePrompt = "[Runtime note: nobody has said anything since your last words. Do what your " +
	"instructions require at this point, or reply with exactly <wait> if nothing is due.]"

NothingSaidSincePrompt stands in for the user turn a provider's API requires when the runtime opens a turn on its own - a clock coming due - and the conversation ends on the agent's last words. It says only what is true.

View Source
const NoticeableGap = time.Second

ObservationContent renders one observation for a provider.

Two things happen here, and the second is a security boundary rather than a formatting choice. Typed supersession becomes plain language, so a provider never sees a revision counter. And content an observer extracted from the world is fenced inside a delimited block with a standing instruction that it is data.

An agent that narrates screen text into its own context is an obvious injection vector. Provenance is the defence, and this is where provenance becomes something the model can act on: user speech is rendered as itself, observed content is rendered as a quotation. Any delimiter that appears inside the observed text is neutralised, so the content cannot close its own fence and continue as if it were the runtime talking. NoticeableGap is the shortest elapsed time worth reporting to a model.

Below it, a gap is the ordinary seam between one item and the next - the pause between a question ending and an answer beginning, the moment a tool takes to return. A person in the room would not have registered those as waiting, and reporting them would be noise wearing the costume of information.

View Source
const ObserverContentPrefix = "<<<observed-content"

ObserverContentPrefix opens the block that observed content is rendered inside. It is exported so a test can prove that observed text appears there and nowhere else.

View Source
const ObserverContentSuffix = ">>>end-observed-content"

ObserverContentSuffix closes that block.

View Source
const PendingRepairInstruction = "" /* 213-byte string literal not displayed */

PendingRepairInstruction is injected by provider adapters only while the canonical trajectory contains an unresolved typed audible-repair obligation. It is runtime policy, not text-authored workflow state.

View Source
const PendingRepairPrompt = "Apply the pending audible-repair obligation now."
View Source
const TerminalToolProposalNotice = "" /* 158-byte string literal not displayed */

TerminalToolProposalNotice is the portable, model-visible projection of a validated proposal disposition. The disposition itself deliberately carries no arguments, and this notice likewise reveals no control payload.

View Source
const WaitToken = "<wait>"

WaitToken is how a phase says it has nothing to say. It is duplicated from cognition rather than imported, because continuation must not depend on the layer that produces the content it carries.

Variables

View Source
var ErrPreempted = errors.New("continuation preempted at resource safe point")

ErrPreempted marks a cooperative resource preemption. Runtimes may resume a continuation from the interrupted canonical prefix at the next safe point.

View Source
var ErrStalePrefix = errors.New("continuation computed from a stale trajectory prefix")

ErrStalePrefix means a continuation completed after another event had already advanced the canonical trajectory. Its output was not committed and must be recomputed from the new prefix.

Functions

func AssistantHeardContent

func AssistantHeardContent(content string, mark spoken.Mark) string

AssistantHeardContent renders an assistant turn as the user received it.

An interrupted turn is two facts, and a projection that carries only one of them is wrong in a specific, reproducible way. Carry only the whole text and the agent believes it said words that were cut off before they were audible: asked to read a long list and interrupted partway, it resumes after the last item it wrote rather than after the last one anybody heard. Carry only the heard part and the words it had prepared are gone, so it either invents a different continuation or starts the list again.

So the turn becomes what was heard, and what was not heard follows it as a runtime note that is unmistakably not speech. The words are still there for the model to continue from; they are simply no longer presented as something the user was told.

func CarriesBackgroundResult

func CarriesBackgroundResult(item trajectory.Item) bool

CarriesBackgroundResult reports whether a silently-produced item left anything for the next spoken turn to work from.

A wait is not a result. It is the reasoner deciding there is nothing to say, and rendering it as one manufactures a reason to speak out of a decision to stay silent: the hint that carries background state tells the voice a result has arrived and to answer from it in its own words, so four consecutive waits reached the voice as four instructions to say something. Measured on a story with two animals in it, that is where the count that arrived before the first animal came from.

The window that renders a conversation for the interaction model already drops a wait, for the same reason and in almost the same words. This is that rule reaching the other place a trajectory is rendered.

func CarriesInternalState

func CarriesInternalState(content string) bool

CarriesInternalState reports whether retained reasoning has anything in it.

An empty one is not a turn. The preamble announces working state and then shows nothing, which reads as the agent having taken a turn and said nothing at all - measured, five of them between four lines of a story, and the voice counted an animal that had not been mentioned. Same shape as a wait rendered as a result: the absence of something presented as its presence.

func ElapsedNotes

func ElapsedNotes(items []trajectory.Item) map[string]string

ElapsedNotes recovers the time axis that projecting a trajectory throws away.

Every item carries the moment it was committed, and every projection so far has dropped it: the model reads an ordered list with no clock, unable to tell a reply that came after two hundred milliseconds from one that came after half a minute - a difference nobody sharing the room could have missed. The gap between consecutive items is that difference, already recorded, and recovering it needs no new field, only a projection that stops discarding what the log already knows.

The gaps are taken from the log rather than from what a caller chooses to emit. An adapter that skips an item still has to account for the time that item occupied, because the wait was real whether or not the item describing it is shown.

func HasBackgroundContent

func HasBackgroundContent(content string) bool

HasBackgroundContent reports whether content is anything more than a wait.

func LatestMediaHandles

func LatestMediaHandles(items []trajectory.Item) map[string]struct{}

LatestMediaHandles selects the media that represents the newest observation of each source in a trajectory.

Observation text remains useful history, but repeatedly attaching every retained keyframe makes a realtime vision request slower and leaves the model choosing between stale and current pixels. All media references on the newest observation of a source are retained; references on older observations are omitted and therefore need not be resolved.

func ObservationContent

func ObservationContent(item trajectory.Item, elapsed string) string

ObservationContent projects one observation as the model should read it, prefixed with how long the wait before it was.

The elapsed note is applied last, and so from outside any framing the content needed. It is the runtime speaking, not the thing observed: text read off a screen is untrusted and gets fenced and neutralised, and a timestamp that ended up inside that fence would be claiming the observed content's authority instead of the runtime's - besides being liable to mangling by the very neutralisation protecting it.

func ObservationRunContent

func ObservationRunContent(run ProviderRun, elapsed map[string]string) string

ObservationRunContent renders a user-observation run as one textual turn. Each surviving observation is rendered independently before joining, so elapsed-time notes and cross-boundary supersession remain attached to the fragment they describe.

func PendingToolProposalContent

func PendingToolProposalContent(call *trajectory.ToolCall) (string, bool)

PendingToolProposalContent projects canonical working state without making it look like assistant-authored tool-call JSON. A pending proposal is still composable: another policy or model may promote it, so its exact name and raw arguments must remain visible until an ordered promotion or disposition is committed.

func ProducedSilently

func ProducedSilently(item trajectory.Item) bool

ProducedSilently reports whether an item came from a provider that could not be heard.

It reads the authority recorded on the item at the moment output committed, rather than any later configuration, so a projection decides what the user was told from the log alone.

func StripMarkers

func StripMarkers(content string) (string, bool)

StripMarkers removes the completion marker from a provider's output and reports whether the turn was declared finished.

It is tolerant about placement because a small model under a short budget puts it where it likes, and about truncation because a budget that runs out mid-marker still expressed the intent.

func StripRuntimeAnnotations

func StripRuntimeAnnotations(content string) (string, bool)

StripRuntimeAnnotations removes the reserved runtime projection note from model-authored assistant content.

ProviderRuns deliberately shows an interrupted assistant turn as the text the person heard followed by an internal note describing the prepared, unheard remainder. That note is context for the next model, not a script. A model can nevertheless copy the note into its own response. Letting that response reach the speech boundary would make implementation metadata audible (and can expose the prepared text), so the first reserved marker is a fail-closed boundary: preserve only the ordinary text before it and drop the rest. The marker is compared case-insensitively because model output is not required to preserve the casing of a copied control token.

This function intentionally does not try to parse a closing bracket. The runtime note may contain arbitrary quoted user text, including brackets; the first marker is the point after which no model-authored content is trusted as speech. It also handles a marker split across streamed chunks because the runner coalesces adjacent assistant deltas before applying it.

func TraceRequest

func TraceRequest(descriptor Descriptor, invocationID string, body []byte)

TraceRequest records one compiled request. It is a no-op unless tracing is configured, and it never returns an error: a trace that could fail a request would be a debugging aid that changes what it is trying to observe.

func ValidateDescriptor

func ValidateDescriptor(descriptor Descriptor) error

ValidateDescriptor validates fields shared by provider implementations.

func ValidateEvent

func ValidateEvent(event Event) error

ValidateEvent rejects ambiguous or partial portable stream events.

func ValidateInvocation

func ValidateInvocation(invocation Invocation, descriptor Descriptor) error

ValidateInvocation checks portable capability and tool definitions before a request reaches a provider.

Types

type Capability

type Capability struct {
	Name                 string `json:"name"`
	Description          string `json:"description"`
	Available            bool   `json:"available"`
	ExecutionPhase       string `json:"execution_phase,omitempty"`
	ConfirmationRequired bool   `json:"confirmation_required,omitempty"`
}

Capability describes what the overall agent can do. Fast models receive the same capability knowledge and may receive the same tool schemas under proposal-only authority; only the slow phase may execute them.

type Completion

type Completion struct {
	StopReason string `json:"stop_reason,omitempty"`
	Usage      Usage  `json:"usage,omitempty"`
	// ReasoningInContent reports that this provider wrote its deliberation
	// into the content field rather than into a reasoning field of its own.
	//
	// It is a fact about how the provider is configured rather than about what
	// it said, and it is the difference between a turn that had nothing to say
	// and a turn that spent its whole output budget thinking. Without it that
	// second case is silence with no cause attached, which is the same failure
	// as saying the thought out loud, minus the evidence.
	ReasoningInContent bool            `json:"reasoning_in_content,omitempty"`
	ProviderStateType  string          `json:"provider_state_type,omitempty"`
	ProviderState      json.RawMessage `json:"provider_state,omitempty"`
}

Completion is terminal provider metadata. ProviderState is an opaque native model-turn representation, such as Gemini content with thought signatures. The matching ProviderStateType prevents cross-provider reinterpretation.

type Descriptor

type Descriptor struct {
	Provider         string           `json:"provider"`
	Model            string           `json:"model"`
	Phase            trajectory.Phase `json:"phase"`
	Effort           Effort           `json:"effort"`
	Streaming        bool             `json:"streaming"`
	NativeStateType  string           `json:"native_state_type,omitempty"`
	RetainsToolCalls bool             `json:"retains_tool_calls"`
	ToolAuthority    ToolAuthority    `json:"tool_authority,omitempty"`
	SpeechAuthority  SpeechAuthority  `json:"speech_authority,omitempty"`
	// SamplingTemperature records an explicit provider temperature in a
	// comparable form. Empty means provider default; "0" is deliberately not
	// empty because deterministic decoding is a material configuration choice.
	SamplingTemperature string `json:"sampling_temperature,omitempty"`
	// Vision declares that this provider can be given images.
	//
	// It is a property of the provider rather than of the runtime, and it is
	// declared rather than probed, because the failure is asymmetric: handing
	// an image to a text-only model is a hard error that fails the turn, and
	// withholding one from a model that could have used it costs only what the
	// narration does not carry. So the default is that it cannot see, and a
	// deployment serving a multimodal model says so.
	Vision bool `json:"vision,omitempty"`
	// ExecutableTools is retained in report JSON for compatibility with the
	// first experimental evidence schema. New code must use ToolAuthority.
	ExecutableTools bool `json:"executable_tools"`
}

Descriptor identifies one configured continuation provider.

func (Descriptor) EffectiveSpeechAuthority

func (descriptor Descriptor) EffectiveSpeechAuthority() SpeechAuthority

EffectiveSpeechAuthority resolves an unset value to voice. Silence is the constraint an arrangement imposes, not the state a provider falls into by omission: a single-provider deployment that never declared anything should answer out loud rather than run mute.

func (Descriptor) EffectiveToolAuthority

func (descriptor Descriptor) EffectiveToolAuthority() ToolAuthority

EffectiveToolAuthority normalizes descriptors written before ToolAuthority existed. The legacy boolean can only mean execute; it can never grant the newer proposal-only authority.

type Effort

type Effort string

Effort is a provider-neutral reasoning-effort request. Adapters must reject unsupported values rather than silently selecting a different effort.

It is either one of the four names or a number of thinking tokens, and it cannot be both, because the thing being described admits only one answer at a time. Gemini says so literally - asking for a level and a budget together is "you can only set only one of thinking budget and thinking level", an HTTP 400 - and a single field is the shape that makes the invalid request impossible to write rather than caught after somebody writes it.

A number says how far to think in tokens; a name lets the provider decide how far. Neither says anything about how long the answer may be. That is a separate quantity, and conflating the two is what silences a voice: a provider spends one allowance on thinking first, so a limit meant to keep a spoken turn short is spent before the turn begins.

const (
	EffortMinimal Effort = "minimal"
	EffortLow     Effort = "low"
	EffortMedium  Effort = "medium"
	EffortHigh    Effort = "high"
)

func ParseEffort

func ParseEffort(value string) (Effort, error)

ParseEffort accepts either form and rejects anything else. A negative number is not a smaller budget, it is a typo.

func (Effort) Budget

func (effort Effort) Budget() (int, bool)

Budget reads an effort written as a number of thinking tokens. Zero is a real budget meaning do not think, and is distinct from an absent one.

func (Effort) Named

func (effort Effort) Named() bool

Named reports whether this effort is one of the four names.

type Emit

type Emit func(Event) error

Emit receives streamed provider events. Returning an error cancels the continuation at the next provider-supported boundary.

type Event

type Event struct {
	Kind     EventKind            `json:"kind"`
	Text     string               `json:"text,omitempty"`
	ToolCall *trajectory.ToolCall `json:"tool_call,omitempty"`
}

Event is one ordered provider output event. ToolCall is complete; adapters assemble provider-specific argument deltas before emitting it.

type EventKind

type EventKind string

EventKind identifies streamed provider output.

const (
	EventReasoningDelta EventKind = "reasoning_delta"
	EventAssistantDelta EventKind = "assistant_delta"
	EventToolCall       EventKind = "tool_call"
)

type Invocation

type Invocation struct {
	Instruction     string           `json:"instruction"`
	SourceRevision  uint64           `json:"source_revision,omitempty"`
	Capabilities    []Capability     `json:"capabilities,omitempty"`
	Tools           []ToolDefinition `json:"tools,omitempty"`
	MaxOutputTokens int              `json:"max_output_tokens,omitempty"`
	// Effort overrides the provider's configured reasoning budget for this one
	// turn. Empty leaves the provider's own setting alone.
	//
	// It is here rather than only on the descriptor because how much time
	// there is depends on the act, not on the deployment. Measured at fifteen
	// repeats, giving the voice a budget gains three or four runs on counting,
	// the visual case and the waiter, and loses seven on cutting into
	// somebody's sentence - where the scenario's own note says waiting until
	// they finish makes the correction useless, and a voice that thinks for a
	// second and a half has already waited.
	//
	// Adapters that cannot vary it per request ignore this, which is the same
	// thing they do with a descriptor effort they cannot honour.
	Effort Effort `json:"effort,omitempty"`
}

Invocation configures one fast or slow continuation. Instruction is supplied as a runtime system instruction and also recorded in the canonical trajectory.

type Media

type Media struct {
	MIMEType string
	Bytes    []byte
}

Media is an attachment resolved from a trajectory handle.

type MediaResolver

type MediaResolver func(handle string) (Media, error)

MediaResolver turns a handle on a trajectory item into the bytes behind it.

The trajectory carries handles rather than bytes because Snapshot is copied for every continuation request. An adapter that can use images calls this; one that cannot never does, and neither pays for the other's needs. A handle whose retention window has passed returns an error, which is an ordinary outcome rather than a failure: the persistent text is what survives.

type Prepared

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

Prepared is a continuation that has been generated and not committed.

Speculative preparation is a latency policy, and it is only safe to be a latency policy because prepared work is private by construction: it has no speech sink and no tool authority until it is adopted at a real safe point. Being wrong therefore costs tokens and nothing else - which is the property that lets the decision to prepare be made on evidence that is still changing.

func (*Prepared) ProvisionalText

func (prepared *Prepared) ProvisionalText() string

ProvisionalText is what the preparation was generated against. Adoption is only sound when the canonical record of the turn says the same thing.

func (*Prepared) Ready

func (prepared *Prepared) Ready() bool

Ready reports whether the preparation produced output worth adopting.

type Provider

type Provider interface {
	Descriptor() Descriptor
	Continue(context.Context, Request, Emit) (Completion, error)
}

Provider streams one continuation over the supplied canonical prefix.

type ProviderRun

type ProviderRun struct {
	Items            []trajectory.Item
	UserObservations bool
}

ProviderRun is one canonical item, or a run of adjacent observations that all carry user authority.

Speech recognisers are allowed to commit more than one final fragment for a single human turn. Presenting those fragments as consecutive chat turns is not equivalent to presenting what the person said: some chat templates assign special meaning to every role boundary. A provider therefore sees an adjacent run as one user turn while the canonical trajectory remains an append-only record of every observation and its provenance.

func ProviderRuns

func ProviderRuns(items []trajectory.Item) []ProviderRun

ProviderRuns groups only adjacent user-authority observations.

Assistant, tool, observer, instruction, and runtime-state items are hard boundaries. The returned values are a projection over copies of the item structs; this function never rewrites the supplied canonical slice.

It is also where an assistant turn becomes what the user heard of it. That belongs here rather than in each provider adapter for the same reason superseded partials do: it is one rule about what a conversation looked like, three adapters would implement it three times, and the one that forgot would be the one whose agent talked past words nobody heard.

type Request

type Request struct {
	InvocationID string              `json:"invocation_id"`
	Descriptor   Descriptor          `json:"descriptor"`
	Trajectory   trajectory.Snapshot `json:"trajectory"`
	Invocation   Invocation          `json:"invocation"`
	// Media resolves attachments referenced by trajectory items. It is nil
	// when the runtime retains none.
	Media MediaResolver `json:"-"`
}

Request is the immutable provider input assembled by Runner.

type RunResult

type RunResult struct {
	InvocationID   string                `json:"invocation_id"`
	SourceRevision uint64                `json:"source_revision,omitempty"`
	StartVersion   uint64                `json:"start_version"`
	EndVersion     uint64                `json:"end_version"`
	AppendedIDs    []string              `json:"appended_ids"`
	AssistantText  string                `json:"assistant_text,omitempty"`
	ToolProposals  []trajectory.ToolCall `json:"tool_proposals,omitempty"`
	ToolCalls      []trajectory.ToolCall `json:"tool_calls,omitempty"`
	Completion     Completion            `json:"completion"`
	Committed      bool                  `json:"committed"`
	Interrupted    bool                  `json:"interrupted,omitempty"`
	// Finished reports that this continuation declared the turn complete. The
	// marker that carried it is stripped before any item is built, so it is
	// visible here and nowhere else.
	Finished bool `json:"finished,omitempty"`
}

RunResult identifies the items appended for one continuation.

type Runner

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

Runner coordinates one provider invocation and atomically appends its output at the next safe point.

func NewRunner

func NewRunner(config RunnerConfig) (*Runner, error)

NewRunner creates an experimental continuation runner.

func (*Runner) Adopt

func (runner *Runner) Adopt(prepared *Prepared) (RunResult, error)

Adopt commits prepared output at the current safe point.

It restamps commit time, because commit time is when something entered the log rather than when it was generated, and a prepared item still carrying its generation time would make the log's clock run backwards. Everything else - the instruction, the output, the provenance - is exactly what the provider produced, so an adopted continuation is indistinguishable from one that was run at this instant except in having been faster.

func (*Runner) Prepare

func (runner *Runner) Prepare(
	ctx context.Context,
	provider Provider,
	invocation Invocation,
	provisional trajectory.Item,
	observer StreamObserver,
) (*Prepared, error)

Prepare generates a continuation against the canonical prefix plus one uncommitted observation, and appends nothing.

The provisional observation carries what perception has heard so far. It is not committed, cannot be committed by this call, and never becomes part of the log: only the model's answer does, and only if Adopt accepts it.

func (*Runner) Run

func (runner *Runner) Run(
	ctx context.Context,
	provider Provider,
	invocation Invocation,
	observer StreamObserver,
) (RunResult, error)

Run invokes provider, forwards validated stream events to observer, and appends completed or interrupted output. If provider returns an error after producing partial output, the partial output is retained with Interrupted.

func (*Runner) RunLive

func (runner *Runner) RunLive(
	ctx context.Context,
	provider Provider,
	invocation Invocation,
	live string,
	observer StreamObserver,
) (RunResult, error)

RunLive invokes a provider over the canonical trajectory plus one utterance that is still being spoken, and commits its output like any other turn.

Every act that speaks into somebody else's turn runs on a sentence that is not in the log yet, and putting that sentence only in the instruction leaves the conversation ending with whatever the agent last said. A provider asked to continue from its own last turn, with nothing new addressed to it, has nothing to continue: measured against Gemini 3.5 Flash, "count them as I mention them" with the animal in the instruction returned an empty string three times out of three, and the same call with the animal as a user turn returned "2" three times out of three. That is the whole of the second animal, the second sentence of an interpretation, and the dish that fits.

func (*Runner) RunLiveProjected

func (runner *Runner) RunLiveProjected(
	ctx context.Context,
	provider Provider,
	invocation Invocation,
	live string,
	projection TrajectoryProjection,
	observer StreamObserver,
) (RunResult, error)

RunLiveProjected combines a read-only trajectory projection with the live user observation that has not entered the canonical log yet. The temporary item is provider-visible only; output still commits against the exact canonical version captured before inference. This is useful when a compact role-specific view must replace stale canonical user text with a newer ASR reconstruction without mutating or fabricating projection items.

func (*Runner) RunProjected

func (runner *Runner) RunProjected(
	ctx context.Context,
	provider Provider,
	invocation Invocation,
	projection TrajectoryProjection,
	observer StreamObserver,
) (RunResult, error)

RunProjected invokes a provider over an explicit experimental projection, while still committing against the exact canonical version captured before inference. A projection therefore cannot create an alternate memory owner.

type RunnerConfig

type RunnerConfig struct {
	Store           *trajectory.Store
	Now             func() uint64
	NextID          func(prefix string) string
	RetainReasoning bool
	// Media resolves attachments for adapters that can use them.
	Media MediaResolver
}

RunnerConfig supplies dependencies. Now must return monotonic nanoseconds. RetainReasoning controls plaintext reasoning only; opaque provider state may still be retained to preserve authenticated same-provider continuation.

type RuntimeAnnotationFilter

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

RuntimeAnnotationFilter removes a reserved runtime projection note from an ordered assistant-text stream without delaying ordinary speech until the provider finishes. It retains only trailing whitespace and the short suffix that could still become the beginning of the marker in a later chunk. Once the marker is complete, every later assistant byte in that stream is discarded.

The filter is stateful and must be used by one stream in event order. It is not safe for concurrent use.

func (*RuntimeAnnotationFilter) Finish

func (filter *RuntimeAnnotationFilter) Finish() string

Finish releases a marker-like suffix when the provider completed without ever producing the reserved marker. It returns nothing after a marker was found and clears the retained suffix in either case.

func (*RuntimeAnnotationFilter) Found

func (filter *RuntimeAnnotationFilter) Found() bool

Found reports whether this stream contained the reserved marker.

func (*RuntimeAnnotationFilter) Push

func (filter *RuntimeAnnotationFilter) Push(content string) string

Push accepts the next provider-authored assistant-text chunk and returns the portion that is safe to expose. The returned text can be empty when the input is a possible marker prefix or arrives after a completed marker.

type SpeechAuthority

type SpeechAuthority string

SpeechAuthority separates producing an answer from being heard saying it.

It is a property of the provider descriptor rather than an inference from its fast/slow phase. A paired reference may keep slow output silent while a slow-only graph grants it voice. The runner records the exact choice on every item's producer, and the action plane refuses to voice only content that was explicitly marked silent.

const (
	// SpeechAuthorityVoice permits assistant content to cross the speech
	// commit boundary. It is the default: a provider that is configured
	// without an opinion is a provider whose answers are meant to be heard.
	SpeechAuthorityVoice SpeechAuthority = "voice"
	// SpeechAuthoritySilent appends assistant content that is never voiced.
	SpeechAuthoritySilent SpeechAuthority = "silent"
)

type StreamObserver

type StreamObserver func(Event) error

StreamObserver receives validated deltas before the safe-point append. A speech planner can use assistant deltas for speculative TTS while the trajectory remains authoritative at completion.

type ToolAuthority

type ToolAuthority string

ToolAuthority separates knowledge of a tool schema from permission to cause a side effect. A proposing continuation may emit a structured candidate call, but the runtime records it as non-executable working state. Only an executing continuation can append an authoritative tool call.

const (
	ToolAuthorityNone    ToolAuthority = "none"
	ToolAuthorityPropose ToolAuthority = "propose"
	ToolAuthorityExecute ToolAuthority = "execute"
)

type ToolDefinition

type ToolDefinition struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  json.RawMessage `json:"parameters"`
	// Background is typed execution policy retained from the tool registry.
	// Provider adapters need not expose it to model APIs; the runtime consumes
	// it at the action boundary after a provider selects the tool.
	Background bool `json:"background,omitempty"`
}

ToolDefinition is a provider-neutral JSON Schema function definition.

type TrajectoryProjection

type TrajectoryProjection func(trajectory.Snapshot) (trajectory.Snapshot, error)

TrajectoryProjection derives model-visible experimental context from an immutable canonical prefix. It cannot change the store or the version used for the eventual compare-and-append commit. Production uses nil (the exact canonical prefix); non-nil projections exist only for registered controls.

type Usage

type Usage struct {
	InputTokens               int64 `json:"input_tokens,omitempty"`
	CachedInputTokens         int64 `json:"cached_input_tokens,omitempty"`
	CachedInputTokensReported bool  `json:"cached_input_tokens_reported,omitempty"`
	OutputTokens              int64 `json:"output_tokens,omitempty"`
	ReasoningTokens           int64 `json:"reasoning_tokens,omitempty"`
	TotalTokens               int64 `json:"total_tokens,omitempty"`
}

Usage contains provider-reported token accounting. Zero fields are valid when a provider does not expose a category.

Jump to

Keyboard shortcuts

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