session

package
v0.49.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 17 Imported by: ? 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

Package session manages persistent conversation sessions.

Sessions are stored as JSON files in ~/.config/moa/sessions/. Each session contains conversation messages, metadata, and a unique ID. The Store provides CRUD operations with atomic writes (temp + rename) to prevent corruption on crash.

Index

Constants

View Source
const (
	MetaModel          = "model"
	MetaCWD            = "cwd"
	MetaPermissionMode = "permission_mode"
	MetaThinking       = "thinking"
	MetaPathScope      = "path_scope"
	MetaAllowedPaths   = "allowed_paths"
	MetaCompactAt      = "compact_at"
	MetaFast           = "fast"
	// MetaDaybreak records whether the session asks for the Daybreak program.
	MetaDaybreak = "daybreak"
	// MetaSessionCostUSD is the session's accumulated spend in USD, so the
	// total survives closing and reopening the session.
	MetaSessionCostUSD = "session_cost_usd"
	MetaOrigin         = "origin"
	// Automation bookkeeping written by the Automation API. The callback fields
	// are set at creation; the idempotency key is only written once the run's
	// first prompt was accepted (see SetIdempotencyKey).
	MetaIdempotencyKey = "idempotency_key"
	MetaCallbackURL    = "callback_url"
	MetaCallbackSecret = "callback_secret"
	// MetaMCPServers holds the per-run MCP servers an automation caller attached
	// to the session (a list of {name, url, headers}). They are session-scoped —
	// never written to any config file — and are replayed on resume so the
	// session reconnects them.
	MetaMCPServers = "mcp_servers"
	// MetaAutomationCreated marks a session the Automation API created itself.
	// Unlike MetaOrigin — a free-form label any creator may pass — it is written
	// on exactly one code path, so it is the authority check for the scoped
	// automation interaction endpoints.
	MetaAutomationCreated = "automation_created"
	// MetaKind classifies a session that is not an ordinary conversation, so
	// listings and routing can tell them apart without loading the runtime.
	// Only KindOwner exists today; an absent key means an ordinary session.
	MetaKind = "kind"
	// MetaOwnerDetached marks a session the user detached from the owner of its
	// codebase: it neither reports to nor is visible to that owner. Stored as
	// true; absent means attached, so reattaching deletes the key rather than
	// writing false, and binaries that predate it simply see an attached
	// session.
	MetaOwnerDetached = "owner_detached"
	// MetaVoiceWake marks a session that owes voice deliveries not saved yet:
	// the wake of voice call minutes, or relays in MetaVoiceRelays; the save
	// that holds the last of them drops it. It is only an index for the startup scan,
	// which reads session headers alone; the minutes record itself says
	// whether, and which, wake is owed.
	MetaVoiceWake = "voice_wake"
	// MetaVoiceRelays holds the voice call relays a session was given and has
	// not saved as messages yet (each delivery_id with what rebuilds it), so
	// a relay queued behind a busy run survives a restart. MetaVoiceWake is
	// set while it holds any.
	MetaVoiceRelays = "voice_relays"
	// MetaLegacyTasks is where versions before the shared task database kept a
	// session's checklist. Nothing reads or writes it any more; it is carried
	// forward untouched so saving a session never deletes what an old JSON
	// held, and so rolling back to an older binary still finds it.
	MetaLegacyTasks = "tasks"
	// MetaCreatorTZ is the IANA timezone of the device that created the
	// session. Absent when unknown (older sessions, the CLI).
	MetaCreatorTZ = "creator_tz"
	// MetaMCPTools is the session's snapshot of the MCP tools it offers the
	// model, by server, with each schema's exact bytes. A restored session
	// offers the same ones before its servers reconnect, so a restart does
	// not rewrite its prompt cache. Absent in older sessions.
	MetaMCPTools = "mcp_tools"
)

RuntimeMetadata keys used for persisting session configuration.

View Source
const (
	TitleSourceAuto   = "auto"
	TitleSourceManual = "manual"
)

Title source values. Empty (legacy) is treated as auto.

View Source
const ArtifactsVersion = 1

ArtifactsVersion is the on-disk schema version of the artifact sidecar.

View Source
const FreshMarkerText = "Started fresh — earlier messages are no longer sent to the model"

FreshMarkerText is the line the transcript shows where the user started fresh. Shared by the live marker and the durable entry, like TrimMarkerText.

View Source
const KindOwner = "owner"

KindOwner marks the conversation of a project owner. Such a session is a real session in every other respect, but it is not work to be handed out: it is hidden from the ordinary session list, never chosen as a destination for an incoming event, and not deletable through the session API.

View Source
const OriginUser = "user"

OriginUser is the implicit origin of a session created by a human through the web client. Sessions persisted before origins existed carry no key and are treated as user-originated.

View Source
const PromptContextVersion = 1

PromptContextVersion is the current PromptContext format.

View Source
const SessionVersion = 2

SessionVersion is the current session format version. V1 (implicit 0): flat Messages array. V2: entry-based tree with branching support.

Variables

View Source
var ErrArtifactsDeleted = errors.New("session: artifacts deleted")

ErrArtifactsDeleted is returned by Upsert once DeleteReferences has run for this store instance: the conversation is gone, so a tool call still inside its critical section must not recreate the sidecar.

View Source
var ErrNotFound = errors.New("session: not found")

ErrNotFound is returned by Load when the session ID does not exist.

Functions

func ApplyPreservedMetadata added in v0.20.0

func ApplyPreservedMetadata(meta, preserved map[string]any) map[string]any

ApplyPreservedMetadata copies preserved creation-time keys into a freshly built metadata map, without overwriting values the runtime already set.

func DeepCopyMessage

func DeepCopyMessage(msg core.AgentMessage) core.AgentMessage

DeepCopyMessage creates a deep copy of an AgentMessage, including Custom map and Content slices with their nested maps.

func DeleteByID

func DeleteByID(baseDir, id string) error

DeleteByID searches all project stores under baseDir and deletes the session.

func ExistsByID added in v0.45.0

func ExistsByID(baseDir, id string) (bool, error)

ExistsByID reports whether a session file named id is in any store under baseDir, without reading it. Unlike the finders, a directory that cannot be read is an error, never absence.

func FindSession

func FindSession(baseDir, id string) (*Session, *FileStore, error)

FindSession searches all project stores under baseDir for a session by ID. Returns the session, the store it was found in, and any error.

func FindSessionReadOnly

func FindSessionReadOnly(baseDir, id string) (*Session, *FileStore, error)

FindSessionReadOnly searches all project stores without migrating or writing the matching session. It is the read-only counterpart to FindSession.

func FindSessionValidated added in v0.41.0

func FindSessionValidated(baseDir, id string, validate func(*Session) error) (*Session, *FileStore, error)

FindSessionValidated searches all project stores and validates each decoded candidate before Load may migrate or write it. A rejected duplicate does not prevent a later authorized candidate from being selected. validate must not mutate the session.

func FormatTranscript added in v0.35.0

func FormatTranscript(entries []Entry) string

FormatTranscript renders a root→leaf path as a line-oriented transcript that keeps messages and tool calls and stays reasonably paginable with the read tool's offset/limit. Thinking and binary payloads are omitted.

entries must be Tree.Path() (the full active branch), not BuildContext(): compaction does not delete history, and the snapshot is evidence, so pre-compaction messages stay in the file even though the parent model no longer sees them.

func MigrateV1ToV2

func MigrateV1ToV2(sess *Session) error

MigrateV1ToV2 converts a v1 session (flat Messages) to v2 (entry-based tree). Idempotent: returns nil immediately if already v2+. Each message becomes an Entry with a sequential parent chain. If the first message is a compaction_summary, it becomes a CompactionEntry followed by the remaining messages (recording that compaction already happened).

func NewID added in v0.45.0

func NewID() (string, error)

NewID returns a fresh session ID for a caller that records it before the session exists. Unlike newID it has no fallback: it fails instead.

func OwnerDetachedIn added in v0.41.0

func OwnerDetachedIn(meta map[string]any) bool

OwnerDetachedIn reads the detach marker from a metadata map, so a saved summary can be classified without loading the whole session.

func PreservedMetadata added in v0.20.0

func PreservedMetadata(meta map[string]any) map[string]any

PreservedMetadata extracts the creation-time keys that survive snapshots. Returns nil when none are present.

func RemoveArtifacts added in v0.37.0

func RemoveArtifacts(sessionDir, sessionID string) error

RemoveArtifacts deletes the sidecar of a session that has no live writer (an unloaded conversation being deleted).

func RemoveSideFiles added in v0.45.0

func RemoveSideFiles(dir, id string) error

RemoveSideFiles removes what a deleted session left next to its transcript in dir: subagent transcripts, voice call journals, snapshots and artifacts.

func RemoveTranscriptSnapshots added in v0.35.0

func RemoveTranscriptSnapshots(sessionDir, sessionID string) error

RemoveTranscriptSnapshots deletes the snapshot sidecar. No-op if absent.

func TranscriptSnapshotDir added in v0.35.0

func TranscriptSnapshotDir(sessionDir, sessionID string) string

TranscriptSnapshotDir is the sidecar directory that holds frozen parent transcript snapshots for one session: <sessionDir>/<sessionID>.snapshots/.

func TrimMarkerText added in v0.41.0

func TrimMarkerText(tokensRemoved int) string

TrimMarkerText is the one line the transcript shows where a trim happened. Exported so the live event and the durable entry render identically: two copies of the wording would drift, and the line a client paints mid-run would stop matching the one it gets back after a reload.

func UnlinkByID added in v0.45.0

func UnlinkByID(baseDir, id string) (string, error)

UnlinkByID removes only a saved session's transcript file and returns the store directory it was in. The session is gone once it returns nil; its side files are then removed with RemoveSideFiles.

func ValidateEntries

func ValidateEntries(entries []Entry, leafID string) error

ValidateEntries checks the integrity of a session's entry tree. Returns an error if:

  • duplicate entry IDs
  • missing parent references
  • leaf ID not found
  • cycle detected (from leaf to root)

func ValidateID

func ValidateID(id string) error

ValidateID accepts the opaque identifier generated for persisted sessions. Keeping IDs filename-safe prevents external API inputs from escaping a store.

func WriteTranscriptSnapshot added in v0.35.0

func WriteTranscriptSnapshot(dir string, entries []Entry) (string, error)

WriteTranscriptSnapshot freezes entries (the caller's copy of Tree.Path) into a markdown file and returns its absolute path. The file is immutable in the sense that moa writes it once and never rewrites it; later appends to the live tree cannot appear in it.

Types

type Artifact added in v0.37.0

type Artifact struct {
	ID          string    `json:"id"`
	Path        string    `json:"path"`
	Name        string    `json:"name"`
	Title       string    `json:"title,omitempty"`
	Description string    `json:"description,omitempty"`
	Mime        string    `json:"mime"`
	Size        int64     `json:"size"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

Artifact is one durable reference from a conversation to a live canonical path. It never holds bytes, versions or inode identity: reads always open Path again, so an atomic replacement at the same location is visible.

type ArtifactMeta added in v0.37.0

type ArtifactMeta struct {
	Name        string
	Title       string
	Description string
	Mime        string
	Size        int64
}

ArtifactMeta carries the observed metadata of one publication. Title and Description only overwrite stored values when non-empty, so a bare re-send does not silently erase a caption the agent gave earlier.

type ArtifactStore added in v0.37.0

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

ArtifactStore persists one conversation's artifact references in a sidecar next to its session JSON: "<sessionDir>/<sessionID>.artifacts".

The extension is deliberately NOT ".json": FileStore.List walks every "*.json" in the directory, and a catalog without a session ID in its header would be read in full on every session listing.

The writer instance is unique and owned by the live ManagedSession; handlers open read-only instances, which the atomic rename always shows either the previous or the new catalog.

func NewArtifactStore added in v0.37.0

func NewArtifactStore(sessionDir, sessionID string) *ArtifactStore

NewArtifactStore returns the store for one session. sessionDir is the directory holding "<sessionID>.json" (FileStore.Dir()). Nothing is created until the first Upsert.

func (*ArtifactStore) DeleteReferences added in v0.37.0

func (s *ArtifactStore) DeleteReferences() error

DeleteReferences removes the sidecar and tombstones this instance so a concurrent publication that had not yet entered the critical section cannot recreate it. Original files are never touched.

func (*ArtifactStore) Get added in v0.37.0

func (s *ArtifactStore) Get(id string) (Artifact, bool, error)

Get returns one artifact by ID.

func (*ArtifactStore) List added in v0.37.0

func (s *ArtifactStore) List() ([]Artifact, error)

List returns the stored artifacts, newest update first (ties broken by ID so the order is stable). A missing sidecar is an empty collection, not an error.

func (*ArtifactStore) Path added in v0.37.0

func (s *ArtifactStore) Path() string

Path returns the sidecar path (may not exist).

func (*ArtifactStore) Upsert added in v0.37.0

func (s *ArtifactStore) Upsert(canonicalPath string, meta ArtifactMeta) (Artifact, error)

Upsert publishes canonicalPath in this conversation and returns the stored artifact. One entry per canonical path: a re-send keeps the ID and CreatedAt and refreshes the observed metadata. Returns ErrArtifactsDeleted once the conversation has been deleted.

type BranchTarget added in v0.49.0

type BranchTarget struct {
	Entry    Entry
	Children int
}

BranchTarget is a message entry Branch would accept, with the number of entries that name it as their parent.

type CWDScan added in v0.25.0

type CWDScan struct {
	// CWDs holds the distinct working directories, newest session first.
	CWDs []string
	// Unreadable counts the session files that could not be decoded at all:
	// truncated or corrupt JSON, a shape the header decoder does not
	// recognize, a file that would not open. It is kept apart from NoCWD
	// because it is the only half that can change: such a file may decode on
	// the next run, so a caller that needs the full picture has a reason to
	// look again.
	Unreadable int
	// NoCWD counts the sessions that decoded fine and simply never recorded a
	// working directory — written by a moa old enough not to store one.
	// Re-reading them produces the same answer forever, so a caller deciding
	// whether to retry must not mistake this for evidence it could recover.
	NoCWD int
}

CWDScan is what ScanCWDs could learn about where sessions ran.

func ScanCWDs added in v0.25.0

func ScanCWDs(baseDir string) (CWDScan, error)

ScanCWDs reports the working directories recorded across every project-scoped store under baseDir, reading only each session's header.

It exists next to ListAll rather than on top of it because it must never fall back to a full read: ListAll's readSummary retries a file it could not stream by loading all of it, which for a damaged multi-megabyte transcript means reading the whole thing to answer a question about its first hundred bytes. A caller that only wants the header treats such a file as unreadable and says so — that is what Unreadable is for. ListAll keeps its fallback, since a session list that silently dropped recoverable sessions would be a regression for every other caller.

func (CWDScan) Unmappable added in v0.25.0

func (s CWDScan) Unmappable() int

Unmappable is the number of sessions that could not say which directory they ran in, for either reason.

type CompactionData

type CompactionData struct {
	Summary          string   `json:"summary"`
	FirstKeptEntryID string   `json:"first_kept_entry_id"`
	TokensBefore     int      `json:"tokens_before"`
	ReadFiles        []string `json:"read_files,omitempty"`
	ModifiedFiles    []string `json:"modified_files,omitempty"`
	// Summarizer is the optional telemetry of the summarizing call; entries
	// written before it existed load with nil.
	Summarizer *core.CompactionSummarizer `json:"summarizer,omitempty"`
}

CompactionData records a non-destructive compaction event.

func (CompactionData) IsEmpty

func (c CompactionData) IsEmpty() bool

IsEmpty returns true if the CompactionData has no summary (zero value).

type ConfigChangeData

type ConfigChangeData struct {
	Model    string `json:"model,omitempty"`
	Thinking string `json:"thinking,omitempty"`
}

ConfigChangeData records a configuration change (model, thinking, etc.).

func (ConfigChangeData) IsEmpty

func (c ConfigChangeData) IsEmpty() bool

IsEmpty returns true if the ConfigChangeData is zero-valued.

type Entry

type Entry struct {
	ID        string    `json:"id"`
	ParentID  string    `json:"parent_id,omitempty"`
	Timestamp time.Time `json:"ts"`
	Type      EntryType `json:"type"`

	// Type-specific data (only one populated per entry):
	Message    core.AgentMessage `json:"message,omitempty"`
	Compaction CompactionData    `json:"compaction,omitempty"`
	Trim       TrimData          `json:"trim,omitempty"`
	Fresh      FreshData         `json:"fresh,omitempty"`
	Config     ConfigChangeData  `json:"config,omitempty"`
	Label      string            `json:"label,omitempty"`
}

Entry is a single immutable unit in the session log. All fields are stored by value to enforce immutability.

func DeepCopyEntry

func DeepCopyEntry(e Entry) Entry

DeepCopyEntry creates a deep copy of an Entry, including all mutable nested data.

type EntryType

type EntryType string

EntryType identifies the kind of entry in the session log.

const (
	EntryMessage    EntryType = "message"
	EntryCompaction EntryType = "compaction"
	EntryTrim       EntryType = "trim"
	// EntryFresh cuts the model's context without a summary. Versions that
	// predate it skip the entry and rebuild the full context.
	EntryFresh  EntryType = "fresh"
	EntryConfig EntryType = "config"
	EntryLabel  EntryType = "label"
)

type FileStore

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

FileStore manages session persistence on disk. Sessions are stored as individual JSON files in a directory. Writes are atomic (temp file + rename) to prevent corruption.

func FindSessionStoreReadOnly added in v0.37.0

func FindSessionStoreReadOnly(baseDir, id string) (*FileStore, error)

FindSessionStoreReadOnly locates the project store owning a session without loading its transcript. It opens only the exact "<id>.json" candidate and decodes the header prefix, so a handler that just needs the session's directory (artifact catalog, sidecars) does not pay for the whole conversation history on every request — unlike FindSessionReadOnly, which calls LoadReadOnly.

A missing session returns ErrNotFound; a candidate that exists but cannot be read or whose header does not identify it is a real error, so callers can answer 404 and 500 differently.

func NewFileStore

func NewFileStore(baseDir, cwd string) (*FileStore, error)

NewFileStore creates a FileStore for sessions scoped to the given CWD. baseDir is the root sessions directory (empty = ~/.config/moa/sessions/). cwd determines the project subdirectory. Empty cwd uses baseDir directly (legacy/tests).

func OpenFileStoreReadOnly added in v0.45.0

func OpenFileStoreReadOnly(baseDir, cwd string) (*FileStore, error)

OpenFileStoreReadOnly returns the store of cwd under baseDir as NewFileStore would, without creating its directory.

func (*FileStore) Create

func (s *FileStore) Create() *Session

Create creates a new empty session with a unique ID (v2 format).

func (*FileStore) Delete

func (s *FileStore) Delete(id string) error

Delete removes a session by ID.

func (*FileStore) Dir

func (s *FileStore) Dir() string

Dir returns the session storage directory.

func (*FileStore) Exists added in v0.45.0

func (s *FileStore) Exists(id string) (bool, error)

Exists reports whether anything occupies the session's path, without reading it: a damaged file, a directory or a dangling link is there too. An error is neither answer.

func (*FileStore) Latest

func (s *FileStore) Latest() (*Session, error)

Latest returns the most recently updated session. Returns nil, nil if no sessions exist.

func (*FileStore) List

func (s *FileStore) List() ([]Summary, error)

List returns summaries of all sessions, sorted by Updated descending (newest first). Uses a streaming json.Decoder that stops as soon as it reaches the entries/messages field, so it never reads (or allocates) the — potentially multi-megabyte — conversation history just to show a session list.

func (*FileStore) Load

func (s *FileStore) Load(id string) (*Session, error)

Load reads a session by ID. Returns ErrNotFound (wrapped) if the session does not exist.

func (*FileStore) LoadReadOnly

func (s *FileStore) LoadReadOnly(id string) (*Session, error)

LoadReadOnly reads a session without performing the legacy v1 migration. Consumers which promise a read-only operation (for example transcript export) must use this method: Load may write a migrated copy to disk.

func (*FileStore) Save

func (s *FileStore) Save(sess *Session) error

Save writes a session to disk atomically. Updates the session's Updated timestamp before writing.

func (*FileStore) SaveNew added in v0.45.0

func (s *FileStore) SaveNew(sess *Session) error

SaveNew is a session's first save when its ID was chosen before it was created: it never replaces a file already at the session's path, and reports one with an error wrapping fs.ErrExist. Later saves use Save.

type FreshData added in v0.42.0

type FreshData struct {
	FirstKeptEntryID string `json:"first_kept_entry_id,omitempty"`
	TokensBefore     int    `json:"tokens_before,omitempty"`
	TokensAfter      int    `json:"tokens_after,omitempty"`
}

FreshData records a "start fresh": from here on the model's context starts at FirstKeptEntryID and nothing stands in for what came before. Like a compaction boundary, but without a summary. The token counters are telemetry; they reconstruct nothing.

func (FreshData) IsEmpty added in v0.42.0

func (f FreshData) IsEmpty() bool

IsEmpty returns true if the FreshData has no cut point (zero value). An empty fresh entry is ignored: it is what an older version leaves behind when it rewrites a session it does not fully understand.

type PromptContext added in v0.49.0

type PromptContext struct {
	Version int `json:"version"`
	// CWD is the directory the prompt was built for; a session restored
	// elsewhere builds a new one.
	CWD         string    `json:"cwd"`
	Now         time.Time `json:"now"`
	Git         string    `json:"git,omitempty"`
	AgentsMD    string    `json:"agents_md,omitempty"`
	SkillsIndex string    `json:"skills_index,omitempty"`
	MemoryIndex string    `json:"memory_index,omitempty"`
	OwnerRole   string    `json:"owner_role,omitempty"`
	OwnerBook   string    `json:"owner_book,omitempty"`
	// System is the base system prompt exactly as the session last installed
	// it (without the goal directive, which is composed on top).
	System string `json:"system"`
}

PromptContext is what a session's system prompt was built from, and the prompt itself, frozen with the session.

The prompt is part of the cached prefix, and Anthropic binds every signed thinking block to that prefix: rebuilding it after a restart with a new date, commit or AGENTS.md costs the cache and every thinking block in the conversation. So a restored session sends System byte for byte, and only a compaction, Start fresh or a reload builds a new one (owner's decision, 18/11/2026).

The inputs are kept beside the prompt so a rebuild that is not one of those (the tool set changing) keeps the context the session was frozen with.

func (*PromptContext) UnmarshalJSON added in v0.49.0

func (pc *PromptContext) UnmarshalJSON(b []byte) error

UnmarshalJSON never fails: the snapshot is derived data that can always be rebuilt, so a value this binary cannot decode (a later format, a damaged file) reads as an unusable one and the session is built afresh instead of becoming impossible to open.

func (*PromptContext) Usable added in v0.49.0

func (pc *PromptContext) Usable(cwd string) bool

Usable reports whether pc can be restored into a session working in cwd.

type Session

type Session struct {
	// Header fields — read by partial-read list optimization
	ID      string    `json:"id"`
	Version int       `json:"version"`
	Created time.Time `json:"created"`
	Updated time.Time `json:"updated"`
	Title   string    `json:"title"`
	// TitleSource records how Title was set: "manual" (user renamed) or "auto"
	// (derived / LLM-generated). Empty is legacy and treated as auto.
	TitleSource string         `json:"title_source,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`

	// V2: entry-based tree log
	LeafID  string  `json:"leaf_id,omitempty"`
	Entries []Entry `json:"entries,omitempty"`

	// V1 legacy (only present in old sessions, cleared after migration)
	Messages        []core.AgentMessage `json:"messages,omitempty"`
	CompactionEpoch int                 `json:"compaction_epoch,omitempty"`

	// PromptContext is the session's frozen prompt. It comes after the
	// conversation so listing sessions never reads it. Absent in sessions
	// saved before it existed.
	PromptContext *PromptContext `json:"prompt_context,omitempty"`
}

Session represents a persistent conversation.

Field ordering matters: summary fields (ID, Version, Title, Metadata) come first so the readSummary partial-read optimization (4KB prefix) still works.

func (*Session) CompactAtMeta

func (s *Session) CompactAtMeta() int

CompactAtMeta returns the persisted soft compaction threshold in tokens, or 0 when none was set (the default window-based behavior). Metadata round-trips through JSON, so a number read back from disk arrives as float64 while one set in this process is still an int — both are accepted.

func (*Session) DaybreakMeta added in v0.47.0

func (s *Session) DaybreakMeta() bool

DaybreakMeta returns whether the Daybreak program was on when this session was last saved. Missing and malformed values mean off.

func (*Session) FastMeta added in v0.35.0

func (s *Session) FastMeta() bool

FastMeta returns whether premium speed was enabled when this session was last saved. Missing and malformed values preserve the historical default.

func (*Session) Kind added in v0.41.0

func (s *Session) Kind() string

Kind returns the session classification, or "" for an ordinary session.

func (*Session) Origin added in v0.20.0

func (s *Session) Origin() string

Origin returns the persisted origin, defaulting to OriginUser when absent.

func (*Session) OwnerDetached added in v0.41.0

func (s *Session) OwnerDetached() bool

OwnerDetached reports whether the user detached this session from the owner of its codebase.

func (*Session) PathMeta

func (s *Session) PathMeta() (scope string, allowedPaths []string)

PathMeta returns the persisted path configuration from Metadata.

func (*Session) Rename

func (s *Session) Rename(title string, maxLen int)

Rename sets a user-chosen title and marks it manual so auto-titling never overwrites it.

func (*Session) RuntimeMeta

func (s *Session) RuntimeMeta() (model, cwd, permissionMode, thinking string)

RuntimeMeta returns the persisted runtime configuration from Metadata. Missing keys return empty strings.

func (*Session) SetAutoTitle

func (s *Session) SetAutoTitle(title string, maxLen int)

SetAutoTitle applies an auto-generated title, unless the user has manually renamed the session. Empty/whitespace titles are ignored.

func (*Session) SetIdempotencyKey added in v0.20.0

func (s *Session) SetIdempotencyKey(key string)

SetIdempotencyKey records the Automation API key this session answers. It is written only after the run's first prompt was accepted, so a session that never received one stays unreachable by key. An empty key is not stored.

func (*Session) SetOrigin added in v0.20.0

func (s *Session) SetOrigin(origin string)

SetOrigin records who created the session (e.g. "user", "automation", or a caller-chosen label such as "linear-webhook"). An empty origin is not stored: missing means user.

func (*Session) SetOwnerDetached added in v0.41.0

func (s *Session) SetOwnerDetached(detached bool)

SetOwnerDetached records or clears the detach marker. Clearing deletes the key: an attached session never carries it.

func (*Session) SetPathMetadata

func (s *Session) SetPathMetadata(scope string, allowedPaths []string)

SetPathMetadata persists path scope and allowed paths to session metadata.

func (*Session) SetRuntimeMetadata

func (s *Session) SetRuntimeMetadata(model, cwd, permissionMode, thinking string)

SetRuntimeMetadata persists the core session configuration (model, cwd, permission mode, thinking level) into Metadata. Called on every state change and at session creation. Centralizes what gets persisted so all frontends (serve, headless CLI) stay consistent.

func (*Session) SetTitle

func (s *Session) SetTitle(text string, maxLen int)

SetTitle sets the session title from a user message. Only sets if title is empty (first message). Truncates to maxLen.

func (*Session) TitleIsManual

func (s *Session) TitleIsManual() bool

TitleIsManual reports whether the user explicitly renamed the session. A legacy empty source counts as auto.

type SessionStore

type SessionStore interface {
	Create() *Session
	Save(sess *Session) error
	Load(id string) (*Session, error)
	Latest() (*Session, error)
	List() ([]Summary, error)
	Delete(id string) error
}

SessionStore abstracts session persistence. FileStore implements this for disk-based storage. External consumers (e.g., HTTP servers) implement it for database storage.

Contract:

  • Create returns a new Session with a unique ID and timestamps set. It does NOT persist — call Save.
  • Save persists the session. It MUST set Updated to the current time before writing.
  • Load returns the session or ErrNotFound (wrapped or direct — use errors.Is).
  • Latest returns the most recently updated session, or (nil, nil) if the store is empty.
  • List returns summaries sorted by Updated descending. Empty store returns (nil, nil).
  • Delete is idempotent — deleting a non-existent session returns nil.

type SubagentCacheAudit added in v0.46.0

type SubagentCacheAudit struct {
	Version     int                      `json:"version"`
	JobID       string                   `json:"job_id"`
	ResumedFrom string                   `json:"resumed_from,omitempty"`
	Count       uint64                   `json:"count"`
	First       core.RequestFingerprint  `json:"first"`
	Last        *core.RequestFingerprint `json:"last,omitempty"`
}

SubagentCacheAudit is the cache-diagnostics sidecar of one subagent job: content-free fingerprints (hashes and cache-marker positions) of its first and most recent provider requests, plus how many requests were observed. It lives apart from the transcript because the transcript is rewritten on every title/end update and must not erase it.

Count is the number of final provider request bodies built for THIS job. Every resume starts a new job with its own audit file, so counts are never aggregated across resumes. An HTTP retry of the same body is one request; a fast-mode fallback that rebuilds the body is another. The file is written when the first request is built (Last nil) and again when the job ends, so a crash in between leaves only First and Count 1. Last is also nil when the final fingerprint could not be computed. To judge whether a resume kept the cache prefix, compare the original job's Last with the resumed job's First (linked by ResumedFrom), not First and Last of one job.

The file holds hashes only, but hashes can confirm guessed content: treat it as private.

type SubagentStore

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

SubagentStore persists subagent transcripts for one parent session in a side directory: <session dir>/<sessionID>.subagents/<jobID>.json.

func NewSubagentStore

func NewSubagentStore(sessionDir, sessionID string) *SubagentStore

NewSubagentStore returns a store rooted at "<sessionDir>/<sessionID>.subagents". sessionDir is the directory holding the parent session's <id>.json (e.g. FileStore.Dir()). The directory is created lazily on first Save.

func (*SubagentStore) Dir

func (s *SubagentStore) Dir() string

Dir returns the side-directory path (may not exist yet).

func (*SubagentStore) LegacyResult added in v0.30.0

func (s *SubagentStore) LegacyResult(jobID string) (string, error)

LegacyResult reads the final assistant text from one legacy transcript without constructing its complete Messages slice. Completed transcripts written before Result existed need that fallback for their restored cards, but retaining every message merely to recover its final text defeats the summary path's memory savings.

func (*SubagentStore) List

func (s *SubagentStore) List() ([]SubagentTranscript, error)

List returns all persisted transcripts for the session, newest-finished first. Missing directory yields an empty slice (not an error).

func (*SubagentStore) ListSummaries added in v0.30.0

func (s *SubagentStore) ListSummaries() ([]SubagentTranscript, error)

ListSummaries returns persisted transcript headers, newest-finished first. It stops before Messages because callers that only render subagent cards do not need to allocate every child conversation merely to show its metadata. Missing directories and unreadable headers keep List's established result: an empty slice and skipped sidecars, respectively.

The decoded headers are reused while every sidecar's size and mtime stay unchanged: WebSocket init asks for this list on every reconnect, and decoding the same files again was the dominant heap cost of those payloads.

func (*SubagentStore) Load

func (s *SubagentStore) Load(jobID string) (*SubagentTranscript, error)

Load reads one transcript by jobID. Returns ErrNotFound (wrapped) if absent.

func (*SubagentStore) LoadCacheAudit added in v0.46.0

func (s *SubagentStore) LoadCacheAudit(jobID string) (*SubagentCacheAudit, error)

LoadCacheAudit reads one job's cache audit. Returns ErrNotFound (wrapped) if the job has none.

func (*SubagentStore) LoadOutcome added in v0.41.0

func (s *SubagentStore) LoadOutcome(jobID string) (SubagentTranscript, error)

LoadOutcome reads one transcript's HEADER — status, result, error, task — without decoding its messages. It is what a parent needs to recover the verdict of a subagent whose in-memory job is gone: the conversation itself would be megabytes, and none of it is the answer.

A transcript left in "running" by a crash is reported as interrupted rather than running: nothing is executing it, and presenting a dead job as live would have the parent wait forever.

func (*SubagentStore) Remove

func (s *SubagentStore) Remove() error

Remove deletes the entire side directory (used when the parent session is deleted). No-op if it doesn't exist.

func (*SubagentStore) Save

Save atomically writes one transcript to <jobID>.json.

func (*SubagentStore) SaveCacheAudit added in v0.46.0

func (s *SubagentStore) SaveCacheAudit(a SubagentCacheAudit) error

SaveCacheAudit atomically overwrites the job's audit with a complete snapshot. It never reads the previous file: a snapshot is self-contained, so a corrupt or stale file is simply replaced.

type SubagentTranscript

type SubagentTranscript struct {
	JobID  string `json:"job_id"`
	Task   string `json:"task"`
	Title  string `json:"title,omitempty"`
	Model  string `json:"model"`
	Status string `json:"status"`
	// Result and Error retain the terminal outcome separately from the child
	// transcript so a parent timeline can restore the correct terminal card.
	Result     string      `json:"result,omitempty"`
	Error      string      `json:"error,omitempty"`
	Thinking   string      `json:"thinking,omitempty"`
	Async      bool        `json:"async"`
	StartedAt  time.Time   `json:"started_at,omitempty"`
	FinishedAt time.Time   `json:"finished_at,omitempty"`
	Usage      *core.Usage `json:"usage,omitempty"`
	CostUSD    float64     `json:"cost_usd,omitempty"`
	// ContextPercent is how full the child's own window was when it finished
	// (0-100). Stored alongside usage so reopening a finished subagent
	// restores the same reading it had while it ran. A POINTER because 0 is a
	// real reading (a child that barely used its window) and has to stay
	// distinguishable from a transcript written before this was recorded:
	// nil means unknown, and unknown hides the ring instead of drawing an
	// empty one.
	ContextPercent *int `json:"context_percent,omitempty"`
	// Daybreak is whether the child ran with the Daybreak program, so a
	// resume continues in the same mode. Absent on older transcripts (off).
	Daybreak bool                `json:"daybreak,omitempty"`
	Messages []core.AgentMessage `json:"messages"`
	// SystemPrompt is the prompt the child ran with, so a resume sends the
	// same one. After the messages: summaries never read it. Absent on older
	// transcripts.
	SystemPrompt string `json:"system_prompt,omitempty"`
}

SubagentTranscript is the persisted record of one subagent's sub-conversation. Stored in a side directory next to the parent session so a subagent's transcript survives restarts and can be reopened after it finished, without bloating the parent session's own tree/history.

type Summary

type Summary struct {
	ID          string         `json:"id"`
	Created     time.Time      `json:"created"`
	Updated     time.Time      `json:"updated"`
	Title       string         `json:"title"`
	TitleSource string         `json:"title_source,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

Summary is a lightweight session descriptor without messages. Used for listing sessions without loading full conversation data.

func ListAll

func ListAll(baseDir string) ([]Summary, error)

ListAll returns summaries from all project-scoped stores under baseDir. If baseDir is empty, uses the default. Returns partial results on errors.

type ToolCallRepair added in v0.47.0

type ToolCallRepair func(originMsgID string, call core.Content) (core.AgentMessage, bool)

ToolCallRepair gives a caller the first chance to close a tool call that has no result: it is told the call and the message that carried it, and returns the result to record, or false to leave the call to the generic repair.

type Tree

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

Tree is an append-only entry log that supports branching. It maintains an index for O(1) lookup and a leaf pointer for the current branch tip. All public methods are safe for concurrent use.

Key methods:

  • BuildContext() returns messages for the LLM (handles compaction)
  • AllMessages() returns ALL messages along the current path (for display)
  • Branch() moves the leaf to enable forking
  • Snapshot() returns a deep-copied (entries, leafID) pair for persistence

func NewTree

func NewTree() *Tree

NewTree creates an empty tree.

func NewTreeFromEntries

func NewTreeFromEntries(entries []Entry, leafID string) (*Tree, error)

NewTreeFromEntries reconstructs a tree from persisted entries. Returns an error if the entries are invalid (see ValidateEntries).

func NewTreeFromEntriesRepairing added in v0.47.0

func NewTreeFromEntriesRepairing(entries []Entry, leafID string, repair ToolCallRepair) (*Tree, error)

NewTreeFromEntriesRepairing is NewTreeFromEntries with repair consulted for each unresolved tool call before the generic "result unavailable" closes it.

func (*Tree) Adopt added in v0.46.0

func (t *Tree) Adopt(staged *Tree, rev uint64) bool

Adopt replaces this tree's contents with staged, a copy returned by Stage at revision rev, in one step: readers see the tree either before or after the whole change. It refuses (returns false) when the tree changed since the copy was taken, since installing it would discard that change. The pointer stays the same, so every holder of it sees the adopted state. staged must not be used afterwards.

func (*Tree) AllMessages

func (t *Tree) AllMessages() []core.AgentMessage

AllMessages returns ALL messages along the current path (for display). Includes pre-compaction messages. Compaction entries become synthetic status messages.

func (*Tree) Append

func (t *Tree) Append(e Entry) string

Append adds an entry as a child of the current leaf and advances the leaf. The entry's ID and Timestamp are set automatically. ParentID is set to the current leaf. The Message field is deep-copied to enforce immutability. Returns the assigned entry ID.

func (*Tree) Branch

func (t *Tree) Branch(entryID string) error

Branch moves the leaf pointer to the given entry ID. Next Append creates a child of that entry (starting a new branch). Returns an error if:

  • the entry ID doesn't exist
  • the target is a tool_result (would leave dangling tool_call)
  • the resulting path (as BuildContext would see it) leaves any assistant tool_call without a matching tool_result

func (*Tree) BranchBefore added in v0.46.0

func (t *Tree) BranchBefore(entryID string) (string, error)

BranchBefore moves the leaf to just before a user message, so the message can be edited and sent again as a sibling. It returns the new leaf, which is "" when nothing precedes the message (the branch becomes empty; the old one stays in the tree).

A message sent while moa was working has a tool_result above it (directly, or through other steers delivered with it), and no branch may end there. Landing then falls back to the nearest earlier entry that is a valid target and not itself a user message: the last complete moa answer (or a boundary). A user message is skipped on the way up so the re-sent message never ends up right after another unanswered one.

func (*Tree) BranchTargets added in v0.49.0

func (t *Tree) BranchTargets(ctx context.Context) ([]BranchTarget, error)

BranchTargets returns, in log order, every message entry for which ValidBranchTarget reports nil, in one O(N) pass instead of one path copy per entry. It is the bulk form of that check and must agree with it exactly.

The pass walks the tree from its roots keeping the tool-call balance of the context the current path would produce: a tool call is unresolved when its last call comes after its last result. That context starts at the entry the last boundary (compaction or non-empty fresh cut) keeps, which usually lies above the boundary on the path, so reaching a boundary rebuilds the balance from that entry; every other step adds or removes one entry's calls and is undone on the way back up. Trims only rewrite the text of results, never their call IDs, so they do not affect the balance.

It returns ctx's error as soon as ctx is cancelled. The read lock is held for the whole pass.

func (*Tree) BuildContext

func (t *Tree) BuildContext() ([]core.AgentMessage, int)

BuildContext returns messages for the LLM provider and the compaction epoch.

Algorithm:

  1. Walk the current path (root → leaf)
  2. Find the LAST compaction entry (most recent wins for multi-compaction)
  3. If compaction found: emit compaction_summary + messages from firstKeptEntryID → leaf
  4. If no compaction: emit all message entries
  5. Only include LLM-relevant roles (user, assistant, tool_result, compaction_summary)

func (*Tree) Children

func (t *Tree) Children(entryID string) []Entry

Children returns direct children of the given entry. Returned entries are shallow copies; do not mutate.

func (*Tree) Clear

func (t *Tree) Clear()

Clear resets the tree to empty state.

func (*Tree) DisplayMessagesSince added in v0.28.0

func (t *Tree) DisplayMessagesSince(entryID string) ([]core.AgentMessage, bool)

DisplayMessagesSince returns the display projection strictly after entryID when entryID is on the current root-to-leaf path. The boolean is false for an empty, unknown, or off-path token; callers must then use a full snapshot. A compaction remains a display marker, exactly as it does in AllMessages.

func (*Tree) Entries

func (t *Tree) Entries() []Entry

Entries returns a shallow copy of all entries. For persistence, prefer Snapshot() which deep-copies messages.

func (*Tree) Entry

func (t *Tree) Entry(id string) (Entry, bool)

Entry returns an entry by ID.

func (*Tree) HasMsgID added in v0.21.0

func (t *Tree) HasMsgID(msgID string) bool

HasMsgID reports whether an ID is reserved anywhere in the tree, by an entry or a legacy message identity. Uniqueness spans every branch: navigating away does not release an ID, and rebuilt summaries share their boundary's entry ID.

func (*Tree) LeafID

func (t *Tree) LeafID() string

LeafID returns the current branch tip entry ID.

func (*Tree) Len

func (t *Tree) Len() int

Len returns the total number of entries across all branches.

func (*Tree) Path

func (t *Tree) Path() []Entry

Path returns entries from root to the current leaf, in order. Returned entries are shallow copies; do not mutate.

func (*Tree) Rev added in v0.49.0

func (t *Tree) Rev() uint64

Rev returns the tree's mutation counter: it changes with every Append, Branch, BranchBefore, Clear and Adopt, and entries are never mutated in place, so two equal revisions of one tree hold the same entries and leaf.

func (*Tree) Snapshot

func (t *Tree) Snapshot() ([]Entry, string)

Snapshot returns a deep copy of all entries and the current leaf ID atomically. Entries are deep-copied (including messages) so the caller can serialize without races. Use this instead of separate Entries()+LeafID() calls for persistence.

func (*Tree) SnapshotRev added in v0.49.0

func (t *Tree) SnapshotRev() ([]Entry, string, uint64)

SnapshotRev is Snapshot plus the revision the copy was taken at.

func (*Tree) Stage added in v0.46.0

func (t *Tree) Stage() (*Tree, uint64)

Stage returns a private deep copy of the tree to build a change on, and the revision it was taken at. Nothing done to the copy is visible here until Adopt installs it whole.

func (*Tree) TrimWatermark added in v0.41.0

func (t *Tree) TrimWatermark() string

TrimWatermark returns the MsgID up to which the current path has already been trimmed, or "" when no trim applies. The agent carries it so the next trim can only move forward: without it, a restored session would plan from scratch and re-elide a region already elided under possibly different rules.

func (*Tree) ValidBranchTarget

func (t *Tree) ValidBranchTarget(entryID string) error

ValidBranchTarget reports whether branching to entryID would be accepted by Branch, without mutating the tree. Callers building branch-picker UIs should use this to filter candidates so they never offer a target that Branch would reject (e.g. an assistant turn with unresolved tool calls).

func (*Tree) VisitDisplayMessages added in v0.44.1

func (t *Tree) VisitDisplayMessages(fn func(*core.AgentMessage))

VisitDisplayMessages calls fn, in transcript order, with every message entry of the current path. Compaction, trim and fresh markers are not visited: they are session_event rows, never assistant turns. It lets an aggregate over the transcript (see core.CacheUsageAccumulator) run without materialising the projection. fn must not retain the pointer nor call back into the tree.

func (*Tree) VisitTranscript added in v0.46.0

func (t *Tree) VisitTranscript(fn func(*core.AgentMessage))

VisitTranscript calls fn, in order, with every message of the current path as originally recorded — including what a compaction, trim or fresh start keeps away from the model — and with a session_event at each of those boundaries, where its entry sits. It reads under the tree's lock without materialising the projection: fn must not retain the pointer nor call back into the tree.

type TrimData added in v0.41.0

type TrimData struct {
	WatermarkEntryID  string `json:"watermark_entry_id"`
	ProjectionVersion int    `json:"projection_version"`
	TokensBefore      int    `json:"tokens_before,omitempty"`
	TokensRemoved     int    `json:"tokens_removed,omitempty"`
	Results           int    `json:"results,omitempty"`
}

TrimData records a context trim: every eligible tool result between the previous trim's watermark and this one was replaced by a placeholder in the model's context. The originals stay in the tree — this entry is a projection rule, not a deletion.

WatermarkEntryID and ProjectionVersion are the only reconstructive state. The version pins the elision rules that produced this region, so a later change to the placeholder format cannot rewrite it and break the byte identity the provider's prefix cache depends on. The counters are telemetry for the UI and the logs; they reconstruct nothing.

func (TrimData) IsEmpty added in v0.41.0

func (t TrimData) IsEmpty() bool

IsEmpty returns true if the TrimData has no watermark (zero value).

Jump to

Keyboard shortcuts

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