session

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package session stores coding-agent conversations as pi-compatible JSONL trees. It intentionally accepts legacy and partially malformed records on read because the upstream session manager does the same.

Index

Constants

View Source
const (
	EnvAgentDir   = "PI_CODING_AGENT_DIR"
	EnvSessionDir = "PI_CODING_AGENT_SESSION_DIR"
)
View Source
const CurrentVersion = 3

Variables

View Source
var ErrHarnessStorageReplacement = errors.New("session: harness-backed session replacement requires a SessionRepo")

ErrHarnessStorageReplacement prevents lifecycle operations from silently detaching a runtime from its harness repository.

Functions

func AssertValidSessionID

func AssertValidSessionID(id string) error

func DefaultSessionDir

func DefaultSessionDir(cwd, agentDir string) (string, error)

DefaultSessionDir computes and creates the cwd-specific directory.

func DefaultSessionDirPath

func DefaultSessionDirPath(cwd, agentDir string) (string, error)

DefaultSessionDirPath computes the cwd-specific directory without creating it. The replacement rules intentionally mirror the cross-platform regular expressions in upstream.

func FindMostRecentSession

func FindMostRecentSession(sessionDir, cwd string) string

FindMostRecentSession returns an empty string on discovery errors, matching upstream's best-effort continue behavior. When cwd is non-empty, old headers without cwd are excluded.

func MarshalJSONL

func MarshalJSONL(entries []*FileEntry) ([]byte, error)

func MigrateSessionEntries

func MigrateSessionEntries(entries []*FileEntry, generators ...IDGenerator) (bool, error)

MigrateSessionEntries upgrades v1/v2 records to v3 in place. The optional generator supplies entry-id candidates; collisions are retried exactly as in upstream.

Types

type AggregateStats added in v0.4.1

type AggregateStats struct {
	InputTokens           int64
	OutputTokens          int64
	CacheReadTokens       int64
	CacheWriteTokens      int64
	Cost                  float64
	LatestCacheHitRate    float64
	HasLatestCacheHitRate bool
}

type Clock

type Clock func() time.Time

type CompactionResult

type CompactionResult struct {
	Summary              string    `json:"summary"`
	FirstKeptEntryID     string    `json:"firstKeptEntryId"`
	TokensBefore         int64     `json:"tokensBefore"`
	EstimatedTokensAfter int64     `json:"estimatedTokensAfter"`
	Usage                *ai.Usage `json:"usage,omitempty"`
	Details              any       `json:"details,omitempty"`
}

CompactionResult is the coding-agent event/RPC shape. The public agent harness has a separate retained-tail result contract in v0.81.

type FileEntry

type FileEntry struct {
	Type   string
	Header *SessionHeader
	Entry  *SessionEntry
	// contains filtered or unexported fields
}

FileEntry is either a session header, an ordinary tree entry, or another valid JSON value. Raw valid values are retained so parsing remains as permissive as upstream.

func LoadEntriesFromFile

func LoadEntriesFromFile(path string) ([]*FileEntry, error)

LoadEntriesFromFile streams a session without imposing a maximum line size. A valid file starts with a session record whose id is a JSON string.

func ParseSessionEntries

func ParseSessionEntries(content string) []*FileEntry

ParseSessionEntries parses valid JSON lines and silently skips blank or malformed lines. It does not validate the session header or run migrations.

func (*FileEntry) MarshalJSON

func (entry *FileEntry) MarshalJSON() ([]byte, error)

func (*FileEntry) Raw

func (entry *FileEntry) Raw() ([]byte, error)

type IDGenerator

type IDGenerator func() (string, error)

type NewSessionOptions

type NewSessionOptions struct {
	ID            *string
	ParentSession *string
}

type Option

type Option func(*managerOptions)

func WithAgentDir

func WithAgentDir(path string) Option

func WithClock

func WithClock(clock Clock) Option

func WithCwdOverride

func WithCwdOverride(path string) Option

func WithEntryIDGenerator

func WithEntryIDGenerator(generator IDGenerator) Option

func WithHarnessRepo

func WithHarnessRepo(repo harness.SessionRepo) Option

func WithParentSession

func WithParentSession(path string) Option

func WithSessionID

func WithSessionID(id string) Option

func WithSessionIDGenerator

func WithSessionIDGenerator(generator SessionIDGenerator) Option

type OptionalEntryFields

type OptionalEntryFields struct {
	Details    any
	HasDetails bool
	Usage      *ai.Usage
	FromHook   *bool
}

type SessionContext

type SessionContext struct {
	Messages        []json.RawMessage
	ThinkingLevel   string
	Model           *SessionModel
	ActiveToolNames []string
}

func BuildSessionContext

func BuildSessionContext(entries []SessionEntry, leafID *string) SessionContext

type SessionEntry

type SessionEntry struct {
	Type      string
	ID        string
	ParentID  *string
	Timestamp string

	Message          json.RawMessage
	ThinkingLevel    string
	Provider         string
	ModelID          string
	ActiveToolNames  []string
	Summary          string
	FirstKeptEntryID string
	TokensBefore     float64
	Details          json.RawMessage
	Usage            *ai.Usage
	FromHook         *bool
	FromID           string
	CustomType       string
	Data             json.RawMessage
	Content          json.RawMessage
	Display          bool
	TargetID         string
	LeafTargetID     *string
	Label            *string
	Name             string
	// contains filtered or unexported fields
}

func BuildContextEntries

func BuildContextEntries(entries []SessionEntry, leafID *string) []SessionEntry

func GetLatestCompactionEntry

func GetLatestCompactionEntry(entries []SessionEntry) *SessionEntry

func (SessionEntry) MarshalJSON

func (entry SessionEntry) MarshalJSON() ([]byte, error)

func (SessionEntry) MarshalJSONWithParent

func (entry SessionEntry) MarshalJSONWithParent(parentID *string) ([]byte, error)

MarshalJSONWithParent preserves the entry's original member order and unknown fields while replacing parentId, matching object spread followed by a parentId override in upstream JSONL branch export.

type SessionHeader

type SessionHeader struct {
	Type          string
	Version       *int
	ID            string
	Timestamp     string
	CWD           string
	ParentSession *string
	Metadata      json.RawMessage
	// contains filtered or unexported fields
}

func (SessionHeader) MarshalJSON

func (header SessionHeader) MarshalJSON() ([]byte, error)

type SessionIDGenerator

type SessionIDGenerator func(time.Time) (string, error)

type SessionInfo

type SessionInfo struct {
	Path              string
	ID                string
	CWD               string
	Name              *string
	ParentSessionPath *string
	Created           time.Time
	Modified          time.Time
	MessageCount      int
	FirstMessage      string
	AllMessagesText   string
}

func List

func List(cwd, sessionDir string, onProgress SessionListProgress, options ...Option) []SessionInfo

List returns sessions for cwd. A custom flat session directory is filtered by the cwd stored in each header.

func ListAll

func ListAll(sessionDir string, onProgress SessionListProgress, options ...Option) []SessionInfo

ListAll returns every session in a custom flat directory, or all project directories below the configured agent sessions directory.

type SessionListProgress

type SessionListProgress func(loaded, total int)

type SessionManager

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

func ContinueRecent

func ContinueRecent(cwd, sessionDir string, options ...Option) (*SessionManager, error)

func Create

func Create(cwd, sessionDir string, options ...Option) (*SessionManager, error)

func ForkFrom

func ForkFrom(sourcePath, targetCWD, sessionDir string, options ...Option) (*SessionManager, error)

ForkFrom copies a complete session into a new persisted session rooted at targetCWD. Only the header is replaced; all other JSON values retain their JavaScript parse/stringify representation.

func FromHarnessStorage

func FromHarnessStorage(storage harness.SessionStorage, options ...Option) (*SessionManager, error)

FromHarnessStorage exposes one harness session through the coding-agent SessionManager API. Both views retain the same storage as their source of truth; no snapshot is made.

func InMemory

func InMemory(cwd string, options ...Option) (*SessionManager, error)

func Open

func Open(path, sessionDir string, options ...Option) (*SessionManager, error)

func (*SessionManager) AggregateStats added in v0.4.1

func (manager *SessionManager) AggregateStats() (AggregateStats, uint64)

func (*SessionManager) AppendActiveToolsChange

func (manager *SessionManager) AppendActiveToolsChange(activeToolNames []string) (string, error)

func (*SessionManager) AppendCompaction

func (manager *SessionManager) AppendCompaction(
	summary string,
	firstKeptEntryID string,
	tokensBefore int64,
	options ...OptionalEntryFields,
) (string, error)

func (*SessionManager) AppendCustomEntry

func (manager *SessionManager) AppendCustomEntry(customType string, data ...any) (string, error)

func (*SessionManager) AppendCustomMessageEntry

func (manager *SessionManager) AppendCustomMessageEntry(customType string, content any, display bool, details ...any) (string, error)

func (*SessionManager) AppendLabelChange

func (manager *SessionManager) AppendLabelChange(targetID string, label *string) (string, error)

func (*SessionManager) AppendMessage

func (manager *SessionManager) AppendMessage(message any) (string, error)

func (*SessionManager) AppendModelChange

func (manager *SessionManager) AppendModelChange(provider, modelID string) (string, error)

func (*SessionManager) AppendSessionInfo

func (manager *SessionManager) AppendSessionInfo(name string) (string, error)

func (*SessionManager) AppendThinkingLevelChange

func (manager *SessionManager) AppendThinkingLevelChange(level string) (string, error)

func (*SessionManager) Branch

func (manager *SessionManager) Branch(id string) error

func (*SessionManager) BranchWithSummary

func (manager *SessionManager) BranchWithSummary(
	branchFromID *string,
	summary string,
	options ...OptionalEntryFields,
) (string, error)

func (*SessionManager) BuildContextEntries

func (manager *SessionManager) BuildContextEntries() []SessionEntry

func (*SessionManager) BuildSessionContext

func (manager *SessionManager) BuildSessionContext() SessionContext

func (*SessionManager) CreateBranchedSession

func (manager *SessionManager) CreateBranchedSession(leafID string) (string, error)

CreateBranchedSession replaces the manager with the root-to-leaf path in a new session, preserving resolved labels for retained entries.

func (*SessionManager) GetBranch

func (manager *SessionManager) GetBranch(fromID ...string) []SessionEntry

func (*SessionManager) GetCWD

func (manager *SessionManager) GetCWD() string

func (*SessionManager) GetChildren

func (manager *SessionManager) GetChildren(parentID string) []SessionEntry

func (*SessionManager) GetCwd

func (manager *SessionManager) GetCwd() string

func (*SessionManager) GetEntries

func (manager *SessionManager) GetEntries() []SessionEntry

func (*SessionManager) GetEntry

func (manager *SessionManager) GetEntry(id string) *SessionEntry

func (*SessionManager) GetHeader

func (manager *SessionManager) GetHeader() *SessionHeader

func (*SessionManager) GetLabel

func (manager *SessionManager) GetLabel(id string) *string

func (*SessionManager) GetLatestCompactionTimestamp

func (manager *SessionManager) GetLatestCompactionTimestamp() (string, bool)

func (*SessionManager) GetLeafEntry

func (manager *SessionManager) GetLeafEntry() *SessionEntry

func (*SessionManager) GetLeafID

func (manager *SessionManager) GetLeafID() *string

func (*SessionManager) GetSessionDir

func (manager *SessionManager) GetSessionDir() string

func (*SessionManager) GetSessionFile

func (manager *SessionManager) GetSessionFile() string

func (*SessionManager) GetSessionID

func (manager *SessionManager) GetSessionID() string

func (*SessionManager) GetSessionName

func (manager *SessionManager) GetSessionName() *string

func (*SessionManager) GetTree

func (manager *SessionManager) GetTree() []*SessionTreeNode

func (*SessionManager) HarnessMetadata

func (manager *SessionManager) HarnessMetadata() (harness.SessionMetadata, bool)

func (*SessionManager) HarnessRepo

func (manager *SessionManager) HarnessRepo() harness.SessionRepo

func (*SessionManager) IsHarnessBacked

func (manager *SessionManager) IsHarnessBacked() bool

IsHarnessBacked reports whether mutations are delegated to a harness store.

func (*SessionManager) IsPersisted

func (manager *SessionManager) IsPersisted() bool

func (*SessionManager) JSONL

func (manager *SessionManager) JSONL() ([]byte, error)

func (*SessionManager) NewSession

func (manager *SessionManager) NewSession(options ...NewSessionOptions) (string, error)

func (*SessionManager) ResetLeaf

func (manager *SessionManager) ResetLeaf()

func (*SessionManager) SetSessionFile

func (manager *SessionManager) SetSessionFile(path string) error

func (*SessionManager) UsesDefaultSessionDir

func (manager *SessionManager) UsesDefaultSessionDir() bool

type SessionModel

type SessionModel struct {
	Provider string `json:"provider"`
	ModelID  string `json:"modelId"`
}

type SessionTreeNode

type SessionTreeNode struct {
	Entry          SessionEntry       `json:"entry"`
	Children       []*SessionTreeNode `json:"children"`
	Label          *string            `json:"label,omitempty"`
	LabelTimestamp *string            `json:"labelTimestamp,omitempty"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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