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_017_sessions).
Index ¶
- Constants
- Variables
- func NewSessionID() string
- func ReadEvents(dir, id string) ([]*adksession.Event, error)
- func SearchTerms(query string) []string
- func TitleFrom(prompt string) string
- func ValidateID(id string) error
- func ValidateName(name string) error
- type Match
- type Message
- type PersistentService
- func (p *PersistentService) AppendEvent(ctx context.Context, s adksession.Session, ev *adksession.Event) error
- func (p *PersistentService) Create(ctx context.Context, req *adksession.CreateRequest) (*adksession.CreateResponse, error)
- func (p *PersistentService) Delete(ctx context.Context, req *adksession.DeleteRequest) error
- func (p *PersistentService) Get(ctx context.Context, req *adksession.GetRequest) (*adksession.GetResponse, error)
- func (p *PersistentService) HasEvents(id string) bool
- func (p *PersistentService) List(ctx context.Context, req *adksession.ListRequest) (*adksession.ListResponse, error)
- func (p *PersistentService) Pin(id string) (unpin func())
- func (p *PersistentService) Truncate(ctx context.Context, appName, userID, id string, keep int) error
- type SessionRecord
- type Storage
- func (s *Storage) Active() *SessionRecord
- func (s *Storage) AddMessage(role, content string) error
- func (s *Storage) Append(msg Message) error
- func (s *Storage) AppendSubagentEvent(id string, ev any) error
- func (s *Storage) AppendTo(id string, msg Message) error
- func (s *Storage) CreateSession(id, title, agent string) (*SessionRecord, error)
- func (s *Storage) Delete(id string) error
- func (s *Storage) FindName(name string) (*SessionRecord, error)
- func (s *Storage) Fork(srcID string) (*SessionRecord, error)
- func (s *Storage) Get(id string) (*SessionRecord, error)
- func (s *Storage) LastTurn(id string) (traceparent string, index int)
- func (s *Storage) List() ([]*SessionRecord, error)
- func (s *Storage) ListWorkspace(workspace string) ([]*SessionRecord, error)
- func (s *Storage) Load(id string) (*SessionRecord, error)
- func (s *Storage) Move(id string) (*SessionRecord, error)
- func (s *Storage) Open(ref string) (rec *SessionRecord, branched bool, err error)
- func (s *Storage) Release()
- func (s *Storage) RemoveEmpty() (int, error)
- func (s *Storage) Rename(title string) error
- func (s *Storage) SetLastTurn(id, traceparent string, index int) error
- func (s *Storage) SetUsage(id string, u api.Usage) error
- func (s *Storage) SetWorkspace(dir string)
- func (s *Storage) Snapshot(srcID, name string, replace bool) (*SessionRecord, error)
- func (s *Storage) TranscriptPath(id string) string
- func (s *Storage) Truncate(n int) error
- func (s *Storage) Usage(id string) (api.Usage, bool)
- func (s *Storage) Workspace() string
- type TurnRef
Constants ¶
const ( OriginWorker = "worker" // a worker's run, scheduled or not OriginBackground = "background" // a detached run (blitz --bg) OriginEval = "eval" // an eval's case (deleted once it's scored) )
What started a session (SessionRecord.Origin); a chat has none.
const ( KindSteer = "steer" KindHook = "hook" KindRule = "rule" // after-agent rules asking for a revision (spec_041_gates) 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 ¶
var ErrInvalidID = errors.New("invalid session id")
ErrInvalidID is returned for session IDs that could escape the storage directory.
var Resident = 4
Resident is how many sessions stay in memory with no turn running in them.
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). A line that doesn't parse (torn by a crash) is skipped, as replay skips it (SES-21a), so a session that resumes also exports.
func SearchTerms ¶
SearchTerms splits a query into words and "quoted phrases".
func TitleFrom ¶
TitleFrom makes a session title from a prompt: its first non-empty line, with whitespace collapsed and long text cut short.
func ValidateID ¶
ValidateID reports whether id is safe to use as a file name component.
func ValidateName ¶
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.
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.
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.
Only the few sessions used last stay in memory (Resident), and those a turn runs in (Pin); the others are dropped and loaded again from their file when next asked for, so a service that runs many sessions (a worker's every run is one) doesn't keep every conversation it ever ran.
func NewPersistentService ¶
func NewPersistentService(dir string) (*PersistentService, error)
NewPersistentService stores event logs in dir (created owner-only).
func (*PersistentService) AppendEvent ¶
func (p *PersistentService) AppendEvent(ctx context.Context, s adksession.Session, ev *adksession.Event) error
AppendEvent records the event in memory, then durably appends final events.
func (*PersistentService) Create ¶
func (p *PersistentService) Create(ctx context.Context, req *adksession.CreateRequest) (*adksession.CreateResponse, error)
Create creates a session, replaying stored events if the ID was used before.
func (*PersistentService) Delete ¶
func (p *PersistentService) Delete(ctx context.Context, req *adksession.DeleteRequest) error
Delete removes the session and its stored events.
func (*PersistentService) Get ¶
func (p *PersistentService) Get(ctx context.Context, req *adksession.GetRequest) (*adksession.GetResponse, error)
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 ¶
func (p *PersistentService) List(ctx context.Context, req *adksession.ListRequest) (*adksession.ListResponse, error)
List delegates to the in-memory service.
func (*PersistentService) Pin ¶ added in v0.3.4
func (p *PersistentService) Pin(id string) (unpin func())
Pin keeps session id in memory until the returned func is called: a turn's events go to the session the runner loaded, which must still be there. Pins nest (two turns in one session).
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"`
// Origin is what started the session: OriginWorker, OriginBackground,
// or "" for a chat.
Origin string `json:"origin,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 ¶
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 ¶
AddMessage appends a message to the active session.
func (*Storage) AppendSubagentEvent ¶ added in v0.8.10
AppendSubagentEvent adds ev, an event of a sub-agent that session id ran in the foreground, to the session's sub-agent log (<id>.subagents.jsonl), so what the sub-agent did and asked can be read afterwards. The event names its agent (Author).
func (*Storage) AppendTo ¶
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. A session another storage of this process has active is that storage's to write (SES-49a).
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 ¶
Delete removes saved session id (a snapshot too): its metadata, transcript, event log and sub-agent 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 ¶
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 ¶
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 ¶
Rename sets the active session's title (shown in /session list and the terminal title). An empty title is refused.
func (*Storage) SetLastTurn ¶
SetLastTurn records the latest turn of session id in its metadata.
func (*Storage) SetUsage ¶
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 ¶
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 ¶
TranscriptPath is where session id's messages are kept (JSON lines), for hooks; "" for an invalid ID.
func (*Storage) Truncate ¶
Truncate keeps the active session's first n messages and drops the rest (rewinding the conversation). The file is replaced atomically.