Documentation
¶
Overview ¶
Package session — branch.go implements session branching. Branches allow creating divergent conversation paths from a fork point.
Package session provides a file-based session.Service implementation that persists sessions as JSONL files on disk.
Index ¶
- Constants
- func BuildSummarizedEvents(events []*session.Event, summary string, keepUserTokens int) []*session.Event
- func GenerateSessionID() string
- func SessionModel(baseDir, sessionID string) string
- type AutoCompactConfig
- type AutoCompactOutcome
- type BranchInfo
- type CompactConfig
- type CompactionAction
- type FileService
- func (s *FileService) ATIFWriter(sessionID string) *atif.Writer
- func (s *FileService) ActiveBranch(sessionID string) string
- func (s *FileService) AppendEvent(_ context.Context, curSession session.Session, event *session.Event) error
- func (s *FileService) Archive(_ context.Context, req *session.DeleteRequest) error
- func (s *FileService) AutoCompact(sessionID, appName, userID string, bodyTokens, windowSize int64, ...) (AutoCompactOutcome, error)
- func (s *FileService) ClearEvents(sessionID, appName, userID string) error
- func (s *FileService) Compact(sessionID, appName, userID string, summarizer Summarizer, cfg CompactConfig) error
- func (s *FileService) Create(_ context.Context, req *session.CreateRequest) (*session.CreateResponse, error)
- func (s *FileService) CreateBranch(sessionID, appName, userID, branchName string) error
- func (s *FileService) Delete(ctx context.Context, req *session.DeleteRequest) error
- func (s *FileService) EstimateTokens(sessionID, appName, userID string) (int, error)
- func (s *FileService) Get(_ context.Context, req *session.GetRequest) (*session.GetResponse, error)
- func (s *FileService) GetPlanContext(sessionID string) (*PlanContext, error)
- func (s *FileService) GetSessionTitle(sessionID string) (string, error)
- func (s *FileService) LastSessionID(appName, userID string) string
- func (s *FileService) List(_ context.Context, req *session.ListRequest) (*session.ListResponse, error)
- func (s *FileService) ListBranches(sessionID, appName, userID string) ([]BranchInfo, string, error)
- func (s *FileService) SetSessionModel(sessionID, modelName string) error
- func (s *FileService) SetSessionTitle(sessionID, title string) error
- func (s *FileService) SwitchBranch(sessionID, appName, userID, branchName string) error
- func (s *FileService) UpdatePlanContext(sessionID string, ctx *PlanContext) error
- type Meta
- type PlanContext
- type ShedResult
- type Summarizer
Constants ¶
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.
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).
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.
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 SessionModel ¶ added in v0.0.53
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 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 (*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 (s *FileService) Create(_ context.Context, req *session.CreateRequest) (*session.CreateResponse, error)
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 (s *FileService) Get(_ context.Context, req *session.GetRequest) (*session.GetResponse, error)
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 (s *FileService) List(_ context.Context, req *session.ListRequest) (*session.ListResponse, error)
func (*FileService) ListBranches ¶
func (s *FileService) ListBranches(sessionID, appName, userID string) ([]BranchInfo, string, error)
ListBranches returns all branches for a session.
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) 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) 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) 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 Meta ¶
type Meta struct {
ID string `json:"id"`
AppName string `json:"appName"`
UserID string `json:"userID"`
WorkDir string `json:"workDir,omitempty"`
Model string `json:"model"`
Title string `json:"title,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
PlanContext *PlanContext `json:"planContext,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
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 ¶
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.