index

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 15 Imported by: ? modules, 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 index defines immutable transcript entries and their model-facing projection. It performs no workflow, planner, or store writes. Callers bind a Source to the authorized root run scope before rendering or walking segments.

Index

Constants

View Source
const (
	// Message appends one stored caller or resume message verbatim.
	Message EntryKind = "message"
	// Assistant merges one transcript slice with its dispatched call batch.
	Assistant EntryKind = "assistant"
	// ToolResult projects one result into its batch's user message.
	ToolResult EntryKind = "tool_result"
	// Clarification appends nonempty raw answer text as a user message.
	Clarification EntryKind = "clarification"
	// TypedInput records an answer without producing model messages.
	TypedInput EntryKind = "typed_input"
	// Structural applies a versioned workflow-authored rendering operation.
	Structural EntryKind = "structural"

	// CarriedResult is a permanent continuation placeholder, including Keep results.
	CarriedResult StructuralKind = "carried_result"

	// UnknownTool produces an unknown-tool error from one tool-name parameter.
	UnknownTool StructuralKind = "unknown_tool"
	// PolicyDenial records a policy rejection; without IDs it produces no message.
	PolicyDenial StructuralKind = "policy_denial"
	// ConfirmationDenial projects the schema-compliant JSON in its text parameter.
	ConfirmationDenial StructuralKind = "confirmation_denial"
	// SynthesizedError projects an error from one text parameter.
	SynthesizedError StructuralKind = "synthesized_error"
	// Cancellation produces the time-budget cancellation result.
	Cancellation StructuralKind = "cancellation"
	// FinalizeResults closes calls in the last assistant message with errors.
	FinalizeResults StructuralKind = "finalize_results"
	// FinalizeHint appends the system guidance selected by Reason.
	FinalizeHint StructuralKind = "finalize_hint"
	// Reminders joins its text parameters into one system message per batch.
	Reminders StructuralKind = "reminders"
	// HideBookkeeping removes named calls from earlier assistant messages and
	// omits their following results. Stored entries and segment hashes never change.
	HideBookkeeping StructuralKind = "hide_bookkeeping"

	// TemplateProtocolVersion versions the structural templates for protocol 5.
	TemplateProtocolVersion = 5
	// MaxInlineTextBytes is the inline structural parameter bound.
	MaxInlineTextBytes = 16 * 1024
)

Variables

This section is empty.

Functions

func ComputeChain

func ComputeChain(previous runstore.Hash, entry MessageEntry) (runstore.Hash, error)

ComputeChain hashes the previous chain and the complete deterministic entry encoding, excluding Chain itself. This binds order, content and rendering metadata, including later hiding operations, without rewriting earlier entries.

func EncodeSegment

func EncodeSegment(seg IndexSegment) ([]byte, runstore.Hash, error)

EncodeSegment returns deterministic JSON v2 bytes and their run-store hash. A hash is an address, not proof that the segment has been stored.

func RecordedRole

func RecordedRole(entry MessageEntry) (model.ConversationRole, error)

RecordedRole supplies Units with the role recorded by the content writer. It never resolves content, so pure decisions use only immutable index facts.

func Render

func Render(ctx context.Context, entries []MessageEntry, source Source) ([]*model.Message, error)

Render resolves entries in order without mutating them or their content. Record hashes and typed-input payloads are never read. Provider validation and recovery corrections remain the planner activity's concern.

func RenderTail

func RenderTail(ctx context.Context, entries []MessageEntry, source Source, hidden map[string]bool, cleared map[MessageID]string) ([]*model.Message, error)

RenderTail renders a selected suffix with hidden calls inherited from its prefix and precomputed cleared-result text. Neither map is mutated.

func ResultContent

func ResultContent(ctx context.Context, source Source, entry MessageEntry) (any, error)

ResultContent projects a result exactly as Render does, without loading an omitted body. The returned value is suitable for deterministic previewing.

func StructuralSize

func StructuralSize(entry MessageEntry, texts []string, openIDs []string) (contextmeasure.MessageSize, error)

StructuralSize measures the existing template projection with writer-owned parameter text. FinalizeResults receives the last assistant's still-open IDs. This is deterministic and reads no external content; hashes only select the supplied parameters, including text too large for inline storage.

Types

type ByteRange

type ByteRange struct {
	From    int `json:"from"`
	Through int `json:"through"`
}

ByteRange is an inclusive unsummarised range in the original result.

type CheckpointRecord

type CheckpointRecord struct {
	// Prev addresses the preceding record within this run.
	Prev *runstore.Hash `json:"prev"`
	// From qualifies the previous run's latest checkpoint for continuation.
	From *RunCheckpoint `json:"from"`
	// Earlier summarizes history behind From.
	Earlier EarlierReceipt `json:"earlier"`
	// Summary addresses the latest summary text, if any.
	Summary *runstore.Hash `json:"summary"`
	// SummaryRun is the run against which bare summary citations resolve.
	SummaryRun string `json:"summary_run"`
	// SummaryPos binds copied bare citations to their original chain position.
	SummaryPos int `json:"summary_pos,omitzero"`
	// CitedUsers are the user index lines cited by the summary.
	CitedUsers []IndexLine `json:"cited_users"`
	// Receipt contains only the receipt lines added by this record.
	Receipt []ReceiptLine `json:"receipt"`
	// Through is the last entry covered by the checkpoint.
	Through MessageID `json:"through"`
	// Chain binds the entries through Through.
	Chain runstore.Hash `json:"chain"`
	// Fingerprint identifies the context configuration.
	Fingerprint Fingerprint `json:"fingerprint"`
	// Prompt identifies the prompt that produced Summary.
	Prompt *prompt.PromptRef `json:"prompt"`
	// Calls names every summarizer invocation behind the summary.
	Calls []runstore.CallKey `json:"calls"`
}

CheckpointRecord is immutable compaction evidence. K8 resolves records but does not produce them; K12/K15 own checkpoint production and projection.

type EarlierReceipt

type EarlierReceipt struct {
	// Calls and Assistants count collapsed receipt lines across earlier runs.
	Calls      int `json:"calls,omitzero"`
	Assistants int `json:"assistants,omitzero"`

	// Runs counts earlier runs.
	Runs int `json:"runs"`
	// Messages counts earlier messages.
	Messages int `json:"messages"`
	// First is the first earlier run position.
	First int `json:"first"`
	// Last is the last earlier run position.
	Last int `json:"last"`
	// Users holds the bounded carried user index lines.
	Users []IndexLine `json:"users"`
}

EarlierReceipt summarizes history preceding a continued run's checkpoint.

type EntryKind

type EntryKind string

EntryKind identifies the encoding and rendering operation of an entry.

type Fingerprint

type Fingerprint string

Fingerprint identifies the context configuration recorded with a checkpoint.

type IndexLine

type IndexLine struct {
	// ID is the indexed message position.
	ID MessageID `json:"id"`
	// Text is the bounded first line.
	Text string `json:"text"`
	// Origin qualifies a carried message.
	Origin *Origin `json:"origin,omitzero"`
}

IndexLine is a bounded user-message index line with citation provenance.

type IndexSegment

type IndexSegment struct {
	Prev    *runstore.Hash `json:"prev,omitzero"`
	First   MessageID      `json:"first"`
	Entries []MessageEntry `json:"entries"`
}

IndexSegment contains a nonempty contiguous slice of immutable entries. Prev is nil only for the first segment, whose First must be 1.

func NewSegment

func NewSegment(prev, previousChain runstore.Hash, entries []MessageEntry) (IndexSegment, error)

NewSegment copies entries, computes their running chains, and checks their sequence. previousChain is the last committed entry's Chain (empty at start). It does not store anything or advance a head; only a successful store write authorizes adoption of the hash returned by EncodeSegment.

type MessageEntry

type MessageEntry struct {
	ID    MessageID       `json:"id"`
	Kind  EntryKind       `json:"kind"`
	Hash  runstore.Hash   `json:"hash,omitzero"`
	Calls []runstore.Hash `json:"calls,omitzero"`
	// Call identifies the completed model invocation that produced this assistant entry.
	Call       *runstore.CallKey      `json:"call,omitzero"`
	Structural *StructuralEntry       `json:"structural,omitzero"`
	Role       model.ConversationRole `json:"role,omitzero"`
	ToolUseIDs []string               `json:"tool_use_ids,omitzero"`
	// Bytes counts model-facing text bytes, not the stored encoding.
	Bytes   int               `json:"bytes,omitzero"`
	NonText int               `json:"non_text,omitzero"`
	Record  []runstore.Hash   `json:"record,omitzero"`
	Keep    bool              `json:"keep,omitzero"`
	Origin  *Origin           `json:"origin,omitzero"`
	Batch   MessageID         `json:"batch,omitzero"`
	Result  *ResultProjection `json:"result,omitzero"`
	InputID string            `json:"input_id,omitzero"`
	// Output addresses ref-only planner tool-output metadata. It is not model content.
	Output runstore.Hash `json:"output,omitzero"`
	Chain  runstore.Hash `json:"chain,omitzero"`
}

MessageEntry records one immutable operation in transcript order. Hash addresses one model.Message, an assistant transcript slice, canonical result JSON, raw clarification text, or typed input JSON according to Kind. Calls addresses the exact dispatched tool requests, in dispatch order. Adjacent results with the same nonzero Batch form one user message; Batch is the first result entry's ID. Record is server-only and never rendered.

func Walk

func Walk(ctx context.Context, source Source, head runstore.Hash) ([]MessageEntry, error)

Walk reconstructs exactly the committed entries reachable from head. It rejects missing content, altered bytes, sequence gaps and broken entry chains. Pending entries and orphaned segments are intentionally not part of this walk.

func (MessageEntry) ContentBytes

func (e MessageEntry) ContentBytes() int

ContentBytes reports canonical result length. Earlier entries store that length in Bytes; measured entries retain it in their result projection.

func (MessageEntry) OmitsResultContent

func (e MessageEntry) OmitsResultContent() bool

OmitsResultContent reports whether the stored successful result is projected as a size-limit omission using only the entry's preview and bounds.

type MessageID

type MessageID uint64

MessageID is the one-based position of an entry within a run.

type Origin

type Origin struct {
	Scope string    `json:"scope"`
	Run   string    `json:"run"`
	Pos   int       `json:"pos"`
	ID    MessageID `json:"id"`
	Form  string    `json:"form"`
}

Origin reserves continuation provenance for K18; it is nil in K7.

type ReceiptLine

type ReceiptLine struct {
	// Kind is call, assistant or part.
	Kind string `json:"kind"`
	// MessageID identifies the entry containing an unsummarised part.
	MessageID MessageID `json:"message_id,omitzero"`
	// Part is the one-based part within MessageID.
	Part int `json:"part,omitzero"`
	// Format and Bytes describe an unaccepted image or document.
	Format string `json:"format,omitzero"`
	Bytes  int    `json:"bytes,omitzero"`
	// ToolUseID identifies a covered model-eligible call.
	ToolUseID string `json:"tool_use_id,omitzero"`
	// Unsummarised names result byte ranges not yet summarised.
	Unsummarised []ByteRange `json:"unsummarised,omitzero"`
	// From is the first covered message.
	From MessageID `json:"from"`
	// Through is the last covered message.
	Through MessageID `json:"through"`
	// Tool names an evicted tool call, if any.
	Tool string `json:"tool,omitzero"`
	// Text contains the bounded argument preview or assistant first line.
	Text string `json:"text,omitzero"`
	// Origin qualifies a carried receipt.
	Origin *Origin `json:"origin,omitzero"`
}

ReceiptLine describes one evicted call, assistant message or unsummarised range.

type RenderBudget

type RenderBudget struct {
	MaxPins          int `json:"max_pins,omitzero"`
	MaxPinnedParts   int `json:"max_pinned_parts,omitzero"`
	KeepUserTokens   int `json:"keep_user_tokens,omitzero"`
	MaxSummaryTokens int `json:"max_summary_tokens,omitzero"`
	ReceiptTokens    int `json:"receipt_tokens,omitzero"`
	FramingTokens    int `json:"framing_tokens,omitzero"`
	PreviewTokens    int `json:"preview_tokens,omitzero"`
}

RenderBudget reserves token budgets for later compaction tickets.

type Renderer

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

Renderer incrementally applies immutable entries within one run. It is not concurrency-safe.

func (*Renderer) Append

func (r *Renderer) Append(ctx context.Context, entries []MessageEntry, source Source) error

Append renders only new entries. Discard the renderer after an error.

func (*Renderer) Messages

func (r *Renderer) Messages() ([]*model.Message, error)

Messages returns an owned snapshot using the same JSON boundary as Temporal.

type ResultProjection

type ResultProjection struct {
	// Parts addresses a user-message blob containing runtime-owned attachments.
	Parts runstore.Hash `json:"parts,omitzero"`
	// ContentBytes retains the canonical result size independently of measured
	// preview bytes, so omission and cleared placeholders preserve their meaning.
	ContentBytes int            `json:"content_bytes,omitzero"`
	Preview      TextParameter  `json:"preview,omitzero"`
	Bounds       *agent.Bounds  `json:"bounds,omitzero"`
	Error        *TextParameter `json:"error,omitzero"`
}

ResultProjection contains only metadata needed by the existing transcript projection. A non-nil Error preserves IsError even for empty error text.

type RunCheckpoint

type RunCheckpoint struct {
	// Scope owns the checkpoint content.
	Scope string `json:"scope"`
	// Run identifies the publishing run.
	Run string `json:"run"`
	// Hash addresses that run's checkpoint.
	Hash runstore.Hash `json:"hash"`
}

RunCheckpoint qualifies a checkpoint address by its root scope and run.

type Source

type Source func(context.Context, runstore.Hash) ([]byte, error)

Source reads exact stored bytes by hash within one root run scope.

type StructuralEntry

type StructuralEntry struct {
	Kind            StructuralKind  `json:"kind"`
	ProtocolVersion int             `json:"protocol_version"`
	Text            []TextParameter `json:"text,omitzero"`
	Reason          string          `json:"reason,omitzero"`
}

StructuralEntry is a versioned rendering operation. Text contains template arguments (or a denial's canonical JSON), never unbounded inline content. Reason selects a finalize hint. IDs and batch membership live on MessageEntry.

type StructuralKind

type StructuralKind string

StructuralKind identifies a workflow-authored operation or template.

type TextParameter

type TextParameter struct {
	Text string        `json:"text,omitzero"`
	Hash runstore.Hash `json:"hash,omitzero"`
}

TextParameter holds either inline UTF-8 text (at most 16 KiB) or a hash of the complete text bytes. Writers must use RecordContent for larger text.

type ViewRef

type ViewRef struct {
	// ChainPos identifies the current run without walking earlier runs.
	ChainPos int `json:"chain_pos,omitzero"`
	// CarriedPartial keeps recall available for carried previews/placeholders.
	CarriedPartial bool `json:"carried_partial,omitzero"`
	// ContextFingerprint binds checkpoint production to the run settings.
	ContextFingerprint string         `json:"context_fingerprint,omitzero"`
	IndexHead          runstore.Hash  `json:"index_head,omitzero"`
	Pending            []MessageEntry `json:"pending,omitzero"`
	Checkpoint         *runstore.Hash `json:"checkpoint,omitzero"`
	TailFrom           MessageID      `json:"tail_from,omitzero"`
	ClearedThrough     MessageID      `json:"cleared_through,omitzero"`
	PreviewThrough     MessageID      `json:"preview_through,omitzero"`
	ForceClearThrough  MessageID      `json:"force_clear_through,omitzero"`
	Pinned             []MessageID    `json:"pinned,omitzero"`
	Budget             RenderBudget   `json:"budget,omitzero"`
}

ViewRef names the committed index and one step's pending entries. All fields after Pending are reserved and must remain zero during K7.

Jump to

Keyboard shortcuts

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