session

package
v0.107.39 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const MaxExistsIDs = 5000

MaxExistsIDs bounds one existence query.

Variables

View Source
var ErrAnchor = errors.New("user message anchor not found")
View Source
var ErrClosed = errors.New("session store is closed")
View Source
var ErrHistoryDeleted = errors.New("history was explicitly deleted")
View Source
var ErrHistoryStale = errors.New("session history changed in another process")

ErrHistoryStale 表示调用方持有的 History 落后于磁盘上的记录(另一个进程写入了消息); 保存会覆盖对方的消息,所以被拒绝。调用方应重新加载会话。

View Source
var ErrNotFound = errors.New("session not found")
View Source
var ErrRevision = errors.New("history revision conflict")
View Source
var ErrRunElsewhere = errors.New("session is running in another process")

ErrRunElsewhere 表示另一个进程正在这个会话里运行回合。

View Source
var ErrSummaryRescanLimited = errors.New("session summary rescan is rate limited")
View Source
var ErrTooManySummaryWaiters = errors.New("too many session change waiters")

Functions

func FindTranscript added in v0.103.0

func FindTranscript(root, id string) (string, error)

Types

type ArchiveFilter added in v0.107.28

type ArchiveFilter uint8

ArchiveFilter selects sessions by their archived flag. The zero value keeps the historical behavior: archived sessions are hidden.

const (
	// ArchiveExclude lists only sessions that are not archived (the default).
	ArchiveExclude ArchiveFilter = iota
	// ArchiveInclude lists archived and unarchived sessions.
	ArchiveInclude
	// ArchiveOnly lists only archived sessions.
	ArchiveOnly
)

func ParseArchiveFilter added in v0.107.28

func ParseArchiveFilter(raw string) (ArchiveFilter, error)

ParseArchiveFilter reads the HTTP `archived` query value; empty means exclude.

func (ArchiveFilter) Listed added in v0.107.28

func (f ArchiveFilter) Listed(meta Meta, messageCount int) bool

Listed reports whether a session summary belongs to a list under this filter: a top-level (non-subagent) session with at least one message whose archived flag passes the filter.

func (ArchiveFilter) Matches added in v0.107.28

func (f ArchiveFilter) Matches(archived bool) bool

Matches reports whether a session with this archived flag passes the filter.

type Compaction

type Compaction struct {
	RunID     string   `json:"run_id,omitempty"`
	Seq       int      `json:"seq"`
	Cutoff    int      `json:"cutoff"`
	Summary   string   `json:"summary"`
	Model     string   `json:"model"`
	Usage     ai.Usage `json:"usage"`
	DropPrior bool     `json:"drop_prior,omitempty"`
	Fresh     bool     `json:"fresh,omitempty"`
}

type ExternalRun added in v0.107.30

type ExternalRun struct {
	Client    string    `json:"client"`
	PID       int       `json:"pid,omitempty"`
	StartedAt time.Time `json:"started_at"`
}

ExternalRun 描述另一个进程中正在运行的回合。

type History added in v0.103.0

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

func (*History) Boundary added in v0.103.0

func (h *History) Boundary(cut int) (int, error)

func (*History) Clone added in v0.107.0

func (h *History) Clone() *History

func (*History) Compact added in v0.103.0

func (h *History) Compact(summary string, cutoff int, model string, usage ai.Usage) error

func (*History) NewContext added in v0.104.0

func (h *History) NewContext(cutoff int) error

func (*History) Observe added in v0.103.0

func (h *History) Observe(msgs []ai.Message) error

func (*History) Sequence added in v0.103.0

func (h *History) Sequence(index int) (int, bool)

type HistorySearchMatch added in v0.107.0

type HistorySearchMatch struct {
	SessionID     string    `json:"session_id"`
	Title         string    `json:"title"`
	CWD           string    `json:"cwd"`
	MessageID     string    `json:"message_id,omitempty"`
	MessageOffset *int      `json:"message_offset,omitempty"`
	Role          string    `json:"role,omitempty"`
	Snippet       string    `json:"snippet"`
	Score         float64   `json:"score"`
	UpdatedAt     time.Time `json:"updated_at"`
}

type HistorySearchResult added in v0.107.0

type HistorySearchResult struct {
	Matches   []HistorySearchMatch `json:"matches"`
	Truncated bool                 `json:"truncated"`
}

type HistorySnapshot added in v0.107.0

type HistorySnapshot struct {
	Meta           Meta
	CreatedAt      time.Time
	Messages       []ai.Message
	Offsets        []int
	ActiveMessages []ai.Message
	Revision       string
}

type Meta

type Meta struct {
	CreatedAt time.Time `json:"-"`
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	Model     string    `json:"model"`
	Provider  string    `json:"provider"`
	CWD       string    `json:"cwd"`
	Goal      string    `json:"goal"`
	// GoalMemoryOff records that the goal text was written while memory was off.
	GoalMemoryOff   bool      `json:"goal_memory_off,omitempty"`
	ForkedFrom      string    `json:"forked_from"`
	ForkSeq         int       `json:"fork_seq"`
	Tags            []string  `json:"tags"`
	Pinned          bool      `json:"pinned"`
	Archived        bool      `json:"archived"`
	Shared          bool      `json:"shared"`
	ShareCreatedAt  time.Time `json:"share_created_at,omitempty"`
	ShareUpdatedAt  time.Time `json:"share_updated_at,omitempty"`
	ShareToken      string    `json:"share_token,omitempty"`
	ShareRedactTool bool      `json:"share_redact_tool,omitempty"`
	Effort          string    `json:"effort"`
	UsageIn         int       `json:"usage_in"`
	UsageCached     int       `json:"usage_cached"`
	UsageOut        int       `json:"usage_out"`
	UsageCacheWrite int       `json:"usage_cache_write,omitempty"`

	SubUsage   map[string]ai.Usage `json:"sub_usage"`
	ModelUsage map[string]ai.Usage `json:"model_usage,omitempty"`
	UpdatedAt  time.Time           `json:"updated_at"`

	TaskID                   string `json:"task_id"`
	ImportSourceID           string `json:"import_source_id,omitempty"`
	ImportFingerprint        string `json:"import_fingerprint,omitempty"`
	ImportMetadata           string `json:"import_metadata,omitempty"`
	ImportContentFingerprint string `json:"import_content_fingerprint,omitempty"`
}

func (Meta) UsageSummary added in v0.103.0

func (m Meta) UsageSummary(msgs []ai.Message) ai.UsageSummary

type Page added in v0.103.0

type Page struct {
	Sessions []Meta
	// MessageCounts[i] is the stored message count of Sessions[i], read with the
	// page so callers never reload a transcript just to count its messages.
	MessageCounts []int
	// ExternalRuns[i] 非空表示另一个进程正在 Sessions[i] 里运行回合。
	ExternalRuns []*ExternalRun
	Next         *PageCursor
	Total        int
	Epoch        string
	Revision     uint64
}

type PageCursor added in v0.103.0

type PageCursor struct {
	UpdatedAt time.Time `json:"updatedAt"`
	ID        string    `json:"id"`
}

func (PageCursor) Valid added in v0.103.0

func (c PageCursor) Valid() bool

type PageOptions added in v0.103.0

type PageOptions struct {
	CWD             *string
	After           *PageCursor
	Limit           int
	Offset          int
	IncludeEmpty    bool
	Shared          *bool
	SharedOnly      bool
	IncludeArchived bool
	// Archive selects by archived flag; IncludeArchived (older callers) widens
	// the default ArchiveExclude to ArchiveInclude.
	Archive ArchiveFilter
	Pinned  *bool
}

type RunElsewhereError added in v0.107.30

type RunElsewhereError struct{ Run ExternalRun }

RunElsewhereError 带上占用会话的进程信息;errors.Is(err, ErrRunElsewhere) 成立。

func (*RunElsewhereError) Error added in v0.107.30

func (e *RunElsewhereError) Error() string

func (*RunElsewhereError) Is added in v0.107.30

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

type RunLease added in v0.107.30

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

RunLease 是本进程持有的运行租约。

func (*RunLease) ID added in v0.107.30

func (l *RunLease) ID() string

ID 返回租约所属的会话。

func (*RunLease) Release added in v0.107.30

func (l *RunLease) Release() error

Release 释放租约;可以重复调用。

type Schedule

type Schedule struct {
	ID       int       `json:"id"`
	Schedule string    `json:"schedule"`
	Prompt   string    `json:"prompt"`
	Anchor   time.Time `json:"anchor"`
	LastFire time.Time `json:"last_fire"`
}

type Store

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

func Open

func Open(dir string) (*Store, error)

func OpenHome added in v0.103.0

func OpenHome(home string) (*Store, error)

func OpenProjectDir added in v0.107.6

func OpenProjectDir(dir string) (*Store, error)

OpenProjectDir reads both flat legacy sessions and project-grouped sessions.

func OpenProjectHome added in v0.103.0

func OpenProjectHome(home string) (*Store, error)

func (*Store) AcquireRun added in v0.107.30

func (s *Store) AcquireRun(id, client string) (*RunLease, error)

AcquireRun 为会话 id 取得运行租约。另一个进程持有时返回 *RunElsewhereError; 本进程已持有时同样返回该错误(Client 为本进程的 client)。

func (*Store) AddSchedule

func (s *Store) AddSchedule(sessionID, schedule, prompt string, anchor time.Time) (id int, err error)

func (*Store) CheckpointReferences added in v0.107.0

func (s *Store) CheckpointReferences(id string) (map[int]string, error)

func (*Store) ClearMessages

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

func (*Store) ClearSnapshots

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

func (*Store) ClearSnapshotsFrom added in v0.107.0

func (s *Store) ClearSnapshotsFrom(id string, from int) error

func (*Store) Close

func (s *Store) Close() error

func (*Store) CompactionDir added in v0.107.13

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

CompactionDir is the session directory's "compaction" subdirectory, where the agent saves compacted-away turns as markdown. It moves and is deleted with the session.

func (*Store) Compactions

func (s *Store) Compactions(id string) []Compaction

func (*Store) Create

func (s *Store) Create(cwd, model, provider string) (id string, err error)

func (*Store) Delete added in v0.103.0

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

func (*Store) DeleteCompaction

func (s *Store) DeleteCompaction(id string, seq int) error

func (*Store) DeleteFrom

func (s *Store) DeleteFrom(id string, from int) error

func (*Store) DeleteSchedule

func (s *Store) DeleteSchedule(sessionID string, id int) error

func (*Store) Exists added in v0.107.6

func (s *Store) Exists(ids []string) (map[string]bool, error)

Exists reports, for each id, whether Load(id) would find exactly one session, using the same id listing and prefix rule as Load but only file metadata, so callers can confirm many sessions without reading their transcripts.

func (*Store) ExternalRun added in v0.107.30

func (s *Store) ExternalRun(id string) (ExternalRun, bool)

ExternalRun 报告另一个进程是否正在会话 id 里运行回合。本进程持有的租约不算。

func (*Store) Fork

func (s *Store) Fork(srcID string, uptoSeq int, title string) (id string, err error)

func (*Store) ForkTitle

func (s *Store) ForkTitle(base string) (title string, err error)

func (*Store) ForksOf

func (s *Store) ForksOf(id string) (out []Meta, err error)

func (*Store) History added in v0.103.0

func (s *Store) History(id string, initial []ai.Message) (*History, []ai.Message, error)

func (*Store) HistorySnapshot added in v0.107.0

func (s *Store) HistorySnapshot(id string) (out HistorySnapshot, err error)

func (*Store) HistoryStale added in v0.107.30

func (s *Store) HistoryStale(id string, h *History) (bool, error)

HistoryStale 报告磁盘上会话 id 的消息是否已被别处修改,与 h 最后一次加载或保存时不同。

func (*Store) ImportHistory added in v0.107.0

func (s *Store) ImportHistory(id, sourceID, fingerprint, contentFingerprint, metadata, cwd, model, provider, title string, createdAt, updatedAt time.Time, pinned, shared, redact bool, shareToken string, messages []ai.Message, boundary *Compaction) (bool, error)

func (*Store) LastExchange

func (s *Store) LastExchange(id string) (user, assistant string)

func (*Store) LatestInDir

func (s *Store) LatestInDir(dir string) (meta Meta, err error)

func (*Store) ListPage added in v0.103.0

func (s *Store) ListPage(ctx context.Context, options PageOptions) (Page, error)

func (*Store) Load

func (s *Store) Load(idOrPrefix string) (meta Meta, msgs []ai.Message, err error)

func (*Store) LoadTasks

func (s *Store) LoadTasks(id string) ([]Task, error)

func (*Store) MarkFired

func (s *Store) MarkFired(sessionID string, id int, at time.Time) error

func (*Store) MessageSequence added in v0.107.0

func (s *Store) MessageSequence(id, messageID string) (int, error)

func (*Store) MutateHistory added in v0.107.0

func (s *Store) MutateHistory(id, messageID, expectedRevision, title string, replacement *ai.Message) (resultID string, err error)

MutateHistory checks the revision and anchor under the transcript lock. A nil replacement forks through the anchor's reply; otherwise it replaces the raw suffix.

func (*Store) RawMessages

func (s *Store) RawMessages(id string) []ai.Message

func (*Store) Recent

func (s *Store) Recent(n int) (out []Meta, err error)

func (*Store) RecordCompaction

func (s *Store) RecordCompaction(id string, cutoff int, summary, model string, usage ai.Usage) error

func (*Store) ReplaceFrom added in v0.107.0

func (s *Store) ReplaceFrom(id string, from int, msgs []ai.Message, model, provider string) error

ReplaceFrom atomically removes the raw message suffix starting at from and writes the replacement messages at the same raw offsets.

func (*Store) RewindSnapshots added in v0.107.0

func (s *Store) RewindSnapshots(id string, from int, expected map[int]string, apply func(commit func() error) error) error

RewindSnapshots consumes file checkpoints without changing conversation history. apply must undo its filesystem changes if commit fails.

func (*Store) Save

func (s *Store) Save(id string, from int, msgs []ai.Message, model, provider string) error

func (*Store) SaveHistory added in v0.103.0

func (s *Store) SaveHistory(id string, h *History, msgs []ai.Message, model, provider string) error

func (*Store) SaveHistoryWithUsage added in v0.103.0

func (s *Store) SaveHistoryWithUsage(id string, h *History, msgs []ai.Message, model, provider string, usage ai.UsageSummary) error

func (*Store) SaveHistoryWithUsageAtRevision added in v0.107.0

func (s *Store) SaveHistoryWithUsageAtRevision(id string, h *History, msgs []ai.Message, model, provider string, usage ai.UsageSummary, expectedRevision string) error

func (*Store) SaveSubagentTranscript

func (s *Store) SaveSubagentTranscript(parentID, taskID string, msgs []ai.Message, model, provider string) (string, error)

func (*Store) SaveTask

func (s *Store) SaveTask(id string, t Task) error

func (*Store) Schedules

func (s *Store) Schedules(id string) []Schedule

func (*Store) Search added in v0.103.0

func (s *Store) Search(query string, includeArchived bool) (out []Meta, err error)

func (*Store) SearchHistory added in v0.107.0

func (s *Store) SearchHistory(ctx context.Context, query string, limit int) (HistorySearchResult, error)

SearchHistory scans one bounded transcript at a time; it never loads all histories.

func (*Store) SessionsDir added in v0.103.0

func (s *Store) SessionsDir() string

func (*Store) SetArchived added in v0.103.0

func (s *Store) SetArchived(id string, archived bool) error

func (*Store) SetCWD added in v0.107.3

func (s *Store) SetCWD(id, cwd string) error

SetCWD updates the stored workspace and moves project-scoped sessions to the corresponding workspace bucket before writing the new metadata.

func (*Store) SetEffort

func (s *Store) SetEffort(id, effort string) error

func (*Store) SetGoal

func (s *Store) SetGoal(id, goal string) error

func (*Store) SetGoalMemory added in v0.107.6

func (s *Store) SetGoalMemory(id, goal string, memoryOff bool) error

SetGoalMemory stores the goal with whether its text was written while memory was off.

func (*Store) SetModel added in v0.107.0

func (s *Store) SetModel(id, model, provider string) error

func (*Store) SetPinned

func (s *Store) SetPinned(id string, pinned bool) error

func (*Store) SetShared added in v0.107.0

func (s *Store) SetShared(id, token string, enabled, redactToolContent bool) error

func (*Store) SetSnapshot

func (s *Store) SetSnapshot(id string, seq int, ref string) error

func (*Store) SetTags

func (s *Store) SetTags(id string, tags []string) error

func (*Store) SetTitle

func (s *Store) SetTitle(id, title string) error

func (*Store) SetTodos

func (s *Store) SetTodos(id, todos string) error

func (*Store) SetUsage

func (s *Store) SetUsage(id string, usage ai.UsageSummary) error

func (*Store) SharedByToken added in v0.107.0

func (s *Store) SharedByToken(token string) (Meta, []ai.Message, error)

func (*Store) SharedPage added in v0.107.0

func (s *Store) SharedPage(limit int, after *PageCursor) (Page, error)

func (*Store) SnapshotReferenced added in v0.103.0

func (s *Store) SnapshotReferenced(ref string) (bool, error)

func (*Store) Snapshots

func (s *Store) Snapshots(id string) map[int]string

func (*Store) SubagentTranscript

func (s *Store) SubagentTranscript(parentID, taskID string) ([]ai.Message, error)

func (*Store) SummaryChanges added in v0.107.6

func (s *Store) SummaryChanges(ctx context.Context, request SummaryChangeRequest) (SummaryChangeResult, error)

func (*Store) SummaryCursor added in v0.107.6

func (s *Store) SummaryCursor(ctx context.Context) (cursor SummaryCursor, err error)

func (*Store) SummarySnapshot added in v0.107.6

func (s *Store) SummarySnapshot(ctx context.Context) (snapshot SummarySnapshot, err error)

func (*Store) SummarySnapshotFiltered added in v0.107.28

func (s *Store) SummarySnapshotFiltered(ctx context.Context, archive ArchiveFilter) (snapshot SummarySnapshot, err error)

SummarySnapshotFiltered is SummarySnapshot with an explicit archived filter.

func (*Store) TaskLease added in v0.107.31

func (s *Store) TaskLease(id string) (string, error)

TaskLease 返回本进程在会话 id 里运行子代理用的租约名,第一次调用时取得租约。 租约一直持有到 Close(进程退出时由系统释放)。

func (*Store) TaskLeaseLive added in v0.107.31

func (s *Store) TaskLeaseLive(token string) bool

TaskLeaseLive 报告持有子代理租约 token 的进程是否还在运行;本进程持有的也算。

func (*Store) TaskRunningElsewhere added in v0.107.31

func (s *Store) TaskRunningElsewhere(t Task) bool

TaskRunningElsewhere 报告一条保存的子代理记录是否正在另一个仍在运行的进程里运行。

func (*Store) Todos

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

func (*Store) TranscriptPath added in v0.103.0

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

func (*Store) TruncateAtSequence added in v0.107.0

func (s *Store) TruncateAtSequence(id string, seq int) error

TruncateAtSequence removes messages and snapshots at or after seq.

func (*Store) TruncateHistory added in v0.103.0

func (s *Store) TruncateHistory(id string, h *History, cut int) error

func (*Store) UndoCompaction added in v0.103.0

func (s *Store) UndoCompaction(id string, initial []ai.Message) (*History, []ai.Message, error)

func (*Store) UsageStats added in v0.107.34

func (s *Store) UsageStats(ctx context.Context, opts UsageStatsOptions) (UsageStats, error)

UsageStats 汇总最近 opts.Days 天(含今天,按 opts.Location 分日)的用量。

func (*Store) UserHistory

func (s *Store) UserHistory(limit int) (out []string, err error)

func (*Store) UserHistoryEntries added in v0.107.21

func (s *Store) UserHistoryEntries(limit int) (out []UserHistoryEntry, err error)

UserHistoryEntries is UserHistory with each prompt's working directory, so a caller can scope the history to one directory. Entries come newest session first and newest message first within a session; a prompt repeated in the same directory is listed once, at its newest position. A limit of 0 or less means no limit.

type SummaryChange added in v0.107.6

type SummaryChange struct {
	ID           string
	Revision     uint64
	Kind         string
	Listed       bool
	Meta         Meta
	MessageCount int
	ExternalRun  *ExternalRun
}

type SummaryChangeRequest added in v0.107.6

type SummaryChangeRequest struct {
	Epoch  string
	Since  uint64
	Wait   time.Duration
	Rescan bool
}

type SummaryChangeResult added in v0.107.6

type SummaryChangeResult struct {
	Cursor      SummaryCursor
	NextSince   uint64
	Reset       bool
	ResetReason string
	More        bool
	Changes     []SummaryChange
}

type SummaryCursor added in v0.107.6

type SummaryCursor struct {
	Epoch    string
	Revision uint64
	MinSince uint64
}

type SummaryItem added in v0.107.6

type SummaryItem struct {
	Meta         Meta
	MessageCount int
	ExternalRun  *ExternalRun
}

type SummarySnapshot added in v0.107.6

type SummarySnapshot struct {
	Cursor SummaryCursor
	Items  []SummaryItem
}

type Task

type Task struct {
	Model       string    `json:"model,omitempty"`
	Provider    string    `json:"provider,omitempty"`
	ID          string    `json:"id"`
	Description string    `json:"description"`
	Prompt      string    `json:"prompt"`
	Status      string    `json:"status"`
	Report      string    `json:"report"`
	StartedAt   time.Time `json:"started_at"`
	EndedAt     time.Time `json:"ended_at"`
	// ParentToolCallID is the parent's subagent tool call that started it.
	ParentToolCallID string `json:"parent_tool_call_id,omitempty"`
	// Foreground 标记父回合等待其结束的前台子代理;旧记录没有这个字段,都是后台子代理。
	Foreground bool `json:"foreground,omitempty"`
	// ToolCount 和 Usage 是运行它的进程边运行边保存的进度。
	ToolCount int       `json:"tool_count,omitempty"`
	Usage     *ai.Usage `json:"usage,omitempty"`
	// Lease 是运行它的进程持有的子代理租约(见 TaskLease);backend 自己运行的为空。
	// 状态为 running 时,租约仍被持有说明它确实还在另一个进程里运行。
	Lease string `json:"lease,omitempty"`
}

type UsageDay added in v0.107.34

type UsageDay struct {
	Date string // YYYY-MM-DD,按请求的时区
	UsageTokens
	// Models 是各模型(不含 provider)当天的 total。
	Models map[string]int64
}

type UsageModel added in v0.107.34

type UsageModel struct {
	Model, Provider string
	UsageTokens
}

type UsageSession added in v0.107.34

type UsageSession struct {
	ID, Title string
	Total     int64
}

type UsageStats added in v0.107.34

type UsageStats struct {
	Totals                                   UsageTokens
	Sessions                                 int
	Daily                                    []UsageDay   // 只有有用量的日子,按日期升序
	Models                                   []UsageModel // 按 total 降序
	ActiveDays, CurrentStreak, LongestStreak int
	TopModel                                 string
	LongestSession                           *UsageSession
}

type UsageStatsOptions added in v0.107.34

type UsageStatsOptions struct {
	Days     int
	Location *time.Location
	Now      time.Time
}

type UsageTokens added in v0.107.34

type UsageTokens struct {
	Input, Output, CacheRead, CacheWrite int64
	Turns                                int
}

UsageTokens 是一段用量的合计。Input 含缓存读写,CacheRead、CacheWrite 是其中的部分。

func (UsageTokens) Total added in v0.107.34

func (t UsageTokens) Total() int64

func (UsageTokens) Usage added in v0.107.34

func (t UsageTokens) Usage() ai.Usage

Usage 把合计转成 ai.Usage,用于计价。

type UserHistoryEntry added in v0.107.21

type UserHistoryEntry struct {
	Text string
	CWD  string
	At   time.Time
}

UserHistoryEntry is one prompt the user wrote, with the directory its session ran in and when that session was last updated.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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