session

package
v0.1.61 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 12 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 session is the daemon's local state, persisted to a JSON file on the sandbox disk. One daemon per sandbox hosts every agent adapter, so this store is SHARED across agents: chat transcripts and runs are keyed by chatId (globally unique), while per-agent state — CLI session ids and config/creds — is namespaced by agent type so adapters never collide (see the orchestrator's CredView and the (agent, chat) session keys below).

Index

Constants

View Source
const CompletionSaveError = "" /* 183-byte string literal not displayed */

Variables

View Source
var ErrTurnRequestConflict = errors.New("requestId already belongs to a different turn")

Functions

func HistoryBeforeRun

func HistoryBeforeRun(native []agent.Message, recorded []Message, run Run) []agent.Message

An active assistant turn belongs only to the run stream. Keep the native prefix (including forked history and its pagination IDs), then the accepted user input. Filtering also excludes a reply saved just before the run's terminal status write.

Types

type ChatFork

type ChatFork struct {
	SourceChatID string          `json:"sourceChatId"`
	Agent        string          `json:"agent,omitempty"`
	Point        agent.ForkPoint `json:"point"`
}

Origin survives completion, so replaying a lost HTTP acknowledgement returns the existing branch even after its first turn has created the native session.

type ChatImport

type ChatImport struct {
	ChatID, Agent, SessionID, CWD string
	Data                          PortableChat
	// Expected is the selected local history captured before a sync journal was
	// committed. It permits a verified merge/enrichment, never a blind replacement.
	Expected *PortableChat
}

type ChatSession

type ChatSession struct {
	ChatID, Agent, SID, CWD string
	ForkPending             bool
}

ChatSession is a reference into a harness's native store. It contains no messages; discovery and registry migration use it to preserve resume identity.

type ChatSummary

type ChatSummary struct {
	ChatID     string `json:"chatId"`
	Agent      string `json:"agent,omitempty"` // agent type that last ran this chat
	Title      string `json:"title"`
	Messages   int    `json:"messages"`
	UpdatedAt  string `json:"updatedAt"`
	LastStatus string `json:"lastStatus,omitempty"`
	LastRunID  string `json:"lastRunId,omitempty"` // latest run id — lets a list badge/deep-attach a live turn
}

ChatSummary is the daemon's view of a chat, for listing sessions.

type ForkOptions

type ForkOptions struct {
	Agent string
	Point agent.ForkPoint
	// Only durable input metadata is copied; the harness still owns history.
	Attachments []Message
}

type InteractionReply

type InteractionReply struct {
	RunID    string
	Response agent.InteractionResponse
}

type Message

type Message = agent.Message

type MessageQuestion

type MessageQuestion struct {
	ChatID        string            `json:"chatId"`
	RunID         string            `json:"runId"`
	Interaction   agent.Interaction `json:"interaction"`
	ResponseRunID string            `json:"responseRunId,omitempty"`
}

MessageQuestion is durable daemon bookkeeping for a native async question. Native control requests stay in the live supervisor and expire with their run.

type PortableChat

type PortableChat struct {
	Title       string           `json:"title,omitempty"`
	Messages    []Message        `json:"messages"`
	Runs        []Run            `json:"runs"`
	ForkPending bool             `json:"forkPending,omitempty"`
	ForkPoint   *agent.ForkPoint `json:"forkPoint,omitempty"`
}

PortableChat is deliberately selected data, not a state-file backup. Config, credentials, notifications, pending interactions and turn idempotency receipts belong to the original daemon and must never be installed on another machine.

type Run

type Run struct {
	ID         string            `json:"id"`
	ChatID     string            `json:"chatId"`
	Agent      string            `json:"agent,omitempty"` // agent type that executed the turn
	Status     string            `json:"status"`          // "running" | "done" | "error" | "cancelled"
	Error      string            `json:"error,omitempty"`
	ReplyID    string            `json:"replyId,omitempty"` // assistant message id when done
	CreatedAt  string            `json:"createdAt"`
	EndedAt    string            `json:"endedAt,omitempty"`
	Inputs     []agent.UserInput `json:"inputs,omitempty"`
	MessageIDs []string          `json:"messageIds,omitempty"` // ordered response segments when a run includes follow-ups
	// Resolve-mode tree fields (all zero for an ordinary turn):
	ParentID   string `json:"parentId,omitempty"`   // set on a child iteration → its parent resolve Run id
	Kind       string `json:"kind,omitempty"`       // "" ordinary | "resolve" parent
	StopReason string `json:"stopReason,omitempty"` // parent only: "done" | "capped" | "error" — why the loop ended
	Iterations int    `json:"iterations,omitempty"` // parent only: how many child turns ran
}

Run is one durable agent turn. The daemon owns it: it keeps running (and is recorded here) regardless of whether the app is still connected.

Resolve mode introduces a parent/child tree: a "resolve" Run (Kind=="resolve") is the parent the caller waits on, and each auto-continued iteration is an ordinary child Run carrying ParentID. Ordinary single turns leave all of ParentID/Kind/StopReason/Iterations zero, so the shape is unchanged for existing callers.

type SessionRef

type SessionRef struct {
	Agent  string
	SID    string
	CWD    string
	Shared bool // another chat (including a pending fork) still resumes this native session
}

SessionRef identifies one agent's native session for a chat. DeleteChat returns these so the API layer can drive native-transcript deletion per agent (the store never learns transcript paths).

type Store

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

func Open

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

func (*Store) AddMessage

func (st *Store) AddMessage(m Message) error

func (*Store) ArtifactOwners

func (st *Store) ArtifactOwners(excluding string) map[string]string

ArtifactOwners preserves a fork's inherited inputs when its source is deleted. Called only during deletion, under the workspace mutation lock; no idle scan.

func (*Store) ChatCWD

func (st *Store) ChatCWD(chatID string) string

ChatCWD returns the directory turns for this chat ran in (used to locate an agent's native transcript, which is path-scoped). "" if no turn has run yet.

func (*Store) ChatExists

func (st *Store) ChatExists(chatID string) bool

ChatExists reports whether the store has ANY record of a chat — a session, cwd, title, message, or run. Used to 404 a fork of an unknown source and to reject a fork onto an id already in use.

func (*Store) ChatSessions

func (st *Store) ChatSessions() []ChatSession

func (*Store) ChatSummaryFor

func (st *Store) ChatSummaryFor(chatID string) ChatSummary

ChatSummaryFor builds the listing summary for a single chat id, mirroring the per-chat aggregation Chats does. It is best-effort and works for a message-less chat (e.g. a fresh fork, whose native history is shared until its first turn branches it): such a chat reports zero messages and the user title (or "New chat"). The rename/fork API handlers use this to return the updated/new summary.

func (*Store) Chats

func (st *Store) Chats() []ChatSummary

Chats lists the chats the daemon has recorded (newest activity first), with a title derived from the first user message.

func (*Store) Children

func (st *Store) Children(parentID string) []Run

Children returns every child iteration of a resolve parent run, oldest→newest (append order). It is the run tree the caller reads to inspect per-iteration outcomes; an ordinary run or an unknown id yields an empty slice.

func (*Store) CommitInteractionReply

func (st *Store) CommitInteractionReply(ref InteractionReply, responseRunID string, message Message, run *Run) error

CommitInteractionReply atomically records the answer and its user message. A resumed turn also writes its Run in this transaction, before execution starts. The reply is never marked answered merely because the user tapped Send.

func (*Store) CompleteRun added in v0.1.54

func (st *Store) CompleteRun(run Run, messages []Message) (Run, error)

CompleteRun commits the terminal status and transcript together. Unlike a rejected admission, a completed native turn cannot be rolled back or safely rerun. If disk writes fail, retain its output and an explicit terminal error in memory; the next successful state write includes both. The caller must report the error instead of sending a success result or notification.

func (*Store) Config

func (st *Store) Config() map[string]string

Config returns a copy of the whole namespaced config map. Callers scope to one agent through the orchestrator's CredView (key prefix "<agent>:"); the runner and API never read this raw map directly.

func (*Store) DeleteChat

func (st *Store) DeleteChat(chatID string) ([]SessionRef, error)

DeleteChat removes ALL of a chat's mindwire bookkeeping — its per-agent session pointers, cwd, title, fork markers, messages, and runs — and returns a SessionRef for every (agent, session) the chat mapped to so the caller can delete each agent's native transcript (the source of truth). The store deliberately does not touch native files: it doesn't know their paths. Idempotent — deleting a chat with no records succeeds with an empty ref list.

func (*Store) DeleteNotifyChannel

func (st *Store) DeleteNotifyChannel(id string) error

DeleteNotifyChannel removes a channel by id. Idempotent — deleting an unknown id is a no-op.

func (*Store) DeleteNotifyRule

func (st *Store) DeleteNotifyRule(id string) error

DeleteNotifyRule removes a rule by id. Idempotent — deleting an unknown id is a no-op.

func (*Store) ExportChat

func (st *Store) ExportChat(agentType, chatID string) (PortableChat, error)

func (*Store) ForkChat

func (st *Store) ForkChat(srcChatID, newChatID string, options ...ForkOptions) error

ForkChat clones a chat's session mapping into a new chat id so the fork transparently shows the shared native history until its first turn branches it. It seeds Sessions[agent, newChatID] from the source for every agent that has one, copies the cwd and title, and records a fork-pending marker per agent (consumed by the runner to force ForkOnResume on turn one). Only durable attachment metadata is retained; GET messages reads native history until it branches. Errors if the source is unknown or the target id is already in use.

func (*Store) ForkMatches

func (st *Store) ForkMatches(source, target, before string) bool

func (*Store) Get

func (st *Store) Get(key string) string

func (*Store) GetRun

func (st *Store) GetRun(id string) (Run, bool)

func (*Store) HasPendingMessageQuestion

func (st *Store) HasPendingMessageQuestion(runID string) bool

func (*Store) HistoryRevision

func (st *Store) HistoryRevision(chatID string) string

HistoryRevision is a constant-time change token for daemon-owned history and interaction overlays. It adds no transcript copy, file read or idle work. A fresh epoch after restart conservatively invalidates clients' retained pages.

func (*Store) ImportChats

func (st *Store) ImportChats(chats []ChatImport) error

ImportChats is one atomic JSON-store write. Replaying a recovered transaction cannot duplicate a message/run, and ID collisions fail rather than overwrite.

func (*Store) LatestRun

func (st *Store) LatestRun(chatID string) (Run, bool)

LatestRun returns the most recent TOP-LEVEL run for a chat (runs are append-ordered, so the last match wins). The app uses this to reattach a chat's in-flight turn stream after reopening. Resolve child iterations (ParentID != "") are skipped: their events stream on the PARENT topic, so a reattach must target the parent — which, as the last top-level run, is exactly what this returns.

func (*Store) MessageQuestion

func (st *Store) MessageQuestion(runID, id string) (MessageQuestion, bool)

func (*Store) Messages

func (st *Store) Messages(chatID string) []Message

func (*Store) NotifyChannel

func (st *Store) NotifyChannel(id string) (agent.NotifyChannel, bool)

NotifyChannel returns a deep copy of one channel by id, or ok=false if unknown.

func (*Store) NotifyChannels

func (st *Store) NotifyChannels() []agent.NotifyChannel

NotifyChannels returns a deep copy of every configured channel.

func (*Store) NotifyConfig

func (st *Store) NotifyConfig() (url, channel, token string)

NotifyConfig returns the provisioned notification webhook (url, channel, token).

func (*Store) NotifyFormat

func (st *Store) NotifyFormat() agent.NotifyChannelType

func (*Store) NotifyRule

func (st *Store) NotifyRule(id string) (agent.NotifyRule, bool)

NotifyRule returns a deep copy of one rule by id, or ok=false if unknown.

func (*Store) NotifyRules

func (st *Store) NotifyRules() []agent.NotifyRule

NotifyRules returns a deep copy of every configured routing rule.

func (*Store) OverlayInteractions

func (st *Store) OverlayInteractions(chatID string, parts []agent.Part) []agent.Part

OverlayInteractions applies the same daemon-owned answer state to native history, recorded history and run snapshots. Forked/imported native questions without a record in this chat are read-only; they cannot answer another chat.

func (*Store) PendingFork

func (st *Store) PendingFork(agentType, chatID string) *agent.ForkPoint

PendingFork remains armed across failures and daemon restarts. SetSession commits the new native ID and clears this marker in the same atomic write.

func (*Store) PrepareFork

func (st *Store) PrepareFork(adapter agent.Adapter, source, before, defaultCWD string) (ForkOptions, error)

Shared by HTTP and the embedded SDK; adapters own every native boundary.

func (*Store) ReconcileRunning

func (st *Store) ReconcileRunning(reason string) error

ReconcileRunning marks any run still "running" as errored — called once at startup. A daemon restart abandons in-flight turns (they ran on the process's context), so without this a stale run stays "running" forever and a client reattaching would hang on a topic nothing publishes to.

func (*Store) RecordMessageQuestion

func (st *Store) RecordMessageQuestion(chatID, runID string, it agent.Interaction) (agent.Interaction, error)

RecordMessageQuestion runs before publishing the question. Replayed native items cannot reopen an answered question. Save failures never claim persistence.

func (*Store) RestoreChatSessions

func (st *Store) RestoreChatSessions(refs []ChatSession) error

RestoreChatSessions fills missing references atomically, with a single state write for an entire native inventory. A newer running session always wins.

func (*Store) RunForRequest added in v0.1.54

func (st *Store) RunForRequest(id string) (Run, bool)

RunForRequest recovers an accepted server-generated operation receipt. Callers must validate their own persisted payload digest before using this lookup.

func (*Store) SaveRun

func (st *Store) SaveRun(run Run) error

func (*Store) SaveRunInput

func (st *Store) SaveRunInput(runID string, input agent.UserInput, digest string) (Run, error)

SaveRunInput reserves the retry receipt before native delivery. A lost HTTP response, client reconnect, or daemon restart cannot submit it a second time.

func (*Store) SaveTurnMessages

func (st *Store) SaveTurnMessages(messages []Message) error

SaveTurnMessages replaces the acknowledged input placeholders with the completed, interleaved transcript in one write. Other chats are untouched.

func (*Store) SaveTurnStart

func (st *Store) SaveTurnStart(run Run, message *Message, requestID, digest string) error

SaveTurnStart commits the ingress message, run and optional retry receipt together, before the supervisor launches any harness operation.

func (*Store) Session

func (st *Store) Session(agentType, chatID string) string

Session returns the CLI session id for (agent, chat), or "" if none. Keyed per agent so a chatId addressed by two adapters keeps independent resume state.

func (*Store) Set

func (st *Store) Set(key, val string) error

func (*Store) SetChatCWD

func (st *Store) SetChatCWD(chatID, cwd string) error

func (*Store) SetMany

func (st *Store) SetMany(values map[string]string) error

SetMany commits one settings edit together so a turn cannot see half a model / reasoning change. A failed disk write also restores the in-memory snapshot.

func (*Store) SetNotifyChannel

func (st *Store) SetNotifyChannel(ch agent.NotifyChannel) error

SetNotifyChannel upserts a channel by id (replacing a same-id entry, else appending).

func (*Store) SetNotifyConfig

func (st *Store) SetNotifyConfig(url, channel, token string, format ...agent.NotifyChannelType) error

SetNotifyConfig stores the notification webhook the client provisioned.

func (*Store) SetNotifyRule

func (st *Store) SetNotifyRule(r agent.NotifyRule) error

SetNotifyRule upserts a rule by id (replacing a same-id entry, else appending).

func (*Store) SetSession

func (st *Store) SetSession(agentType, chatID, sessionID string) error

func (*Store) SetTitle

func (st *Store) SetTitle(chatID, title string) error

SetTitle records a user-chosen title for a chat (a rename). An empty title clears it, falling back to the native auto-title / first-message snippet.

func (*Store) Title

func (st *Store) Title(chatID string) string

Title returns the user-set title for a chat, or "" if none. This is the rename title, which the listing prefers over the agent's native auto-title (see Chats and the API's chats handler).

func (*Store) TurnRequest

func (st *Store) TurnRequest(id, digest string) (Run, bool, error)

func (*Store) UpdateRunInput

func (st *Store) UpdateRunInput(runID string, input agent.UserInput) error

UpdateRunInput uses copy-on-write so snapshots and HTTP responses never race with native acknowledgements. Accepted messages are also retained for history.

func (*Store) ValidateChatImports

func (st *Store) ValidateChatImports(chats []ChatImport) error

Jump to

Keyboard shortcuts

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