contextview

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultRecentProtectTokens = 20000
View Source
const HistoryTrimNotice = "[System Notice] Some earlier and intervening messages were trimmed to fit the context window. " +
	"If you need information from the trimmed messages, use the available tools " +
	"(such as memory_read or web search) to retrieve it."

HistoryTrimNotice tells the model that budget pressure removed messages. Tiered drops can leave holes mid-history, not only at the head, so the wording stays honest about that. The text is model-visible; change it only deliberately.

View Source
const (
	// MinimumSystemBudgetTokens prevents an active plan from treating a tiny
	// positive remainder as a usable system envelope.
	MinimumSystemBudgetTokens = 256
)

Variables

This section is empty.

Functions

func ApplyProviderRunConfig

func ApplyProviderRunConfig(ctx context.Context, logger *slog.Logger, cfg agentpkg.RunConfig) agentpkg.RunConfig

ApplyProviderRunConfig keeps the direct compiler helper source-compatible. Native execution uses ProviderRunConfigApplier so typed budget failures are returned to the runtime and fail closed before any provider call.

func CollectNonSystemProviderSourceFrags

func CollectNonSystemProviderSourceFrags(ctx context.Context, cfg agentpkg.RunConfig) []contextfrag.ContextFrag

CollectNonSystemProviderSourceFrags preserves the exact SDK message order. A marked current message keeps its original index even though it receives a current-user slot, and raw Query/InlineImages are collected only when the caller has not materialized them yet.

func CollectProviderSourceFrags

func CollectProviderSourceFrags(ctx context.Context, cfg agentpkg.RunConfig) []contextfrag.ContextFrag

CollectProviderSourceFrags derives typed fragments from already-materialized provider fields. It is the legacy fallback; application code normally supplies typed system sections directly.

func ComputeContextBudgetPlan

func ComputeContextBudgetPlan(window, outputReserve, toolDefsCost, currentRequestCost int) (*contextfrag.ContextBudgetPlan, error)

ComputeContextBudgetPlan allocates the fixed reserves named by the provider envelope contract. outputReserve is the resolved generation limit, so the plan reserves exactly what the provider request may emit.

func FinalizeRuntimeContextMarkdown added in v0.20.0

func FinalizeRuntimeContextMarkdown(blocks []string) string

FinalizeRuntimeContextMarkdown joins section blocks with the runtime context document spacing and bounds the complete resource.

func FinalizeRuntimeContextMarkdownFromJoined added in v0.20.0

func FinalizeRuntimeContextMarkdownFromJoined(joined string) string

finalizeRuntimeContextMarkdownWithAudit bounds the joined document and reports the pre-prune byte size so renderers can audit a raw head/tail cut that happened after selection. FinalizeRuntimeContextMarkdownFromJoined bounds an already-joined document.

func FormatMemoryContext added in v0.20.0

func FormatMemoryContext(text string) string

FormatMemoryContext frames provider recall as escaped, untrusted reference data without changing the legacy MemoryContextCollector payload.

func JoinRuntimeContextBlocks added in v0.20.0

func JoinRuntimeContextBlocks(blocks []string) string

JoinRuntimeContextBlocks joins section blocks with the runtime context document spacing without bounding the result.

func ProviderRunConfigApplier

func ProviderRunConfigApplier(logger *slog.Logger) agentpkg.ContextViewApplier

func ToolUsageFrag

func ToolUsageFrag(usage string, scope contextfrag.Scope) contextfrag.ContextFrag

func TrimNoticeFrag

func TrimNoticeFrag(scope contextfrag.Scope) contextfrag.ContextFrag

TrimNoticeFrag is the synthetic fragment the builder splices in when budget trimming dropped history, mirroring the legacy resolver notice message.

Types

type BudgetEnvelope

type BudgetEnvelope struct {
	MaxTokens int
	// Plan activates unified provider-envelope budgeting. Nil preserves the
	// legacy unbudgeted provider selection path. Either Plan or
	// EnforceProtectedBudget makes the budget a provider allowance, which
	// charges fragments at least the provider envelope estimate.
	Plan *contextfrag.ContextBudgetPlan
	// EnforceProtectedBudget makes MaxTokens a hard allowance that includes
	// must-keep fragments without reactivating the turn-start system pass.
	// Step reselection uses it to fail closed when newly injected protected
	// context cannot fit the remaining provider envelope.
	EnforceProtectedBudget bool
	// RecentProtectTokens bands the newest droppable history within this many
	// charged tokens to drop last. Zero disables the window.
	RecentProtectTokens int
	ToolExchange        *contextfrag.ToolExchangePolicy
}

type BuildInput

type BuildInput struct {
	Scope           contextfrag.Scope
	Intent          contextfrag.Intent
	Sources         []SourceSpec
	Targets         []contextfrag.RenderTarget
	Budget          BudgetEnvelope
	DynamicMutators []contextfrag.DynamicMutator
	Options         BuildOptions
	// Mutations is the run's live mutation ledger; renderers record
	// post-selection changes such as a final render prune onto it.
	Mutations *contextfrag.MutationLedger
}

type BuildOptions

type BuildOptions struct {
	DryRun bool
}

type BuildTrace

type BuildTrace struct {
	CollectDurations map[string]int64
	SelectionSummary SelectionSummary
	PlacementSummary PlacementSummary
	RenderSummaries  map[contextfrag.RenderTarget]RenderSummary
	Warnings         []contextfrag.ValidationWarning
}

type Builder

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

func NewBuilder

func NewBuilder(collectors CollectorRegistry, selector Selector, placer Placer, renderers RendererRegistry) *Builder

func (*Builder) Build

func (b *Builder) Build(ctx context.Context, input BuildInput) (*ContextView, error)

type CollectRequest

type CollectRequest struct {
	Scope  contextfrag.Scope
	Intent contextfrag.Intent
	Config any
}

type Collector

type Collector interface {
	Name() string
	Collect(context.Context, CollectRequest) ([]contextfrag.ContextFrag, error)
}

type CollectorRegistry

type CollectorRegistry interface {
	Get(name string) (Collector, bool)
	Names() []string
}

type ContextView

type ContextView struct {
	Intent      contextfrag.Intent
	SourceFrags []contextfrag.ContextFrag
	Selected    []contextfrag.ContextFrag
	Placement   PlacementPlan
	Manifest    contextfrag.Manifest
	Rendered    map[contextfrag.RenderTarget]RenderedPayload
	Trace       BuildTrace
}

type CurrentUserCollector

type CurrentUserCollector struct{}

func (*CurrentUserCollector) Collect

func (*CurrentUserCollector) Name

func (*CurrentUserCollector) Name() string

type CurrentUserConfig

type CurrentUserConfig struct {
	Query string
}

type DiscussContextCollector

type DiscussContextCollector struct{}

func (*DiscussContextCollector) Collect

func (*DiscussContextCollector) Name

type DiscussContextConfig

type DiscussContextConfig struct {
	// ComposedMessages is the authoritative output of timeline composition
	// when non-nil.
	ComposedMessages []timeline.ContextMessage
	// InlineImages are freshly surfaced attachments delivered as native vision
	// input on the latest user message.
	InlineImages []sdk.ImagePart
}

type DiscussContextInput

type DiscussContextInput struct {
	ComposedMessages []timeline.ContextMessage
	InlineImages     []sdk.ImagePart
	SystemFrags      []contextfrag.ContextFrag
}

DiscussContextInput carries the authoritative timeline composition and already-typed system fragments for one discuss turn.

type DiscussSDKContextBuilder

type DiscussSDKContextBuilder struct{}

DiscussSDKContextBuilder assembles typed source fragments for a discuss turn without reverse-parsing a system prompt that is already structured.

func (*DiscussSDKContextBuilder) CollectDiscussSourceFrags

func (*DiscussSDKContextBuilder) CollectDiscussSourceFrags(
	ctx context.Context,
	scope contextfrag.Scope,
	system string,
	input DiscussContextInput,
) ([]contextfrag.ContextFrag, error)

type DropRecord

type DropRecord struct {
	FragID string
	Ref    contextfrag.ContextRef
	Reason string
}

type FragmentSelector

type FragmentSelector struct{}

func (*FragmentSelector) ProfileFor

func (*FragmentSelector) ProfileFor(intent contextfrag.Intent) IntentProfile

func (*FragmentSelector) Select

type HistoryMessagesCollector

type HistoryMessagesCollector struct{}

func (*HistoryMessagesCollector) Collect

func (*HistoryMessagesCollector) Name

type HistoryMessagesConfig

type HistoryMessagesConfig struct {
	Messages []sdk.Message
	// CurrentUserMessageIndex identifies a current request already carried in
	// Messages. The history collector omits it and the current-user collector
	// retains it in the current-user slot.
	CurrentUserMessageIndex *int
	// MemoryMessageIndex identifies materialized memory recall that must be
	// collected separately without changing its provider message position.
	MemoryMessageIndex *int
	// TokenEstimates carries per-message token estimates computed at the
	// source. Missing entries fall back to fragment-side estimation.
	TokenEstimates []int
	// TrimmablePrefix marks the leading message count that may be dropped.
	// Messages at or after the boundary are protected.
	TrimmablePrefix int
	// RepairToolClosures applies the shared repair when a caller has not
	// already repaired its materialized message stream.
	RepairToolClosures bool
}

type HookContextCollector

type HookContextCollector struct{}

func (*HookContextCollector) Collect

func (*HookContextCollector) Name

func (*HookContextCollector) Name() string

type HookContextConfig

type HookContextConfig struct {
	// Text is the combined resolver-hook AppendContext text materialized by
	// the application. The collector owns its role, placement, and cap.
	Text string
}

type IdentityPlacer

type IdentityPlacer struct{}

func (IdentityPlacer) Place

type InlineImageCollector

type InlineImageCollector struct{}

func (*InlineImageCollector) Collect

func (*InlineImageCollector) Name

func (*InlineImageCollector) Name() string

type InlineImageConfig

type InlineImageConfig struct {
	Images []sdk.ImagePart
}

type IntentProfile

type IntentProfile struct {
	Intent        contextfrag.Intent
	MustKeepSlots []contextfrag.Slot
	// MustKeepFrag evaluates retention that depends on fragment policy rather
	// than provider placement alone.
	MustKeepFrag func(contextfrag.ContextFrag) bool
	// SlotTrustFloors declares the minimum trust level per slot.
	SlotTrustFloors map[contextfrag.Slot]contextfrag.TrustLevel
}

type MapCollectorRegistry

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

func NewMapCollectorRegistry

func NewMapCollectorRegistry(collectors ...Collector) *MapCollectorRegistry

func (*MapCollectorRegistry) Get

func (r *MapCollectorRegistry) Get(name string) (Collector, bool)

func (*MapCollectorRegistry) Names

func (r *MapCollectorRegistry) Names() []string

type MapRendererRegistry

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

func NewMapRendererRegistry

func NewMapRendererRegistry(renderers ...Renderer) *MapRendererRegistry

func (*MapRendererRegistry) Get

type MemoryContextCollector

type MemoryContextCollector struct{}

func (*MemoryContextCollector) Collect

func (*MemoryContextCollector) Name

type MemoryContextConfig

type MemoryContextConfig struct {
	Text    string
	Message *sdk.Message
	Index   int
}

type NoopRenderer

type NoopRenderer struct {
	TargetName contextfrag.RenderTarget
}

func (NoopRenderer) Render

func (NoopRenderer) Target

type PassthroughSelector

type PassthroughSelector struct{}

func (PassthroughSelector) ProfileFor

func (PassthroughSelector) Select

type PlacementItem

type PlacementItem struct {
	FragID    string
	Slot      contextfrag.Slot
	Position  int
	CacheHint contextfrag.CacheClass
	Ref       contextfrag.ContextRef
}

type PlacementPlan

type PlacementPlan struct {
	StablePrefixHash   string
	FirstVolatileIndex int
	Items              []PlacementItem
}

type PlacementSummary

type PlacementSummary struct {
	StablePrefixFrags int
	DynamicFrags      int
}

type Placer

type Placer interface {
	Place([]contextfrag.ContextFrag, contextfrag.Intent) PlacementPlan
}

type RenderInput

type RenderInput struct {
	Intent    contextfrag.Intent
	Selected  []contextfrag.ContextFrag
	Placement PlacementPlan
	Manifest  *contextfrag.Manifest
	Scope     contextfrag.Scope
	Target    contextfrag.RenderTarget
}

type RenderSummary

type RenderSummary struct {
	Target      contextfrag.RenderTarget
	ContentHash string
	ItemCount   int
}

type RenderedPayload

type RenderedPayload struct {
	Target      contextfrag.RenderTarget
	ContentHash string
	Data        any
}

type Renderer

type Renderer interface {
	Target() contextfrag.RenderTarget
	Render(context.Context, RenderInput) (RenderedPayload, error)
}

type RendererRegistry

type RendererRegistry interface {
	Get(contextfrag.RenderTarget) (Renderer, bool)
}

type RuntimeFullContextRenderer added in v0.20.0

type RuntimeFullContextRenderer struct {
	Config RuntimeRenderConfig
}

func (*RuntimeFullContextRenderer) Render added in v0.20.0

func (*RuntimeFullContextRenderer) Target added in v0.20.0

type RuntimeRenderConfig added in v0.20.0

type RuntimeRenderConfig struct {
	Mode            RuntimeRenderMode
	ContextMarkdown string
	ContextURI      string
}

type RuntimeRenderMode added in v0.20.0

type RuntimeRenderMode string
const RuntimeRenderModeChat RuntimeRenderMode = "chat"

type RuntimeRenderedPayload added in v0.20.0

type RuntimeRenderedPayload struct {
	ContextMarkdown string
	ContextURI      string
	ContentHash     string
}

type RuntimeSection added in v0.20.0

type RuntimeSection struct {
	ID         string
	Text       string
	Kind       contextfrag.Kind
	Trust      contextfrag.TrustLevel
	Priority   int
	CacheClass contextfrag.CacheClass
	Budget     contextfrag.BudgetPolicy
}

RuntimeSection is one structurally assembled block of the runtime context resource.

type RuntimeSectionsCollector added in v0.20.0

type RuntimeSectionsCollector struct{}

RuntimeSectionsCollector maps structurally assembled runtime sections to fragments without reparsing their Markdown content.

func (*RuntimeSectionsCollector) Collect added in v0.20.0

func (*RuntimeSectionsCollector) Name added in v0.20.0

type RuntimeSectionsConfig added in v0.20.0

type RuntimeSectionsConfig struct {
	Sections []RuntimeSection
}

type SDKMessagesRenderer

type SDKMessagesRenderer struct{}

func (*SDKMessagesRenderer) Render

func (*SDKMessagesRenderer) Target

type SDKRenderedPayload

type SDKRenderedPayload struct {
	System       string
	Messages     []sdk.Message
	Query        string
	InlineImages []sdk.ImagePart
}

type SelectionResult

type SelectionResult struct {
	Selected []contextfrag.ContextFrag
	Dropped  []contextfrag.ContextFrag
	// FatalError stops rendering while allowing Builder to return the partial,
	// content-light selection audit accumulated before the failure.
	FatalError error
	// TrimNotice reports that budget trimming dropped history and the builder
	// must splice the trim notice into Selected at TrimNoticeIndex.
	TrimNotice      bool
	TrimNoticeIndex int
	Edited          []contextfrag.ContextEditTrace
	// EditReasons maps an edited fragment ID to its stable selection reason.
	EditReasons map[string]string
	Warnings    []contextfrag.ValidationWarning
	Summary     SelectionSummary
}

type SelectionSummary

type SelectionSummary struct {
	TotalCollected int
	TotalSelected  int
	TotalDropped   int
	DropReasons    []DropRecord
}

type SelectionTag

type SelectionTag string
const (
	TagMustKeep            SelectionTag = "must_keep"
	TagPreserveRecent      SelectionTag = "preserve_recent"
	TagPreserveToolClosure SelectionTag = "preserve_tool_closure"
	TagCanDrop             SelectionTag = "can_drop"
)

type SourceSpec

type SourceSpec struct {
	Name   string
	Config any
}

type StablePrefixPlacer

type StablePrefixPlacer struct{}

func (StablePrefixPlacer) Place

type StaticCollector

type StaticCollector struct {
	CollectorName string
	Frags         []contextfrag.ContextFrag
}

func (StaticCollector) Collect

func (StaticCollector) Name

func (c StaticCollector) Name() string

type SystemPromptCollector

type SystemPromptCollector struct{}

SystemPromptCollector reverse-parses a flat system prompt string for callers that do not already provide typed source fragments.

func (*SystemPromptCollector) Collect

func (*SystemPromptCollector) Name

func (*SystemPromptCollector) Name() string

type SystemPromptConfig

type SystemPromptConfig struct {
	System    string
	ToolUsage string
	// SplitWorkspace splits the workspace instruction section into its own
	// fragment even without embedded tool usage, so an agent-side tool usage
	// fragment can sort between prompt and workspace instructions.
	SplitWorkspace bool
}

type TaggedFrag

type TaggedFrag struct {
	Frag contextfrag.ContextFrag
	Tags []SelectionTag
	// Tokens is the cost budget arithmetic charges for Frag. A hard provider
	// budget prices it with the envelope estimator so selection and the
	// rendered-envelope check agree; the fragment's own estimate is left
	// untouched so selection decisions do not read as trims.
	Tokens int
}

func (TaggedFrag) HasTag

func (t TaggedFrag) HasTag(tag SelectionTag) bool

Jump to

Keyboard shortcuts

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