session

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package session — branch.go implements session branching. Branches allow creating divergent conversation paths from a fork point.

Package session — merge.go implements safe merging of a remote sessions tree into the local one. It is the merge half of an rsync-based session sync: rsync stages the remote tree, this code folds it into the local tree without ever deleting or truncating local data.

Package session provides a file-based session.Service implementation that persists sessions as JSONL files on disk.

Index

Constants

View Source
const (
	EnvAgentID       = "PI_AGENT_ID"
	EnvAgentType     = "PI_AGENT_TYPE"
	EnvRunID         = "PI_RUN_ID"
	EnvSpecName      = "PI_SPEC_NAME"
	EnvSlice         = "PI_RUN_SLICE"
	EnvCycle         = "PI_RUN_CYCLE"
	EnvParentSession = "PI_PARENT_SESSION"
	EnvAgentBranch   = "PI_AGENT_BRANCH"
	// EnvWorktreeRoot is already set by the orchestrator for path
	// normalization; the agent context records it too so a worktree on disk
	// can be traced back to the spec it belongs to.
	EnvWorktreeRoot = "PI_WORKTREE_ROOT"
)

Environment variables carrying a spawned agent's place in its run tree.

They ride the existing PI_ allowlist prefix (internal/subagent/environ.go), so a parent that sets them reaches its child without further plumbing. The child records them on its own session metadata at creation time, which turns every question the 2026-08-10 investigation answered by inference — which coordinator owns this worker, which spec, which slice, is this a retry — into a field lookup.

View Source
const MaxGoalObjectiveBytes = 4000

MaxGoalObjectiveBytes caps the objective text. It bounds what the objective costs in the system prompt on every turn, so it is measured in bytes: four thousand Han characters would cost four times what four thousand ASCII ones do.

View Source
const MaxSessionTitle = 200

MaxSessionTitle caps the persisted session title. Anything longer is truncated so meta.json stays small and terminal titles (which use this value via OSC 0) fit on a single line.

View Source
const SummarizationPrompt = `` /* 513-byte string literal not displayed */

SummarizationPrompt is the instruction given to the summarizing model. Adapted from Codex's compact prompt (codex-rs/prompts/templates/compact/prompt.md).

View Source
const SummaryPrefix = "Another language model started to solve this problem and produced a summary of its thinking process. " +
	"Use the information in this summary to continue the work and avoid duplicating it. Here is the summary:"

SummaryPrefix introduces the summary in the rebuilt conversation, telling the resuming model where the text came from.

View Source
const UnknownModel = "unknown"

UnknownModel is the placeholder written to meta.Model when the caller did not supply one. meta.json always carries a non-empty "model" field so log consumers (CLI status, /sessions list, the ATIF trajectory) never have to branch on absence.

Variables

This section is empty.

Functions

func BuildSummarizedEvents added in v0.0.48

func BuildSummarizedEvents(events []*session.Event, summary string, keepUserTokens int) []*session.Event

BuildSummarizedEvents performs the Codex-style rebuild: the initial context prefix, then the user's own messages newest-first up to keepUserTokens, then a single summary event.

Tool calls and results are dropped entirely — that is the point, they are the bulk. User messages are preserved because they carry intent that a summary paraphrases lossily, and losing the user's own words is the failure mode that makes a compacted session feel like it forgot what was asked.

func GenerateSessionID added in v0.0.23

func GenerateSessionID() string

GenerateSessionID creates a time-sortable session ID. Format: yymmdd-hhmm-xxxxx-xxxxx (23 chars total). The yymmdd-hhmm prefix makes IDs naturally sortable by creation time.

func SessionBackend added in v0.0.80

func SessionBackend(baseDir, sessionID string) (provider, baseURL string, ok bool)

SessionBackend returns the provider and endpoint recorded for a session. It returns false when the session metadata is unavailable or predates backend recording.

func SessionModel added in v0.0.53

func SessionModel(baseDir, sessionID string) string

SessionModel returns the model recorded in a session's metadata, or an empty string when the session is unknown or its model was never recorded.

Deliberately not a FileService method: startup needs this before any session is loaded, and going through the cache would parse the whole events.jsonl (and rebuild the ATIF trajectory) to read a single metadata field.

Types

type AgentContext added in v0.0.82

type AgentContext struct {
	AgentID   string `json:"agentID,omitempty"`   // the orchestrator's ID for this agent
	AgentType string `json:"agentType,omitempty"` // task | worker | quick-task | code-reviewer | explore
	ParentID  string `json:"parentSessionID,omitempty"`
	RunID     string `json:"runID,omitempty"` // groups every session of one /run
	SpecName  string `json:"specName,omitempty"`
	Slice     int    `json:"slice,omitempty"`
	Cycle     int    `json:"cycle,omitempty"` // /run retry index
	Worktree  string `json:"worktree,omitempty"`
	Branch    string `json:"branch,omitempty"`
	Status    string `json:"status,omitempty"` // terminal status, written when the run ends
}

AgentContext records where a session sits in an agent tree.

Reconstructing a run previously meant grouping sessions by workDir and inferring roles from title prefixes; sessions in numerically-named worktrees (.pi-go/tasks/763098722000) could not be attributed to a spec by any recorded field at all, and three such worktrees are still on disk with nothing to say what they were for. Every question that investigation had to answer by inference is a field here.

func AgentContextFromEnv added in v0.0.82

func AgentContextFromEnv() *AgentContext

AgentContextFromEnv builds an AgentContext from the spawn environment, or returns nil when this process was not spawned as part of an agent tree.

An interactive session sets none of these, so the block stays absent from meta.json exactly as PlanContext does.

func (*AgentContext) Env added in v0.0.82

func (a *AgentContext) Env() []string

Env renders the context as environment assignments for a child process. Empty fields are omitted so a child never inherits a misleading zero.

type AutoCompactConfig added in v0.0.48

type AutoCompactConfig struct {
	// Enabled turns auto-compaction on. Manual /compact works regardless.
	Enabled bool `json:"enabled"`

	// ShedPercent is the share of the context window at which superseded tool
	// results are dropped. Default 60.
	ShedPercent int `json:"shed_percent"`

	// SummarizePercent is the share at which a full summarizing rebuild runs.
	// Default 88. Upstream Codex uses 90 as a hard ceiling that user config may
	// only lower; 88 leaves headroom for the summarization call itself.
	SummarizePercent int `json:"summarize_percent"`

	// KeepUserMessageTokens caps the user messages carried across a summarizing
	// rebuild, newest first. Matches Codex's COMPACT_USER_MESSAGE_MAX_TOKENS.
	KeepUserMessageTokens int `json:"keep_user_message_tokens"`

	// KeepRecentEvents is the tail of the conversation that shedding never
	// touches, so the model always retains its immediate working set.
	KeepRecentEvents int `json:"keep_recent_events"`
}

AutoCompactConfig controls the two-stage auto-compaction trigger.

func DefaultAutoCompactConfig added in v0.0.48

func DefaultAutoCompactConfig() AutoCompactConfig

DefaultAutoCompactConfig returns the two-stage defaults: shed at 60% of the context window, summarize at 90%.

func (AutoCompactConfig) Decide added in v0.0.48

func (c AutoCompactConfig) Decide(bodyTokens, windowSize int64) CompactionAction

Decide returns the action for the given body size. bodyTokens is the context accumulated after the stable cached prefix; windowSize is the model's full context window. A zero or unknown windowSize disables auto-compaction, since a percentage of an unknown quantity is meaningless.

type AutoCompactOutcome added in v0.0.48

type AutoCompactOutcome struct {
	Action        CompactionAction
	TokensBefore  int
	TokensAfter   int
	ResultsShed   int
	EventsDropped int
}

AutoCompactOutcome reports what an auto-compaction pass did, so callers can tell the user and reset any state that assumed the old window.

func (AutoCompactOutcome) Reclaimed added in v0.0.48

func (o AutoCompactOutcome) Reclaimed() int

Reclaimed returns the estimated tokens freed.

func (AutoCompactOutcome) String added in v0.0.48

func (o AutoCompactOutcome) String() string

String renders a one-line summary for the TUI and session log.

type BranchInfo

type BranchInfo struct {
	Name      string  `json:"name"`
	Head      int     `json:"head"`                // index of the last event in this branch
	Parent    *string `json:"parent"`              // parent branch name, nil for main
	ForkPoint int     `json:"forkPoint,omitempty"` // event index where this branch forked from parent
}

BranchInfo describes a named branch within a session.

type CompactConfig

type CompactConfig struct {
	// MaxTokens is the approximate token threshold that triggers compaction.
	// Default: 100000.
	MaxTokens int

	// KeepRecent is the number of recent events to keep uncompacted.
	// Default: 10.
	KeepRecent int
}

CompactConfig controls when and how compaction runs.

func DefaultCompactConfig

func DefaultCompactConfig() CompactConfig

DefaultCompactConfig returns sensible default compaction settings.

type CompactionAction added in v0.0.48

type CompactionAction int

CompactionAction is what the auto-compactor decided to do.

const (
	// CompactionNone means the context is comfortably within budget.
	CompactionNone CompactionAction = iota
	// CompactionShed means drop superseded tool-result payloads.
	CompactionShed
	// CompactionSummarize means run a full summarizing rebuild.
	CompactionSummarize
)

func (CompactionAction) String added in v0.0.48

func (a CompactionAction) String() string

type FileService

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

FileService implements session.Service with file-based JSONL persistence. Sessions are stored in baseDir/<session-id>/ with meta.json and events.jsonl.

func NewFileService

func NewFileService(baseDir string) (*FileService, error)

NewFileService creates a new file-based session service. baseDir is the directory where sessions are stored (e.g., ~/.pi-go/sessions).

func (*FileService) ATIFWriter added in v0.0.14

func (s *FileService) ATIFWriter(sessionID string) *atif.Writer

ATIFWriter returns the ATIF writer for the given session, or nil if not found.

func (*FileService) ActiveBranch

func (s *FileService) ActiveBranch(sessionID string) string

ActiveBranch returns the name of the currently active branch.

func (*FileService) AppendEvent

func (s *FileService) AppendEvent(_ context.Context, curSession session.Session, event *session.Event) error

func (*FileService) Archive added in v0.0.23

func (s *FileService) Archive(_ context.Context, req *session.DeleteRequest) error

Archive moves the session directory under baseDir to archiveDir/yyyy/mm/dd/ using the current time. It removes the session from the in-memory cache.

func (*FileService) AutoCompact added in v0.0.48

func (s *FileService) AutoCompact(
	sessionID, appName, userID string,
	bodyTokens, windowSize int64,
	cfg AutoCompactConfig,
	summarizer Summarizer,
) (AutoCompactOutcome, error)

AutoCompact runs the two-stage compaction for a session.

bodyTokens is the context accumulated after the stable cached prefix and windowSize is the model's full context window; the caller reads both from the token tracker. Passing a zero windowSize disables auto-compaction rather than guessing, because compacting on a guessed budget can discard a session's history for no reason.

The summarizer is only invoked for the summarize stage, so the cheap shed path never costs an LLM call.

func (*FileService) ClearEvents added in v0.0.48

func (s *FileService) ClearEvents(sessionID, appName, userID string) error

ClearEvents drops every event from a session, in memory and on disk, so the next LLM request starts from an empty context window.

This is what the TUI's /clear needs and what Compact cannot provide: compaction replaces history with a summary (which is still history) and returns early when the session is under its token threshold, so on a short session it is a no-op. Clearing is unconditional.

Everything that is not conversation is preserved: session state, meta (title, model, timestamps), plan context and branches all survive. The user cleared the conversation, not the session.

The ATIF writer is replaced with a fresh one so the trajectory numbering restarts alongside the events rather than continuing over a history that no longer exists.

func (*FileService) Compact

func (s *FileService) Compact(sessionID, appName, userID string, summarizer Summarizer, cfg CompactConfig) error

Compact checks if the session's events exceed the token threshold and, if so, summarizes older events using the provided summarizer function. The older events are replaced with a single summary event while recent events are preserved. The events file on disk is rewritten.

func (*FileService) Create

func (*FileService) CreateBranch

func (s *FileService) CreateBranch(sessionID, appName, userID, branchName string) error

CreateBranch creates a new branch from the current position in the session. The new branch starts with a copy of events up to the current head of the active branch.

func (*FileService) Delete

func (s *FileService) Delete(ctx context.Context, req *session.DeleteRequest) error

Delete archives the session (moves to archive/yyyy/mm/dd/) instead of deleting.

func (*FileService) EstimateTokens

func (s *FileService) EstimateTokens(sessionID, appName, userID string) (int, error)

EstimateTokens returns an approximate token count for a session's events. Uses a simple chars/4 heuristic.

func (*FileService) Get

func (*FileService) GetAgentContext added in v0.0.82

func (s *FileService) GetAgentContext(sessionID string) (*AgentContext, error)

GetAgentContext returns the agent context for a session, or nil if unset.

func (*FileService) GetGoal added in v0.3.7

func (s *FileService) GetGoal(sessionID string) (*Goal, error)

GetGoal returns a copy of a session's goal, or nil when none is set.

A copy, not the stored pointer: a caller that mutated the returned struct would otherwise change metadata it never told the service about, which is the same aliasing problem UpdateGoal avoids from the other side.

func (*FileService) GetPlanContext added in v0.0.15

func (s *FileService) GetPlanContext(sessionID string) (*PlanContext, error)

GetPlanContext returns the plan context for the given session, or nil if not found.

func (*FileService) GetSessionTitle added in v0.0.43

func (s *FileService) GetSessionTitle(sessionID string) (string, error)

GetSessionTitle returns the current title for the given session, or "" if the session has no title set. Returns an error for unknown sessions.

func (*FileService) LastSessionID

func (s *FileService) LastSessionID(appName, userID string) string

LastSessionID returns the most recently updated session ID, or "" if none.

func (*FileService) List

func (*FileService) ListBranches

func (s *FileService) ListBranches(sessionID, appName, userID string) ([]BranchInfo, string, error)

ListBranches returns all branches for a session.

func (*FileService) ListMeta added in v0.0.92

func (s *FileService) ListMeta(appName, userID string) ([]Meta, error)

ListMeta returns the metadata of every session under baseDir for the given app, newest first. It reads only meta.json, never events, so listing a large store stays cheap. An empty userID matches every user. Directories without readable metadata are skipped.

func (*FileService) SetSessionModel added in v0.0.23

func (s *FileService) SetSessionModel(sessionID, modelName string) error

SetSessionModel records the model name used by the agent for the given session and persists it to meta.json. Empty model names are normalized to UnknownModel so meta.json's "model" field is never blank.

func (*FileService) SetSessionProvider added in v0.0.56

func (s *FileService) SetSessionProvider(sessionID, provider, baseURL string) error

SetSessionProvider records which backend served the model, and the base URL when one was configured.

The model name alone is ambiguous: the same string routed to ollama, to a hosted gateway, or to a vendor API is three different models with three different failure modes. Recording the name without the backend leaves a transcript that cannot be reproduced. Both fields are optional — an empty value clears rather than writes a blank string, so meta.json stays quiet when there is nothing to say.

func (*FileService) SetSessionTitle added in v0.0.43

func (s *FileService) SetSessionTitle(sessionID, title string) error

SetSessionTitle records a human-readable title for the given session and persists it to meta.json. The title is trimmed, truncated to MaxSessionTitle, and stripped of control characters so it can be embedded in terminal escape sequences (OSC 0) without breaking the surrounding output stream. An empty title clears the field.

func (*FileService) SetSessionVersion added in v0.1.6

func (s *FileService) SetSessionVersion(sessionID, version string) error

SetSessionVersion records the pi-go build that produced the session and persists it to meta.json. An empty version clears the field rather than writing a blank string, the same way SetSessionProvider treats its optional values: a session written by a build with no version stamped has nothing to say, and "version": "" would read as a claim that it does.

func (*FileService) SetSessionWorkDir added in v0.0.92

func (s *FileService) SetSessionWorkDir(sessionID, dir string) error

SetSessionWorkDir records the working directory a session runs in and persists it to meta.json. Create captures the process's own cwd, which is right for the CLI but not for a server that hosts sessions for directories it was not started in — an ACP editor's project, an A2A actor's workspace.

func (*FileService) SwitchBranch

func (s *FileService) SwitchBranch(sessionID, appName, userID, branchName string) error

SwitchBranch switches the active branch for a session. The session's in-memory events are replaced with the branch's events.

func (*FileService) UpdateAgentContext added in v0.0.82

func (s *FileService) UpdateAgentContext(sessionID string, ctx *AgentContext) error

UpdateAgentContext records a session's place in an agent tree. Pass nil to clear it.

func (*FileService) UpdateGoal added in v0.3.7

func (s *FileService) UpdateGoal(sessionID string, goal *Goal) error

UpdateGoal writes a session's goal to metadata. Pass nil to clear it.

The value is copied on the way in, and GetGoal copies it on the way out, so the service owns the metadata it holds. Storing the caller's pointer aliased the TUI's live goal into the session: the TUI mutates that struct without the FileService locks — a `/goal pause` typed while Esc's canceled agent is still draining is the easy case — and AppendEvent marshals the whole meta concurrently under those locks. The race was between a goal field write and AppendEvent's writeMeta, and copying at both boundaries is what removes it rather than making it rarer.

The whole struct is written, not a delta, because every field is derived from one in-memory goal: the loop counter and the completion note change for different reasons, and a partial update would need the two writers to interleave without losing each other's edit.

func (*FileService) UpdatePlanContext added in v0.0.15

func (s *FileService) UpdatePlanContext(sessionID string, ctx *PlanContext) error

UpdatePlanContext updates the plan session context in the session metadata. Pass nil to clear the context.

type Goal added in v0.3.7

type Goal struct {
	Objective string     `json:"objective"`
	Status    GoalStatus `json:"status"`

	// Cycles is the number of automatic turns /goal has started for this
	// objective. It is persisted so resuming a session continues the same
	// budget rather than granting a fresh one.
	Cycles int `json:"cycles,omitempty"`
	// MaxCycles is the budget Cycles is spent against, recorded when the goal
	// was set. Zero means the setting was not recorded; the TUI then applies
	// its current default rather than treating the goal as unbounded.
	MaxCycles int `json:"maxCycles,omitempty"`
	// Turn is the cycle that most recently ran, kept so goal_complete can
	// report which turn it belongs to.
	Turn int `json:"turn,omitempty"`

	CreatedAt int64 `json:"createdAt,omitempty"` // unix seconds
	UpdatedAt int64 `json:"updatedAt,omitempty"`
	// CompletedAt is when goal_complete closed the goal, zero when it has not.
	CompletedAt int64 `json:"completedAt,omitempty"`
	// CompletionNote is the agent's own summary of what satisfied the
	// objective, shown once in the transcript when the goal closes.
	CompletionNote string `json:"completionNote,omitempty"`
}

Goal is a persistent session objective the agent pursues across turns.

The loop fields are what make this different from a prompt: Cycles counts how many times /goal has re-entered the agent, so a goal that never completes stops at the budget instead of running until the process dies. Turn is the cycle the most recent turn belongs to — the TUI stamps it onto each cycle's prompt, and the agent's goal_complete tool reports it back, so a completion reported while cycle N was running cannot close a goal that cycle N+1 has already reopened.

type GoalStatus added in v0.3.7

type GoalStatus string

GoalStatus is where a session objective sits in its lifecycle.

Only Active drives work. Complete is terminal: it is written by the agent's goal_complete tool, and unlike Paused it is not reversible by /goal resume — a finished objective that can be restarted by one command is a loop waiting to happen.

const (
	GoalStatusActive   GoalStatus = "active"
	GoalStatusPaused   GoalStatus = "paused"
	GoalStatusComplete GoalStatus = "complete"
)

type HostEnv added in v0.0.56

type HostEnv struct {
	// GOOS/GOARCH and CPU count, for reading the numbers below in proportion.
	OS   string `json:"os,omitempty"`
	Arch string `json:"arch,omitempty"`
	CPUs int    `json:"cpus,omitempty"`

	// TotalMemoryBytes is physical RAM; AvailableMemoryBytes is what was free
	// at session start. The ratio is what matters — "68MB free of 32GB" is the
	// shape of a machine about to start killing things.
	TotalMemoryBytes     uint64 `json:"totalMemoryBytes,omitempty"`
	AvailableMemoryBytes uint64 `json:"availableMemoryBytes,omitempty"`

	// Disk figures are for the session directory's filesystem, which is where
	// transcripts, the palace DB and any worktrees land.
	DiskTotalBytes uint64 `json:"diskTotalBytes,omitempty"`
	DiskFreeBytes  uint64 `json:"diskFreeBytes,omitempty"`
}

HostEnv is a snapshot of the machine at session start.

It exists to answer one question after the fact: when a process died with nothing but "signal: killed" to show for it, was the machine out of something? A SIGKILL from an OOM killer, a timeout, and a manual kill are indistinguishable at the point the error is read, and by the time anyone investigates the memory pressure that caused it is long gone. Recording the numbers up front turns a guess into a check.

Every field is best-effort: a platform that will not report one leaves it zero rather than failing session creation over diagnostics.

type MergeOptions added in v0.0.87

type MergeOptions struct {
	// DryRun reports what would change without writing anything.
	DryRun bool
}

MergeOptions controls MergeRemoteSessions.

type MergeReport added in v0.0.87

type MergeReport struct {
	// Added counts sessions that existed only on the remote side.
	Added int
	// Merged counts sessions present on both sides that were folded together.
	Merged int
	// Errors lists per-session failures; the run continues past them.
	Errors []string
}

MergeReport summarizes one MergeRemoteSessions run.

func MergeRemoteSessions added in v0.0.87

func MergeRemoteSessions(localDir, remoteDir string, opts MergeOptions) (MergeReport, error)

MergeRemoteSessions folds every session under remoteDir into localDir in place. Sessions that exist only on the remote side are copied in. Sessions present on both sides are merged:

  • events.jsonl: the local file is never rewritten — remote-only events are appended. If one side is a strict continuation of the other (the common "one machine continued the session" case) the missing tail is appended; otherwise the remote events whose IDs are absent locally are appended. Appending (rather than replace) means a pi still writing to the session cannot lose its events to the merge: both processes only ever add lines, at worst interleaved.
  • meta.json: the copy with the newer updatedAt wins.
  • trajectory.atif.json / acp.jsonl: the winning side's copy wins.
  • branches/: per-branch events are merged with the same append rule; branches.json branch entries are merged by name, preserving local-only branches.

Local-only sessions are never touched, and nothing is ever deleted. All writes are atomic (temp + rename) or pure appends, so an interrupted merge leaves each file either old or new, never torn.

type Meta

type Meta struct {
	ID      string `json:"id"`
	AppName string `json:"appName"`
	UserID  string `json:"userID"`
	WorkDir string `json:"workDir,omitempty"`

	// Version is the pi-go build that produced the session, as reported by
	// `pi version` (version plus short commit, e.g. "1.4.2+a1b2c3d"). Without
	// it a session directory cannot say which build wrote it, so a symptom
	// observed in a transcript cannot be tied to a release or bisected to a
	// commit — the same reason Model and Provider are recorded alongside the
	// transcript rather than left to inference.
	Version string `json:"version,omitempty"`

	// Model is the model name as configured. Provider is recorded alongside it
	// because the same name means different things to different backends —
	// "qwen2.5:latest" via ollama and via a hosted gateway are not the same
	// model, and a transcript that records only the name cannot tell them apart
	// after the fact.
	Model    string `json:"model"`
	Provider string `json:"provider,omitempty"`
	BaseURL  string `json:"baseURL,omitempty"`

	Title     string    `json:"title,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`

	// Host is a snapshot of the machine when the session began. It is here so a
	// process that later dies with nothing but "signal: killed" can be checked
	// against the resources it had, instead of guessed at.
	Host *HostEnv `json:"host,omitempty"`

	PlanContext *PlanContext `json:"planContext,omitempty"`

	// Goal is the session's /goal objective, or nil when none is set. It lives
	// next to PlanContext rather than in the TUI's own state because a goal is
	// a property of the work, not of the front end: resuming the session must
	// bring the objective back, and the loop counter has to survive a restart
	// for the same reason a resumed /run keeps its budget.
	Goal *Goal `json:"goal,omitempty"`

	// Agent records this session's place in a /run or /plan agent tree. It is
	// absent for ordinary interactive sessions.
	Agent *AgentContext `json:"agentContext,omitempty"`
}

Meta holds session metadata persisted in meta.json.

type PlanContext added in v0.0.15

type PlanContext struct {
	TaskName  string `json:"taskName,omitempty"`
	RoughIdea string `json:"roughIdea,omitempty"`
	SpecDir   string `json:"specDir,omitempty"`
	Phase     string `json:"phase,omitempty"`
}

PlanContext holds the /plan session context for resume.

type ShedResult added in v0.0.48

type ShedResult struct {
	EventsScanned  int
	ResultsShed    int
	BytesReclaimed int
}

ShedResult reports what a shedding pass reclaimed.

func ShedSupersededToolResults added in v0.0.48

func ShedSupersededToolResults(events []*session.Event, keepRecent int) ([]*session.Event, ShedResult)

ShedSupersededToolResults drops the payload of tool results that a later call on the same target has superseded, replacing each with a short stub.

This is the cheap compaction stage: no LLM call, no rewriting of the stable prefix, and the conversation's shape — every call and its response — is preserved, so tool-call/response pairing stays intact for providers that validate it.

The most recent keepRecent events are never touched, so the model's immediate working set always survives in full. Only the newest result for a given (tool, args) is kept; older ones are stale by definition, since the newest call re-read the same target.

func ShedSupersededToolResultsWithDedup added in v0.0.48

func ShedSupersededToolResultsWithDedup(
	events []*session.Event, keepRecent int, dedupPointers map[string]bool,
) ([]*session.Event, ShedResult)

ShedSupersededToolResultsWithDedup is the form shed uses when a dedup callback has already produced pointer stubs in this session. dedupPointers is the set of payload strings the deduper wrote; any response whose primary field matches one of them is treated as a tiny pointer (not a candidate for shedding) so the *real* earlier result it points at is never replaced with a stub, which would dangle the pointer.

Passing nil for dedupPointers preserves the original behavior.

type Summarizer

type Summarizer func(events []*session.Event) (string, error)

Summarizer is a function that takes a slice of events to be summarized and returns a summary text. This is typically backed by an LLM call.

var SimpleSummarizer Summarizer = func(events []*session.Event) (string, error) {
	return fmt.Sprintf("[Compacted %d events]", len(events)), nil
}

SimpleSummarizer is a basic summarizer that returns a placeholder summary. Useful for manual /compact invocations where no LLM is needed.

func LLMSummarizer added in v0.0.48

func LLMSummarizer(ctx context.Context, llm llmmodel.LLM) Summarizer

LLMSummarizer returns a Summarizer backed by a real model call. It renders the events being dropped as a transcript and asks the model for a handoff summary.

The returned Summarizer never fails the compaction outright: if the model call errors or comes back empty, it returns a degraded placeholder so the caller still reclaims the context rather than aborting and staying over budget with no way to recover.

Jump to

Keyboard shortcuts

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