store

package
v0.78.1 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: AGPL-3.0 Imports: 23 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 store is lich's persistence layer: a single SQLite database holding open projects, their terminal sessions and the settings scoped globally or to one project — provider binaries and defaults, the permission and sandbox rungs, the gh account. The one thing it holds that is not workspace metadata is what a *parked* session said: a bounded copy of the conversation, indexed for the history search (transcripts.go), written when the session is closed and dropped when its row is. Nothing a live session says is ever stored; that is read off the provider's own transcript. The file is <config-dir>/lich/lich.db, or lich-dev.db under LICH_DEV so a rig never touches an installed lich's workspace (databasePath).

The window's UI preferences live here too, in the settings table: the window keeps no storage of its own.

Index

Constants

View Source
const (
	// SessionConfined runs this session in the sandbox whatever the rung says.
	SessionConfined = "on"
	// SessionUnconfined runs it on the machine whatever the rung says.
	SessionUnconfined = "off"
)

Session sandbox answers, the row's own spelling. Empty is not one of them: it is the absence of an answer, and it means the provider's rung decides.

View Source
const (
	// SandboxOff runs sessions straight on the machine. The default.
	SandboxOff = "off"
	// SandboxAsk leaves the answer to whoever opens the session — the New
	// worktree dialog and the New session menu both put the question — and
	// confines the session where there is nobody to put it to.
	SandboxAsk = "ask"
	// SandboxWorktrees confines sessions in a worktree and leaves the project's
	// own checkout alone — a worktree is the throwaway one, which is the split
	// skipPermissionsKey already makes for the opposite reason.
	SandboxWorktrees = "worktrees"
	// SandboxEverywhere confines every session of the provider.
	SandboxEverywhere = "everywhere"
)

Sandbox rungs, ordered by how much of the machine a session can reach. They are the stored spelling of the control in Settings › Providers, and anything this list does not name reads as SandboxOff — an unknown value must never be the answer that leaves a session unconfined by accident, but it must also never confine one the user never asked to confine.

View Source
const CostSourceMixed = "mixed"

CostSourceMixed labels a total whose money came off both rungs — some of it priced here, some of it reported by the provider that spent it. It is a fact of the sum rather than of any provider, which is why it is not one of providers.CostSource's answers.

Variables

View Source
var ErrConversationHeld = errors.New("this conversation already has a session in lich")

ErrConversationHeld is an adoption refused because a session row already holds the conversation: another window adopted it first, or lich opened it.

Functions

This section is empty.

Types

type ClosedHistory

type ClosedHistory = api.ClosedHistory

type ClosedSession

type ClosedSession = api.ParkedSession

type Conversation

type Conversation struct {
	Kind  string
	ID    string
	Title string
	Cwd   string
	// Unix seconds of the last activity the provider recorded.
	UpdatedAt int64
	// Profile is the profile (Claude Code or Codex) whose directory holds the
	// conversation, "personal" for the default one; "" for other providers.
	Profile string
}

Conversation is one conversation a provider keeps on disk, as its own store describes it: whoever started it, lich or not. internal/terminal reads them (terminal.Conversations); Cwd is the directory the agent ran in, which is what ties the conversation to a project.

type CostReport

type CostReport = api.CostReport

type CostTotal

type CostTotal = api.CostTotal

type CostTotalsOptions

type CostTotalsOptions = api.CostTotalsOptions

type ExternalSession

type ExternalSession = api.ExternalSession

type ForfeitedSchedule

type ForfeitedSchedule struct {
	Label  string `json:"label"`
	At     int64  `json:"at"`
	Prompt string `json:"prompt"`
}

ForfeitedSchedule is one scheduled prompt that went with a deleted session: what that session was called, when the prompt was due, and the prompt itself. It carries no session id — the row is gone, so there is nothing left to route to, and the label is the only name the user ever knew it by.

func (ForfeitedSchedule) Notice

func (f ForfeitedSchedule) Notice() (summary, detail string)

Notice words one forfeit for a desktop notification: the headline names the session, the second line what the prompt was going to say and when. Both are bounded by the notifier itself (internal/system, notifyLimit), which is why the prompt goes in whole rather than cut to some length chosen here.

type NewerSchemaError

type NewerSchemaError struct {
	Found int
	Known int
}

NewerSchemaError is an open refused because the database was written by a newer lich than this one. Opening it anyway would let this binary write its defaults over columns it does not know about, so it is not opened at all.

func (*NewerSchemaError) Error

func (e *NewerSchemaError) Error() string

type Project

type Project = api.Project

type ProjectAdded

type ProjectAdded = api.ProjectAdded

type ProjectClosed

type ProjectClosed = api.ProjectClosed

type ProjectsReordered

type ProjectsReordered = api.ProjectsReordered

type Recent

type Recent = api.RecentProject

type Service

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

Service owns the SQLite connection and exposes persistence to the window.

func New

func New() (*Service, error)

New opens (creating if absent) the SQLite database under the user's config directory and applies the schema.

func (*Service) AddHandsOn

func (s *Service) AddHandsOn(sessionID string, seconds int64) error

AddHandsOn folds another stretch of hands-on time into a session's total, in whole seconds. The accumulator that measures it holds no absolute figure of its own (internal/terminal.handsOn), so this adds rather than sets: a lich that restarts resumes counting onto what the last one wrote instead of starting the session over at zero.

The SELECT ... WHERE EXISTS writes nothing for a session whose row is already gone — closed while its last stretch was still being written — for the same reason SaveCostLedger does it: that is a race, not a failure.

func (*Service) AddProject

func (s *Service) AddProject(_ context.Context, opts api.AddProjectOptions) (api.None, error)

AddProject persists a newly opened project and marks it open. Reopening a previously closed project keeps its stored sessions, name, path and tab position intact — only is_open flips back to 1. A brand-new project takes the position after the last one, so it opens as the rightmost tab.

func (*Service) AddSession

func (s *Service) AddSession(_ context.Context, opts api.AddSessionOptions) (api.None, error)

AddSession inserts a session, makes it the project's active one and records the project's next label counter, all atomically. Kind selects what the session's PTY runs (a provider id or "shell"); empty defaults to "claude", which is the schema's own default and the answer for a caller that reached this over RPC without one. Path is the session's working directory when it lives in a git worktree; empty means the project's. The session takes the position after the project's last one, so it appends to the card list even once the user has dragged the others around. opts.Sandbox is whether this session runs confined ("on"/"off", empty to follow the provider's rung). It is written with the row rather than after it because the PTY reads it on the very first spawn: a second call would race the card the insert is about to put on screen, and lose that race silently — the session would open unconfined and stay that way until something respawned it.

func (*Service) AddSessionFrom

func (s *Service) AddSessionFrom(_ context.Context, opts api.AddSessionFromOptions) (api.None, error)

AddSessionFrom is AddSession for a session opened by delegation: opts.OriginID is the session that asked for it and opts.OriginLabel what that session was called at the time. Both are written with the row rather than after it, so a card can never exist without the origin it was created with; opts.Folder, "" for none, is written with it for AddSessionInFolder's reason.

It is a second entry point rather than two more arguments on AddSession because the window — the only caller reaching this over RPC — never has an origin to pass. Only internal/spawn does.

func (*Service) AddSessionInFolder

func (s *Service) AddSessionInFolder(_ context.Context, opts api.AddSessionInFolderOptions) (api.None, error)

AddSessionInFolder is AddSession for a session opened into a folder (a folder's +). The folder is written with the row rather than after it: filing is an UPDATE, and a lich that died between the two would bring the session back unfiled.

func (*Service) AdoptExternalSession

func (s *Service) AdoptExternalSession(_ context.Context, opts api.AdoptExternalSessionOptions) (api.None, error)

AdoptExternalSession files a conversation started outside lich as a parked session of opts.ProjectID under opts.SessionID, so the history's own resume (ReopenSession) brings it back like any session lich closed. opts.Path is the ExternalSession's, "" for the project's own directory.

func (*Service) ClaudeProfile

func (s *Service) ClaudeProfile(projectID string) string

ClaudeProfile is the profile a Claude Code session born in this project now runs in, "" for Personal.

func (*Service) Close

func (s *Service) Close() error

Close releases the database connection, after waiting out a backfill still indexing parked sessions (transcripts.go). Waiting rather than racing: the goroutine writes through this same connection, and closing it under one is a failed write logged as if the disk had gone.

func (*Service) CloseProject

func (s *Service) CloseProject(_ context.Context, opts api.ProjectIDOptions) (api.None, error)

CloseProject marks a project closed without deleting it or its sessions, so it can be reopened later with its session state restored. closed_seq is what orders the reopen menu; a counter rather than a timestamp, so two closes in the same second still order.

func (*Service) CloseSession

func (s *Service) CloseSession(_ context.Context, opts api.ParkSessionOptions) (api.None, error)

CloseSession parks a session instead of deleting it: is_open flips to 0, which hides it from LoadState while keeping its row — and its provider session id — intact for a later resume. The project's active session moves to opts.ActiveID (the neighbor the window picked).

Every close lands here. DeleteSession is what the checkout's own removal uses, where the row must not outlive the directory it points at.

closed_at is stamped in the same statement rather than after it: it is what orders the history the parked row exists to appear in, and a row parked without one sorts as if it had been closed before everything else. The branch is stamped with it, and this is the only place it ever is — the history search runs in SQL, so a branch nothing wrote down cannot be typed to find the row showing it.

The conversation is indexed here too, and this is the only place it ever is: a parked session's transcript is read once, bounded, and written into the FTS index the history search matches on (transcripts.go). Doing it at the close is what keeps a search off the disk entirely: the alternative is reading every parked session's transcript on every character typed.

git and the transcript are both asked before the transaction opens: the store holds a single connection, and a subprocess or a 32 MB read under the write lock stalls every other caller for as long as it takes.

func (*Service) ClosedProjectCount

func (s *Service) ClosedProjectCount(_ context.Context, opts api.SearchTermOptions) (int, error)

ClosedProjectCount counts the closed projects matching opts.Term, which is how a list capped at recentLimit says what it is leaving out: the reopen menu points at the palette when there are more, and the palette's own group header reports the matches it could not fit. A COUNT over one indexed flag is cheap enough to ask for beside the list itself.

func (*Service) ClosedSessions

func (s *Service) ClosedSessions(_ context.Context, opts api.SearchTermOptions) (ClosedHistory, error)

ClosedSessions returns the parked sessions (is_open = 0) matching opts.Term, the last one closed first, up to closedSessionLimit of them. An empty opts.Term is the plain history: the most recently closed, whatever they are named. Sessions of closed projects answer too: a project hidden from the tab strip still owns the work done in it, and resuming one of its sessions is what reopens it.

A row answers on either of two matches, and the OR between them is the whole point: every whitespace-separated word appearing in the name, the project's name, the path or the branch it was parked on (the same reading the palette's own filter gives a query), or the conversation itself mentioning them, out of the FTS index the close wrote (transcripts.go). A row matched on its conversation carries the Snippet that made it one, and one matched by name carries none.

Both are matched here rather than in the window because the window only ever sees one page of rows, and a session parked further back than that page would be unfindable. LIKE is case-insensitive for ASCII in SQLite, which is what makes the name half a search and not a prefix test.

Total counts the whole match, not the page: without it an opts.Term matching more parked sessions than fit would answer with closedSessionLimit rows and no way for the list to say so. Indexing counts the parked sessions the backfill has not reached yet, which is the other way this answer can be short; asking for one with an opts.Term is what starts that backfill.

A conversation is listed once, by its newest park, and not at all while a card has it open (newestOfItsConversation): its copies, left by a `/resume` typed into another card, all reopen the same transcript.

rowid is the tiebreak, not the order, for RecentProjects' reason twice over: it dates the insert, and a resumed session is reinserted — so rows parked before closed_at existed all carry 0 and fall back to it together.

func (*Service) CodexProfile

func (s *Service) CodexProfile(projectID string) string

CodexProfile is the profile a Codex session born in this project now runs in, "" for Personal.

func (*Service) ColorFolder

func (s *Service) ColorFolder(projectID, folder, color string) ([]string, error)

ColorFolder paints every session filed under one project's folder, as the window's folder "Color" does card by card, and returns the ids it painted. A folder has no colour of its own: it shows the one its cards share.

func (*Service) ConversationHolder

func (s *Service) ConversationHolder(providerSessionID, sessionID string) (string, error)

ConversationHolder is the open session other than sessionID that runs providerSessionID, or "" when no other card has it open. Parked rows are not asked: they run nothing until reopened, and reopen hands back the open card instead (reopen).

func (*Service) CostLedger

func (s *Service) CostLedger(sessionID, transcriptID string) (int64, string, float64, error)

CostLedger returns how far a session's cost accounting has read into one of its provider transcripts: the byte offset counted up to, the message id the last counted line belonged to, and what that stretch cost in USD.

A session accumulates one ledger per transcript it has run through — `/clear` starts a new conversation, and its transcript gets its own row while the old one keeps what it already counted. A pair nothing has been counted for yet reads as offset 0 and cost 0, the correct starting point, so a missing row is not an error.

func (*Service) CostReadout

func (s *Service) CostReadout() bool

CostReadout reports whether the session cost readout is on. Any read failure answers off, which is the safe default for a number most users must not see.

func (*Service) CostTotals

func (s *Service) CostTotals(_ context.Context, opts CostTotalsOptions) (CostReport, error)

CostTotals sums the ledger by project. project narrows it to one by name, case-insensitively; provider to one session kind; either empty means all of them. since, in unix seconds, keeps only the sessions active on or after it, and 0 keeps every session lich still remembers.

A session's activity is its last counted turn, because that is the only date the ledger carries — the row is a running total with no per-turn history behind it. So a window selects *sessions active in it*, counted whole, rather than slicing each session's money by day: a session that ran through the boundary brings all of its cost with it. A session with nothing counted is dated by when it was parked, or by now while it is open, so an unpriced session that is still running is unpriced in every window ending today.

Only sessions lich still holds a row for are in reach at all: a deleted session took its ledger with it (ON DELETE CASCADE) and is in no total, neither counted nor excluded.

func (*Service) DeleteProject

func (s *Service) DeleteProject(id string) error

DeleteProject removes a project and, through ON DELETE CASCADE, its sessions. Closing keeps a project for a later reopen; this is for the row that outlived the directory it points at, which nothing can reopen anymore.

Its settings go by hand, because the settings table carries no foreign key and a project id is derived from its path: a directory recreated where a deleted one stood would otherwise inherit that project's provider, gh account and binary overrides with nothing in the UI saying where they came from. An empty id is refused for the same reason — it is the global scope, and deleting a project must never take every global setting with it.

Both deletes are one transaction: the settings are only orphaned once the project they belong to is gone, so a failure between them would leave the row standing with its provider, gh account and binary overrides silently wiped.

func (*Service) DeleteSession

func (s *Service) DeleteSession(projectID, sessionID, activeID string) error

DeleteSession removes a session for good and sets the project's active session to activeID (the neighbor the window picked, or "" when none remain).

func (*Service) ExternalSessions

func (s *Service) ExternalSessions(_ context.Context, _ api.None) ([]ExternalSession, error)

ExternalSessions lists the conversations on disk that lich holds no row for and never deleted one for, and that ran in a checkout of a project lich knows, open or closed. Newest first.

A conversation whose directory is gone is left out: there is nowhere to resume it, the same reason a history row without its checkout cannot be.

func (*Service) ForgetClaudeProfile

func (s *Service) ForgetClaudeProfile(slug string) error

ForgetClaudeProfile clears every setting that names a deleted profile, so a project set to it falls back to the global value and the global one to Personal. The sessions born in it keep their mark: what they ran in is a fact about them, and resuming one reports the profile gone (ErrProfileGone).

func (*Service) ForgetCodexProfile

func (s *Service) ForgetCodexProfile(slug string) error

ForgetCodexProfile is ForgetClaudeProfile for a Codex profile.

func (*Service) ForgetOMPProfile

func (s *Service) ForgetOMPProfile(slug string) error

ForgetOMPProfile is ForgetClaudeProfile for an oh-my-pi profile.

func (*Service) ForgetSession

func (s *Service) ForgetSession(_ context.Context, opts api.SessionIDOptions) (api.None, error)

ForgetSession deletes one parked session for good, with every other parked copy of its conversation: the history lists a conversation once (ClosedSessions), so a copy left behind would take the forgotten row's place. It is the way out for the row whose checkout was removed behind lich's back: nothing can resume it, and PurgeWorktreeSessions never ran for it because the removal never went through the app.

is_open = 0 is the whole guard: a session on screen is closed, never forgotten, so an id belonging to a live card matches nothing here. A row that was already gone is not an error, and only the rows a delete actually removed are reported gone.

func (*Service) ForgetXDGProfile

func (s *Service) ForgetXDGProfile(kind, slug string) error

ForgetXDGProfile is ForgetClaudeProfile for an opencode, Cursor CLI or Kiro CLI profile.

func (*Service) ForgottenProviderSessions

func (s *Service) ForgottenProviderSessions() (map[string]bool, error)

ForgottenProviderSessions is the set of provider conversation ids lich once held a session for and deleted for good: the ones a listing of the conversations on disk must not offer back as started outside lich. The triggers of addProviderSessionTombstones keep it, so every path that deletes a row is covered. A row deleted before the table existed left no stone.

func (*Service) GHAccountForPath

func (s *Service) GHAccountForPath(path string) string

GHAccountForPath returns the gh account login configured for the project the checkout at path belongs to, or "" for none. The path is a project directory or one of its worktrees — the project services address a checkout by path, never by project id, so the mapping is resolved here.

func (*Service) GetSetting

func (s *Service) GetSetting(_ context.Context, opts api.GetSettingOptions) (string, error)

GetSetting returns a setting's value for the given scope. An empty opts.ProjectID reads the global value. A missing setting returns "" and no error.

func (*Service) HandsOn

func (s *Service) HandsOn(sessionID string) (int64, error)

HandsOn is how long a session has been worked on, in whole seconds. A session nothing has been counted for yet answers 0, which is the right starting point, so a missing row is not an error.

func (*Service) InheritSubagent

func (s *Service) InheritSubagent(sessionID, forkedFrom string) error

InheritSubagent gives a fork the subagent depth of the session that ran the conversation it branches, forkedFrom, when that one was a subagent. The fork's row is a fresh insert, so without this a copy of a worker would open cards a worker that deep does not.

func (*Service) InheritUltracode

func (s *Service) InheritUltracode(sessionID, forkedFrom string) error

InheritUltracode turns ultracode on for a fork when the session that ran the conversation it branches, forkedFrom, has it on. The fork's row is a fresh insert that knows nothing of its parent, and Claude Code drops ultracode on --resume, fork included, so without this the copy would run without it.

func (*Service) LoadState

func (s *Service) LoadState(_ context.Context, _ api.None) ([]Project, error)

LoadState returns the open projects (is_open = 1) with their sessions, in the order the user dragged them into. It is the single hydration call the window makes on launch to restore the workspace.

Rows that predate the position column all carry the default 0, so the rowid tiebreak keeps them in insertion order until a first drag assigns positions.

func (*Service) MarkForked

func (s *Service) MarkForked(_ context.Context, opts api.SessionIDOptions) (api.None, error)

MarkForked records that opts.ID was born branching its origin's conversation, written by the window that opens the fork along with the row.

func (*Service) OMPProfile

func (s *Service) OMPProfile(projectID string) string

OMPProfile is the profile an oh-my-pi session born in this project now runs in, "" for Personal.

func (*Service) PasteUnfold

func (s *Service) PasteUnfold(providerID string) bool

PasteUnfold reports whether a long paste into this provider lands unfolded.

func (*Service) ProjectAt

func (s *Service) ProjectAt(path string) (string, string)

ProjectAt names the project rooted at path — id and name — or two empty strings when no project is. Closed projects answer too: a row hidden from the tab strip still owns its directory, and relocating another project onto it would be the same collision.

func (*Service) ProjectPath

func (s *Service) ProjectPath(projectID string) string

ProjectPath returns the directory of the project with this id, or "" when there is no such project. It is the main checkout — a session running in a worktree has its own directory and still belongs to this one, which is what makes the answer worth asking for.

func (*Service) PromptLanguage

func (s *Service) PromptLanguage() prompt.Lang

PromptLanguage is the language lich writes agent prompts in. An absent or unknown value, or a failed read, is English, the default every session got before the setting existed.

func (*Service) ProviderBin

func (s *Service) ProviderBin(providerID, projectID string) string

ProviderBin resolves a provider's binary path for a project: the project override wins, then the global value, then "" (letting the terminal fall back to the provider's default). A parked layer is skipped as if it were unset. It is the single call the terminal service makes when spawning a session's PTY.

func (*Service) ProviderEnabled

func (s *Service) ProviderEnabled(providerID string) (bool, error)

ProviderEnabled reports whether the user turned providerID on, read the way the windows read provider.<id>.enabled: Claude is on unless switched off, since it was always offered before providers could be chosen, and every other provider is opt-in.

func (*Service) ProviderSession

func (s *Service) ProviderSession(sessionID string) (string, error)

ProviderSession returns the provider conversation id recorded for a lich session, or "" when none has been reported yet (or the session is gone — a missing row is not an error). Pairs with SetProviderSession: the context-usage read locates a transcript by this id.

func (*Service) PurgeWorktreeSessions

func (s *Service) PurgeWorktreeSessions(_ context.Context, opts api.WorktreeSessionsOptions) (api.None, error)

PurgeWorktreeSessions deletes every session row for the worktree at opts.Path in a project — the live one and any parked leftovers alike — so removing a worktree never strands a hidden row that a later resume could resurrect against a checkout that no longer exists. The empty-path guard is load-bearing: a project's own sessions carry no path, so an unguarded delete would wipe them all. Idempotent — no matching rows is not an error.

func (*Service) RecentProjects

func (s *Service) RecentProjects(_ context.Context, opts api.SearchTermOptions) ([]Recent, error)

RecentProjects returns the closed projects matching opts.Term, the last one closed first, up to recentLimit of them. An empty opts.Term is the plain reopen list: the most recently closed, whatever they are named.

opts.Term is matched here rather than in the window for the reason ClosedSessions matches its own: the window only ever sees one page of rows, so a project closed further back than that page would be unreachable by name.

rowid is the tiebreaker, not the order: it dates a project's first open, so on its own it hid a long-standing project behind newer ones the moment it was closed. Rows closed before closed_seq existed carry 0 and keep falling back to it.

func (*Service) RenameFolder

func (s *Service) RenameFolder(_ context.Context, opts api.RenameProjectFolderOptions) ([]string, error)

RenameFolder renames one project's folder, and takes it apart when `opts.To` is empty — ungrouping every session filed under it in one write.

Scoped to a project because the name is the identity: two projects can both hold an "Apps" folder, and renaming one must not reach into the other. Parked sessions are rewritten along with the open ones (no is_open clause): a resumed session comes back into the folder it was filed under, which has to be the folder's name now rather than the one it wore at the close.

An empty `opts.From` is refused, or the call would sweep every unfiled session in the project into a folder nobody asked for.

It returns the ids of every row it rewrote, parked ones included. They come from the write itself rather than a read before it: a session filed under `opts.From` in between is moved too, and a caller announcing the move from its own earlier read would leave that card behind.

func (*Service) RenameSession

func (s *Service) RenameSession(_ context.Context, opts api.LabelSessionOptions) (api.None, error)

RenameSession updates a session's display label from an explicit user rename. It clears label_auto so the automatic ai-title (SetSessionTitle) never stomps a name the user chose.

func (*Service) ReopenSession

func (s *Service) ReopenSession(_ context.Context, opts api.ReopenSessionOptions) (*Session, error)

ReopenSession resumes one parked session by its own id — the history list's door, where the row was picked rather than looked up. Returns nil when no parked session has that id, which is what a row already resumed in another window looks like.

Deliberately not scoped to a project: the row names its own, and that is the only answer that stays right for a session parked in a project the caller is not looking at — which is most of the history.

func (*Service) ReopenWorktreeSession

func (s *Service) ReopenWorktreeSession(_ context.Context, opts api.ReopenWorktreeSessionOptions) (*Session, error)

ReopenWorktreeSession resumes the session parked for the worktree at opts.Path, the last one closed there. Returns nil when nothing is parked at opts.Path — the caller then opens a brand-new session.

An empty opts.Path is refused, and that guard is load-bearing for the same reason PurgeWorktreeSessions carries one: a project's own sessions are stored with no path, so an unguarded lookup would answer the worktree picker with a parked session that never lived in a worktree at all.

func (*Service) ReorderProjects

func (s *Service) ReorderProjects(_ context.Context, opts api.ReorderProjectsOptions) (api.None, error)

ReorderProjects records the tab order after a drag. It writes every project's position from the full list the window rendered, so the stored order is rewritten as a whole rather than patched around the moved tab.

func (*Service) ReorderSessions

func (s *Service) ReorderSessions(_ context.Context, opts api.ReorderSessionsOptions) (api.None, error)

ReorderSessions records a project's card order after a drag, writing every position from the full list. Scoped to the project so an id belonging to another project's list can never take a position in this one.

func (*Service) ReplaceConversationCost

func (s *Service) ReplaceConversationCost(sessionID, conversationID string, cost float64) error

ReplaceConversationCost records cost as the whole of what one conversation has cost, for a provider that reported the figure itself: its row is written with no offset to resume from, and the rows of its sub-agents' transcripts (keyed by the conversation id, a slash and the file) are dropped, since the reported figure already counts them. The row is marked reported, which puts the session on that rung in CostTotals. Like SaveCostLedger it writes nothing for a session whose row is already gone.

func (*Service) SandboxDefault

func (s *Service) SandboxDefault(providerID, projectID, cwd string) bool

SandboxDefault reports whether a session of this provider, starting in cwd, is confined unless something says otherwise. cwd picks the scope the same way SkipPermissions does: anything but the project's own directory is a worktree, and a project whose path cannot be read falls back to the main checkout.

SandboxAsk answers true here, and does so whichever checkout the session starts in. It is the rung that hands the decision to whoever opens the session, so this function is only reached for it when there was nobody to hand it to — an MCP open_session, `lich open`, a respawn of a row nothing ever recorded an answer on. The rung exists to confine agents working unattended, and a session no human is opening is the unattended case exactly, so the answer nobody chose is the confined one.

func (*Service) SandboxGHToken

func (s *Service) SandboxGHToken(projectID string) bool

SandboxGHToken reports whether a confined session in this project is given a GitHub token in its environment, which is what makes gh work inside one: the token lives in the system keyring, and a private home cannot reach it.

func (*Service) SandboxLevel

func (s *Service) SandboxLevel(providerID, projectID string) string

SandboxLevel returns the rung configured for a provider in a project: the project's own value, then the global one, then SandboxOff. An unreadable or unrecognised value is SandboxOff for the reason the constants give.

func (*Service) SandboxSSHAgent

func (s *Service) SandboxSSHAgent(projectID string) bool

SandboxSSHAgent reports whether a confined session in this project is given the user's ssh agent, which is what makes `git push` work inside one.

func (*Service) SaveCostLedger

func (s *Service) SaveCostLedger(
	sessionID, transcriptID string, offset int64, lastMessage string, cost float64,
) error

SaveCostLedger records the position and total of one transcript's accounting, stamped with the moment it was written — the only date a session's spend ever carries, and what CostTotals windows on. The SELECT ... WHERE EXISTS writes nothing for a session whose row is already gone (closed while its last turn was still being counted) instead of letting the foreign key raise: that is a race, not a failure, and it is the same silent miss SetProviderSession takes.

func (*Service) SaveForkCostOffset

func (s *Service) SaveForkCostOffset(sessionID, forkedFrom string) error

SaveForkCostOffset records, on a session just forked from the conversation forkedFrom, what lich had counted that conversation to cost at this moment — which is the stretch the fork's own transcript carries a copy of and the ledger is about to count a second time. SessionCost and CostTotals take it back off, so the pair adds up to what was actually spent.

The offset is a snapshot in dollars, not in tokens, because the ledger it is read out of is one: a counted stretch is never re-priced (scanTranscriptCost resumes past it), so the parent's own figure does not move when a price refresh lands either, and a token offset re-priced later would drift away from the number the parent still shows.

It is the raw ledger row rather than the parent's readout, which is what makes a fork of a fork right: the parent's row holds the gross cost of its own transcript, history included, and that whole stretch is what the copy repeats. A conversation lich has counted nothing for offsets nothing.

func (*Service) SessionBranch

func (s *Service) SessionBranch(sessionID string) string

SessionBranch names the branch of the checkout a session is running in: for the row about to be parked, and for the report a subagent sends home (internal/relay). A session with no path of its own runs in its project's directory, which is then the checkout to ask about.

Every failure answers "": a store without the wiring, a session id nothing matches, a directory git cannot name a branch for. None of them is worth refusing a close over — the row loses the branch as a search term and keeps everything else.

func (*Service) SessionCost

func (s *Service) SessionCost(sessionID string) (float64, error)

SessionCost is what a session has cost so far: the sum of every transcript it has run through, less what a fork inherited from the conversation it was branched from (SaveForkCostOffset). Zero for a session that has counted nothing yet — whether that zero is worth showing is the caller's call, since an unpriced model must read as "no number", never as free.

The subtraction is floored at zero: a fork whose ledger has not caught up with its inherited history yet would otherwise report money back.

func (*Service) SessionEffort

func (s *Service) SessionEffort(sessionID string) string

SessionEffort returns the effort recorded for a session, or "" for none or on a read failure, which leaves the provider on its own default as SessionModel does.

func (*Service) SessionExists

func (s *Service) SessionExists(sessionID string) bool

SessionExists reports whether a session's row is still there, open or parked, the two states a row can be in; only a delete removes it. It is what tells lich's dropped-file copies apart from the ones an unclean exit orphaned (internal/drop): the copies of a session that still exists are still worth keeping, whatever their age.

A read that failed answers true: the row not being readable is not the row being gone, and the caller deletes on a false.

func (*Service) SessionKind

func (s *Service) SessionKind(sessionID string) string

SessionKind is the provider a session runs, "" for a session with no row or when the read fails: a caller that needs the answer to be right asks the session's spawn first.

func (*Service) SessionModel

func (s *Service) SessionModel(sessionID string) string

SessionModel returns the model recorded for a session, or "" for none — which is what a session opened from the window has, and what leaves the provider on its own default. A read failure answers "" for the same reason: the model is an override, and the provider's default is the safe thing to fall back to.

func (*Service) SessionProfile

func (s *Service) SessionProfile(sessionID string) (string, error)

SessionProfile is the profile a session runs in, "" for Personal and for a session with no row. A failed read is an error rather than Personal: spawning into the wrong account is not a default to fall back to.

func (*Service) SessionSandbox

func (s *Service) SessionSandbox(sessionID string) string

SessionSandbox returns the answer recorded for a session, or "" when nobody decided for this one and the provider's rung stands. A read failure answers "": the row is an override, and deferring to the setting is the honest fallback.

func (*Service) SessionSubagentDepth

func (s *Service) SessionSubagentDepth(sessionID string) int

SessionSubagentDepth is how many subagent levels below a session nobody opened as one this session runs, 0 for such a session. A read failure answers 0, which leaves the user's setting in charge.

func (*Service) SessionUltracode

func (s *Service) SessionUltracode(sessionID string) bool

SessionUltracode reports whether a session was opened with ultracode on. A read failure answers false, the provider's own default, as SessionModel does.

func (*Service) SetActiveSession

func (s *Service) SetActiveSession(_ context.Context, opts api.ActiveSessionOptions) (api.None, error)

SetActiveSession records which session is focused within a project.

func (*Service) SetBranchOf

func (s *Service) SetBranchOf(fn func(path string) string)

SetBranchOf registers how to read a checkout's git branch (project.Branch). CloseSession stamps the answer on the row it parks, which is what makes the branch searchable in the history query.

It is startup wiring, called before anything serves. Without it a park records no branch, which costs that row nothing but the branch as a search term.

func (*Service) SetCheckoutsOf

func (s *Service) SetCheckoutsOf(fn func(projectPath string) ([]string, error))

SetCheckoutsOf registers how to list a repository's checkouts, its own directory included (project.Service.ListCheckouts). Startup wiring; without it a conversation matches a project only by the project's own directory.

func (*Service) SetConversationsOf

func (s *Service) SetConversationsOf(fn func() []Conversation)

SetConversationsOf registers how to list the conversations on disk (terminal.Conversations). Startup wiring; without it there are no external sessions, which is what every test that does not wire it gets.

func (*Service) SetProjectChanged

func (s *Service) SetProjectChanged(fn func(name string, data any))

SetProjectChanged registers what to run for each change to the project list once it is committed. The three events above are what it is told.

It is startup wiring, called before anything serves: lich hands it the events hub. Without it a change costs nothing but the notice.

func (*Service) SetProviderSession

func (s *Service) SetProviderSession(sessionID, providerSessionID string) error

SetProviderSession records the provider conversation id running inside a lich session's PTY, reported by the provider's session-start hook. A session whose row does not exist yet (the hook racing session persistence) matches nothing and is not an error — the id is simply dropped, which is acceptable for the features it backs. Re-reporting (e.g. after a resume) overwrites with the latest id.

func (*Service) SetScheduleForfeited

func (s *Service) SetScheduleForfeited(fn func(ForfeitedSchedule))

SetScheduleForfeited registers what to run for each scheduled prompt lost to a delete — DeleteSession, ForgetSession, PurgeWorktreeSessions and DeleteProject, never CloseSession, which parks the row and brings the schedule back with the card.

It is startup wiring, called before anything serves. Without it a forfeit costs nothing but the notice: the log line is written either way.

func (*Service) SetSessionColor

func (s *Service) SetSessionColor(_ context.Context, opts api.SessionColorOptions) (api.None, error)

SetSessionColor paints a session's card with a palette colour, or hands it back to the theme with an empty name. The name is stored as given: the palette lives in the window, which draws a name it does not know as no colour at all.

func (*Service) SetSessionEffort

func (s *Service) SetSessionEffort(sessionID, effort string) error

SetSessionEffort records the reasoning effort a session's provider was asked to run at, read back the way SetSessionModel's is.

func (*Service) SetSessionFolder

func (s *Service) SetSessionFolder(_ context.Context, opts api.SessionFolderOptions) (api.None, error)

SetSessionFolder files a session under a folder, or takes it out of one with an empty name — the sidebar block the user groups by assignment rather than by checkout. A session is in at most one folder, so this is a write, never an append.

The name is not looked up anywhere: a folder is the set of sessions carrying its name, so filing the first session under a name is what creates it and taking the last one out is what ends it. Nothing here trims or folds case — the window hands over a name the user picked from its own list of them, and a second name differing by a space is a second folder they can see and rename.

func (*Service) SetSessionGone

func (s *Service) SetSessionGone(fn func(sessionID string))

SetSessionGone registers what to run when a session's row is deleted for good — DeleteSession, PurgeWorktreeSessions and ForgetSession, never CloseSession, which parks the row for a later resume and leaves everything hanging off it alone.

It is startup wiring, called before anything serves: lich hangs the cleanup of that session's dropped-file copies on it (internal/drop), which is what makes a copy outlive its drop and not its session.

func (*Service) SetSessionMCPServers

func (s *Service) SetSessionMCPServers(sessionID string, servers []string) error

SetSessionMCPServers records the MCP servers a session's provider could reach at the spawn that just happened. The window divides a tool name against them (native/cmd/lich-native/toolline.go), and the row is what a window restart comes back to — the PTY is still running by then, so there is no second spawn to report it again.

An empty list clears the row rather than parking "[]": a session that reached nothing and a session nobody has spawned read the same way, and both mean the card shows a tool name whole.

func (*Service) SetSessionModel

func (s *Service) SetSessionModel(sessionID, model string) error

SetSessionModel records the model a session was born on, so every spawn that starts a new conversation for it (the first view, a restart) repeats the flag. A resume does not: the conversation's own model is the provider's to restore (terminal.modelArgs).

It is written once, right after the row is created. A session whose row is gone matches nothing and is not an error.

func (*Service) SetSessionPinned

func (s *Service) SetSessionPinned(_ context.Context, opts api.SessionPinnedOptions) (api.None, error)

SetSessionPinned pins or unpins a session — the flag the sidebar reads to hoist a card to the head of the list, and to withhold its close affordances. It leaves position untouched, so an unpinned session falls back to the slot the last drag gave it rather than landing wherever the pinned block ended.

func (*Service) SetSessionProfile

func (s *Service) SetSessionProfile(sessionID, profile string) error

SetSessionProfile records the profile a session runs in, "" for Personal. A session is born in its project's profile (addSession); this moves it, which is what Continue in does once its conversation has moved, and what a resume does when the conversation turns out to live in another profile.

func (*Service) SetSessionRenamed

func (s *Service) SetSessionRenamed(fn func(sessionID, label string))

SetSessionRenamed registers what to run once RenameSession has written a label, which is how every window learns of a rename it did not make itself. The auto-applied ai-title is not routed through it: the terminal reports that one on its own.

It is startup wiring, called before anything serves. Without it a rename is stored and no window is told.

func (*Service) SetSessionSandbox

func (s *Service) SetSessionSandbox(sessionID, sandbox string) error

SetSessionSandbox records whether one session runs confined, overriding the provider's rung for that session alone. It is written when a session is opened — the dialog's answer — and read on every later spawn, so a respawn after a reload and the resume of a parked worktree session are confined the same way the user opened them.

Anything that is not one of the two answers clears the override rather than parking an unreadable value: a row that says neither is a row that follows the setting, which is the state every session starts in.

func (s *Service) SetSessionSandboxLinks(sessionID string, links []string) error

SetSessionSandboxLinks records the home paths this session's sandbox skipped for being symlinks, home-relative — what the card names as not mounted, so a ~/.gitconfig symlinked out of a dotfiles repository is an absence the session is told about rather than one it discovers by failing. Written by the spawn that resolved them, and read back on hydration for the reason above: the PTY outlives the window.

func (*Service) SetSessionSchedule

func (s *Service) SetSessionSchedule(sessionID string, at int64, prompt string) error

SetSessionSchedule parks a prompt to be typed at a session later. at is unix seconds; 0, or an empty prompt, clears whatever was there — there is nothing else to cancel, because a session holds one scheduled prompt at a time and scheduling again replaces it.

A session whose row is gone matches nothing and is not an error: the schedule belongs to the card, and a card that is gone has taken its schedule with it.

func (*Service) SetSessionSubagentDepth

func (s *Service) SetSessionSubagentDepth(sessionID string, depth int) error

SetSessionSubagentDepth records that a session was opened as another session's subagent, depth levels below a session nobody opened as one (internal/spawn, OpenSubagent), so every spawn of it, a resume included, knows how deep it runs. The subagent column holds the depth; 0 is a session nobody opened as a subagent, which is every row written before nesting.

func (*Service) SetSessionTitle

func (s *Service) SetSessionTitle(sessionID, title string) (bool, error)

SetSessionTitle sets a session's label from the provider's ai-title reported by the Stop hook, but only while the label is still automatic: a prior RenameSession clears label_auto and makes this a no-op, so a user's own name is never overwritten. Reports whether the label actually changed, so the caller only pushes a UI update when it did.

The label it already carries is excluded in SQL rather than compared here: SQLite counts a row it processed even when the write changes nothing, and a provider whose title is derived once and re-reported on every turn would otherwise take the write lock and emit a title event per turn.

func (*Service) SetSessionUltracode

func (s *Service) SetSessionUltracode(sessionID string) error

SetSessionUltracode records that a session was opened with ultracode on, so every later spawn of it asks for ultracode again.

func (*Service) SetSessionUnread

func (s *Service) SetSessionUnread(_ context.Context, opts api.SessionUnreadOptions) (api.None, error)

SetSessionUnread records whether a session's last finished turn is still waiting to be read: the mark behind the card's solid ring. Two writers, one edge each. The terminal service sets it on a turn's own boundaries, so a turn that ends with no window attached is still news when one opens; the window clears it when the card is read, which is the only side that knows what the user looked at.

A session whose row is gone matches nothing, which is not an error: a card closed between a turn ending and this write has no mark left to carry.

func (*Service) SetSetting

func (s *Service) SetSetting(_ context.Context, opts api.SetSettingOptions) (api.None, error)

SetSetting writes a setting's value for the given scope. An empty opts.ProjectID sets the global value.

func (*Service) SetTranscriptOf

func (s *Service) SetTranscriptOf(fn func(providerSessionID, cwd string) (text string, cut bool))

SetTranscriptOf registers how to read a conversation as searchable prose (terminal.TranscriptText), given the provider's own conversation id and the directory the session ran in. The second answer is whether the cap dropped the oldest of that conversation, which the row it is written to carries.

It is startup wiring, called before anything serves. Without it a session parks with no index and the history search matches names alone, which is what every test that does not wire it gets, and what lich did before the index existed.

func (*Service) SetWorktreePort

func (s *Service) SetWorktreePort(path string, port int) error

SetWorktreePort records port as the reservation for the checkout at path, replacing any earlier one.

func (*Service) SkipPermissions

func (s *Service) SkipPermissions(providerID, projectID, cwd string) bool

SkipPermissions reports whether a session of this provider, starting in cwd, runs without its permission prompts. cwd picks the scope: anything but the project's own directory is a worktree. A project whose path cannot be read falls back to the main-checkout setting — a session lich cannot place is not one to answer for with the more permissive of two flags.

func (*Service) SubagentCards

func (s *Service) SubagentCards(providerID string) bool

SubagentCards reports whether this provider's general-purpose subagents run as lich sessions.

func (*Service) Ultracode

func (s *Service) Ultracode(providerID string) bool

Ultracode reports whether every session of this provider spawns with ultracode on.

func (*Service) WorktreePorts

func (s *Service) WorktreePorts() map[string]int

WorktreePorts returns the dev-server port reserved for each checkout, keyed by path. A reservation is what makes the port a checkout owns survive a restart of lich, so the allocator can hand a colliding checkout a different number instead of both reading the same one off a hash.

Reservations whose directory is gone — a removed worktree, a checkout deleted by hand, a crash between the two — are deleted on the way out. The allocator is this table's only reader, so purging here is the whole lifecycle: nothing else has to remember to release a port, and a stale row can never hold a number against a live checkout. A read failure yields an empty map, which degrades allocation to the hash rather than failing the spawn.

type Session

type Session = api.Session

Jump to

Keyboard shortcuts

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