Skip to main content

SessionStore

Struct SessionStore 

Source
pub struct SessionStore { /* private fields */ }

Implementations§

Source§

impl SessionStore

Source

pub const API_ORIGIN: &str = "api"

The origin POST /v1/chat/completions writes: a headless call is a run, not a conversation, and it must not look like one in a listing or in --continue.

Source

pub fn new(dir: impl Into<PathBuf>) -> Self

Source

pub fn dir(&self) -> &Path

Source

pub fn new_id(&self) -> String

Sortable, unique-enough id: <unix-ms>-<pid>-<counter>.

Source

pub async fn lock(&self, id: &str, wait: Duration) -> Result<SessionLock>

Take an exclusive lock on one session so two processes (the CLI and the dashboard, or two shells) cannot interleave their messages into the same transcript. Waits up to wait for a holder to finish. Dropping the guard releases it, and the OS releases it if the process dies, so a crashed run leaves nothing stuck.

On non-Unix targets no cross-process lock is taken (the guard is inert); within one process the runtime’s own per-session mutex still applies.

Source

pub fn try_lock(&self, id: &str) -> Result<Option<SessionLock>>

One non-blocking attempt at the same lock lock takes, for a caller that has no future to await it in — a UI thread asking “is a run in flight?” before it fires a /loop tick (#173). Ok(Some) means the caller now holds it and must drop it.

It is the same primitive, not a second opinion: the lock is flock, and a session’s lock file is a session’s lock file whether the take is polled or instantaneous.

Source

pub fn set_goal(&self, goal: &Goal) -> Result<()>

#172: write a session’s goal, replacing whatever was there.

One goal per session, so this is an upsert rather than an append: /goal <text> on a session that already has one replaces it, which is what “one standing goal” means.

Source

pub fn set_plan(&self, session: &str, items: &[Item]) -> Result<u64>

#657: replace a session’s plan and report the revision it is now at.

One act, four statements, one transaction: the session row (a plan can exist before the session has any messages), the revision, the deletion of the old steps, and the new ones. #565 is why they are not four autocommit calls — a crash between the delete and the insert would leave a plan with no steps, which reads as “nothing to do”.

The revision is read back inside the transaction rather than computed here: two writers racing must not both believe they are at revision 4.

Source

pub fn plan(&self, session: &str) -> Result<Option<Plan>>

#657: a session’s plan, in the order it was written, if it has one.

Source

pub fn goal(&self, id: &str) -> Result<Option<Goal>>

#172: a session’s goal, if it has one.

Source

pub fn clear_goal(&self, id: &str) -> Result<()>

Remove a session’s goal and its judgements (/goal clear).

Source

pub fn record_goal_turn(&self, id: &str, judgement: &Judgement) -> Result<()>

Record one judgement, keyed by the turn number it judged.

Source

pub fn goal_turns(&self, id: &str) -> Result<Vec<Judgement>>

Every judgement about a session’s goal, oldest first.

Source

pub fn live_goals(&self) -> Result<Vec<Goal>>

Every goal a process could still work on — Active or Paused, newest first.

The dashboard’s sweeper asks this each pass: a goal is due when its last turn said “continue”, which is a fact on the row, not a timer in a task.

Source

pub fn is_busy(&self, id: &str) -> bool

Whether some process is running this session right now — the busy test /loop uses.

A probe, not a reservation: it takes the lock and releases it, so a run that starts in the same instant is not blocked by the question. What it answers is “was it free a moment ago”, which is what a tick landing on a busy session needs to know.

Source

pub fn exists(&self, id: &str) -> bool

Source

pub fn record_pending( &self, id: &str, seq: i64, calls: &[Pending], ) -> Result<()>

Record the calls of one assistant message as waiting for an answer.

A row that already exists keeps its decision: the same call recorded twice has the same answer or none, and the second recording can arrive while the run that asked is already stopping, which is exactly when overwriting a decision would lose it.

Source

pub fn record_pending_at( &self, id: &str, seq: i64, ord: usize, calls: &[Pending], ) -> Result<()>

The same, with the position calls[0] holds in its assistant message.

ord is half of the row’s key, so a caller that records one call at a time has to pass the position that call actually holds: every call written at 0 collides with the first one, and ON CONFLICT DO NOTHING then drops the rest of the turn silently (#547).

Source

pub fn pending_calls(&self, id: &str) -> Result<Vec<PendingCall>>

Every recorded call for a session, oldest message first and in the order the model made them — the order eclipse approve --index N counts in.

Source

pub fn decide_pending( &self, id: &str, seq: i64, ord: usize, decision: &Decision, by: &str, ) -> Result<()>

Write the answer for one recorded call. Refused if the call is not recorded: an approval for a call that does not exist would resolve nothing, and silently accepting it would tell the user their answer counted.

Source

pub fn log_decision( &self, id: &str, call: &Pending, decision: &Decision, by: &str, ) -> Result<()>

Note a ruling that had no waiting row: a judge’s allow or deny (#340).

Those calls never become pending — nothing is waiting on them — so there is no row to hang the decider on, and the log is the only place the decision can live. Written best-effort by the caller: a bookkeeping failure must never turn an approval into a refusal.

Source

pub fn approval_log(&self, id: &str) -> Result<Vec<Ruling>>

Every ruling recorded for a session, oldest first (#340).

The pending rows are transient by design, so this is the only place “who let this through” survives. One row per answered call: the decision as stored (allow, deny:<why>) and who answered it.

Source

pub fn clear_pending(&self, id: &str) -> Result<usize>

Forget the recorded calls of a session — the run that asked has answered them in the transcript, or the session is gone. Returns how many rows went.

Source

pub fn clear_call(&self, id: &str, call_id: &str) -> Result<usize>

Forget one recorded call — its answer has been written into the transcript as the tool result, which is the durable record a reader actually reads.

Source

pub fn last_seq(&self, id: &str) -> Result<i64>

The seq a session’s transcript ends at, or -1 for an empty one.

Source

pub fn set_tool_outcome( &self, id: &str, call_id: &str, is_error: bool, ) -> Result<()>

Append one message to the session, creating it on first use. How one tool call ended, for the marks a replayed session draws (#447).

The verdict belongs beside the message, not inside it: a tool message is the model’s wire shape, and a field there would either be sent to the model or skipped and never stored. The call id is what a replayed row joins on, so it is the key.

Source

pub fn tool_outcomes(&self, id: &str) -> Result<HashMap<String, bool>>

Every recorded verdict for a session, by call id. An empty map is a session recorded before this table existed, and the reader falls back to reading the text.

Source

pub fn append(&self, id: &str, message: &Message) -> Result<()>

Source

pub fn append_seq(&self, id: &str, message: &Message) -> Result<i64>

append, returning the seq the message was stored under. A pending approval is keyed by the message that carried the call, so the loop needs the number it cannot compute itself: the store owns sequence allocation.

Source

pub fn begin_subagent(&self, id: &str, parent: &str, route: &str) -> Result<()>

Create the session row for a subagent, marked with where it came from, before it has a message. The origin is what sessions list shows and what --continue skips; the transcript of the parent never mentions the child. A row that already exists is left as it is.

Source

pub fn begin_flare(&self, id: &str, run: &str, n: usize) -> Result<()>

Create the row for one flare of a run (#171), before it has a message.

A flare is a child like a subagent’s, and the run id is not a session id — it names the ledger row, not a conversation — so it is only checked for shape here.

Source

pub fn begin_flare_run( &self, id: &str, task: &str, routes: &[String], jobs: usize, parent: &str, ) -> Result<()>

Open the run’s ledger row (#171), before the first child starts.

Source

pub fn flare_job_running( &self, run: &str, n: usize, route: &str, session: &str, ) -> Result<()>

A child has its session and is about to call the model.

Source

pub fn flare_job_done(&self, done: &FlareJobRow) -> Result<()>

How that child ended, and what it cost. state is one word: done, failed or dropped.

Source

pub fn finish_flare_run( &self, id: &str, state: &str, prompt: Option<u64>, completion: Option<u64>, iterations: usize, ) -> Result<()>

Close the run: its state and what all its children cost together.

Source

pub fn cancel_flare_run(&self, id: &str) -> Result<bool>

Ask a run to stop, from any process. The run checks between children, so a queued flare is dropped before it starts rather than after it has paid for its first turn.

Source

pub fn flare_cancel_requested(&self, id: &str) -> Result<bool>

Whether anyone has asked this run to stop.

Source

pub fn flare_runs(&self, limit: usize) -> Result<Vec<FlareRunRow>>

The runs, newest first — what flares list and the dashboard read.

Source

pub fn flare_run( &self, id: &str, ) -> Result<Option<(FlareRunRow, Vec<FlareJobRow>)>>

One run and its children, in the lead’s order.

Source

pub fn flares_of(&self, run: &str) -> Result<Vec<SessionInfo>>

The flares a run started, in the order the lead asked for them.

A run that was cancelled part-way has fewer rows than jobs, and that is the honest answer: a flare that never started has no transcript to open.

Source

pub fn begin_api(&self, id: &str) -> Result<()>

Create the row for an API call, tagged, before it has a message.

It has to happen before the run: append creates an untagged row when none exists, and a row that arrives as native can never be told apart from one a person typed. A row that already exists is left as it is.

Source

pub fn origin(&self, id: &str) -> Result<Option<String>>

Where a session came from, or None when there is no such row (#509).

The send path asks this one question: a turn’s agent is decided by the row’s own origin, so a transcript opened by id is the bot’s conversation too. One row rather than a listing — the dashboard answers a request per keystroke elsewhere and a full list here would be a scan to learn one string.

Source

pub fn begin_bot(&self, id: &str, name: &str) -> Result<()>

Create the row for a bot’s conversation, marked bot:<name>, before it has a message (#509).

The row has to exist first for the same reason an API call’s does: append creates an untagged row when none exists, and a bot’s conversation that arrived as native would sit in the human’s list for the rest of its life.

Source

pub fn bot_session(&self, name: &str) -> Result<String>

The bot’s live conversation, creating one when it has none (#509).

One conversation is what “an identity” means: the Bots tab’s open button and every later send land in the same transcript until it is cleared. A cleared one is archived, not deleted, so the next open starts a new row beside it and the count the tab shows still says it happened.

Source

pub fn bot_sessions(&self, name: &str) -> Result<Vec<String>>

Every conversation name has that is still open, newest first: what clearing a bot archives (#509).

Source

pub fn prune_api_sessions(&self, cutoff_ms: u64) -> Result<usize>

Delete the API’s own sessions older than cutoff_ms (unix milliseconds): the ones /v1/chat/completions leaves behind, and nothing else. Returns how many went.

A script polling the API writes a session per call; without this they accumulate until the listing and the search degrade. Pinned sessions stay — a person who pinned one meant it — and so does every session a person started.

Source

pub fn load_records(&self, id: &str) -> Result<Vec<Record>>

Load all records in order. A row whose stored body cannot be parsed is an error naming the session and the record, because silently dropping a message would make the transcript lie.

Source

pub fn load(&self, id: &str) -> Result<Vec<Message>>

Source

pub fn title(&self, id: &str) -> Result<Option<String>>

The name set with rename, if any.

Source

pub fn rename(&self, id: &str, title: &str) -> Result<()>

Give an existing session a title (trimmed; 1-200 characters, no control characters). The transcript is left untouched.

A human’s title outranks anything the machine writes, so this is the one path that sets TitleSource::User — and a later set_title from the naming pass cannot take it back.

Source

pub fn set_title( &self, id: &str, title: &str, source: TitleSource, ) -> Result<bool>

Write a title written by the machine, unless a better-sourced one is already there.

derived < llm < user, enforced here rather than by whoever calls: the naming pass runs in a task of its own, so a rename landing between the read and the write is normal, and the database is the only place where “the user’s name wins” can be a fact instead of a hope. Returns whether the row changed.

Source

pub fn title_if_unnamed(&self, id: &str, name: &str) -> Result<bool>

set_title for a session found by id, only if nothing names it yet.

This is stage one: it runs on the turn’s own path, costs nothing, and cannot fail. A title that already exists is left alone whatever wrote it, so an imported or renamed session is never relabelled by the machine.

Source

pub fn claim_title_upgrade(&self, id: &str) -> Result<bool>

Take the one naming attempt this session is allowed, or None when it has had it.

The claim is a single UPDATE, so two processes racing on the same fresh session cannot both decide to spend a call — one gets the row, the other gets nothing.

Two kinds of session are never claimed. A child of delegate has a name nobody reads outside the parent’s list, and an api session is a headless call: naming one would put a second request on every programmatic turn, which is exactly the cost the cheap route exists to avoid. Both still get the derived name, which is free.

Returns whether this caller owns the one call.

Source

pub fn title_attempt_failed(&self, id: &str, why: &str) -> Result<()>

Record why the naming attempt did not land. The derived title stays, and the note is what stops a second call: the failure is remembered rather than retried on every resume.

Source

pub fn release_title_claim(&self, id: &str) -> Result<()>

Give up the claim without recording a failure: nothing was tried, so the session is still eligible if a later run is configured to name it.

Source

pub fn set_last_cost(&self, id: &str, cost: &TurnCost) -> Result<()>

Record what a turn cost, as one JSON snapshot beside the session (#344).

updated_ms is deliberately untouched: this is bookkeeping about a turn, not activity in the session, and a write that reordered the list would make a session nobody is talking to jump to the top of Today.

A write against a session that no longer exists is not an error. The turn had already happened; the record goes with the transcript it describes, and a run whose session was deleted mid-flight must not fail over its own bookkeeping.

Source

pub fn set_image_seen( &self, id: &str, seq: u64, index: usize, text: &str, ) -> Result<bool>

Record what a model that can see said about one picture on a stored message (#346).

Written once, on the turn that attached the picture, and read back by every later request. Without it a session that once attached a screenshot pays for the same description on every turn afterwards, and the prompt for a past turn changes under the conversation that is still talking about it — two ways to be wrong, both silent. Returns whether a stored picture was actually changed. false is not an error: the message or the picture is gone, and the description was for a turn that already happened — but the caller can now tell a write from a no-op, which it could not when this returned ().

Source

pub fn last_cost(&self, id: &str) -> Result<Option<TurnCost>>

The last turn’s numbers for one session, or None — never having run and having lost the record are the same answer here, because both mean “there is nothing honest to show”.

Source

pub fn set_pinned(&self, id: &str, pinned: bool) -> Result<()>

Pin or unpin a session: a pinned one sorts first in every listing and no retention policy deletes it. The transcript is left untouched.

Source

pub fn set_archived(&self, id: &str, archived: bool) -> Result<()>

Archive or unarchive a session: an archived one is out of list and out of every retention policy, and keeps its messages, its title and its place in search.

The same shape as set_pinned on purpose — one column, one UPDATE, and one function both surfaces call — so archived cannot be a thing the CLI knows and the dashboard guesses at.

Source

pub fn memory(&self, id: &str) -> Result<Option<Memory>>

The session’s stored memory. Ok(None) if there is none; an error if the row is unreadable, too large or not valid JSON of the expected shape. The content is not validated here: see Memory::validate and usable_memory.

Source

pub fn readable_memory(&self, id: &str) -> Option<Memory>

The stored memory if it passes Memory::validate: a missing, unreadable, corrupt or invalid row is treated as no memory.

Source

pub fn save_handoff( &self, id: &str, covered: Trimmed, span: (Option<u64>, Option<u64>), text: &str, judgement: Option<Judgement>, ) -> Result<()>

Store the compiled handoff for covered, replacing whatever the record held.

An existing memory that does not validate is replaced rather than preserved — a malformed record is not a fact worth defending, and refusing to save would leave the session with no handoff at all.

Source

pub fn save_memory(&self, id: &str, memory: &Memory) -> Result<()>

Store memory for an existing session, replacing any earlier one. The transcript is never touched. Invalid memory is refused.

Most callers want save_handoff, which builds the record around the document being stored; this is the raw setter.

Source

pub fn delete(&self, id: &str) -> Result<()>

Remove a session’s transcript, title and memory. Errors if it does not exist.

Source

pub fn prune_candidates( &self, keep_days: u64, keep_count: usize, now_ms: u64, include_archived: bool, ) -> Result<PrunePlan>

What a retention policy would delete: sessions whose last activity is older than keep_days days, plus all but the newest keep_count. A limit of 0 is disabled; both 0 selects nothing. Nothing is deleted here.

Last activity is the newest record’s timestamp. A session imported from a legacy file with no readable records keeps that file’s modification time, so a corrupt old transcript can still be pruned.

A pinned session is never a candidate, whatever the limits say, and the plan counts how many that kept out of reach so the caller can say so. A pinned session still holds its place in the ranking: the policy keeps N sessions, and a pinned one among them is still one of the N — the same accounting auto_prune’s protect has always used.

An archived session is not a candidate either, unless include_archived says so (#240): archiving is how a finished conversation stops taking a row, and a prune that quietly deleted the thing a person filed away would be a worse version of the delete it was chosen over. It keeps its place in the ranking too, like a pin, and is counted in PrunePlan::archived_kept so the caller can name the flag that would have taken it.

Source

pub fn auto_prune( &self, keep_days: u64, keep_count: usize, now_ms: u64, protect: Option<&str>, ) -> Result<AutoPrune>

Apply a retention policy unattended, as [sessions] auto_prune does at CLI startup. Mirrors the manual --force rule: it deletes only when the policy would remove at most PRUNE_CONFIRM_ABOVE sessions, otherwise it deletes nothing and reports how many it would have removed. With both limits 0 it never deletes. protect (the session about to be resumed) is never deleted, even if it is old.

An archived session is never deleted here: a policy that runs with nobody watching has no way to be given --archived, so the flag that would allow it is not one this path can take.

Source

pub fn export(&self, id: &str, format: ExportFormat) -> Result<String>

The full stored transcript: every request/response turn and tool call, in order. The system prompt is not stored in sessions, so it is not included.

Source

pub fn list(&self) -> Result<Vec<SessionInfo>>

Sessions sorted newest first, pinned ones first of all — the list a person reads.

Every surface lists through this method — sessions list, the /resume picker and the dashboard — so pinning is one ordering rule in one place rather than three.

An archived session is not here, and that is the whole of what archiving means (#240): it keeps its messages, search still finds it and list_with_archived still names it, so the one query that has to know about the flag is this one.

Source

pub fn list_with_archived(&self) -> Result<Vec<SessionInfo>>

Every session, archived ones included and marked, in the same order.

For the places that have to show an archived row: sessions list --archived, the dashboard’s filter, and the name lookups behind search and the recall block — a hit in an archived session is still a hit, and a session named by an id with no title beside it reads as a session that was deleted.

Source

pub fn list_bots(&self) -> Result<Vec<BotSessions>>

The bot conversations the Bots tab lists (#509), newest activity first.

One query, the same one the human’s list reads — a bot’s sessions are in that list and filtered out of it, never a second table and never a second ordering rule. A bot’s own row is what the tab groups: the newest conversation, when it last spoke, how much is in it.

Source

pub fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>>

Full-text search over the stored messages, newest first.

Uses SQLite’s FTS5 when the bundled library has it and LIKE when it does not — both are behind this one method, so callers never branch on it, and both answer in the same order: newest message first, ties broken by position. Which backend runs depends on how SQLite was compiled, and two installs must not disagree about what “the first 20 hits” means. FTS5 matches on word boundaries, LIKE matches substrings; that difference is the price of the fallback, and it is one a searcher can see, unlike an arbitrary result order.

Source

pub fn search_with( &self, query: &str, limit: usize, include_children: bool, ) -> Result<Vec<SearchHit>>

search, with child conversations in the answer when include_children.

The human’s discovery results leave bots and flares out (#509, #171): a bot answering on a lane, or a flare reading a crate, writes to the same archive, and “search my transcripts” that returned someone else’s conversation — one the searcher never had — would be a search that lies about who said it. The agent’s session_search exposes the flag; nothing else has a reason to.

Source

pub fn has_fts(&self) -> bool

Whether full-text search is available (the bundled library normally has it).

Trait Implementations§

Source§

impl Clone for SessionStore

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SessionStore

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Forget for SessionStore

§

impl Freeze for SessionStore
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze, *const ArcInner<Mutex<Option<Db>>> is !null: Freeze, PhantomData<ArcInner<Mutex<Option<Db>>>>: Freeze,

§

impl Move for SessionStore

§

impl RefUnwindSafe for SessionStore

§

impl Send for SessionStore
where RawVecInner: Send, Arc<Mutex<Option<Db>>>: Send,

§

impl Sync for SessionStore
where RawVecInner: Sync, Arc<Mutex<Option<Db>>>: Sync,

§

impl Unpin for SessionStore
where *const u8 is !null: Unpin, Arc<Mutex<Option<Db>>>: Unpin,

§

impl UnsafeUnpin for SessionStore
where *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, *const ArcInner<Mutex<Option<Db>>> is !null: UnsafeUnpin, PhantomData<ArcInner<Mutex<Option<Db>>>>: UnsafeUnpin,

§

impl UnwindSafe for SessionStore
where RawVecInner: UnwindSafe, Arc<Mutex<Option<Db>>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more