session

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 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 stores conversations: each session's metadata and its messages and events on disk, snapshots to branch from, search over a session's history, and the store ADK reads the conversation from (spec_sessions_017).

Index

Constants

View Source
const (
	KindSteer = "steer"
	KindHook  = "hook"
	KindPlan  = "plan" // the approved plan's go-ahead
	KindTask  = "task" // a background task that ended (the model's side)
)

Kinds of user message other than prompts.

Variables

View Source
var ErrInvalidID = errors.New("invalid session id")

ErrInvalidID is returned for session IDs that could escape the storage directory.

Functions

func NewSessionID

func NewSessionID() string

NewSessionID returns a collision-resistant session identifier.

func ReadEvents

func ReadEvents(dir, id string) ([]*adksession.Event, error)

ReadEvents reads session id's stored event log from dir, for exports (nil when it has none).

func SearchTerms

func SearchTerms(query string) []string

SearchTerms splits a query into words and "quoted phrases".

func TitleFrom

func TitleFrom(prompt string) string

TitleFrom makes a session title from a prompt: its first non-empty line, with whitespace collapsed and long text cut short.

func ValidateID

func ValidateID(id string) error

ValidateID reports whether id is safe to use as a file name component.

func ValidateName

func ValidateName(name string) error

ValidateName reports whether name can label a snapshot. Names follow the ID rules (they never reach a path, but are shown and typed like IDs) and can't start with "session-", so a name is never mistaken for an ID. "latest" is taken by --resume.

Types

type Match

type Match struct {
	Index   int // position in the transcript
	Message Message
	Hits    int    // distinct terms found
	Excerpt string // the text around the first hit
}

Match is a transcript message that mentions a search's terms.

func Search(msgs []Message, query string, limit int) (matches []Match, total int)

Search finds the messages that mention any of query's terms, case insensitively, and returns at most limit of them: those with the most distinct terms first, then the most recent, presented oldest first. Earlier /search commands are skipped. total counts every match.

type Message

type Message struct {
	Role      string    `json:"role"` // "user", "model", "tool"
	Content   string    `json:"content"`
	Timestamp time.Time `json:"timestamp"`
	// Kind tells user messages apart: "" for a prompt, KindSteer for a
	// message sent while a turn ran, KindHook for a stop hook's request.
	// Only prompts are rewind points.
	Kind string `json:"kind,omitempty"`
	// Events is how many events the session's event log held before this
	// prompt, so rewinding the conversation can cut the log there. Unset for
	// other messages and for prompts recorded by older versions.
	Events *int `json:"events,omitempty"`
}

Message represents a single chat turn.

func (Message) IsPrompt

func (m Message) IsPrompt() bool

IsPrompt reports whether m is a prompt the user sent (a rewind point).

type PersistentService

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

PersistentService is an ADK session service that keeps sessions in memory and appends every final event to <dir>/<session>.events.jsonl, so a conversation (including tool calls and compaction summaries) can be resumed in a later process by using the same session ID.

func NewPersistentService

func NewPersistentService(dir string) (*PersistentService, error)

NewPersistentService stores event logs in dir (created owner-only).

func (*PersistentService) AppendEvent

AppendEvent records the event in memory, then durably appends final events.

func (*PersistentService) Create

Create creates a session, replaying stored events if the ID was used before.

func (*PersistentService) Delete

Delete removes the session and its stored events.

func (*PersistentService) Get

Get returns a session, loading it from disk on first access after a restart.

func (*PersistentService) HasEvents

func (p *PersistentService) HasEvents(id string) bool

HasEvents reports whether a stored event log exists for id.

func (*PersistentService) List

List delegates to the in-memory service.

func (*PersistentService) Truncate

func (p *PersistentService) Truncate(ctx context.Context, appName, userID, id string, keep int) error

Truncate keeps the first keep events of a session and drops the rest, on disk (atomically) and in memory (rewinding the conversation).

type SessionRecord

type SessionRecord struct {
	ID           string    `json:"id"`
	Title        string    `json:"title"`
	Agent        string    `json:"agent"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	MessageCount int       `json:"message_count"`
	// Workspace is the canonical workspace directory the session belongs to;
	// empty for sessions created before sessions were workspace-scoped.
	Workspace string `json:"workspace,omitempty"`
	// LastTurn identifies the trace of the most recent turn so the next one,
	// even in a later process, can link to it. Empty with telemetry off.
	LastTurn *TurnRef `json:"last_turn,omitempty"`
	// Usage is the session's usage so far (calls, tokens, cost, the last
	// prompt's size), kept after each model call so it survives a restart.
	Usage *api.Usage `json:"usage,omitempty"`
	// Name labels a snapshot saved with /session save; "" otherwise.
	Name string `json:"name,omitempty"`
	// From is the session this one was copied from: the saved session for
	// a snapshot, the snapshot for a session started from one.
	From string `json:"from,omitempty"`
	// MovedFrom is the workspace the session was in before /cd moved it
	// here, and MovedAt how many messages it had then: prompts before
	// that were in the other workspace.
	MovedFrom string `json:"moved_from,omitempty"`
	MovedAt   int    `json:"moved_at,omitempty"`
	// Messages is populated by Load and for the active session; List leaves it
	// empty and reports MessageCount instead.
	Messages []Message `json:"messages,omitempty"`
}

SessionRecord holds persistent metadata and chat history for a session.

type Storage

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

Storage manages persistent sessions on disk. Metadata lives in <id>.meta.json (small, rewritten atomically) and messages are appended to <id>.jsonl, so adding a message costs O(message) rather than O(session).

func NewStorage

func NewStorage(dir string) (*Storage, error)

NewStorage creates session storage in the specified directory.

func (*Storage) Active

func (s *Storage) Active() *SessionRecord

Active returns a snapshot of the currently active session, or nil.

func (*Storage) AddMessage

func (s *Storage) AddMessage(role, content string) error

AddMessage appends a message to the active session.

func (*Storage) Append

func (s *Storage) Append(msg Message) error

Append adds msg (stamped now) to the active session.

func (*Storage) AppendTo

func (s *Storage) AppendTo(id string, msg Message) error

AppendTo adds msg (stamped now) to session id, active or not: a turn's messages go to the session it runs in, whatever another client (or a service that restarted since the session was opened) made active. A session with no metadata yet is created under id.

func (*Storage) CreateSession

func (s *Storage) CreateSession(id, title, agent string) (*SessionRecord, error)

CreateSession starts a new session and makes it active. With title "" the session is named after its first prompt (see AddMessage). It is saved with its first message: until then it isn't listed or loadable.

func (*Storage) Delete

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

Delete removes saved session id (a snapshot too): its metadata, transcript and event log. The session open here, or in another storage of this process (a workspace's, a background run's), is refused with api.ErrSessionOpen; an unknown one is api.ErrSessionNotFound. Sessions copied from it keep their own files.

func (*Storage) FindName

func (s *Storage) FindName(name string) (*SessionRecord, error)

FindName returns the snapshot called name, or nil. Names are unique across workspaces, like IDs.

func (*Storage) Fork

func (s *Storage) Fork(srcID string) (*SessionRecord, error)

Fork copies session srcID to a new, unnamed session (From set) and makes it active, for /fork to cut.

func (*Storage) Get

func (s *Storage) Get(id string) (*SessionRecord, error)

Get reads a session with its messages without making it active.

func (*Storage) LastTurn

func (s *Storage) LastTurn(id string) (traceparent string, index int)

LastTurn returns the latest turn recorded for session id: from memory for the active session, otherwise from its metadata file. It returns ("", 0) when there is none.

func (*Storage) List

func (s *Storage) List() ([]*SessionRecord, error)

List returns saved session metadata sorted by update time descending. Message bodies are not read.

func (*Storage) ListWorkspace

func (s *Storage) ListWorkspace(workspace string) ([]*SessionRecord, error)

ListWorkspace returns sessions belonging to workspace, newest first.

func (*Storage) Load

func (s *Storage) Load(id string) (*SessionRecord, error)

Load loads a session by ID and makes it active.

func (*Storage) Move

func (s *Storage) Move(id string) (*SessionRecord, error)

Move makes session id this storage's workspace's and active: /cd carried it here from the workspace it was in, which it remembers with the number of messages it had then (PAR-SES-40). It becomes active only once the move is saved.

func (*Storage) Open

func (s *Storage) Open(ref string) (rec *SessionRecord, branched bool, err error)

Open makes a session active by ID or snapshot name. An ID resumes that session in place. A snapshot, by name or by ID, is never continued: a new session copied from it starts instead (branched is true), so the snapshot stays as it was saved.

func (*Storage) Release added in v0.3.0

func (s *Storage) Release()

Release lets go of the active session, so other storages of this process write it, and delete it, themselves again: for a storage made for one run, when the run ends.

func (*Storage) RemoveEmpty

func (s *Storage) RemoveEmpty() (int, error)

RemoveEmpty deletes the empty chats earlier versions saved when a chat was opened rather than with its first message: metadata with no title, no messages, no transcript and no history. The active session and named chats are kept. It returns how many it removed.

func (*Storage) Rename

func (s *Storage) Rename(title string) error

Rename sets the active session's title (shown in /session list and the terminal title). An empty title is refused.

func (*Storage) SetLastTurn

func (s *Storage) SetLastTurn(id, traceparent string, index int) error

SetLastTurn records the latest turn of session id in its metadata.

func (*Storage) SetUsage

func (s *Storage) SetUsage(id string, u api.Usage) error

SetUsage saves session id's usage so far in its metadata. A session this store doesn't have (a worker run's, kept elsewhere) is left alone.

func (*Storage) SetWorkspace

func (s *Storage) SetWorkspace(dir string)

SetWorkspace records the workspace new sessions belong to.

func (*Storage) Snapshot

func (s *Storage) Snapshot(srcID, name string, replace bool) (*SessionRecord, error)

Snapshot saves a named copy of session srcID: its transcript, metadata and the model's event log, under a new ID. The source is left as it is and stays active. An existing snapshot with the name is an ErrSnapshotNameTaken error unless replace is set, in which case it is deleted once the new one is written.

func (*Storage) TranscriptPath

func (s *Storage) TranscriptPath(id string) string

TranscriptPath is where session id's messages are kept (JSON lines), for hooks; "" for an invalid ID.

func (*Storage) Truncate

func (s *Storage) Truncate(n int) error

Truncate keeps the active session's first n messages and drops the rest (rewinding the conversation). The file is replaced atomically.

func (*Storage) Usage

func (s *Storage) Usage(id string) (api.Usage, bool)

Usage returns the usage saved for session id, and whether there is any.

func (*Storage) Workspace

func (s *Storage) Workspace() string

Workspace returns the workspace new sessions belong to.

type TurnRef

type TurnRef struct {
	Traceparent string `json:"traceparent"`
	Index       int    `json:"index"`
}

TurnRef is the W3C traceparent of a turn's span and the turn's number within the session (1-based).

Jump to

Keyboard shortcuts

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