compaction

package
v1.2.15 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 8 Imported by: 0 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

This file (US-003) ties the compaction pieces together: given a message list and settings, it finds the cut point, extracts file operations from the summarized range, generates the structured summary, and returns a CompactionResult ready to be persisted as a session compaction entry and used to rebuild the agent context. Mirrors pi's prepareCompaction + compact.

This file (US-003) covers summarization: the structured prompts, the conversation serializer, file-operation extraction, and GenerateSummary, which drives a provider stream to turn compacted history into a structured checkpoint summary. It mirrors pi's harness/compaction/compaction.ts prompts and utils.ts helpers, adapted to golder's flat message list and Provider stream.

Package compaction implements context-window token accounting and the decision of when a long session must be compacted, mirroring pi's harness/compaction/compaction.ts.

This file (US-001) covers the token side: estimating a message's token footprint from a character heuristic, deriving the current context-token usage (preferring provider-reported Usage over estimation), and the ShouldCompact threshold check. Cut-point finding (US-002) and summarization (US-003) live in sibling files.

Index

Constants

View Source
const SUMMARIZATION_SYSTEM_PROMPT = `` /* 310-byte string literal not displayed */

SUMMARIZATION_SYSTEM_PROMPT instructs the model to only emit the structured summary and never continue the conversation. Verbatim from pi.

Variables

View Source
var DefaultCompactionSettings = CompactionSettings{
	Enabled:          true,
	ReserveTokens:    16384,
	KeepRecentTokens: 20000,
}

DefaultCompactionSettings matches pi's DEFAULT_COMPACTION_SETTINGS.

Functions

func EstimateTokens

func EstimateTokens(msg agentcore.Message) int

EstimateTokens returns a conservative token estimate for one message using the same character heuristic as pi's estimateTokens (ceil(chars / 4)).

func GenerateSummary

func GenerateSummary(
	ctx context.Context,
	stream provider.StreamFn,
	model provider.Model,
	msgs []agentcore.Message,
	reserveTokens int,
	previousSummary string,
	cfg provider.StreamConfig,
) (string, error)

GenerateSummary drives a provider stream to summarize msgs into a structured checkpoint. When previousSummary is non-empty it uses the update template and embeds the prior summary in <previous-summary> tags; otherwise it uses the first-time template. maxTokens is bounded to min(0.8*reserveTokens, model.MaxOutputTokens) as in pi. The returned text is the concatenation of the assistant response's text blocks. A terminal error/aborted response is surfaced as an error.

func ShouldCompact

func ShouldCompact(contextTokens, contextWindow int, settings CompactionSettings) bool

ShouldCompact reports whether context usage has exceeded the usable window, matching pi: contextTokens > contextWindow - reserveTokens. Disabled settings or a non-positive contextWindow (unknown) never trigger compaction.

Types

type CompactionDetails

type CompactionDetails struct {
	// ReadFiles are files read but not modified in the compacted range.
	ReadFiles []string `json:"readFiles"`
	// ModifiedFiles are files written or edited in the compacted range.
	ModifiedFiles []string `json:"modifiedFiles"`
}

CompactionDetails records the files touched in the compacted history, stored alongside a compaction entry so a later iterative compaction can seed its file lists. Mirrors pi's CompactionDetails.

type CompactionResult

type CompactionResult struct {
	// Summary is the structured summary that replaces the compacted history.
	Summary string
	// FirstKeptIndex is the index of the first retained message.
	FirstKeptIndex int
	// TokensBefore is the estimated context tokens before compaction.
	TokensBefore int
	// Details holds the file operations extracted from the compacted range.
	Details CompactionDetails
}

CompactionResult is the outcome of a compaction: the summary text (with file metadata appended), the index where retained history begins, the estimated tokens before compaction, and the extracted file details. Mirrors pi's CompactionResult, adapted to golder's flat message list (index vs entry id).

func Compact

func Compact(
	ctx context.Context,
	stream provider.StreamFn,
	model provider.Model,
	msgs []agentcore.Message,
	settings CompactionSettings,
	prevCompactionIndex int,
	prevDetails *CompactionDetails,
	previousSummary string,
	cfg provider.StreamConfig,
) (*CompactionResult, error)

Compact prepares and generates a compaction over msgs. It cuts at FindCutPoint(msgs, settings.KeepRecentTokens), summarizes messages in [prevCompactionIndex+1, firstKeptIndex) (seeding file ops from a prior compaction's details when provided), and appends <read-files>/<modified-files> metadata to the summary. previousSummary, when non-empty, switches to the iterative update template.

prevCompactionIndex is the index of the last already-applied compaction point (-1 when none); summarization starts just after it so each compaction only covers the newly accumulated history. prevDetails carries that compaction's file lists so long-lived reads/edits survive across successive compactions.

It returns (nil, nil) when there is nothing to compact (no valid cut point or an empty summarization range).

func (*CompactionResult) Message

Message builds the CompactionMessage to persist for this result: the summary text plus the estimated tokens-before and the file details (as raw JSON).

func (*CompactionResult) RebuildContext

func (r *CompactionResult) RebuildContext(msgs []agentcore.Message, now int64) agentcore.MessageList

RebuildContext returns the post-compaction message list: the compaction checkpoint followed by the retained recent messages (msgs[FirstKeptIndex:]). The summarized prefix is dropped and replaced by the single checkpoint, keeping context continuous while staying within the window. Mirrors pi's post-compact context reconstruction (summary entry + retained tail).

type CompactionSettings

type CompactionSettings struct {
	// Enabled gates automatic compaction decisions.
	Enabled bool
	// ReserveTokens is reserved for the summary prompt and its output; the
	// effective usable window is contextWindow - ReserveTokens.
	ReserveTokens int
	// KeepRecentTokens is the approximate recent-context token budget to retain
	// after compaction (consumed by FindCutPoint in US-002).
	KeepRecentTokens int
}

CompactionSettings holds the thresholds and retention knobs for compaction, mirroring pi's CompactionSettings.

type ContextUsageEstimate

type ContextUsageEstimate struct {
	// Tokens is the estimated total context tokens.
	Tokens int
	// UsageTokens is the tokens reported by the most recent assistant usage block.
	UsageTokens int
	// TrailingTokens is the estimated tokens after that usage block.
	TrailingTokens int
	// LastUsageIndex is the index of the message that provided usage, or -1 when
	// none exists.
	LastUsageIndex int
}

ContextUsageEstimate reports the derived context-token usage for a message list, mirroring pi's ContextUsageEstimate.

func EstimateContextTokens

func EstimateContextTokens(msgs []agentcore.Message) ContextUsageEstimate

EstimateContextTokens computes context-token usage for messages, preferring the most recent valid assistant Usage block and estimating only the messages that follow it. When no usage is available it estimates every message. This mirrors pi's estimateContextTokens.

type CutPointResult

type CutPointResult struct {
	// FirstKeptIndex is the index of the first message retained after
	// compaction; everything before it is summarized.
	FirstKeptIndex int
	// TurnStartIndex is the index of the user message that starts the turn the
	// cut falls inside, or -1 when the cut lands on a clean turn boundary.
	TurnStartIndex int
	// IsSplitTurn reports whether the cut splits an in-progress assistant turn.
	IsSplitTurn bool
}

CutPointResult describes the cut selected for compaction, mirroring pi's CutPointResult (adapted to golder's flat message list).

func FindCutPoint

func FindCutPoint(msgs []agentcore.Message, keepRecentTokens int) CutPointResult

FindCutPoint finds the compaction cut that keeps approximately keepRecentTokens worth of the most recent messages. It accumulates token estimates from the newest message backwards; once the retained budget is reached it snaps to the nearest valid cut point at or after that message, never splitting a toolCall from its toolResult. This mirrors pi's findCutPoint.

When no valid cut point exists, it keeps everything (FirstKeptIndex 0).

type FileOperations

type FileOperations struct {
	// Read holds files read but not necessarily modified.
	Read map[string]struct{}
	// Written holds files written by full-file write operations.
	Written map[string]struct{}
	// Edited holds files modified by edit operations.
	Edited map[string]struct{}
}

FileOperations accumulates the file paths a compaction range touched, split by access kind. Mirrors pi's FileOperations.

func NewFileOps

func NewFileOps() FileOperations

NewFileOps returns an empty file-operation accumulator.

Jump to

Keyboard shortcuts

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