session

package
v2.10.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 21 Imported by: 0 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 persists Scribe's conversations, per-turn file checkpoints and prompt history.

A project's sessions live under <root>/.scribe/sessions/<id>/:

meta.json       Meta (pretty JSON, 0600)
messages.jsonl  one llm.Message per line, append-only during a session
ui.jsonl        opaque UI records (json.RawMessage per line), so the
                transcript re-renders exactly on resume
plan.json       optional
checkpoints.json, blobs/<sha256>   written by Checkpoints (checkpoint.go)

A global index at config.Home()/sessions.json maps session id to project root so a session can be resumed from any directory.

Index

Constants

View Source
const (
	PickFile    = "file"
	PickAgent   = "agent"
	PickCommand = "command"
	PickModel   = "model"
	PickHistory = "history" // a prompt picked from Ctrl+R history search
)

Pick kinds. Each has its own ranking; a key is a file path, an agent name, a command name or a model id.

View Source
const (
	HistoryCap        = 5000
	HistoryPruneSlack = 50
)

HistoryCap is the most prompts kept in history.jsonl. The file is pruned back to HistoryCap once it holds HistoryPruneSlack more, so the rewrite happens about once every fifty prompts rather than on every one.

View Source
const FrecencyCap = 500

FrecencyCap bounds how many keys are remembered per kind. The least ranked keys are dropped first.

Variables

View Source
var (
	ErrNothingToUndo = errors.New("nothing to undo")
	ErrNothingToRedo = errors.New("nothing to redo")
	ErrTurnRunning   = errors.New("a turn is still running")
)

ErrNothingToUndo and ErrNothingToRedo report an empty stack.

View Source
var ErrAmbiguous = errors.New("session id prefix is ambiguous")

ErrAmbiguous means an id prefix matches more than one session.

View Source
var ErrConflict = errors.New("files changed since the turn that wrote them")

ErrConflict means files changed on disk after the turn that wrote them.

View Source
var ErrHistoryMoved = errors.New("the conversation changed after this undo, so its messages cannot go back in place; redo with force to re-apply the files and append them")

ErrHistoryMoved is returned by Redo when the conversation has changed since the undo, so its messages cannot go back in their place. Redo with force re-applies the files and appends the messages at the end.

View Source
var ErrNoAnchor = errors.New("this session has no message anchor for the turns after that one, so the conversation cannot be cut there")

ErrNoAnchor means a later turn has no recorded message anchor (a session from before anchors were kept), so the conversation cannot be cut there.

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

ErrNotFound means no session matches the id or prefix.

Functions

func AppendHistory

func AppendHistory(text, cwd string) error

AppendHistory records a submitted prompt made in cwd. Blank prompts are ignored. A prompt identical to the most recent one is not added again. A prompt that was submitted before is moved to the top: its older copies are removed and it is appended again, so each text appears once. When the file grows past HistoryCap+HistoryPruneSlack, the oldest entries are dropped.

func DeriveTitle

func DeriveTitle(text string) string

DeriveTitle makes a session title from a prompt: the trimmed first line, shortened to 60 characters, or "Empty session" when there is no text.

func FindGlobal

func FindGlobal(idPrefix string) (*Store, Meta, error)

FindGlobal resolves an id or unique prefix across all projects using the global index. It returns the project's Store and the session's Meta, so `lectern code --resume <id>` works from any directory.

func RecordPick

func RecordPick(kind, key string) error

RecordPick notes that the person picked key of kind now. Blank keys are ignored.

func TopPicks

func TopPicks(kind string, n int) ([]string, error)

TopPicks returns up to n keys of kind, best ranked first (n <= 0 means all). Ties are broken by key so the order is stable.

func ValidateRestored

func ValidateRestored(msgs []llm.Message) ([]llm.Message, int)

ValidateRestored makes a message history loaded from disk safe to send again. It drops what no provider accepts and leaves the rest alone:

  • a message with an unknown role, or with no parts once its bad parts are gone, is dropped;
  • a tool result whose call is not in an earlier message is dropped, since providers reject a result with no call to answer.

It deliberately keeps a tool call that has no result yet. That is what an interrupted turn looks like, and the agent's continue logic depends on it (agent.Unfinished). It returns the repaired history and how many parts were dropped.

Types

type Checkpoint

type Checkpoint struct {
	Turn    int
	Prompt  string
	Files   []string // paths relative to the project root, sorted
	Created time.Time
	Undone  bool
	// Added and Removed are the text lines the turn added and removed across
	// its files, for the checkpoint rail. Binary files and files over
	// lineDeltaMaxLines count as zero.
	Added   int
	Removed int
	// CtxUsed and CtxWindow are the context fill when the turn ended; zero
	// when it was not recorded (checkpoints from older sessions).
	CtxUsed   int
	CtxWindow int
}

Checkpoint describes one turn that changed files.

type Checkpoints

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

Checkpoints record what each agent turn changed on disk, so the turn can be undone and redone. It implements tools.FileTracker.

Design notes (versus per-turn git tags):

  • Nothing touches git. The index, stash and tags are never read or written, so staged changes and the user's own edits are safe.
  • Files are stored as raw bytes, content-addressed by SHA-256 under blobs/, so binary files restore exactly, including their mode.
  • Each file gets a "before" state captured the first time a turn writes it and an "after" state captured when the turn ends. Undo compares the file with "after" first, so edits made outside the agent are reported as conflicts rather than silently overwritten.
  • Undo first saves the current state of the files it changes, so Redo can put them back exactly.
  • A turn that wrote no files leaves no checkpoint.

func NewCheckpoints

func NewCheckpoints(s *Store, id string) (*Checkpoints, error)

NewCheckpoints loads the checkpoints of session id. A corrupt checkpoints.json is set aside (as checkpoints.json.corrupt) and an empty set returned along with an error describing it; the returned value is usable either way. A turn left open by a crash is finished using the files' current contents.

func (*Checkpoints) BeforeWrite

func (c *Checkpoints) BeforeWrite(abs string)

BeforeWrite snapshots abs before the agent changes it. The first call in a turn for a given file records its state; later calls are no-ops. Outside a turn it does nothing.

func (*Checkpoints) Begin

func (c *Checkpoints) Begin(turn int, prompt string)

Begin starts the checkpoint for turn. A turn still open is ended first.

func (*Checkpoints) Diff

func (c *Checkpoints) Diff(turn int) (string, error)

Diff returns a unified diff of what turn changed, from its before-state to its after-state (or to the current file when the after-state is unknown). Binary files are reported, not diffed.

func (*Checkpoints) End

func (c *Checkpoints) End() error

End closes the open turn. Turns that wrote no files are dropped. Otherwise the after-state of each file is recorded, undone turns are discarded (their redo data is no longer valid), and the redo stack is cleared. It returns the first error seen during the turn.

func (*Checkpoints) Fold

func (c *Checkpoints) Fold(text string)

Fold adds a steering message, sent while the turn runs, to that turn's checkpoint, so the checkpoint's prompt covers everything the turn was asked to do. Steering never starts a checkpoint of its own. Outside a turn it does nothing.

func (*Checkpoints) List

func (c *Checkpoints) List() []Checkpoint

List returns the turns that changed files, oldest first.

func (*Checkpoints) MarkRead

func (c *Checkpoints) MarkRead(abs string)

MarkRead records that the model has read abs as it is now.

func (*Checkpoints) Redo

func (c *Checkpoints) Redo(force bool) ([]int, error)

Redo re-applies the most recent undo operation. The files must still hold the state Undo left them in, or it returns a *ConflictError unless force. It returns the turns re-applied.

func (*Checkpoints) RestoreTo

func (c *Checkpoints) RestoreTo(turn int, force bool) ([]int, error)

RestoreTo reverts every turn after turn (Turn > turn), newest first, as one undo operation. It returns the turns reverted; there may be none.

func (*Checkpoints) SetContext

func (c *Checkpoints) SetContext(turn, used, window int) error

SetContext records the context fill (tokens used of the window) at the end of turn, so the context bar can show it while a checkpoint is browsed. It is a no-op when the turn wrote no files (it has no checkpoint). It persists at once, because the record is only ever written on turn end.

func (*Checkpoints) SetHistory

func (c *Checkpoints) SetHistory(h History)

SetHistory binds the message list that undo and redo keep in step with the files. Without it checkpoints track files only, as before.

func (*Checkpoints) StaleSinceRead

func (c *Checkpoints) StaleSinceRead(abs string) bool

StaleSinceRead reports whether abs changed since the model read it. A file that was never read is not stale. A file that is now gone is.

func (*Checkpoints) TruncateAfter

func (c *Checkpoints) TruncateAfter(turn int, force bool) (int, error)

TruncateAfter makes turn the last turn of the conversation, for sending from an earlier checkpoint. The files of the later turns are reverted as Undo reverts them (conflict-checked unless force), and the messages from the first later turn on are dropped. Messages dropped this way are not kept for redo, and the redo stack is cleared, because the future it held no longer follows from the conversation. It returns how many later turns were dropped.

func (*Checkpoints) Undo

func (c *Checkpoints) Undo(force bool) ([]int, error)

Undo reverts the files of the latest turn that is not undone. It returns that turn's number. If a file changed after the turn wrote it, Undo returns a *ConflictError (matching ErrConflict) and changes nothing, unless force.

func (*Checkpoints) WasRead

func (c *Checkpoints) WasRead(abs string) bool

WasRead reports whether the model has read abs in this session.

type ConflictError

type ConflictError struct {
	Files []string
}

ConflictError lists the files that conflict. It matches ErrConflict.

func (*ConflictError) Error

func (e *ConflictError) Error() string

func (*ConflictError) Is

func (e *ConflictError) Is(target error) bool

Is makes errors.Is(err, ErrConflict) true.

type History

type History interface {
	Messages() []llm.Message
	SetMessages([]llm.Message)
}

History is the agent's message list. Undo drops the messages of the turns it reverts and redo puts them back, so the conversation matches the files.

type HistoryEntry

type HistoryEntry struct {
	Text string    `json:"text"`
	CWD  string    `json:"cwd"`
	At   time.Time `json:"at"`
}

HistoryEntry is one submitted prompt.

func Recent

func Recent(cwd string, n int) ([]HistoryEntry, error)

Recent returns up to n prompts, newest first. An empty cwd means every project; n <= 0 means no limit.

func Search(query string, limit int) ([]HistoryEntry, error)

Search ranks prompts against query for Ctrl+R. Query characters must appear in order (case-insensitive subsequence). Matches are scored, with bonuses for substrings, word starts and consecutive characters, and a penalty for gaps. Ties go to the newer prompt. Duplicate texts are shown once. limit <= 0 means no limit. An empty query returns recent prompts.

type Meta

type Meta struct {
	ID       string    `json:"id"`
	Title    string    `json:"title,omitempty"`
	Created  time.Time `json:"created"`
	Updated  time.Time `json:"updated"`
	Model    string    `json:"model,omitempty"`
	Mode     string    `json:"mode,omitempty"`
	Workdir  string    `json:"workdir"`
	Turns    int       `json:"turns"`
	Tokens   llm.Usage `json:"tokens"`
	CostUSD  float64   `json:"cost_usd"`
	Tags     []string  `json:"tags,omitempty"`
	ParentID string    `json:"parent_id,omitempty"`
	// LecternSessionID links the session to the Lectern session hosting it.
	LecternSessionID string `json:"lectern_session_id,omitempty"`

	// Messages and SizeBytes describe messages.jsonl. They are filled in by
	// Store.List for the session picker and are never written to meta.json.
	Messages  int   `json:"-"`
	SizeBytes int64 `json:"-"`
}

Meta is the per-session header stored in meta.json.

func ListAll

func ListAll() []Meta

ListAll returns sessions from every project in the global index, newest first. Projects whose directory or session has gone are skipped.

type Store

type Store struct {
	Root string // absolute project root
	// contains filtered or unexported fields
}

Store reads and writes the sessions of one project.

func NewStore

func NewStore(root string) *Store

NewStore returns the store for the project at root.

func (*Store) AppendMessages

func (s *Store) AppendMessages(id string, msgs []llm.Message) error

AppendMessages appends msgs to the session's messages.jsonl.

func (*Store) AppendUI

func (s *Store) AppendUI(id string, recs ...json.RawMessage) error

AppendUI appends opaque UI records to ui.jsonl. Each record must be valid JSON; it is stored compacted on one line.

func (*Store) Create

func (s *Store) Create(m *Meta) error

Create writes a new session. An empty ID gets a fresh UUID v4; zero timestamps and an empty Workdir are filled in. m is updated in place.

func (*Store) Delete

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

Delete removes the session directory (including its checkpoints and blobs) and its entry in the global index.

func (*Store) Dir

func (s *Store) Dir(id string) string

Dir returns the directory of session id (it need not exist).

func (*Store) Export

func (s *Store) Export(id, format string) ([]byte, error)

Export renders session id as "markdown" or "json". The markdown transcript summarises tool calls and results in one line each; reasoning is kept in collapsed blocks.

func (*Store) Fork

func (s *Store) Fork(id string, atMessage int) (string, error)

Fork copies session id into a new session containing the first atMessage messages (0 to len). The fork records id as ParentID, starts with zero usage and carries no checkpoints, since their file snapshots belong to the original. UI records are copied only when the fork keeps every message, because UI records are not indexed by message.

func (*Store) List

func (s *Store) List() []Meta

List returns this project's sessions, newest Updated first. Corrupt entries are skipped.

func (*Store) ListHere

func (s *Store) ListHere() []Meta

ListHere returns this project's sessions that the current Scribe home knows about, newest first. The global index is per home (SCRIBE_HOME), so a session made under another home is left out: --continue must not reopen a conversation the current home never recorded.

func (*Store) LoadMessages

func (s *Store) LoadMessages(id string) ([]llm.Message, error)

LoadMessages returns the session's messages. Lines that do not parse (a write cut short by a crash) are skipped, so later messages still load.

func (*Store) LoadPlan

func (s *Store) LoadPlan(id string) (json.RawMessage, error)

LoadPlan returns plan.json, or an error wrapping os.ErrNotExist.

func (*Store) LoadUI

func (s *Store) LoadUI(id string) ([]json.RawMessage, error)

LoadUI returns the UI records in order, skipping unparseable lines.

func (*Store) Open

func (s *Store) Open(idPrefix string) (Meta, error)

Open resolves idPrefix (case-insensitive, unique prefix of the id, or an exact id) and returns its Meta.

func (*Store) ReplaceMessages

func (s *Store) ReplaceMessages(id string, msgs []llm.Message) error

ReplaceMessages atomically rewrites messages.jsonl (used after compaction).

func (*Store) ResolveID

func (s *Store) ResolveID(idPrefix string) (string, error)

ResolveID returns the full id for idPrefix.

func (*Store) SaveMeta

func (s *Store) SaveMeta(m *Meta) error

SaveMeta writes m as the session's meta. Updated is set to now.

func (*Store) SavePlan

func (s *Store) SavePlan(id string, plan json.RawMessage) error

SavePlan stores plan.json for the session.

func (*Store) Search

func (s *Store) Search(query string) []Meta

Search returns sessions whose title or first user message contains query (case-insensitive), newest first. An empty query matches everything.

func (*Store) TruncateUI

func (s *Store) TruncateUI(id string, n int) error

TruncateUI keeps the first n valid UI records and drops the rest, so the transcript matches a conversation cut back to an earlier turn.

Jump to

Keyboard shortcuts

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