host

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 22 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 host supplies reusable policy and checkpoint utilities around the native engine. It owns request compaction and transcript identity/validation; engine owns scheduling, ai owns provider messages, and consumers own storage, credentials, model selection and the summarizer callback. InputMessages converts new host instructions, and ProjectMessage/ProjectContent produce detached display views for plugins and observers. Neither projection is a substitute for the native transcript.

A Compactor transforms only the provider request view (Prepare). Keep the original native messages as the authoritative transcript and persist Checkpoint and Cleared alongside them. Restore verifies the summary envelope/revision, and every request verifies that its prefix still matches before using it. The prefix digest and the facts read from each message are memoized, so a request re-derives only the messages appended since the last. A legacy agentcore.Message display projection is not a native checkpoint and must not be replayed as one.

A stored transcript is read in place. SplitMessages validates it as JSON in one pass and returns each message as its stored bytes; ReadMessages then validates every tool batch and reads, without decoding, the facts batch validation and compaction need from each message in the shape 2ai writes. Compactor.Learn seeds the memo from that read, and PrepareMessages takes the split messages, so a request costs the messages it adds and sends. A summary also records PrefixRawDigest, the digest of its prefix's stored bytes, and a prefix whose bytes match is accepted without the semantic digest.

Requests are reduced in three steps, cheapest first:

  • Tool-result clearing (CompactionPolicy.Clearing, the analogue of the Messages API's clear_tool_uses) replaces old tool results with a placeholder naming the call and how to recover it, keeping the most recent Keep. The boundary is persisted (Cleared/RestoreCleared), so a cleared result is the same bytes on every request; it moves only for a saving of ClearAtLeast, and only past Trigger, once the prompt cache has gone cold, or together with a new summary.
  • Summary: a structured handoff (SummaryInstructions, ExtractSummary, ClampSummary) replaces the settled prefix. CompactionPolicy.Summarize receives the uncleared native prefix, which RenderTranscript turns into bounded role-labelled text and FoldRendered splits on message boundaries. CompactionPolicy.SummarizeView, when set, is tried first with the cleared live view so the call can read the conversation's prompt cache. Reattach appends context the work needs verbatim after the summary, within MaxReattachTokens. Allow defers a summary, Observe reports each one, and after MaxSummaryFailures consecutive failures the Compactor stops asking until a forced (recovery) compaction succeeds. Compact summarizes now, with its own instructions: the host's /compact.
  • Preview: a tool result still too large for the budget is archived (CompactionPolicy.Archive) and replaced by its head and the locator. The preview size depends only on the budget, so it too repeats exactly.

Index

Constants

View Source
const DefaultKeepRecentTokens = 20000

DefaultKeepRecentTokens is the host's default recent-context budget.

View Source
const DefaultKeepToolResults = 5

DefaultKeepToolResults is how many recent tool results clearing keeps.

View Source
const MaxReattachTokens = 8192

MaxReattachTokens bounds what Reattach may add to one summary; a policy also caps it at an eighth of its Budget.

View Source
const MaxSummaryFailures = 3

MaxSummaryFailures is how many consecutive summary attempts may fail before the compactor stops trying at the soft budget. Without it a summarizer that keeps failing is called, and billed, on every request for the rest of the run. A forced compaction still tries: there the alternative is a request the provider rejects.

View Source
const MaxSummaryTokens = 8192

MaxSummaryTokens is the largest handoff a compaction keeps.

View Source
const ReserveTokens = 16384

ReserveTokens leaves room for the next response when deriving a model budget.

View Source
const SummarySystemPrompt = "" /* 317-byte string literal not displayed */

SummarySystemPrompt is the system prompt of a standalone summary call. Its opening words are stable: scripted providers and hosts recognize a summary request by them.

Variables

View Source
var ErrUnsettledEffect = errors.New("native session has an unsettled tool effect")

ErrUnsettledEffect marks a missing physical effect receipt or native tool result.

Functions

func Admit

Admit runs AI fallback while waiting only for the selected prepared request. run calls accept after committing selection and before publishing visible events. Its returned request is the last prepared candidate, used when all candidates fail without committing. AI owns replay/retry/fallback decisions.

func CanonicalJSON

func CanonicalJSON(raw json.RawMessage) ([]byte, error)

CanonicalJSON normalizes object ordering and decimal spelling without rounding opaque native numbers through float64. It is only for identity checks; the original messages remain the replay payload.

func ClampSummary

func ClampSummary(summary string, maxTokens int) string

ClampSummary bounds a handoff that overshot its ceiling. Whole lines are removed from the middle: the format puts the goal first and the current state last, and a line cut in half reads as a complete but wrong fact that every later summary would then carry forward.

func ContextTokens

func ContextTokens(raw json.RawMessage) int

ContextTokens uses settled provider usage plus the appended tail, floored by a local estimate. Rewritten views invalidate older usage anchors without modifying the original billable usage or signed native messages.

func ExtractSummary

func ExtractSummary(reply string) string

ExtractSummary returns the handoff from a summarizer reply: the content of its <summary> block, without the <analysis> scratchpad. A reply without the tags is returned whole, less any analysis block, so a summarizer that ignores the format still yields a usable handoff.

func FoldRendered

func FoldRendered(ctx context.Context, blocks []string, budget int, summarize func(ctx context.Context, previous, segment string) (string, protocol.Usage, error)) (string, protocol.Usage, error)

FoldRendered summarizes rendered blocks inside an input budget. Blocks that fit are summarized in one call. A longer transcript is folded in order, each call carrying the summary so far; a segment always ends on a block boundary, so no call reads half a message. summarize receives the summary so far (empty on the first call) and the next segment.

func InputMessages

func InputMessages(messages []protocol.Message) ([]json.RawMessage, error)

These are newly authored host instructions, never provider/history messages. InputMessages converts newly authored host input only; provider history remains native.

func LocateMember added in v0.3.1

func LocateMember(raw json.RawMessage, name string) (start, end int, ok bool, err error)

LocateMember validates raw as one JSON object, except the value of its member name, and returns the span of that value. The caller must validate that value: when raw is not JSON the span may be anything. ok is false when the member is absent, appears more than once, or another key would also match it under encoding/json's case-insensitive field matching: decode raw with encoding/json then.

func PrefixDigest

func PrefixDigest(messages []json.RawMessage) string

PrefixDigest hashes semantic JSON identity without rounding opaque numbers. transcriptMemo.digest computes the same value incrementally.

func ProjectMessage added in v0.3.1

func ProjectMessage(raw json.RawMessage) (protocol.Message, error)

ProjectMessage is ai.ProjectMessage. A message in the shape 2ai writes is read in one pass over its bytes, without decoding it; any other is left to ai.ProjectMessage, so the projection and its errors are the same.

func RenderTranscript

func RenderTranscript(messages []json.RawMessage) []string

RenderTranscript renders native messages as role-labelled text for a summarizer, one block per message. It drops what a summary cannot use and what only costs tokens: thinking signatures, usage records, timestamps and inline image bytes. System messages are omitted because SummaryView keeps them verbatim. The native messages are not changed.

func SameJSON

func SameJSON(a, b json.RawMessage) bool

SameJSON compares opaque native JSON without modifying its replay bytes.

func SplitMessages added in v0.3.1

func SplitMessages(raw json.RawMessage) ([]json.RawMessage, error)

SplitMessages validates raw as a JSON array and returns its elements as sub-slices of raw: the exact bytes each message was stored as, without copying or decoding them. It fails where json.Unmarshal into a []json.RawMessage fails, and on a null that is no array.

func SummaryAllowance

func SummaryAllowance(prefix json.RawMessage, task string, budget int) (int, error)

SummaryAllowance reserves the immutable host systems/tools and exact task before assigning output to the summary. Small budgets cannot spend a fixed fraction on summary text when tool declarations already fill most of them.

func SummaryInstructions

func SummaryInstructions(maxTokens int, custom string, shared bool) string

SummaryInstructions is the handoff format a summarizer is asked for. maxTokens is the ceiling on the kept summary. custom is the host's or the user's own focus for this compaction and is appended as stated. shared marks a request that continues the live conversation, where tools are declared and the recent messages stay visible after the summary.

func SummaryText

func SummaryText(text string) (string, bool)

SummaryText returns the handoff of a summary message's text, without its label and reattached context, and whether text is a summary at all.

func ValidateMessageList added in v0.3.1

func ValidateMessageList(messages []json.RawMessage) error

ValidateMessageList is ValidateMessages over messages already split, such as the stored elements SplitMessages returned plus a run's appended ones. Called on the messages a run appended after a closed history, it is the check of the whole transcript: a closed batch leaves nothing open.

func ValidateMessages

func ValidateMessages(raw json.RawMessage) error

ValidateMessages checks completed native tool batches without projecting or changing messages. Provider error/aborted partial calls require no results.

Types

type ClearState

type ClearState struct {
	Boundary int            `json:"boundary"`
	At       int64          `json:"at"`
	Locators map[int]string `json:"locators,omitempty"`
}

ClearState is the persisted clearing boundary. Tool results of the authoritative transcript before Boundary are cleared in every request view. At is when the boundary last moved, in Unix milliseconds: provider usage reported before it measured the uncleared view. Locators holds the archive locator of a cleared result by its transcript index.

type CompactionEvent

type CompactionEvent struct {
	// Trigger is "auto" for the soft budget, "forced" for a hard input limit
	// or a provider overflow rejection, and "manual" for Compactor.Compact.
	Trigger string `json:"trigger"`
	// Mode is "shared" when SummarizeView produced the summary and
	// "standalone" when Summarize did.
	Mode       string `json:"mode"`
	PreTokens  int    `json:"pre_tokens"`
	PostTokens int    `json:"post_tokens,omitempty"`
	// PrefixMessages is how many authoritative messages the summary stands for.
	PrefixMessages int            `json:"prefix_messages,omitempty"`
	Failed         bool           `json:"failed,omitempty"`
	Usage          protocol.Usage `json:"usage"`
}

CompactionEvent reports one summary attempt. Token counts are the same estimates the compactor decides with.

type CompactionPolicy

type CompactionPolicy struct {
	// Approximate token counts. A nonpositive Budget disables new summaries;
	// ForWindow can derive or cap it from a model window. KeepRecent is bounded
	// to at least one token and at most half the effective budget.
	Budget, KeepRecent int
	// MaxInputTokens is the model's reserve-aware input ceiling. Budget remains
	// a compaction trigger/target; immutable host tools can exceed a very low
	// target while still fitting the model. Without a known ceiling, Budget is
	// also the fit bound.
	MaxInputTokens int
	// Force permits summarizing a completed latest turn after a confirmed
	// pre-output context rejection. It never replays tools or changes history.
	Force bool
	// Archive saves a full tool result before a request-only preview replaces
	// it. The returned locator must be readable by this run's retrieval tool.
	Archive func(context.Context, string, string, string) (string, error)
	// Task is the consumer's current user request, retained verbatim alongside
	// summaries. It is data, never a system instruction or extra permission.
	Task string
	// Summarize writes the summary of a native prefix, given this summary's
	// Instructions (a manual compaction adds its own focus to them).
	Summarize func(ctx context.Context, prefix json.RawMessage, instructions string) (string, protocol.Usage, error)
	// SummarizeView, when set, is tried before Summarize. It receives the whole
	// request view, so a host can ask for the summary as a continuation of the
	// live conversation and read that conversation from the provider's prompt
	// cache instead of paying for it again. An error or an unusable reply falls
	// back to Summarize.
	SummarizeView func(context.Context, SummaryRequest) (string, protocol.Usage, error)
	// Instructions is the host's or the user's focus for summaries, such as
	// "keep every SQL statement". Summarize and SummarizeView receive it.
	Instructions string
	// Allow is consulted before a summary is paid for. Returning false leaves
	// the view unsummarized for this request and is not counted as a failure.
	// The prefix is the span the summary would replace.
	Allow func(ctx context.Context, prefix json.RawMessage) bool
	// Observe receives one event per summary attempt, successful or not.
	Observe func(CompactionEvent)
	// Clearing clears old tool results from the view before a summary is
	// paid for. The zero value clears with the defaults.
	Clearing ToolResultClearing
	// Reattach, when set, is called after a new summary with every
	// authoritative message it stands for. What it returns, at most maxTokens,
	// is kept after the summary text: context the work still needs verbatim,
	// such as the files being edited, an active plan or a skill in use.
	Reattach func(ctx context.Context, dropped []json.RawMessage, maxTokens int) string
}

CompactionPolicy configures the consumer's request-only transform. The original Agent retains its full transcript, including every tool result.

func (CompactionPolicy) ForWindow

func (p CompactionPolicy) ForWindow(window int) CompactionPolicy

ForWindow derives a request policy without mutating the original budget.

type Compactor

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

Compactor owns one run's request view and persisted summary. Calls must be serialized. It reads the transcripts it is given in place and may keep reading them while it lives: do not modify one after passing it.

func NewCompactor

func NewCompactor(options CompactorOptions) *Compactor

NewCompactor creates a run-owned compactor. Calls are serialized by the host.

func (*Compactor) Accepted added in v0.3.1

func (c *Compactor) Accepted() int

Accepted counts the summaries this compactor has accepted. A request whose count changed rebased the view on a new summary; Checkpoint's bytes may also change when a restored summary gains its byte digest, which is no rebase.

func (*Compactor) Checkpoint

func (c *Compactor) Checkpoint() json.RawMessage

Checkpoint returns an independent copy of the latest persisted summary. A nil result means no summary has been accepted.

func (*Compactor) Cleared

func (c *Compactor) Cleared() json.RawMessage

Cleared returns the persisted clearing boundary, or nil when nothing has been cleared. Persist it with Checkpoint.

func (*Compactor) Compact

func (c *Compactor) Compact(ctx context.Context, raw json.RawMessage, policy CompactionPolicy) error

Compact summarizes every settled message of raw now, whatever its size: the host's "/compact" with policy.Instructions as its focus. It does not consult Allow or the failure breaker, since someone asked for it.

func (*Compactor) Learn added in v0.3.1

func (c *Compactor) Learn(t *Transcript)

Learn gives the compactor what t read, so a request over these messages does not read them again.

func (*Compactor) Prepare

func (c *Compactor) Prepare(ctx context.Context, raw json.RawMessage, policy CompactionPolicy) (json.RawMessage, error)

Prepare verifies the actual outgoing view after compaction. Oversized tool text is recoverable through the existing archive/retrieval seam, never lost. If the request still cannot fit, fail before sending it instead of repeatedly paying for a summary over the same tail. The original transcript is untouched.

func (*Compactor) PrepareMessages added in v0.3.1

func (c *Compactor) PrepareMessages(ctx context.Context, messages []json.RawMessage, policy CompactionPolicy) (json.RawMessage, error)

PrepareMessages is Prepare of the transcript whose elements are messages, each a JSON value: a host holding a transcript as its stored messages need not join it for a request that a summary shortens.

func (*Compactor) Restore

func (c *Compactor) Restore(raw json.RawMessage) error

Restore validates a saved summary before replacing the current checkpoint. The next Transform additionally verifies its digest against the native input.

func (*Compactor) RestoreCleared

func (c *Compactor) RestoreCleared(raw json.RawMessage) error

RestoreCleared reinstates a boundary returned by Cleared.

type CompactorOptions

type CompactorOptions struct {
	Revision string
	Policy   CompactionPolicy
	Record   func(context.Context, json.RawMessage) error
	Usage    func(protocol.Usage)
}

CompactorOptions binds the host's persistence and usage accounting. Record must succeed before a new summary becomes visible to the provider.

type ContextBudgetError

type ContextBudgetError struct{ Estimated, Budget int }

ContextBudgetError contains only safe numeric diagnostics for public hosts.

func (*ContextBudgetError) Error

func (e *ContextBudgetError) Error() string

type Summary

type Summary struct {
	Revision        string          `json:"revision"`
	PrefixCount     int             `json:"prefix_count"`
	PrefixDigest    string          `json:"prefix_digest"`
	PrefixRawDigest string          `json:"prefix_raw_digest,omitempty"`
	Message         json.RawMessage `json:"message"`
}

Summary binds a persisted summary to an exact native transcript prefix. PrefixDigest identifies the prefix semantically (canonical JSON), so a prefix re-encoded with other bytes still matches. PrefixRawDigest, when present, is the SHA-256 of the prefix's stored bytes as one array: the run checks it first, a hash of the bytes rather than a decode of every message, and falls back to PrefixDigest when the bytes differ or a summary written before it existed has none.

func ParseSummary

func ParseSummary(raw string) (Summary, error)

ParseSummary validates a persisted summary envelope.

type SummaryRequest

type SummaryRequest struct {
	// View is the JSON array of native messages the next provider request
	// would carry. Cut is the index at which the retained tail begins: the
	// summary replaces View[:Cut], system messages excepted.
	View         json.RawMessage
	Cut          int
	Revision     string
	Instructions string
}

SummaryRequest is the request view a SummarizeView callback summarizes.

type ToolResultClearing

type ToolResultClearing struct {
	// Disabled turns clearing off; a persisted boundary is then ignored.
	Disabled bool
	// Trigger is the estimated request size past which the boundary may move
	// while the prompt cache is warm. Zero selects half the Budget.
	Trigger int
	// Keep is how many of the most recent tool results stay verbatim. Zero
	// selects DefaultKeepToolResults.
	Keep int
	// ClearAtLeast is the smallest estimated saving worth a boundary move.
	// Zero selects a twentieth of the Budget, and never less than 1024.
	ClearAtLeast int
	// ExcludeTools are never cleared, such as a tool whose result is an
	// instruction the model keeps following.
	ExcludeTools []string
	// CacheTTL is how long the provider keeps a prompt-cache entry. Once the
	// last response is older than this the cache is cold, and the boundary
	// moves whenever that saves ClearAtLeast. Zero selects five minutes.
	CacheTTL time.Duration
}

ToolResultClearing clears old tool results from the request view before a summary is paid for, the analogue of the Messages API's clear_tool_uses context edit. Tool results are most of a long run's context and stop mattering long before the reasoning around them does.

The clearing boundary is persisted (Compactor.Cleared), so a cleared result is rewritten to the same bytes on every request and the provider's prompt cache still reads the prefix. Moving the boundary rewrites every request from the first newly cleared result, so it moves only when that saves at least ClearAtLeast, and only once the request is past Trigger or the cache has already gone cold.

type Transcript added in v0.3.1

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

Transcript is a stored transcript read once: its messages, validated, with what batch validation and the compactor read from each. A run reads every stored message this way exactly once, and hands the result to its Compactor (Learn) instead of reading the messages again per request.

func ReadMessages added in v0.3.1

func ReadMessages(messages []json.RawMessage) (*Transcript, error)

ReadMessages is ValidateMessageList that keeps what it read.

func (*Transcript) PlainRole added in v0.3.1

func (t *Transcript) PlainRole(i int) (role string, ok bool)

PlainRole is the role of message i, read without decoding it, when the message is in the shape 2ai writes; ok is false for any other message: decode that one to learn its role.

Jump to

Keyboard shortcuts

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