Help us shape the future of Go! Take the 2026 Go Developer Survey

session

package
v0.19.8 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 33 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   = nodepath.AgentDirEnv
	EnvSessionDir = "ORB_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.

View Source
var ErrNotOwner = errors.New("session ownership changed")

ErrNotOwner is what a session store returns for an append from a handle that no longer owns the session: another process wrote to it since this one opened it.

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 FindByID added in v0.7.0

func FindByID(cwd, id, sessionDir string, options ...Option) string

FindByID finds an exact project session ID by reading bounded headers only. A custom flat session directory is filtered by the cwd stored in each header.

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

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 WithEntries added in v0.6.0

func WithEntries(entries []*FileEntry) Option

WithEntries restores externally held entries into an in-memory session.

func WithEntryIDGenerator

func WithEntryIDGenerator(generator IDGenerator) Option

func WithHarnessRepo

func WithHarnessRepo(repo harness.SessionRepo) 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
	SystemMessage    json.RawMessage
	FromID           string
	CustomType       string
	Data             json.RawMessage
	Content          json.RawMessage
	Display          bool
	TargetID         string
	// Replacement is a context_edit's raw replacement: JSON null omits the
	// target from model context, {"content": ...} replaces only its content.
	Replacement  json.RawMessage
	LeafTargetID *string
	Label        *string
	Name         string
	// contains filtered or unexported fields
}

func ApplyContextEdits added in v0.14.0

func ApplyContextEdits(entries []SessionEntry) ([]SessionEntry, map[string]bool)

ApplyContextEdits applies each entry's latest context edit on the branch to its message or custom content, and reports the entries an edit omitted.

func BuildContextEntries

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

func GetLatestCompactionEntry

func GetLatestCompactionEntry(entries []SessionEntry) *SessionEntry

func (*SessionEntry) DecodedMessage added in v0.19.5

func (entry *SessionEntry) DecodedMessage() (ai.Message, error)

DecodedMessage is Message decoded, reusing the entry's decode when it has one; the message is shared with the session and must not be modified.

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 {
	ParentID          string
	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.

func ListAllContext added in v0.7.0

func ListAllContext(ctx context.Context, sessionDir string, onUpdate SessionListUpdateFunc, options ...Option) ([]SessionInfo, error)

ListAllContext is the cancellable, progressive companion to ListAll.

func ListContext added in v0.7.0

func ListContext(ctx context.Context, cwd, sessionDir string, onUpdate SessionListUpdateFunc, options ...Option) ([]SessionInfo, error)

ListContext is the cancellable, progressive companion to List. The legacy List API remains a background-context adapter with count-only progress.

func (SessionInfo) Reference added in v0.8.0

func (info SessionInfo) Reference() string

Reference is a real file path for file-backed sessions, otherwise a native ID.

type SessionListProgress

type SessionListProgress func(loaded, total int)

type SessionListUpdate added in v0.7.0

type SessionListUpdate struct {
	Loaded   int
	Total    int
	Sessions []SessionInfo
}

SessionListUpdate is a progressive, context-aware listing update. Sessions is populated periodically and is always sorted by activity when present.

type SessionListUpdateFunc added in v0.7.0

type SessionListUpdateFunc func(SessionListUpdate)

SessionListUpdateFunc receives count updates and periodic partial results.

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

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) AppendContextEdit added in v0.14.0

func (manager *SessionManager) AppendContextEdit(targetID string, replacement json.RawMessage) (string, error)

AppendContextEdit appends a branch-local edit to an earlier model-visible entry: a nil or JSON null replacement omits it from model context, otherwise replacement must be {"content": string | array} and replaces only its content. Raw history, usage and UI history keep the original.

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) BranchPreview added in v0.14.0

func (manager *SessionManager) BranchPreview() (*SessionManager, error)

BranchPreview is an in-memory copy of the header and current branch, for trying appends without touching this session.

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) ContextMessages added in v0.16.0

func (manager *SessionManager) ContextMessages() []any

ContextMessages returns BuildSessionContext's messages decoded: standard roles as ai messages, other roles as their raw JSON. The messages are shared with the session and must not be modified.

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) CustomData added in v0.14.0

func (manager *SessionManager) CustomData(customType string) iter.Seq2[string, json.RawMessage]

CustomData yields the id and data of every custom entry of customType in session order. The data is shared with the session and must not be modified.

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) 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) HasContextEdits added in v0.16.0

func (manager *SessionManager) HasContextEdits() bool

HasContextEdits reports whether the current branch holds a context edit.

func (*SessionManager) IsEmpty added in v0.13.2

func (manager *SessionManager) IsEmpty() bool

IsEmpty reports a conversation nobody wrote in: no message and no name. Orb drops such conversations when it leaves them.

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